SpuntoSpunto/@spunto/build

Gateway

The HTTP gateway in front of a box's ports — the decision table, the pages it serves itself, the /__spunto/* contract, and the relay over a byte tunnel.

Why it exists

Every box exposes its ports on a host of its own (sbx-<id>-3000.spunto.net in Spunto Cloud, worker-<id>-3000.localhost in Spunto Lite). In front of them sits a small proxy that has to decide, for each request, whether to relay it to the box or to answer itself. The box may be stopped, paused, still building, or up with nothing listening on that port. In all of those cases the proxy should not hand the browser a bare 502 or an ERR_EMPTY_RESPONSE.

Its answer is a page. For a stopped box, the page has a play button: opening any port of a stopped box offers to start it, polls until it is ready and reloads the URL that was asked for.

Cloud and Lite each had their own copy of that table, those pages and that polling script, and every fix had to be ported by hand. This module holds the parts they say the same way. Each product keeps what it does differently:

Shared, in this moduleEach product's own
The decision table: relay, or which pageParsing the host
The pages: HTML, CSS, the polling scriptAuthentication (Cloud's session cookie; Lite has none)
The /__spunto/status and /__spunto/start contractReading the box's state (an API call, a SQLite row)
Relaying one request, or one upgrade, over a tunnelOpening the tunnel (a WebSocket relay, an in-process agent connection)

Like the rest of the package it does no I/O and types against no runtime. Requests and sockets are minimal structural interfaces that Node's IncomingMessage and net.Socket satisfy as they are.

import { boxBlockPage, gatewayPageResponse, relayHttp, nothingListeningPage, tunnelFailedPage } from "@spunto/build/gateway"

const context = { noun: "Workspace", subject: `${box.id} · port ${port}` }
const blocked = boxBlockPage({ state: box.state }, context)
if (blocked) return send(blocked)

relayHttp(req, req.socket, openTunnel(box, port), {
  answered: () => res.headersSent,
  onEmpty: (error) => send(error ? tunnelFailedPage(error, context) : nothingListeningPage(port, context)),
})

function send(blocked) {
  const { status, headers, body } = gatewayPageResponse(blocked, { paint, appUrl, accept: req.headers.accept })
  res.writeHead(status, headers).end(body)
}

The decision table

BoxState

type BoxState =
  | "provisioning" | "building" | "pulling" | "starting" | "ready"
  | "stopping" | "stopped" | "pausing" | "paused" | "snapshotting"
  | "running" | "exited" | "unknown" | "deleting" | "error"

These are the states Spunto Cloud's routing uses, the widest vocabulary of the two products. Lite's states (provisioning, building, starting, ready, stopped, error) are a strict subset with the same meaning, so Lite has nothing to translate. Any other string is read as transient: a page that polls until the state changes. BOX_STATE_LABELS and boxStateLabel(state) give the human-readable label shown while polling ("Building image…").

GatewayBox

Prop

Type

Every field after state is something a control plane may know on top of the state. Each one defaults to the answer that changes nothing, so a single-host control plane passes state alone.

boxBlockPage(box, context?)

function boxBlockPage(box: GatewayBox, context?: BoxPageContext): { status: number; page: GatewayPage } | null

Returns null when the request may be relayed. Otherwise it returns the status and the page to answer with. context carries noun ("Sandbox" by default, or "Workspace", capitalized; the pages lower-case it mid-sentence), subject (the monospace chip, see boxSubject(name, port)) and dashboardUrl (the "Open dashboard" link).

BoxPageAction
ready, host onlinenone: relay
stopped / exited / error"… is stopped" / "… is not running"Start
paused"… is paused", with reason as footnoteResume (the same start)
any of the four above, not built"… has no container"Retry
any of the four above, host offline"Node offline"Retry
provisioning, building, pulling, starting, stopping, pausing, snapshotting, unknown stringnamed for what it ispolls
unknown (the host can't be reached)"… is unreachable"Retry
deleting"… is being deleted"
not placed"… unavailable"Retry
boxBlockPage({ state: "ready" })                       // → null
boxBlockPage({ state: "paused", reason: "trial hour" })
// → { status: 503, page: { kind: "stopped", canStart: true, startLabel: "Resume sandbox",
//      title: "Sandbox is paused", detail: "trial hour", … } }
boxBlockPage({ state: "stopped" }, { noun: "Workspace" })!.page.title // → "Workspace is stopped"

boxUpgradeRefusal(box)

function boxUpgradeRefusal(box: GatewayBox): string | null

The same table for a WebSocket upgrade, which can't render a page. It returns null to relay, and otherwise the raw response to end the socket with: an explicit status line instead of a bare drop. The browser lands on the HTML page when it reloads.

boxUpgradeRefusal({ state: "stopped" })
// → "HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nX-Spunto-Reason: worker-stopped\r\n\r\n"

nothingListeningPage(port, context?) and tunnelFailedPage(error, context?)

The two pages of the relay, both 502. The first is for a tunnel that closed without returning a single byte: the box runs, but nothing serves the port. The second is for a tunnel that failed first, with its error as footnote.

The pages

renderGatewayPage(page, options)

function renderGatewayPage(page: GatewayPage, options: {
  paint: GatewayPaint
  appUrl?: string
  brand?: { name?: string; logoUrl?: string | null }
}): string

A complete HTML document with its CSS and script inline and no asset except the logo, which disappears if it can't be loaded. The page must render when the box behind it is completely down. A page's kind sets the status dot and what the page does:

kindMeans
stoppedA play button (canStart) wired to POST /__spunto/start, then polling
startingPolls /__spunto/status from the start (autoPoll)
unavailableNothing to do here, except a Retry button when canRetry
notfoundNothing at this address

The polling script reloads the page when the box becomes ready, and also on any other state change, so the server renders the right page again. It gives up after 15 minutes.

Colours are a parameter

This package depends on no UI library. Each product passes its colours as paint: light and dark values (background, foreground, card, muted, mutedForeground, primary, primaryForeground, destructive, border), usually copied from @spunto/design-system. Dark mode follows prefers-color-scheme.

gatewayPageResponse(blocked, options)

function gatewayPageResponse(
  blocked: { status: number; page: GatewayPage },
  options: { paint: GatewayPaint; appUrl?: string; brand?: …; accept: string | null | undefined },
): { status: number; headers: Record<string, string>; body: string }

A page as a whole response. Only a top-level navigation (an Accept header containing text/html) gets HTML. A background XHR, or a sub-resource of an app that already loaded, gets one line of text/plain, never markup where it expected JSON. Every response carries X-Spunto-Page: <kind>, which tells the gateway's own answers apart from the same status sent by an app, for example in an access log.

The /__spunto/* contract

Two endpoints served by the gateway itself on every host of a box. They are never relayed to the box, so an app in the box that serves /__spunto/ never sees those requests.

GET  /__spunto/status  → 200 { state, nodeOnline? }      read fresh, never from a cache
POST /__spunto/start   → 2xx { state } | 4xx/5xx { error } anything but POST is a 405

GATEWAY_STATUS_PATH, GATEWAY_START_PATH and gatewayControl(url) ("status", "start" or null) name them. GatewayStatusBody and GatewayStartBody give the shape of the answers. A 2xx start means the box is on its way, or already up, and the page reloads. An { error } is shown in red under the button, which stays clickable.

The relay

ByteTunnel

interface ByteTunnel {
  write(data: Uint8Array): void
  end(): void
  onData(listener: (data: Uint8Array) => void): void
  onClose(listener: (error?: string) => void): void
}

A byte stream to one port of the box. What it runs over is the control plane's business: a WebSocket to a relay, an agent connection, a TCP socket. write may be called before the tunnel is open, and queuing until then is the tunnel's job. onClose carries an error when the tunnel failed (or never opened) rather than closed. Only the first close counts.

relayHttp(req, client, tunnel, options)

function relayHttp(req: RelayRequest, client: RelaySocket, tunnel: ByteTunnel, options: {
  onEmpty(error?: string): void
  answered?(): boolean
}): void

Writes the request into the tunnel as raw bytes, then its body, and copies the answer back to the client's socket without parsing it. That means no chunked re-encoding and no keep-alive left hanging: the request goes out with Connection: close, so the end of the tunnel is the end of the response.

Who owns the response depends on whether the box has sent anything yet:

  • Before the first byte, it is still the caller's. If the tunnel ends there, onEmpty(error?) is called, and the caller answers with a page. Use nothingListeningPage when error is undefined and tunnelFailedPage otherwise.
  • After it, the response belongs to the box. A failure from then on ends the socket.
  • answered() (Node: () => res.headersSent) tells the relay that the caller already sent a page. Bytes arriving after that are dropped instead of corrupting it.

When the client goes away, the relay ends the tunnel.

relayUpgrade(req, socket, head, tunnel)

function relayUpgrade(req: RelayRequest, socket: RelaySocket, head: Uint8Array | null | undefined, tunnel: ByteTunnel): void

Relays an upgrade (a dev server's hot reload, an editor's WebSocket) exactly as it came, followed by head, the first packet that Node's upgrade event hands over. It then splices the two streams for as long as either side keeps them open. Check boxUpgradeRefusal before calling it.

agentTunnel(connection, tunnelId, port, timeoutMs?)

function agentTunnel(connection: TunnelingConnection, tunnelId: string, port: number, timeoutMs?: number): ByteTunnel

A ByteTunnel to a port of a box whose agent is connected to this very process, through an AgentConnection from @spunto/build/agent-connection. There is no relay in between. Writes made before the agent opens the tunnel are queued and then sent in order. A refusal (nothing listens on the port), or an agent that never answers, becomes an onClose with the error. If no byte has been written yet, that is the relay's onEmpty.

import { randomUUID } from "node:crypto"

relayHttp(req, req.socket, agentTunnel(conn, randomUUID(), port), {
  answered: () => res.headersSent,
  onEmpty: (error) => send(error ? tunnelFailedPage(error, context) : nothingListeningPage(port, context)),
})
Edit on GitHub

On this page