Skip to content

An open-source, faster Devin alternative

TypeScript

write DO parity broker in cell

Brian Reardon507ced006a3f
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index f60191cd..7e34573d 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -268,6 +268,19 @@ async function proxyWebSocket(
if (req.headers.get("upgrade")?.toLowerCase() !== "websocket") {
return json({ error: "expected websocket upgrade" }, 400);
}
+
+ // Mint the cell-bound cap-token the cell-CP expects in Authorization,
+ // then transparently forward the upgrade to the cell-CP. With the
+ // OPENSANDBOX_WS_BROKER=1 cell-CP path active, the cell-CP's
+ // wsgateway terminates the browser's WS and brokers it against the
+ // worker — redial on upstream close, keepalive, exec-exit suppression,
+ // multi-session per sandbox, etc. live in Go, not here.
+ //
+ // Previously this function did an edge-side WebSocketPair + manual
+ // Blob-aware bridge. That made the cell-CP see the EDGE as the client,
+ // which short-circuited the broker's redial/keepalive — a worker
+ // restart killed the browser's terminal. Replacing the bridge with
+ // a transparent forward puts the broker actually in the middle.
let token: string;
try {
token = await mintCellCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, caller.plan, caller.userID);
@@ -276,130 +289,15 @@ async function proxyWebSocket(
return new Response("token mint failed", { status: 500 });
}
const upstreamURL = cell.base_url.replace(/\/$/, "") + cellPath;
- console.log(`proxyWebSocket: dialing upstream ${upstreamURL}`);
-
- // CF Workers WebSocket fetch: only the Upgrade: websocket header is needed.
- // Setting Connection: Upgrade can confuse the runtime; omit it. The Worker
- // returns a Response with a `.webSocket` property on success (status 101).
- let upstreamResp: Response;
- try {
- upstreamResp = await fetch(upstreamURL, {
- headers: {
- Upgrade: "websocket",
- Authorization: "Bearer " + token,
- },
- });
- } catch (e) {
- console.error(`proxyWebSocket: upstream fetch threw: ${(e as Error).message}`);
- return new Response(`cell websocket fetch failed: ${(e as Error).message}`, { status: 502 });
- }
- console.log(`proxyWebSocket: upstream status=${upstreamResp.status}`);
- const upstream = (upstreamResp as Response & { webSocket?: WebSocket }).webSocket;
- if (!upstream) {
- const errBody = await upstreamResp.text().catch(() => "");
- console.error(`proxyWebSocket: no webSocket on response; body=${errBody.slice(0, 200)}`);
- return new Response(
- `cell websocket connect failed (status ${upstreamResp.status}): ${errBody.slice(0, 200)}`,
- { status: 502 },
- );
- }
- const pair = new WebSocketPair();
- const client = pair[0];
- const server = pair[1];
-
- // CF Workers delivers binary WebSocket frames as Blob and ignores any
- // `binaryType = "arraybuffer"` setter on these proxy WebSockets. We have
- // to detect Blob in the handler and await `.arrayBuffer()` before
- // forwarding. We also use that ArrayBuffer when calling `.send()` so the
- // browser (which has `binaryType="arraybuffer"`) decodes the frame to a
- // plain ArrayBuffer in `event.data`.
-
- // Diagnostic byte counters. Forward binary + text messages between
- // upstream (cell) <-> server (browser-facing half of our pair).
- let upToBrowser = 0;
- let browserToUp = 0;
-
- // forward async-awaits Blob → ArrayBuffer (binary) or passes through
- // strings (text). Sending a Blob directly results in "[object Blob]"
- // text frame, which xterm renders as nothing. The await-chain ordering
- // is preserved per-direction by serializing through a single Promise.
- let upQueue: Promise<unknown> = Promise.resolve();
- let downQueue: Promise<unknown> = Promise.resolve();
- const forward = (
- data: unknown,
- target: WebSocket,
- addBytes: (n: number) => void,
- label: string,
- ): Promise<void> => {
- if (typeof data === "string") {
- addBytes(data.length);
- try { target.send(data); } catch (err) { console.error(`${label}: send (string) failed: ${(err as Error).message}`); }
- return Promise.resolve();
- }
- if (data instanceof ArrayBuffer) {
- addBytes(data.byteLength);
- try { target.send(data); } catch (err) { console.error(`${label}: send (ab) failed: ${(err as Error).message}`); }
- return Promise.resolve();
- }
- if (ArrayBuffer.isView(data)) {
- const v = data as ArrayBufferView;
- const ab = new ArrayBuffer(v.byteLength);
- new Uint8Array(ab).set(new Uint8Array(v.buffer, v.byteOffset, v.byteLength));
- addBytes(ab.byteLength);
- try { target.send(ab); } catch (err) { console.error(`${label}: send (view) failed: ${(err as Error).message}`); }
- return Promise.resolve();
- }
- if (data && typeof (data as any).arrayBuffer === "function") {
- return (data as Blob).arrayBuffer().then(
- (ab) => {
- addBytes(ab.byteLength);
- try { target.send(ab); } catch (err) { console.error(`${label}: send (blob) failed: ${(err as Error).message}`); }
- },
- (err) => { console.error(`${label}: blob.arrayBuffer failed: ${(err as Error).message}`); },
- );
- }
- console.error(`${label}: unknown data shape: ${typeof data} ${(data as any)?.constructor?.name}`);
- return Promise.resolve();
- };
-
- upstream.addEventListener("message", (e) => {
- const isFirst = upToBrowser === 0;
- if (isFirst) {
- console.log(`proxyWebSocket: up->browser first frame typeof=${typeof e.data} ctor=${(e.data as any)?.constructor?.name}`);
- }
- downQueue = downQueue.then(() => forward(e.data, server, (n) => { upToBrowser += n; }, "proxyWebSocket: server.send"));
- });
- server.addEventListener("message", (e) => {
- const isFirst = browserToUp === 0;
- if (isFirst) {
- console.log(`proxyWebSocket: browser->up first frame typeof=${typeof e.data} ctor=${(e.data as any)?.constructor?.name}`);
- }
- upQueue = upQueue.then(() => forward(e.data, upstream, (n) => { browserToUp += n; }, "proxyWebSocket: upstream.send"));
- });
- server.addEventListener("close", (e) => {
- console.log(`proxyWebSocket: server close code=${e.code} reason=${e.reason} (up->browser=${upToBrowser}, browser->up=${browserToUp})`);
- try { upstream.close(e.code, e.reason); } catch {}
- });
- upstream.addEventListener("close", (e) => {
- console.log(`proxyWebSocket: upstream close code=${e.code} reason=${e.reason} (up->browser=${upToBrowser}, browser->up=${browserToUp})`);
- try { server.close(e.code, e.reason); } catch {}
- });
- server.addEventListener("error", (e: any) => {
- console.error(`proxyWebSocket: server error: ${e?.message ?? "unknown"}`);
- try { upstream.close(1011, "client error"); } catch {}
- });
- upstream.addEventListener("error", (e: any) => {
- console.error(`proxyWebSocket: upstream error: ${e?.message ?? "unknown"}`);
- try { server.close(1011, "upstream error"); } catch {}
- });
-
- // Accept AFTER attaching listeners so we don't miss the first frame.
- // The worker emits the shell prompt (~27 bytes) within ~0.5ms of upgrade.
- upstream.accept();
- server.accept();
- console.log(`proxyWebSocket: bridge wired up + accepted`);
-
- return new Response(null, { status: 101, webSocket: client } as any);
+ console.log(`proxyWebSocket: forwarding upgrade to ${upstreamURL}`);
+
+ const fwd = new Request(upstreamURL, req);
+ fwd.headers.set("authorization", "Bearer " + token);
+ // Strip browser cookies — cell-CP authenticates the cap-token, not
+ // dashboard session cookies, and the cookies would only bloat the
+ // upstream request.
+ fwd.headers.delete("cookie");
+ return await fetch(fwd);
}
// ── identity (/me, /orgs, /org, /org/switch) ─────────────────────────────
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 63a6c113..cd0c3b3f 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -31,6 +31,7 @@ import (
"github.com/opensandbox/opensandbox/internal/proxy"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/storage"
+ "github.com/opensandbox/opensandbox/internal/wsgateway"
)
// ServerVersion is the control plane binary version, set at build time via -ldflags.
@@ -622,6 +623,18 @@ func main() {
log.Printf("opensandbox: edge client wired (base=%s)", cfg.CFEdgeBaseURL)
}
+ // Wire the in-process WebSocket broker. When enabled, data-plane
+ // WS routes (/sandboxes/:id/pty/:sid, /exec/:sid, /agent/:sid) go
+ // through internal/wsgateway instead of the legacy proxy's hijack
+ // + io.Copy path — gains redial on upstream close, keepalive,
+ // multi-session, exec-exit suppression, circuit breaker. Gated on
+ // OPENSANDBOX_WS_BROKER=1 so the rollout is a per-cell env flip;
+ // off keeps the legacy transparent forward in place.
+ if os.Getenv("OPENSANDBOX_WS_BROKER") == "1" {
+ server.SetWSGateway(wsgateway.NewGateway())
+ log.Printf("opensandbox: ws-broker enabled (OPENSANDBOX_WS_BROKER=1)")
+ }
+
// Wire Axiom read-only token for the sandbox session logs API.
// Token never leaves this process; the UI proxies its queries through
// /api/sandboxes/:id/logs. Empty token disables the endpoint (503).
diff --git a/internal/api/router.go b/internal/api/router.go
index 5a60c576..1b9890ca 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -28,6 +28,7 @@ import (
"github.com/opensandbox/opensandbox/internal/observability"
"github.com/opensandbox/opensandbox/internal/obslog"
"github.com/opensandbox/opensandbox/internal/proxy"
+ "github.com/opensandbox/opensandbox/internal/wsgateway"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/storage"
)
@@ -63,6 +64,7 @@ type Server struct {
pendingCreates sync.Map // map[sandboxID]*pendingCreate — async sandbox creation tracking
mountSvc *mounts.Service // shared with worker.HTTPServer; nil disables the mounts API
sandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
+ wsGateway *wsgateway.Gateway // nil disables the broker; WS data-plane routes fall back to sandboxAPIProxy
stripeClient *billing.StripeClient // nil if Stripe not configured
redisClient *redis.Client // nil if Redis not configured (for health checks)
adminEvents *AdminEventBus // real-time event bus for admin dashboard
@@ -86,6 +88,17 @@ func (s *Server) SetEdgeClient(c *edgeclient.Client) {
s.edge = c
}
+// SetWSGateway wires the in-process WebSocket broker. When non-nil,
+// data-plane WS routes (/sandboxes/:id/pty/:sid, /exec/:sid, /agent/:sid)
+// route through the broker instead of the legacy SandboxAPIProxy
+// hijack-and-io.Copy path. The broker provides multi-session, redial on
+// upstream close, exec-exit marker handling, keepalive, and circuit
+// breaking — see internal/wsgateway for the spec. Safe to leave nil
+// for cells that prefer the legacy transparent forward.
+func (s *Server) SetWSGateway(gw *wsgateway.Gateway) {
+ s.wsGateway = gw
+}
+
// SetAxiomQueryConfig wires the read-only Axiom token and dataset for
// the sandbox session logs read API. Token never leaves the control
// plane; the UI proxies through us.
@@ -448,16 +461,28 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// Server mode: proxy all data-plane requests to the worker that owns the sandbox
pxy := s.sandboxAPIProxy.ProxyHandler
+ // WS data-plane handler — dispatches dynamically per request so
+ // SetWSGateway works regardless of whether it was called before or
+ // after route registration. Non-WS verbs on the same paths always
+ // go through the proxy: the broker only handles bidi streaming.
+ wsHandler := func(c echo.Context) error {
+ if s.wsGateway != nil {
+ return s.brokerWebSocket(c)
+ }
+ return pxy(c)
+ }
+
// Exec
api.POST("/sandboxes/:id/exec", pxy)
api.GET("/sandboxes/:id/exec", pxy)
- api.GET("/sandboxes/:id/exec/:sessionID", pxy)
+ api.GET("/sandboxes/:id/exec/:sessionID", wsHandler)
api.POST("/sandboxes/:id/exec/:sessionID/kill", pxy)
api.POST("/sandboxes/:id/exec/run", pxy)
// Agent
api.POST("/sandboxes/:id/agent", pxy)
api.GET("/sandboxes/:id/agent", pxy)
+ api.GET("/sandboxes/:id/agent/:sid", wsHandler)
api.POST("/sandboxes/:id/agent/:sid/prompt", pxy)
api.POST("/sandboxes/:id/agent/:sid/interrupt", pxy)
api.POST("/sandboxes/:id/agent/:sid/kill", pxy)
@@ -476,7 +501,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// PTY
api.POST("/sandboxes/:id/pty", pxy)
- api.GET("/sandboxes/:id/pty/:sessionID", pxy)
+ api.GET("/sandboxes/:id/pty/:sessionID", wsHandler)
api.POST("/sandboxes/:id/pty/:sessionID/resize", pxy)
api.DELETE("/sandboxes/:id/pty/:sessionID", pxy)
diff --git a/internal/api/ws_broker.go b/internal/api/ws_broker.go
new file mode 100644
index 00000000..390655dc
--- /dev/null
+++ b/internal/api/ws_broker.go
@@ -0,0 +1,140 @@
+package api
+
+import (
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+
+ "github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
+
+ "github.com/opensandbox/opensandbox/internal/wsgateway"
+)
+
+// brokerWSUpgrader is the gorilla upgrader used for client WS upgrades
+// inside the broker route handlers. CheckOrigin returns true because by
+// the time the request reaches this handler it has already passed the
+// edge's auth (cap-token + API key) and CORS layers — same posture as
+// the existing api/pty.go and api/exec_session.go upgraders.
+var brokerWSUpgrader = websocket.Upgrader{
+ ReadBufferSize: 4096,
+ WriteBufferSize: 4096,
+ CheckOrigin: func(r *http.Request) bool { return true },
+}
+
+// brokerWebSocket is the Echo handler mounted at the data-plane WS paths
+// (/api/sandboxes/:id/pty/:sessionID, /exec/:sessionID, /agent/:sid)
+// when s.wsGateway is non-nil. Replaces the legacy SandboxAPIProxy
+// hijack-and-io.Copy path with the in-process broker, which adds
+// redial, keepalive, exec-exit handling, etc.
+//
+// Auth has already happened upstream (PGAPIKeyMiddleware on the api
+// group). This handler does the worker resolution + broker handoff.
+func (s *Server) brokerWebSocket(c echo.Context) error {
+ if s.wsGateway == nil || s.sandboxAPIProxy == nil {
+ // Belt-and-suspenders. Routes shouldn't be registered without both.
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "ws broker not configured",
+ })
+ }
+ sandboxID := c.Param("id")
+ sessionID := c.Param("sessionID")
+ if sessionID == "" {
+ sessionID = c.Param("sid") // /agent/:sid uses :sid
+ }
+ if sandboxID == "" || sessionID == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "sandbox ID and session ID required",
+ })
+ }
+
+ // Resolve once pre-upgrade so we can return a normal HTTP error if
+ // the sandbox is migrating / stopped / not found. After the upgrade
+ // the only failure channel is the WS close frame.
+ if _, err := s.sandboxAPIProxy.ResolveWorker(c, sandboxID); err != nil {
+ return err
+ }
+
+ // cellPath is the request path verbatim — drives isExec detection
+ // inside the broker (/exec/ and /agent/ flip it; /pty/ doesn't).
+ cellPath := c.Request().URL.Path
+ cellPathStripped := strings.TrimPrefix(cellPath, "/api")
+ rawQuery := c.Request().URL.RawQuery
+
+ // ResolveWorker closure: the broker calls it on initial dial AND on
+ // every redial, so a post-migration worker change picks up
+ // automatically. Route cache (3s TTL inside the proxy) coalesces
+ // rapid back-to-back lookups.
+ //
+ // When the cell-CP reports the sandbox is mid-migration (HTTP 503
+ // with "migrating" in the message), wrap the error with the
+ // wsgateway sentinel so the redial loop switches to the long
+ // migration cadence instead of burning its fast-ladder budget.
+ resolve := func() (string, string, error) {
+ r, err := s.sandboxAPIProxy.ResolveWorker(c, sandboxID)
+ if err != nil {
+ if isMigratingErr(err) {
+ return "", "", fmt.Errorf("%w: %v", wsgateway.ErrUpstreamMigrating, err)
+ }
+ return "", "", err
+ }
+ return buildWorkerWSURL(r.WorkerURL, cellPathStripped, rawQuery), r.Token, nil
+ }
+
+ return s.wsGateway.Serve(c.Response(), c.Request(), &brokerWSUpgrader, wsgateway.ServeOpts{
+ SandboxID: sandboxID,
+ SessionID: sessionID,
+ CellPath: cellPath,
+ ResolveWorker: resolve,
+ })
+}
+
+// isMigratingErr peeks at the echo.HTTPError returned by ResolveWorker
+// and reports whether it's the "sandbox is migrating, retry shortly"
+// flavor — the only ResolveWorker error path that should drive the
+// broker into its migration backoff cadence rather than failing fast.
+func isMigratingErr(err error) bool {
+ if err == nil {
+ return false
+ }
+ var he *echo.HTTPError
+ if !errors.As(err, &he) {
+ return false
+ }
+ if he.Code != http.StatusServiceUnavailable {
+ return false
+ }
+ msg := ""
+ if s, ok := he.Message.(string); ok {
+ msg = s
+ }
+ return strings.Contains(strings.ToLower(msg), "migrating")
+}
+
+// buildWorkerWSURL composes the WebSocket URL the broker should dial
+// against the worker. Worker addresses are http:// (or https://); we
+// flip to ws:// (or wss://) and stitch the cell-stripped path + query.
+//
+// Worker URL examples:
+//
+// http://10.0.0.5:8080 → ws://10.0.0.5:8080/sandboxes/sb-xxx/pty/yyy?api_key=...
+// https://worker.svc → wss://worker.svc/sandboxes/sb-xxx/pty/yyy
+func buildWorkerWSURL(workerAddr, cellPathStripped, rawQuery string) string {
+ scheme := "ws"
+ rest := workerAddr
+ switch {
+ case strings.HasPrefix(workerAddr, "https://"):
+ scheme = "wss"
+ rest = strings.TrimPrefix(workerAddr, "https://")
+ case strings.HasPrefix(workerAddr, "http://"):
+ scheme = "ws"
+ rest = strings.TrimPrefix(workerAddr, "http://")
+ }
+ rest = strings.TrimRight(rest, "/")
+ u := fmt.Sprintf("%s://%s%s", scheme, rest, cellPathStripped)
+ if rawQuery != "" {
+ u += "?" + rawQuery
+ }
+ return u
+}
diff --git a/internal/proxy/sandbox_api_proxy.go b/internal/proxy/sandbox_api_proxy.go
index 05b53cca..459a171e 100644
--- a/internal/proxy/sandbox_api_proxy.go
+++ b/internal/proxy/sandbox_api_proxy.go
@@ -123,6 +123,91 @@ func (p *SandboxAPIProxy) SetWaitForReady(fn func(ctx context.Context, sandboxID
p.waitForReady = fn
}
+// ResolvedRoute is the output of ResolveWorker: the worker's HTTP base
+// URL, its registered worker ID, and a fresh short-TTL sandbox JWT to
+// hand the worker on this request. Used by callers that need to do
+// their own transport (e.g. the WebSocket broker) but want the same
+// auth + routing logic as the proxy.
+type ResolvedRoute struct {
+ WorkerURL string
+ WorkerID string
+ Token string
+}
+
+// ResolveWorker performs the same lookup as ProxyHandler — waits for
+// async creation, rejects migrating, wakes hibernated, returns 404/410
+// equivalents — but instead of forwarding the request, returns the
+// resolved worker URL + token to the caller. Used by the WebSocket
+// broker (internal/wsgateway) which manages its own dialing.
+//
+// Errors are echo HTTP errors with the same status codes ProxyHandler
+// would return, so the caller can `return err` from a route handler and
+// get the right client-facing response.
+func (p *SandboxAPIProxy) ResolveWorker(c echo.Context, sandboxID string) (*ResolvedRoute, error) {
+ if sandboxID == "" {
+ return nil, echo.NewHTTPError(http.StatusBadRequest, "sandbox ID required")
+ }
+ ctx := c.Request().Context()
+
+ if workerURL, workerID, token, ok := p.routeCache.get(sandboxID); ok {
+ return &ResolvedRoute{WorkerURL: workerURL, WorkerID: workerID, Token: token}, nil
+ }
+
+ if p.waitForReady != nil {
+ if err := p.waitForReady(ctx, sandboxID); err != nil {
+ return nil, echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("sandbox %s: creation failed: %v", sandboxID, err))
+ }
+ }
+
+ session, err := p.store.GetSandboxSession(ctx, sandboxID)
+ if err != nil {
+ return nil, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("sandbox %s not found", sandboxID))
+ }
+ if session.Status == "migrating" {
+ return nil, echo.NewHTTPError(http.StatusServiceUnavailable, fmt.Sprintf("sandbox %s is migrating, retry shortly", sandboxID))
+ }
+ if session.Status == "hibernated" {
+ worker, workerURL, err := p.wakeHibernatedSandbox(ctx, sandboxID)
+ if err != nil {
+ return nil, echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("sandbox %s: failed to wake: %v", sandboxID, err))
+ }
+ token := p.mintToken(c, sandboxID, worker.ID)
+ p.routeCache.set(sandboxID, workerURL, worker.ID, token)
+ return &ResolvedRoute{WorkerURL: workerURL, WorkerID: worker.ID, Token: token}, nil
+ }
+ if session.Status == "stopped" || session.Status == "error" {
+ return nil, echo.NewHTTPError(http.StatusGone, fmt.Sprintf("sandbox %s has been stopped", sandboxID))
+ }
+
+ worker := p.registry.GetWorker(session.WorkerID)
+ if worker == nil {
+ // Worker disappeared. Same recover-from-hibernation path the proxy uses,
+ // but we don't have a request to forward here so just surface the error.
+ return nil, echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("worker %s unavailable", session.WorkerID))
+ }
+ if worker.HTTPAddr == "" {
+ return nil, echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("worker %s has no HTTP address", session.WorkerID))
+ }
+ token := p.mintToken(c, sandboxID, session.WorkerID)
+ p.routeCache.set(sandboxID, worker.HTTPAddr, session.WorkerID, token)
+ return &ResolvedRoute{WorkerURL: worker.HTTPAddr, WorkerID: session.WorkerID, Token: token}, nil
+}
+
+// mintToken issues the same 5-minute sandbox JWT the proxy's forward()
+// path uses. Returns empty string if no jwtIssuer is configured (legacy
+// dev mode) — workers then accept anonymous in dev.
+func (p *SandboxAPIProxy) mintToken(c echo.Context, sandboxID, workerID string) string {
+ if p.jwtIssuer == nil {
+ return ""
+ }
+ orgID, _ := auth.GetOrgID(c)
+ t, err := p.jwtIssuer.IssueSandboxToken(orgID, sandboxID, workerID, 5*time.Minute)
+ if err != nil {
+ return ""
+ }
+ return t
+}
+
// InvalidateRouteCache removes a sandbox from the proxy route cache.
// Call this on hibernate, kill, or any event that changes the sandbox→worker mapping.
func (p *SandboxAPIProxy) InvalidateRouteCache(sandboxID string) {
diff --git a/internal/wsgateway/config.go b/internal/wsgateway/config.go
new file mode 100644
index 00000000..5154bf80
--- /dev/null
+++ b/internal/wsgateway/config.go
@@ -0,0 +1,103 @@
+// Package wsgateway is the per-cell WebSocket broker that sits between
+// clients (SDK, dashboard) and workers for PTY/exec/agent sessions.
+//
+// Replaces the CloudFlare-DO implementation that lived in
+// cloudflare-workers/shared/sandbox_ws_gateway.ts on the websocket-edge
+// branch. Same behavioral spec — multi-session per sandbox, redial on
+// upstream close, exit-marker suppression, alarm-tick keepalive,
+// cap-token cache, flap circuit breaker — implemented as a Go subsystem
+// of the cell-CP (opensandbox-server) instead of a CF Durable Object.
+//
+// Why move out of CF: (1) the cell becomes self-hostable without depending
+// on Cloudflare DO infrastructure, (2) single implementation maintained
+// in one language, (3) the cell-CP orchestrates migration AND brokers WS
+// from the same process, so future work can switch the migration handoff
+// from reactive-redial to proactive-handoff via Go channels.
+//
+// Layering:
+//
+// Client ── WS ── CF Worker ── WS ── cell-CP broker ── WS ── Worker ── gRPC ── Agent (in-VM)
+// (auth, cap-mint, (this package: (handlers.go,
+// transparent fwd) redial, keepalive, RebindFromAgent,
+// exit marker, etc.) PTY/exec session
+// map cache, etc.)
+//
+// The broker terminates the client WS on its end and opens an independent
+// WS to the worker. If the worker WS dies (worker restart, migration
+// release, network blip) the broker doesn't kill the client; it redials
+// the worker and the client keeps its connection.
+package wsgateway
+
+import "time"
+
+// AlarmIntervalMS is the keepalive ticker period — empty binary frame on
+// every tick to both client and upstream WS, plus a sweep for idle
+// sandbox actors that no longer hold any sessions. 30s matches the
+// previous DO implementation and is well under CF Workers' ~100s
+// fetch-WS idle drop threshold.
+const AlarmInterval = 30 * time.Second
+
+// Default redial cadence on upstream close — exponential then steady at
+// 4s. Total budget ~25s before the redial loop gives up and closes the
+// client. Same ladder as the DO; chosen so transient worker restarts
+// (≤15s) and live migrations (≤2s) reliably succeed.
+var RedialBackoffMS = []time.Duration{
+ 250 * time.Millisecond,
+ 500 * time.Millisecond,
+ 1 * time.Second,
+ 2 * time.Second,
+ 4 * time.Second,
+ 4 * time.Second,
+ 4 * time.Second,
+ 4 * time.Second,
+ 4 * time.Second,
+ 4 * time.Second,
+}
+
+// Migration-aware cadence: cross-cell live migration can take 30s+ on
+// slow links. When the cell-CP-side dial returns 503 + body matches
+// /migrating/, the redial loop switches to this steadier 2s × 30 cadence
+// for the rest of the cycle.
+const (
+ MigrationBackoff = 2 * time.Second
+ MigrationMaxAttempts = 30
+)
+
+// Circuit breaker: a "redial cycle" is a single call to startRedial
+// regardless of how many internal dial attempts it triggers. After this
+// many cycles within REDIAL_FLAP_WINDOW the broker gives up and closes
+// the client with 1011 / "upstream flapping". Prevents an upstream that
+// keeps closing cleanly (e.g. a worker handler bug) from burning CF
+// Worker subrequests indefinitely.
+const (
+ RedialFlapThreshold = 3
+ RedialFlapWindow = 60 * time.Second
+)
+
+// Cap-token cache: edge mints 120s HS256 JWTs. The broker reuses one
+// across sessions in the same sandbox actor and across redials until it
+// has less than CapRefreshAhead of life left.
+const (
+ CapLifetime = 120 * time.Second
+ CapRefreshAhead = 30 * time.Second
+)
+
+// HandshakeTimeout bounds the worker WS dial. Worker side is in-cluster
+// (sub-millisecond RTT) so this only fires when the worker is actively
+// unhealthy or being restarted.
+const HandshakeTimeout = 10 * time.Second
+
+// WriteTimeout bounds individual WS writes — prevents a slow consumer
+// (client or upstream) from blocking the bridge goroutine indefinitely
+// while still allowing for transient buffer pressure.
+const WriteTimeout = 30 * time.Second
+
+// ExecExitMarkerLen / ExecExitMarkerTag — the agent emits a 5-byte
+// binary frame tagged 0x03 + 4-byte exit code immediately before closing
+// a completed exec session. The broker watches for it to distinguish
+// "session ended cleanly" (close client with 1000 / "exec completed")
+// from "transient upstream loss" (redial).
+const (
+ ExecExitMarkerLen = 5
+ ExecExitMarkerTag = 0x03
+)
diff --git a/internal/wsgateway/dial.go b/internal/wsgateway/dial.go
new file mode 100644
index 00000000..d7db909a
--- /dev/null
+++ b/internal/wsgateway/dial.go
@@ -0,0 +1,105 @@
+package wsgateway
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "regexp"
+ "strings"
+
+ "github.com/gorilla/websocket"
+)
+
+// ErrUpstreamMigrating is the sentinel the ResolveWorker closure (in
+// internal/api/ws_broker.go) returns wrapped via errors.Join when the
+// cell-CP reports the sandbox is mid-migration. The broker's runRedial
+// recognizes it and switches to the longer migration backoff cadence
+// instead of burning the fast-ladder budget on a guaranteed-to-fail dial.
+var ErrUpstreamMigrating = errors.New("upstream migrating")
+
+// DialResult classifies an upstream dial outcome so the redial loop can
+// pick the right backoff policy. Either Conn is non-nil (success), or
+// one of the Terminal/Migrating flags drives the loop's next action.
+type DialResult struct {
+ Conn *websocket.Conn
+ Resp *http.Response
+ Terminal bool // 404 or 410 — resource gone permanently, close client with reason
+ Migrating bool // 503 + body matches /migrating/ — switch to long backoff
+ Status int // last response status (0 if dial threw before headers)
+ BodySnippet string // first 200 bytes of error body if any, for logging
+ Err error // the underlying error from gorilla/websocket
+}
+
+var migratingPattern = regexp.MustCompile(`(?i)migrating`)
+
+// DialUpstream attempts a single WebSocket upgrade against workerWSURL,
+// passing the bearer token as Authorization. Returns a DialResult the
+// caller uses to decide whether to retry, swap to migration backoff, or
+// give up with a terminal close.
+func DialUpstream(workerWSURL, token string) DialResult {
+ header := http.Header{}
+ if token != "" {
+ header.Set("Authorization", "Bearer "+token)
+ }
+ dialer := websocket.Dialer{
+ HandshakeTimeout: HandshakeTimeout,
+ }
+ conn, resp, err := dialer.Dial(workerWSURL, header)
+ if err == nil {
+ return DialResult{Conn: conn, Resp: resp}
+ }
+ status := 0
+ body := ""
+ if resp != nil {
+ status = resp.StatusCode
+ body = snippet(resp.Body)
+ }
+ terminal := status == http.StatusNotFound || status == http.StatusGone
+ migrating := status == http.StatusServiceUnavailable && migratingPattern.MatchString(body)
+ return DialResult{
+ Resp: resp,
+ Terminal: terminal,
+ Migrating: migrating,
+ Status: status,
+ BodySnippet: body,
+ Err: err,
+ }
+}
+
+// Note returns a compact one-line description of the dial outcome for
+// logging — chosen to mirror the DO's "status=X body=Y" format.
+func (r DialResult) Note() string {
+ if r.Conn != nil {
+ return "ok"
+ }
+ parts := []string{fmt.Sprintf("status=%d", r.Status)}
+ if r.BodySnippet != "" {
+ parts = append(parts, "body="+r.BodySnippet)
+ }
+ if r.Err != nil && !errors.Is(r.Err, websocket.ErrBadHandshake) {
+ parts = append(parts, "err="+r.Err.Error())
+ }
+ if r.Terminal {
+ parts = append(parts, "(terminal)")
+ }
+ if r.Migrating {
+ parts = append(parts, "(migrating)")
+ }
+ return strings.Join(parts, " ")
+}
+
+// snippet drains up to 200 bytes from r and returns it as a string for
+// log/error-body use. Closes the body before returning.
+func snippet(r io.ReadCloser) string {
+ if r == nil {
+ return ""
+ }
+ defer r.Close()
+ buf := make([]byte, 200)
+ n, _ := io.ReadFull(r, buf)
+ if n == 0 {
+ return ""
+ }
+ return strings.TrimSpace(string(buf[:n]))
+}
diff --git a/internal/wsgateway/gateway.go b/internal/wsgateway/gateway.go
new file mode 100644
index 00000000..e85e7430
--- /dev/null
+++ b/internal/wsgateway/gateway.go
@@ -0,0 +1,234 @@
+package wsgateway
+
+import (
+ "log"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/gorilla/websocket"
+)
+
+// Gateway is the per-cell broker. One instance per cell-CP process,
+// holding a map of sandboxID → sandboxActor. The cell-CP's WS route
+// handlers (handlers added in Phase 2) call Gateway.Serve with the
+// upgraded client conn and a function that resolves the worker WS URL
+// + sandbox JWT.
+//
+// Routing model: each sandbox gets at most one sandboxActor. Multiple
+// concurrent WS upgrades to the same sandbox (dashboard + SDK, two
+// dashboard tabs, etc.) all share that actor and run as independent
+// sessions inside it. The actor owns a keepalive ticker that fires
+// across all its sessions every AlarmInterval, and a cap-token cache
+// shared across them.
+//
+// Lifecycle:
+// - First Serve for a sandbox creates the actor.
+// - Subsequent Serves attach new Sessions to the existing actor.
+// - When the last session closes, the actor's keepalive loop notices
+// during its next tick, signals shutdown, and the Gateway drops the
+// map entry. Idempotent and tolerant of races.
+type Gateway struct {
+ mu sync.Mutex
+ sandboxes map[string]*sandboxActor
+}
+
+// NewGateway constructs an empty Gateway ready to accept Serve calls.
+func NewGateway() *Gateway {
+ return &Gateway{
+ sandboxes: make(map[string]*sandboxActor),
+ }
+}
+
+// ServeOpts is everything the broker needs to bridge one client WS to
+// the worker. All fields are required.
+type ServeOpts struct {
+ SandboxID string
+ SessionID string
+ CellPath string // e.g. "/api/sandboxes/sb-xxx/pty/yyy" — purely for logging + isExec detection
+
+ // ResolveWorker returns the worker WS URL plus the per-request
+ // sandbox JWT the worker expects in the Authorization header. Called
+ // once on initial dial and again on each redial — so a worker change
+ // (post-migration) is picked up automatically.
+ ResolveWorker func() (workerWSURL string, sandboxToken string, err error)
+}
+
+// Serve upgrades the request to a WebSocket, then runs the broker
+// session against the worker. Returns nil on a clean handoff; non-nil
+// error before the upgrade can be returned to the caller for a normal
+// HTTP error response. Once the upgrade succeeds, all further error
+// reporting happens via WS close frames — Serve returns nil and the
+// caller's HTTP path is done.
+func (g *Gateway) Serve(w http.ResponseWriter, r *http.Request, upgrader *websocket.Upgrader, opts ServeOpts) error {
+ if opts.SandboxID == "" || opts.SessionID == "" || opts.ResolveWorker == nil {
+ return errEmpty("missing required ServeOpts")
+ }
+
+ clientWS, err := upgrader.Upgrade(w, r, nil)
+ if err != nil {
+ // Upgrade already wrote a response.
+ return nil
+ }
+
+ actor := g.getOrCreateActor(opts.SandboxID)
+ sess := &Session{
+ actor: actor,
+ sandboxID: opts.SandboxID,
+ sessionID: opts.SessionID,
+ cellPath: opts.CellPath,
+ isExec: strings.Contains(opts.CellPath, "/exec/") || strings.Contains(opts.CellPath, "/agent/"),
+ clientWS: clientWS,
+ workerWSURLFn: opts.ResolveWorker,
+ done: make(chan struct{}),
+ }
+ actor.addSession(sess)
+ // Run synchronously so the Echo Context the route handler captured —
+ // closures like ResolveWorker that call back into c.Request().Context()
+ // + auth.GetOrgID(c) need it — stays valid until the session ends.
+ // Echo pools Contexts and recycles them once the handler returns; if
+ // we spawned Run() in a goroutine and returned, those closures would
+ // see torn-down/reused state on the next call (404 spam from store
+ // lookups using a stale Context).
+ sess.Run()
+ return nil
+}
+
+// SessionCount returns the total number of live sessions across all
+// sandbox actors. Used by tests + admin endpoints; cheap O(N) over
+// actors, not hot-path.
+func (g *Gateway) SessionCount() int {
+ g.mu.Lock()
+ actors := make([]*sandboxActor, 0, len(g.sandboxes))
+ for _, a := range g.sandboxes {
+ actors = append(actors, a)
+ }
+ g.mu.Unlock()
+ total := 0
+ for _, a := range actors {
+ a.mu.Lock()
+ total += len(a.sessions)
+ a.mu.Unlock()
+ }
+ return total
+}
+
+// getOrCreateActor returns the actor for sandboxID, creating + starting
+// its keepalive ticker if absent.
+func (g *Gateway) getOrCreateActor(sandboxID string) *sandboxActor {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ if a, ok := g.sandboxes[sandboxID]; ok {
+ return a
+ }
+ a := &sandboxActor{
+ sandboxID: sandboxID,
+ gw: g,
+ sessions: make(map[*Session]struct{}),
+ stop: make(chan struct{}),
+ }
+ g.sandboxes[sandboxID] = a
+ go a.runKeepalive()
+ return a
+}
+
+// removeActor drops the actor from the map. Called by the actor itself
+// when it observes "no more sessions" during a keepalive tick.
+func (g *Gateway) removeActor(a *sandboxActor) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ // Guard against races: another Serve might have attached a session
+ // to this actor between the actor's empty-check and removeActor.
+ a.mu.Lock()
+ live := len(a.sessions)
+ a.mu.Unlock()
+ if live > 0 {
+ return
+ }
+ if g.sandboxes[a.sandboxID] == a {
+ delete(g.sandboxes, a.sandboxID)
+ close(a.stop)
+ }
+}
+
+// sandboxActor holds the per-sandbox state shared across concurrent
+// Sessions: the set of live sessions, the cap-token cache (for future
+// re-mint paths), and a keepalive ticker goroutine.
+type sandboxActor struct {
+ sandboxID string
+ gw *Gateway
+
+ mu sync.Mutex
+ sessions map[*Session]struct{}
+
+ capCacheMu sync.Mutex
+ capCache *capCacheEntry
+
+ stop chan struct{} // closed by gateway.removeActor
+}
+
+func (a *sandboxActor) addSession(s *Session) {
+ a.mu.Lock()
+ a.sessions[s] = struct{}{}
+ count := len(a.sessions)
+ a.mu.Unlock()
+ log.Printf("wsgateway: attached session sandbox=%s session=%s active=%d", a.sandboxID, s.sessionID, count)
+}
+
+func (a *sandboxActor) removeSession(s *Session) {
+ a.mu.Lock()
+ delete(a.sessions, s)
+ count := len(a.sessions)
+ a.mu.Unlock()
+ log.Printf("wsgateway: detached session sandbox=%s session=%s active=%d", a.sandboxID, s.sessionID, count)
+}
+
+// runKeepalive fires every AlarmInterval. Sends an empty frame on every
+// session's client+upstream conn, then checks for "no sessions left → ask
+// gateway to drop me." Exits when the gateway closes a.stop.
+func (a *sandboxActor) runKeepalive() {
+ t := time.NewTicker(AlarmInterval)
+ defer t.Stop()
+ for {
+ select {
+ case <-t.C:
+ a.mu.Lock()
+ alive := make([]*Session, 0, len(a.sessions))
+ for s := range a.sessions {
+ alive = append(alive, s)
+ }
+ a.mu.Unlock()
+ if len(alive) == 0 {
+ log.Printf("wsgateway: alarm sandbox=%s — idle, releasing", a.sandboxID)
+ a.gw.removeActor(a)
+ return
+ }
+ for _, s := range alive {
+ s.Keepalive()
+ }
+ log.Printf("wsgateway: alarm sandbox=%s sessions=%d", a.sandboxID, len(alive))
+ case <-a.stop:
+ return
+ }
+ }
+}
+
+// capCacheEntry mirrors the DO's v5 cap-token cache. The cell-CP doesn't
+// currently mint cap-tokens — the edge does that before forwarding — so
+// this cache is reserved for future use (e.g. if the broker grows the
+// ability to mint a fresh token on redial when the edge-provided one has
+// expired). Kept here as the actor's home for shared cross-session state.
+type capCacheEntry struct {
+ Token string
+ MintedAt time.Time
+ OrgID string
+ CellID string
+ Plan string
+}
+
+// errEmpty is the canonical pre-upgrade error so callers don't have to
+// import "errors".
+type errEmpty string
+
+func (e errEmpty) Error() string { return string(e) }
diff --git a/internal/wsgateway/session.go b/internal/wsgateway/session.go
new file mode 100644
index 00000000..5ec0b83f
--- /dev/null
+++ b/internal/wsgateway/session.go
@@ -0,0 +1,402 @@
+package wsgateway
+
+import (
+ "errors"
+ "log"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/gorilla/websocket"
+)
+
+// Session owns one client WebSocket and brokers it against the upstream
+// worker WS. The upstream conn changes across redials; the client conn
+// is fixed for the session's lifetime. All writes to either conn are
+// serialized via clientMu/upstreamMu — gorilla/websocket connections
+// are not goroutine-safe for concurrent writes.
+//
+// The Run() method is the per-session goroutine entry point. It handles
+// initial dial, starts upstream + client read pumps, drives the redial
+// loop on upstream close, and cleans up.
+type Session struct {
+ actor *sandboxActor
+ sandboxID string
+ sessionID string
+ cellPath string
+
+ // isExec drives v6 exit-marker tracking. Set once from the path —
+ // /exec/ or /agent/ → true; /pty/ → false.
+ isExec bool
+
+ clientWS *websocket.Conn
+ clientMu sync.Mutex // serializes writes to clientWS
+
+ upstreamMu sync.RWMutex
+ upstreamWS *websocket.Conn
+
+ // workerWSURL is the cell-CP→worker URL. Recomputed on each redial
+ // from the worker registry so a worker_id change (mid-flight migration
+ // that completed) routes correctly.
+ workerWSURLFn func() (string, string, error) // returns (url, token, error)
+
+ // v6 exec-exit marker. Set when a 5-byte 0x03+exitCode frame arrives
+ // from upstream. On the next upstream close, the broker closes the
+ // client cleanly instead of redialing.
+ execExited atomic.Bool
+
+ // Circuit breaker — bounded slice of recent startRedial timestamps.
+ flapMu sync.Mutex
+ redialTimes []time.Time
+
+ closeOnce sync.Once
+ done chan struct{}
+}
+
+// Run is the per-session goroutine entry. Blocks until the session
+// terminates. Caller is the sandbox actor; it removes the session
+// from its map after Run returns.
+func (s *Session) Run() {
+ defer s.close()
+
+ // Initial dial.
+ url, token, err := s.workerWSURLFn()
+ if err != nil {
+ log.Printf("wsgateway: initial url resolve failed sandbox=%s session=%s: %v", s.sandboxID, s.sessionID, err)
+ s.closeClient(websocket.CloseInternalServerErr, "upstream resolve failed")
+ return
+ }
+ dial := DialUpstream(url, token)
+ if dial.Conn == nil {
+ log.Printf("wsgateway: initial dial failed sandbox=%s session=%s %s", s.sandboxID, s.sessionID, dial.Note())
+ if dial.Terminal {
+ s.closeClient(websocket.CloseNormalClosure, terminalReason(dial))
+ } else {
+ s.closeClient(websocket.CloseInternalServerErr, "upstream connect failed")
+ }
+ return
+ }
+ s.setUpstream(dial.Conn)
+
+ log.Printf("wsgateway: opened sandbox=%s session=%s path=%s", s.sandboxID, s.sessionID, s.cellPath)
+
+ // Start client reader (reads from client, writes to current upstream).
+ clientDone := make(chan struct{})
+ go s.pumpClientToUpstream(clientDone)
+
+ // Start upstream reader. Loop here so a redial can restart it with a
+ // new upstream while the same client conn stays attached.
+ upstreamDone := make(chan struct{})
+ go s.pumpUpstreamToClient(dial.Conn, upstreamDone)
+
+ for {
+ select {
+ case <-clientDone:
+ // Client went away; tear down upstream and exit.
+ s.upstreamClose(websocket.CloseNormalClosure, "client closed")
+ return
+
+ case <-upstreamDone:
+ // Upstream closed. If exec exited, that's the natural end.
+ if s.execExited.Load() {
+ log.Printf("wsgateway: exec exited — closing client sandbox=%s session=%s", s.sandboxID, s.sessionID)
+ s.closeClient(websocket.CloseNormalClosure, "exec completed")
+ return
+ }
+ // Circuit breaker — too many flaps in the window.
+ if !s.recordRedial() {
+ log.Printf("wsgateway: redial flap threshold hit sandbox=%s session=%s — closing client", s.sandboxID, s.sessionID)
+ s.closeClient(websocket.CloseInternalServerErr, "upstream flapping")
+ return
+ }
+ // Drive the redial loop. New upstream conn replaces the old;
+ // kick off a new pump goroutine. Pass clientDone so the loop
+ // bails immediately if the client disconnects mid-backoff
+ // instead of wasting the full ~25s window.
+ newUp, terminal, reason, ok := s.runRedial(clientDone)
+ if !ok {
+ log.Printf("wsgateway: redial exhausted sandbox=%s session=%s", s.sandboxID, s.sessionID)
+ if terminal {
+ s.closeClient(websocket.CloseNormalClosure, reason)
+ } else {
+ s.closeClient(websocket.CloseInternalServerErr, "upstream unrecoverable")
+ }
+ return
+ }
+ s.setUpstream(newUp)
+ upstreamDone = make(chan struct{})
+ go s.pumpUpstreamToClient(newUp, upstreamDone)
+
+ case <-s.done:
+ return
+ }
+ }
+}
+
+// pumpClientToUpstream reads frames from the client WS and writes them
+// to whichever upstream is currently bound on the session. Exits when
+// the client closes or errors; signals via done.
+//
+// Frames sent during a redial window (upstream temporarily nil or
+// closed) are dropped silently — matches the DO's behavior. Bidirectional
+// buffering of client→upstream is a deliberate non-goal here (the
+// session would have to choose how much to buffer; SDK retries handle it).
+func (s *Session) pumpClientToUpstream(done chan struct{}) {
+ defer close(done)
+ for {
+ mt, data, err := s.clientWS.ReadMessage()
+ if err != nil {
+ return
+ }
+ s.upstreamMu.RLock()
+ u := s.upstreamWS
+ s.upstreamMu.RUnlock()
+ if u == nil {
+ continue // drop during redial window
+ }
+ if err := writeOne(u, &s.upstreamMu, mt, data); err != nil {
+ // Don't return — upstream might come back via redial. The
+ // upstream reader will detect the close and trigger redial.
+ continue
+ }
+ }
+}
+
+// pumpUpstreamToClient reads from the specific upstream conn passed in
+// (does NOT swap on redial — a fresh goroutine is started for each new
+// upstream by the session main loop). Forwards every frame to the
+// client. Watches for the exec exit marker.
+func (s *Session) pumpUpstreamToClient(upstream *websocket.Conn, done chan struct{}) {
+ defer close(done)
+ for {
+ mt, data, err := upstream.ReadMessage()
+ if err != nil {
+ return
+ }
+ // v6 exec-exit detection. 5-byte binary frame, leading 0x03.
+ if s.isExec && mt == websocket.BinaryMessage && len(data) == ExecExitMarkerLen && data[0] == ExecExitMarkerTag {
+ s.execExited.Store(true)
+ }
+ if err := writeOne(s.clientWS, &s.clientMu, mt, data); err != nil {
+ return
+ }
+ }
+}
+
+// runRedial walks the backoff ladder, dialing the upstream each tick.
+// Returns (conn, terminal, reason, ok). On terminal failure (sandbox
+// stopped, 404/410), terminal=true and reason carries the close message;
+// ok=false. On success, ok=true and conn is the new upstream. On
+// exhausted attempts or client disconnect during backoff, ok=false and
+// terminal=false.
+//
+// Switches to migration cadence on first 503/migrating.
+//
+// clientDone is the channel pumpClientToUpstream closes when the client
+// disconnects — selected on during each backoff sleep so we don't spend
+// 25s+ in a dead loop when the user already hung up.
+func (s *Session) runRedial(clientDone <-chan struct{}) (*websocket.Conn, bool, string, bool) {
+ log.Printf("wsgateway: redial start sandbox=%s session=%s", s.sandboxID, s.sessionID)
+
+ inMigration := false
+ attempt := 0
+ for {
+ var delay time.Duration
+ var limit int
+ if inMigration {
+ delay = MigrationBackoff
+ limit = MigrationMaxAttempts
+ } else {
+ if attempt >= len(RedialBackoffMS) {
+ return nil, false, "", false
+ }
+ delay = RedialBackoffMS[attempt]
+ limit = len(RedialBackoffMS)
+ }
+ if attempt >= limit {
+ return nil, false, "", false
+ }
+
+ select {
+ case <-time.After(delay):
+ case <-clientDone:
+ log.Printf("wsgateway: redial: client gone during backoff sandbox=%s session=%s", s.sandboxID, s.sessionID)
+ return nil, false, "", false
+ case <-s.done:
+ return nil, false, "", false
+ }
+
+ url, token, err := s.workerWSURLFn()
+ if err != nil {
+ log.Printf("wsgateway: redial: url resolve failed sandbox=%s session=%s: %v", s.sandboxID, s.sessionID, err)
+ // Cell-CP signaling "currently migrating" → switch to the
+ // longer cadence (no point burning fast-ladder attempts at a
+ // resolve that's deterministically going to fail until the
+ // migration commits).
+ if errors.Is(err, ErrUpstreamMigrating) && !inMigration {
+ log.Printf("wsgateway: redial: cell reports migrating (resolve) — switching to migration backoff sandbox=%s", s.sandboxID)
+ inMigration = true
+ attempt = 0
+ continue
+ }
+ attempt++
+ continue
+ }
+
+ log.Printf("wsgateway: redial: attempt %d/%d sandbox=%s session=%s → %s%s",
+ attempt+1, limit, s.sandboxID, s.sessionID, url,
+ func() string {
+ if inMigration {
+ return " (migrating)"
+ }
+ return ""
+ }())
+
+ dial := DialUpstream(url, token)
+ if dial.Conn != nil {
+ log.Printf("wsgateway: redial: success on attempt %d sandbox=%s session=%s", attempt+1, s.sandboxID, s.sessionID)
+ return dial.Conn, false, "", true
+ }
+ log.Printf("wsgateway: redial: attempt %d failed — %s", attempt+1, dial.Note())
+ if dial.Terminal {
+ return nil, true, terminalReason(dial), false
+ }
+ if dial.Migrating && !inMigration {
+ log.Printf("wsgateway: redial: switching to migration backoff sandbox=%s session=%s", s.sandboxID, s.sessionID)
+ inMigration = true
+ attempt = 0
+ continue
+ }
+ attempt++
+ }
+}
+
+// recordRedial appends the current time to the recent-cycles slice and
+// returns true if we're still under the flap threshold within the
+// window. Returns false when threshold is reached → caller closes client.
+func (s *Session) recordRedial() bool {
+ s.flapMu.Lock()
+ defer s.flapMu.Unlock()
+ now := time.Now()
+ cutoff := now.Add(-RedialFlapWindow)
+ pruned := s.redialTimes[:0]
+ for _, t := range s.redialTimes {
+ if t.After(cutoff) {
+ pruned = append(pruned, t)
+ }
+ }
+ s.redialTimes = pruned
+ if len(s.redialTimes) >= RedialFlapThreshold {
+ return false
+ }
+ s.redialTimes = append(s.redialTimes, now)
+ return true
+}
+
+// Keepalive sends an empty binary frame on both ends. Called by the
+// sandbox actor's ticker every AlarmInterval. Empty frames are no-ops
+// on every receiver — see the file header in the worker handlers and
+// the agent for proof. Defends middleboxes against idle drop.
+func (s *Session) Keepalive() {
+ s.upstreamMu.RLock()
+ u := s.upstreamWS
+ s.upstreamMu.RUnlock()
+ if u != nil {
+ _ = writeOne(u, &s.upstreamMu, websocket.BinaryMessage, nil)
+ }
+ _ = writeOne(s.clientWS, &s.clientMu, websocket.BinaryMessage, nil)
+}
+
+// setUpstream swaps the bound upstream conn atomically. Old conn is NOT
+// closed here — caller decides whether the old conn is already closed
+// (the usual case after redial) or needs a goodbye frame (rare).
+func (s *Session) setUpstream(c *websocket.Conn) {
+ s.upstreamMu.Lock()
+ s.upstreamWS = c
+ s.upstreamMu.Unlock()
+}
+
+// closeClient sends a close frame to the client and tears down the
+// session. Idempotent.
+func (s *Session) closeClient(code int, reason string) {
+ s.clientMu.Lock()
+ _ = s.clientWS.WriteControl(
+ websocket.CloseMessage,
+ websocket.FormatCloseMessage(code, reason),
+ time.Now().Add(time.Second),
+ )
+ s.clientMu.Unlock()
+ _ = s.clientWS.Close()
+}
+
+// upstreamClose tears down the current upstream conn (used when the
+// client disconnects so the worker also sees an upstream close).
+func (s *Session) upstreamClose(code int, reason string) {
+ s.upstreamMu.Lock()
+ u := s.upstreamWS
+ s.upstreamWS = nil
+ s.upstreamMu.Unlock()
+ if u == nil {
+ return
+ }
+ _ = u.WriteControl(
+ websocket.CloseMessage,
+ websocket.FormatCloseMessage(code, reason),
+ time.Now().Add(time.Second),
+ )
+ _ = u.Close()
+}
+
+// close is the session's terminal cleanup. Closes both conns, signals
+// done, and notifies the actor so it can drop the entry.
+func (s *Session) close() {
+ s.closeOnce.Do(func() {
+ close(s.done)
+ _ = s.clientWS.Close()
+ s.upstreamMu.Lock()
+ u := s.upstreamWS
+ s.upstreamWS = nil
+ s.upstreamMu.Unlock()
+ if u != nil {
+ _ = u.Close()
+ }
+ s.actor.removeSession(s)
+ })
+}
+
+// writeOne sends a single WS message holding the given lock, with a
+// bounded deadline. Returns error on write failure or closed conn so
+// the caller can decide whether to drop, retry, or tear down. Accepts
+// sync.Locker so callers can pass either a *sync.Mutex (clientMu) or
+// the write half of a *sync.RWMutex (upstreamMu).
+func writeOne(c *websocket.Conn, mu sync.Locker, mt int, data []byte) error {
+ mu.Lock()
+ defer mu.Unlock()
+ _ = c.SetWriteDeadline(time.Now().Add(WriteTimeout))
+ return c.WriteMessage(mt, data)
+}
+
+// terminalReason maps a terminal-status DialResult into the close
+// reason string sent to the client. Mirrors the DO's wording so
+// clients that pattern-match on the reason continue to work.
+func terminalReason(dial DialResult) string {
+ if strings.Contains(strings.ToLower(dial.BodySnippet), "stopped") {
+ return "sandbox stopped"
+ }
+ if dial.Status == 0 {
+ return "cell gone"
+ }
+ return "cell " + httpStatusText(dial.Status)
+}
+
+func httpStatusText(s int) string {
+ switch s {
+ case 404:
+ return "404"
+ case 410:
+ return "410"
+ default:
+ return "unavailable"
+ }
+}