Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

3.0 KB
Raw Blame
/*
 * SPDX-License-Identifier: AGPL-3.0
 * Copyright (c) 2026 BoxLite AI
 */

import { Logger } from '@nestjs/common'
import type { ClientRequest } from 'node:http'
import type { Socket } from 'node:net'

// `ensureReady` can wait for the state lock, for STOPPED, for the lock again and for
// STARTED, `AUTO_RESUME_TIMEOUT_SECONDS` each, before the runner answers the upgrade.
export const ATTACH_HANDSHAKE_TIMEOUT_MS = 120_000

const logger = new Logger('AttachHandshake')

/** Answers an upgrade request that will not be upgraded, then closes the socket. */
export function respondAndClose(socket: Socket, status: number, reason: string): void {
  try {
    socket.write(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
  } catch {
    // Socket may already be torn down — ignore.
  }
  socket.destroy()
}

// A socket `error` always follows `destroy(error)`, which already marked the socket
// destroyed; this handler exists so the event has a listener.
function onSocketError(this: Socket): void {
  this.destroy()
}

/**
 * Owns the client socket of one attach upgrade from the `upgrade` event until httpxy
 * takes it over, and bounds the whole handshake. Node drops the HTTP server's socket
 * `error` listener before emitting `upgrade`, and httpxy installs its own only once the
 * runner request starts; an `error` in between would otherwise exit the process.
 */
export class AttachHandshake {
  private proxyReq?: ClientRequest
  private readonly timer: NodeJS.Timeout

  constructor(private readonly socket: Socket) {
    socket.on('error', onSocketError)
    socket.once('close', this.release)
    this.timer = setTimeout(() => this.expire(), ATTACH_HANDSHAKE_TIMEOUT_MS)
    this.timer.unref()
  }

  /**
   * httpxy owns the socket's `error` from here, and the handshake ends when the runner
   * request does. Called from the proxy's `proxyReqWs` event, after httpxy installed
   * its own handler.
   */
  bind(proxyReq: ClientRequest): void {
    this.socket.removeListener('error', onSocketError)
    this.proxyReq = proxyReq
    proxyReq.once('upgrade', this.release)
    proxyReq.once('response', this.release)
    proxyReq.once('error', this.release)
    proxyReq.once('close', this.release)
  }

  private readonly release = (): void => {
    clearTimeout(this.timer)
    this.socket.removeListener('error', onSocketError)
    this.socket.removeListener('close', this.release)
    this.proxyReq?.removeListener('upgrade', this.release)
    this.proxyReq?.removeListener('response', this.release)
    this.proxyReq?.removeListener('error', this.release)
    this.proxyReq?.removeListener('close', this.release)
  }

  private expire(): void {
    this.release()
    logger.warn(`Attach handshake exceeded ${ATTACH_HANDSHAKE_TIMEOUT_MS / 1000} s`)
    // With an error so the audit session completes its record, and before the client
    // closes: that close also makes the audit session destroy this request.
    this.proxyReq?.destroy(new Error('attach handshake timed out'))
    respondAndClose(this.socket, 504, 'Gateway Timeout')
  }
}