Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 49 additions & 44 deletions src/gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@
* the member list. Intents 0 means zero events — no messages, no presence
* reads — just the connection, the handshake, and heartbeats.
*
* WebSocket Hibernation: ctx.acceptWebSocket() parks the socket with the
* Cloudflare edge and evicts the object between events; DO alarms wake it
* for heartbeats. A cron trigger (every 5 min) pings /ensure as a
* self-healing backstop. Nothing here needs a process or a keep-alive server.
* Runtime model: the socket is held IN-MEMORY, not via the WebSocket
* Hibernation API — hibernation (ctx.acceptWebSocket) exists only for
* incoming WebSocketPair server-sides; calling it on an outbound socket
* throws "pair has already been accepted", so no session ever opened.
* The DO stays resident while the socket is open; if the edge evicts the
* isolate, the socket dies with it and the cron backstop (every 5 min)
* reconnects from a fresh instance. Alarms drive heartbeats and survive
* evictions via storage. Nothing here needs a process or a keep-alive server.
*
* Token: DISCORD_TOKEN — a real Worker secret (wrangler secret put), the
* only secret this Worker reads. If it is unset, the DO simply never
* connects; commands keep working without it.
* Token: DISCORD_TOKEN — a real Worker secret, the only secret this Worker
* reads. If it is unset, the DO simply never connects; commands keep
* working without it.
*/
import type { Env } from './interactions';

Expand Down Expand Up @@ -56,6 +60,9 @@ function freshSession(): GatewaySession {
};
}

/** Live in this isolate only; an eviction wipes it and the cron reconnects. */
let liveSocket: WebSocket | null = null;

