Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(cloud): let go of dead connections without keeping the relay awake

leepokai20c6e0b29231
diff --git a/cloud/src/relay.ts b/cloud/src/relay.ts
index 60a2e8b1..50b0efde 100644
--- a/cloud/src/relay.ts
+++ b/cloud/src/relay.ts
@@ -44,6 +44,7 @@ interface HostAttachment {
kid: string;
ready: boolean;
at: number;
+ retired?: Retired;
}
interface DeviceAttachment {
role: "device";
@@ -53,8 +54,15 @@ interface DeviceAttachment {
offer?: string;
at: number;
msgs: number;
+ retired?: Retired;
}
type Attachment = HostAttachment | DeviceAttachment;
+/** A socket the DO let go of: nothing is sent to it, and it's closed with `code` once that's free (§7.6). */
+interface Retired {
+ at: number;
+ code: number;
+ reason: string;
+}
export interface Acl {
v: 1;
@@ -108,6 +116,8 @@ export class ComputerRelay extends DurableObject<Env> {
private readonly sql: SqlStorage;
/** Per-link rate windows (device → DO only). Lost on hibernation, which is acceptable (§7.6). */
private readonly rates = new Map<string, { start: number; msgs: number; bytes: number }>();
+ /** Sockets this instance retired. Hibernation drops it, so a socket still in it later means the DO never slept. */
+ private readonly retiredHere = new WeakSet<WebSocket>();
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
@@ -168,14 +178,10 @@ export class ComputerRelay extends DurableObject<Env> {
return errorResponse(403, "forbidden");
}
// A new host connection replaces the old one (§7.2).
- let wasOnline = false;
for (const old of this.ctx.getWebSockets("host")) {
const a = old.deserializeAttachment() as HostAttachment;
- wasOnline ||= a.ready;
- old.serializeAttachment({ ...a, ready: false });
- this.safeClose(old, 4009, "replaced");
+ if (!a.retired) await this.retire(old, a, now, 4009, "replaced");
}
- if (wasOnline) await this.hostOffline(now);
const { 0: client, 1: server } = new WebSocketPair();
this.ctx.acceptWebSocket(server, ["host"]);
server.serializeAttachment({ role: "host", kid, ready: false, at: now } satisfies HostAttachment);
@@ -341,6 +347,8 @@ export class ComputerRelay extends DurableObject<Env> {
override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
const a = ws.deserializeAttachment() as Attachment;
+ // It's alive after all, so closing it is quick.
+ if (a.retired) return this.safeClose(ws, a.retired.code, a.retired.reason);
if (typeof message !== "string") return this.safeClose(ws, 4002, "protocolError");
let msg: Msg;
try {
@@ -568,10 +576,22 @@ export class ComputerRelay extends DurableObject<Env> {
private async closed(ws: WebSocket): Promise<void> {
const a = ws.deserializeAttachment() as Attachment;
this.safeClose(ws, 1000, "");
- await this.gone(ws, a, Date.now());
+ if (!a.retired) await this.gone(ws, a, Date.now());
+ }
+
+ /**
+ * Lets go of a socket: nothing is sent to it any more and the bookkeeping runs now. It isn't closed yet: closing
+ * a peer that's unreachable keeps the DO awake (billed) until TCP gives up, while a socket left alone doesn't.
+ * The alarm closes it later if it speaks again, or if the DO never got to sleep (data queued for it may be
+ * what keeps it awake, and only closing frees that).
+ */
+ private async retire(ws: WebSocket, a: Attachment, now: number, code: number, reason: string): Promise<void> {
+ ws.serializeAttachment({ ...a, ...(a.role === "host" ? { ready: false } : {}), retired: { at: now, code, reason } });
+ this.retiredHere.add(ws);
+ await this.gone(ws, a, now);
}
- /** Bookkeeping for a socket that closed or that the DO is closing. */
+ /** Bookkeeping for a socket that closed or that the DO let go of. */
private async gone(ws: WebSocket, a: Attachment, now: number): Promise<void> {
if (a.role === "host") {
if (a.ready) await this.hostOffline(now, ws);
@@ -583,15 +603,16 @@ export class ComputerRelay extends DurableObject<Env> {
override async alarm(): Promise<void> {
const now = Date.now();
- // Silent sockets close, device ones too: what the DO sends a peer that stopped reading stays queued,
- // and the queue keeps the DO awake (billed as duration) until the connection finally dies, often hours.
+ // Silent sockets, device ones too, are retired: whatever the DO sends a peer that stopped reading stays
+ // queued and keeps the DO awake (billed as duration) until the connection dies, often hours later.
for (const ws of this.ctx.getWebSockets()) {
const a = ws.deserializeAttachment() as Attachment;
- const last = Math.max(a.at, this.ctx.getWebSocketAutoResponseTimestamp(ws)?.getTime() ?? 0);
- if (now - last <= SILENT_TIMEOUT_MS) continue;
- if (a.role === "host") ws.serializeAttachment({ ...a, ready: false });
- this.safeClose(ws, 1011, "timeout");
- await this.gone(ws, a, now);
+ const heard = Math.max(a.at, this.ctx.getWebSocketAutoResponseTimestamp(ws)?.getTime() ?? 0);
+ if (a.retired) {
+ if (heard > a.retired.at || this.retiredHere.has(ws)) this.safeClose(ws, a.retired.code, a.retired.reason);
+ } else if (now - heard > SILENT_TIMEOUT_MS) {
+ await this.retire(ws, a, now, 1011, "timeout");
+ }
}
for (const row of this.sql
.exec<{ dk: string; nonce: string }>("SELECT dk, nonce FROM mailbox WHERE exp <= ?", now)
@@ -666,7 +687,10 @@ export class ComputerRelay extends DurableObject<Env> {
}
private devices(): [WebSocket, DeviceAttachment][] {
- return this.ctx.getWebSockets("device").map((ws) => [ws, ws.deserializeAttachment() as DeviceAttachment]);
+ return this.ctx
+ .getWebSockets("device")
+ .map((ws): [WebSocket, DeviceAttachment] => [ws, ws.deserializeAttachment() as DeviceAttachment])
+ .filter(([, a]) => !a.retired);
}
private deviceByLink(link: unknown): WebSocket | undefined {
@@ -680,7 +704,7 @@ export class ComputerRelay extends DurableObject<Env> {
private toHosts(msg: object): void {
const text = JSON.stringify(msg);
- for (const ws of this.ctx.getWebSockets("host")) send(ws, text);
+ for (const ws of this.ctx.getWebSockets("host")) if (!(ws.deserializeAttachment() as HostAttachment).retired) send(ws, text);
}
private acl(): Acl | null {
diff --git a/cloud/test/relay.test.ts b/cloud/test/relay.test.ts
index 8b1ec294..8c0da870 100644
--- a/cloud/test/relay.test.ts
+++ b/cloud/test/relay.test.ts
@@ -201,12 +201,13 @@ describe("presence and forwarding", () => {
expect(await hostWs.nextT("pong")).toEqual({ t: "pong" });
});
- it("a new host socket replaces the old: 4009, then offline → online", async () => {
+ it("a new host socket replaces the old: offline → online, 4009 once the old one speaks", async () => {
const { host, device, hostWs, dev } = await pair();
expect(await dev.nextT("presence")).toMatchObject({ online: true });
const next = await socket("/v1/relay/host?v=1", host.sign);
- expect(await hostWs.closed()).toBe(4009);
expect(await dev.nextT("presence")).toMatchObject({ online: false });
+ hostWs.send({ t: "ready" });
+ expect(await hostWs.closed()).toBe(4009);
next.send(acl(host, [{ dk: dkOf(device), grant: null }]));
await next.nextT("acl.ok");
next.send({ t: "ready" });
@@ -227,22 +228,41 @@ describe("presence and forwarding", () => {
const again = await hostSocket(host, [{ dk: dkOf(ref.signKey()), grant: null }]);
expect(await dev.closed()).toBe(4003); // not in the new ACL
- // Silent for > 90 s: the alarm closes it with 1011.
+ // Silent for > 90 s: offline at the next alarm, closed with 1011 by a later one the DO stayed awake for.
await runInDurableObject(stub(host), (_, state) => {
for (const ws of state.getWebSockets("host")) ws.serializeAttachment({ ...ws.deserializeAttachment(), at: Date.now() - 91_000 });
});
+ await env.DB.prepare("UPDATE computers SET online = 1 WHERE id = ?").bind(host.cid).run();
+ await runDurableObjectAlarm(stub(host));
+ const after = await env.DB.prepare("SELECT online FROM computers WHERE id = ?").bind(host.cid).first<{ online: number }>();
+ expect(after?.online).toBe(0);
await runDurableObjectAlarm(stub(host));
expect(await again.closed()).toBe(1011);
});
- it("closes a silent device socket and tells the host its link is gone", async () => {
+ it("retires a silent device socket: the host's link closes, the socket once it speaks", async () => {
const { host, hostWs, dev } = await pair();
await dev.nextT("presence");
const { link } = await hostWs.nextT("open");
await ageDevices(host);
await runDurableObjectAlarm(stub(host));
- expect(await dev.closed()).toBe(1011);
expect(await hostWs.nextT("close")).toMatchObject({ link });
+ // Retired: left out of presence, and closed when it shows it's alive.
+ hostWs.ws.close(1000, "bye");
+ await dev.none((m) => m.t === "presence");
+ dev.send({ t: "mbox.list" });
+ expect(await dev.closed()).toBe(1011);
+ });
+
+ it("closes a retired device socket when the DO never got to sleep", async () => {
+ const { host, hostWs, dev } = await pair();
+ await dev.nextT("presence");
+ await hostWs.nextT("open");
+ await ageDevices(host);
+ await runDurableObjectAlarm(stub(host));
+ await hostWs.nextT("close");
+ await runDurableObjectAlarm(stub(host));
+ expect(await dev.closed()).toBe(1011);
});
it("keeps a device socket that pings", async () => {
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index 08f48c05..6972d022 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -358,7 +358,7 @@ Device 准入(DO):
- `ws.serializeAttachment`:host `{role:"host", kid, ready: boolean}`;device `{role:"device", dk, link, pair: boolean, offer?: string}`。
- **「host 在線」的唯一定義**:存在一條 host socket 且其 attachment `ready == true`。presence、mailbox 接受與否(§7.7)、`data` 轉送全部用這一個定義。
- `ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair('{"t":"ping"}', '{"t":"pong"}'))`:client 必須送**完全相同**的字串 `{"t":"ping"}`。
-- 新的 host 連線到來時,舊 host socket 以 `4009 replaced` 關閉;所有 device socket 收到 `presence online:false`(新 host socket 的 `ready` 之後再送 `online:true`)。
+- 新的 host 連線到來時,舊 host socket 立即退役(見 §7.6),之後以 `4009 replaced` 關閉;所有 device socket 收到 `presence online:false`(新 host socket 的 `ready` 之後再送 `online:true`)。
- host 端:relay socket 每次重新連線,都丟棄全部 link 狀態(channel、訂閱、進行中的 request)。
- device 端:每次收到 `presence online:true` 都丟棄舊 channel 金鑰、重新送 `hello`。
@@ -424,7 +424,7 @@ Channel 訊息與 DO 訊息的 `t` 值不重疊:channel 只有 `hello`/`welcom
### 7.6 心跳、重連、限流
- 心跳:host 與 device 每 30 秒送 `{"t":"ping"}`(中繼);直連時 host 每 15 秒送 WebSocket Ping frame,client 45 秒沒收到任何資料視為斷線。
-- DO alarm:只要有 socket 或 mailbox 項目就每 60 秒一次:任何 socket(host 與 device)的 `ctx.getWebSocketAutoResponseTimestamp()` 超過 90 秒 → 以 `1011` 關閉;host 標記離線,device 通知 host `close` 該 link。device 也要關:送往不再讀取的 peer 的資料會卡在佇列,DO 因此無法 hibernate、整段被計 duration,直到 TCP 斷線(常是數小時)。清除過期 mailbox(通知 `mbox.expired`)與過期 nonces。
+- DO alarm:只要有 socket 或 mailbox 項目就每 60 秒一次:任何 socket(host 與 device)的 `ctx.getWebSocketAutoResponseTimestamp()` 超過 90 秒 → **退役**:attachment 記 `retired`,之後 DO 不再送任何東西給它;host 標記離線,device 通知 host `close` 該 link。退役的 socket 不立刻關:對已經連不到的 peer 呼叫 `close()` 會讓 DO 一直醒著(計 duration)到 TCP 放棄為止,放著不動則不會。它之後再說話(收到訊息、或 ping 時間晚於退役時間)就以記下的 code 關閉;若 DO 從退役起一直沒睡過(同一個 instance 還記得它),下一次 alarm 也關它,因為卡在它佇列裡的資料可能正是 DO 睡不著的原因,只有關掉才會釋放。清除過期 mailbox(通知 `mbox.expired`)與過期 nonces。
- 重連退避:host 1 s 起倍增至 60 s、device 1 s 起倍增至 30 s,皆 full jitter;穩定 60 秒後重置。
- `4100 paired` → 立即以一般模式重連(§4.1)。
- 不重試的 close code:`4001 unauthorized`、`4003 revoked`、`4410 pairingExpired`(device 顯示需重新授權);`4009 replaced` → host 等 5 分鐘再試並記錄 `error`(可能有人複製了 `identity.json`);`4400 unsupportedVersion` → 顯示需要更新。