export class GatewayPresence {
constructor(private ctx: DurableObjectState, private env: Env) {}

Expand All @@ -64,21 +71,17 @@ export class GatewayPresence {
if (url.pathname !== '/ensure') return new Response('Not found', { status: 404 });
await this.ensure();
const session = await this.getSession();
return Response.json({ sockets: this.ctx.getWebSockets().length, session });
return Response.json({
socketLive: liveSocket !== null && liveSocket.readyState === WebSocket.OPEN,
session,
});
}

/** Cron backstop: connect if there is no live socket and no recent fatal. */
/** Cron backstop: connect if this isolate holds no live socket. */
async ensure(): Promise<void> {
if (liveSocket && liveSocket.readyState === WebSocket.OPEN) return;
liveSocket = null;
const session = await this.getSession();
// A persisted awaitingAck means the last heartbeat never got its ACK:
// the socket is dead even if it still counts in getWebSockets() (silent
// death delivers no close event). Force-close and reconnect.
if (session.awaitingAck) {
for (const ws of this.ctx.getWebSockets()) {
try { ws.close(4000, 'stale: unacked heartbeat'); } catch { /* already closed */ }
}
}
if (this.ctx.getWebSockets().length > 0) return;
if (session.lastFatalAt !== null && Date.now() - session.lastFatalAt < FATAL_COOLDOWN_MS) {
return;
}
Expand Down Expand Up @@ -106,11 +109,18 @@ export class GatewayPresence {
}
await this.ctx.storage.put('session', freshSession());
const ws = new WebSocket(url + (url.includes('?') ? '&' : '?') + 'v=10&encoding=json');
this.ctx.acceptWebSocket(ws);
ws.onmessage = (e) => void this.handleMessage(String(e.data)).catch(() => this.killSocket(ws));
ws.onclose = (e) => void this.handleClose(e.code).catch(() => {});
ws.onerror = () => void this.handleClose(4000).catch(() => {});
liveSocket = ws;
// Safety: if HELLO never arrives, the alarm resets the zombie socket.
await this.ctx.setAlarm(Date.now() + 30_000);
}

private killSocket(ws: WebSocket): void {
try { ws.close(4000, 'handler error'); } catch { /* already closed */ }
}

private async getSession(): Promise<GatewaySession> {
return (await this.ctx.storage.get<GatewaySession>('session')) ?? freshSession();
}
Expand All @@ -122,45 +132,44 @@ export class GatewayPresence {
await this.ctx.setAlarm(Date.now() + delay);
}

private async sendHeartbeat(ws: WebSocket, session: GatewaySession): Promise<void> {
ws.send(heartbeatPayload(session.lastSeq));
private async sendHeartbeat(session: GatewaySession): Promise<void> {
if (!liveSocket || liveSocket.readyState !== WebSocket.OPEN) return;
liveSocket.send(heartbeatPayload(session.lastSeq));
session.awaitingAck = true;
await this.ctx.storage.put('session', session);
await this.ctx.setAlarm(Date.now() + (session.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_MS));
}

async alarm(): Promise<void> {
const session = await this.getSession();
const sockets = this.ctx.getWebSockets();
const ws = sockets[0];
if (!ws) {
if (!liveSocket || liveSocket.readyState !== WebSocket.OPEN) {
liveSocket = null;
await this.ensure();
return;
}
if (session.heartbeatIntervalMs === null) {
// HELLO never arrived — zombie socket; close triggers the reconnect path.
try { ws.close(4000, 'no hello'); } catch { /* already closed */ }
try { liveSocket.close(4000, 'no hello'); } catch { /* already closed */ }
return;
}
if (session.awaitingAck) {
// Missed heartbeat ACK — the gateway spec says reconnect.
try { ws.close(4000, 'missed ack'); } catch { /* already closed */ }
try { liveSocket.close(4000, 'missed ack'); } catch { /* already closed */ }
return;
}
try {
await this.sendHeartbeat(ws, session);
await this.sendHeartbeat(session);
} catch {
// Socket died without a close event — close it so the reconnect
// path (webSocketClose / cron ensure) takes over.
try { ws.close(4000, 'send failed'); } catch { /* already closed */ }
// Send on a silently-dead socket — force the reconnect path.
try { liveSocket.close(4000, 'send failed'); } catch { /* already closed */ }
liveSocket = null;
await this.scheduleReconnect(await this.getSession());
}
}

async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
if (typeof message !== 'string') return;
private async handleMessage(raw: string): Promise<void> {
let payload: { op?: number; s?: number | null; d?: Record<string, unknown> };
try {
payload = JSON.parse(message) as typeof payload;
payload = JSON.parse(raw) as typeof payload;
} catch {
return;
}
Expand All @@ -174,8 +183,8 @@ export class GatewayPresence {
session.reconnectBackoffMs = MIN_BACKOFF_MS;
session.lastFatalAt = null;
await this.ctx.storage.put('session', session);
if (this.env.DISCORD_TOKEN) {
ws.send(JSON.stringify({
if (this.env.DISCORD_TOKEN && liveSocket) {
liveSocket.send(JSON.stringify({
op: 2,
d: {
token: this.env.DISCORD_TOKEN,
Expand All @@ -189,18 +198,19 @@ export class GatewayPresence {
session.awaitingAck = false;
await this.ctx.storage.put('session', session);
} else if (op === 1) {
await this.sendHeartbeat(ws, session);
await this.sendHeartbeat(session);
} else if (op === 7 || op === 9) {
// Server-requested reconnect / invalid session — fresh identify.
try { ws.close(4000, 'server requested reconnect'); } catch { /* already closed */ }
if (liveSocket) { try { liveSocket.close(4000, 'server requested reconnect'); } catch { /* already closed */ } }
} else if (op === 0) {
// READY and friends — presence is set by the connection itself;
// persist the sequence number.
await this.ctx.storage.put('session', session);
}
}

async webSocketClose(ws: WebSocket, code: number, _reason: string, _wasClean: boolean): Promise<void> {
private async handleClose(code: number): Promise<void> {
liveSocket = null;
const session = await this.getSession();
if (classifyClose(code) === 'fatal') {
session.lastFatalAt = Date.now();
Expand All @@ -209,9 +219,4 @@ export class GatewayPresence {
}
await this.scheduleReconnect(session);
}

async webSocketError(_ws: WebSocket, _error: unknown): Promise<void> {
await this.scheduleReconnect(await this.getSession());
}
}