diff --git a/packages/cli/src/remote/host-liveness.ts b/packages/cli/src/remote/host-liveness.ts new file mode 100644 index 0000000000..4010ebe4f0 --- /dev/null +++ b/packages/cli/src/remote/host-liveness.ts @@ -0,0 +1,100 @@ +/** + * Client-side heartbeat for the Node remote client (ADR-0019, #973). + * + * The client pings once at attach, which starts the host's own watch, then + * every {@link HOSTED_HEARTBEAT_INTERVAL_MS} while attached. Before each ping + * it checks how long the host has been silent: once no frame of any kind has + * arrived for {@link HOSTED_CLIENT_LIVENESS_TIMEOUT_MS}, the socket is treated as + * dropped and `onSilent` runs once instead of pinging a socket the host has + * already closed. The watch belongs to one socket and never outlives it. + * + * Every timer is unref'd, so an idle attached client never keeps a finished + * script alive. + */ +import { HOSTED_CLIENT_LIVENESS_TIMEOUT_MS, HOSTED_HEARTBEAT_INTERVAL_MS, type BridgeMessage } from '../bridge/protocol.js'; + +interface HeartbeatTiming { + intervalMs: number; + timeoutMs: number; +} + +const DEFAULT_TIMING: HeartbeatTiming = { intervalMs: HOSTED_HEARTBEAT_INTERVAL_MS, timeoutMs: HOSTED_CLIENT_LIVENESS_TIMEOUT_MS }; +let timing = DEFAULT_TIMING; + +/** + * Shorten the heartbeat for a test; `undefined` restores it. The 15 and 45 + * seconds are fixed by ADR-0019; this is not a user setting and no public + * entry point exports it. + */ +export function setHeartbeatForTesting(next: HeartbeatTiming | undefined): void { + timing = next ?? DEFAULT_TIMING; +} + +export interface HostLivenessOptions { + /** Send one frame on the watched socket; a throw counts as a drop. */ + send(message: BridgeMessage): void; + /** Called once, with the silence window, when the host has gone silent or the ping cannot be sent. */ + onSilent(timeoutMs: number): void; +} + +export interface HostLiveness { + /** Record a frame from the host. */ + heard(): void; + /** Stop the watch; called when the socket closes. Idempotent. */ + stop(): void; +} + +/** Ping now and on every interval; call `onSilent` once the host stops answering. */ +export function watchHostLiveness(options: HostLivenessOptions): HostLiveness { + const { intervalMs, timeoutMs } = timing; + let lastHeardAt = Date.now(); + let pings = 0; + let timer: ReturnType | undefined; + let stopped = false; + + function stop(): void { + stopped = true; + clearTimeout(timer); + timer = undefined; + } + + function drop(): void { + stop(); + options.onSilent(timeoutMs); + } + + function ping(): void { + pings += 1; + try { + options.send({ type: 'ping', id: `heartbeat-${pings}` }); + } catch { + drop(); + return; + } + schedule(); + } + + function schedule(): void { + if (stopped) return; + const remainingMs = timeoutMs - (Date.now() - lastHeardAt); + timer = setTimeout(beat, Math.max(0, Math.min(intervalMs, remainingMs))); + timer.unref?.(); + } + + function beat(): void { + const hasGoneSilent = Date.now() - lastHeardAt >= timeoutMs; + if (hasGoneSilent) { + drop(); + return; + } + ping(); + } + + ping(); + return { + heard: () => { + lastHeardAt = Date.now(); + }, + stop, + }; +} diff --git a/packages/cli/src/remote/index.ts b/packages/cli/src/remote/index.ts index 4960e80fa5..f6836fd7c6 100644 --- a/packages/cli/src/remote/index.ts +++ b/packages/cli/src/remote/index.ts @@ -55,6 +55,7 @@ import type { import { isBridgeMessage, MAX_BRIDGE_FRAME_BYTES, NO_SANDBOX_ERROR_MESSAGE, STORAGE_BYTE_ROUTE_CAPABILITY } from '../bridge/protocol.js'; import { encodeBridgeMessage } from '../bridge/frame-output.js'; import { createOperationBudget } from '../bridge/operation-budget.js'; +import { watchHostLiveness, type HostLiveness } from './host-liveness.js'; import { cliVersion } from '../pkg-version.js'; import { MAX_STORAGE_OP_BYTES, storagePayloadTooLarge } from '../serve/worker/protocol.js'; import { hasValidAttachFields } from '../bridge/attach-validation.js'; @@ -1007,7 +1008,10 @@ export async function connectRemoteSandbox( { serveUrl, opTimeoutMs: options.opTimeoutMs }, ); + let liveness: HostLiveness | undefined; + let silenceReason: string | undefined; ws.on('message', (raw) => { + liveness?.heard(); let parsed: unknown; try { parsed = JSON.parse(raw.toString()); @@ -1065,6 +1069,7 @@ export async function connectRemoteSandbox( onConnectionLost(reason); }; ws.on('close', (code) => { + liveness?.stop(); // A policy close (1008) is the host refusing this client, not a restart: // it is final, as ADR 0019 rules, so retrying would only be refused again. // Its `permission-denied` code tells the lazy handle not to retry. @@ -1073,7 +1078,7 @@ export async function connectRemoteSandbox( core.fail('remote sandbox connection closed by the host for a policy violation', REFUSED_CODE); return; } - loseConnection('remote sandbox connection closed (serve stopped or connection lost)'); + loseConnection(silenceReason ?? 'remote sandbox connection closed (serve stopped or connection lost)'); }); ws.on('error', (err) => loseConnection(`remote sandbox connection failed: ${err.message}`)); @@ -1106,6 +1111,18 @@ export async function connectRemoteSandbox( throw err; } attached = true; + // Pings go straight to the socket: they bypass the operation budget and + // never ref it, so an idle script still exits. A silent host is a drop. + const startHeartbeat = (): HostLiveness => + watchHostLiveness({ + send: (message) => ws.send(JSON.stringify(message)), + onSilent: (timeoutMs) => { + silenceReason = `the remote sandbox sent nothing for ${timeoutMs / 1000}s`; + ws.terminate(); + }, + }); + const isOpen = ws.readyState === WebSocket.OPEN; + if (isOpen) liveness = startHeartbeat(); // A host with a byte route takes Storage bytes over HTTP, authorized by the // session token its init.json hands a local process. @@ -1118,6 +1135,7 @@ export async function connectRemoteSandbox( channel: { ...core.channel, byteRoute: async () => byteRoute }, close() { closedByClient = true; + liveness?.stop(); core.dispose('remote sandbox connection closed by the client'); try { ws.close(); diff --git a/packages/cli/test/remote/host-liveness.test.ts b/packages/cli/test/remote/host-liveness.test.ts new file mode 100644 index 0000000000..7a628a8af8 --- /dev/null +++ b/packages/cli/test/remote/host-liveness.test.ts @@ -0,0 +1,101 @@ +/** + * The Node remote client's heartbeat (ADR-0019, #973). Unit evidence with + * faked timers; `reconnect.test.ts` drives the same watch over a real `ws` + * server that stops answering without closing. + */ +import { afterEach, beforeEach, describe, expect, it, jest } from 'bun:test'; +import { HOSTED_CLIENT_LIVENESS_TIMEOUT_MS, HOSTED_HEARTBEAT_INTERVAL_MS, type BridgeMessage } from '../../src/bridge/protocol.js'; +import { watchHostLiveness } from '../../src/remote/host-liveness.js'; + +function startWatch(send: (message: BridgeMessage) => void = () => {}) { + const sent: BridgeMessage[] = []; + let silences = 0; + const liveness = watchHostLiveness({ + send: message => { + sent.push(message); + send(message); + }, + onSilent: () => { + silences += 1; + }, + }); + return { liveness, sent, silences: () => silences }; +} + +beforeEach(() => { + jest.useFakeTimers(); +}); + +afterEach(() => { + jest.useRealTimers(); +}); + +describe('watchHostLiveness', () => { + it('pings at start, then once per interval while the host answers', () => { + const { liveness, sent } = startWatch(); + expect(sent).toEqual([{ type: 'ping', id: 'heartbeat-1' }]); + for (let beat = 2; beat <= 6; beat += 1) { + jest.advanceTimersByTime(HOSTED_HEARTBEAT_INTERVAL_MS - 1); + expect(sent).toHaveLength(beat - 1); + jest.advanceTimersByTime(1); + expect(sent).toHaveLength(beat); + liveness.heard(); + } + expect(new Set(sent.map(message => message.type === 'ping' && message.id)).size).toBe(sent.length); + liveness.stop(); + }); + + it('reports silence once, at the first check after the timeout, instead of pinging', () => { + const { sent, silences } = startWatch(); + jest.advanceTimersByTime(HOSTED_CLIENT_LIVENESS_TIMEOUT_MS - 1); + expect(silences()).toBe(0); + const pingsBeforeTimeout = sent.length; + jest.advanceTimersByTime(1); + expect(silences()).toBe(1); + expect(sent).toHaveLength(pingsBeforeTimeout); + jest.advanceTimersByTime(10 * HOSTED_CLIENT_LIVENESS_TIMEOUT_MS); + expect(silences()).toBe(1); + expect(sent).toHaveLength(pingsBeforeTimeout); + }); + + it('counts any frame from the host, so a host that keeps sending is never silent', () => { + const { liveness, silences } = startWatch(); + for (let elapsed = 0; elapsed < 4 * HOSTED_CLIENT_LIVENESS_TIMEOUT_MS; elapsed += HOSTED_CLIENT_LIVENESS_TIMEOUT_MS / 3) { + jest.advanceTimersByTime(HOSTED_CLIENT_LIVENESS_TIMEOUT_MS / 3); + liveness.heard(); + } + expect(silences()).toBe(0); + liveness.stop(); + }); + + it('measures silence from the last frame, not from the last ping', () => { + const { liveness, silences } = startWatch(); + jest.advanceTimersByTime(HOSTED_CLIENT_LIVENESS_TIMEOUT_MS - 5_000); + liveness.heard(); + jest.advanceTimersByTime(HOSTED_CLIENT_LIVENESS_TIMEOUT_MS - 1); + expect(silences()).toBe(0); + jest.advanceTimersByTime(1); + expect(silences()).toBe(1); + }); + + it('sends nothing and reports nothing once stopped', () => { + const { liveness, sent, silences } = startWatch(); + liveness.stop(); + jest.advanceTimersByTime(10 * HOSTED_CLIENT_LIVENESS_TIMEOUT_MS); + expect(sent).toHaveLength(1); + expect(silences()).toBe(0); + }); + + it('treats a ping the socket refuses as a drop', () => { + let refuses = false; + const { sent, silences } = startWatch(() => { + if (refuses) throw new Error('socket closed'); + }); + refuses = true; + jest.advanceTimersByTime(HOSTED_HEARTBEAT_INTERVAL_MS); + expect(silences()).toBe(1); + jest.advanceTimersByTime(10 * HOSTED_CLIENT_LIVENESS_TIMEOUT_MS); + expect(sent).toHaveLength(2); + expect(silences()).toBe(1); + }); +}); diff --git a/packages/cli/test/remote/loop-hold.test.ts b/packages/cli/test/remote/loop-hold.test.ts index c2a86b0037..6771d003b8 100644 --- a/packages/cli/test/remote/loop-hold.test.ts +++ b/packages/cli/test/remote/loop-hold.test.ts @@ -11,10 +11,19 @@ * * 2. Version skew: a live tab whose SharedWorker predates a new op returns * a raw "Unknown method: …" — the client appends restart/reload guidance. + * + * 3. Heartbeat (#973): a real Node process attached over `ws` keeps pinging + * while idle and still exits when its script ends. It runs the built CLI, + * so build first. PYRIC_TEST_NODE optionally selects the Node executable. */ import 'fake-indexeddb/auto'; import { describe, it, expect } from 'bun:test'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { WebSocketServer } from 'ws'; import { initializeSandbox } from 'pyric/sandbox'; import { getFirestore } from 'pyric/firestore'; import { createBridge, type Bridge } from '../../src/bridge/server/bridge.js'; @@ -343,3 +352,73 @@ describe('remote core — version-skew guidance on Unknown method', () => { } }); }); + +// ─── Heartbeat timers never hold the loop (#973) ─────────────────────────── + +/** A bridge host that acknowledges attach, answers ops, and counts pings. */ +async function startPingCountingHost(): Promise<{ url: string; pings: () => number; stop: () => Promise }> { + const http = createServer(); + const server = new WebSocketServer({ server: http, path: '/__pyric/sandbox' }); + http.listen(0, '127.0.0.1'); + await once(http, 'listening'); + let pings = 0; + server.on('connection', (socket) => { + socket.on('message', (raw) => { + const msg = JSON.parse(raw.toString()) as BridgeMessage; + const reply = (frame: BridgeMessage): void => socket.send(JSON.stringify(frame)); + if (msg.type === 'attach') { + reply({ type: 'attach-ack', protocol: 1, bridgeVersion: 'test', peerConnected: true, clientSessionId: 's' }); + } else if (msg.type === 'ping') { + pings += 1; + reply({ type: 'pong', id: msg.id }); + } else if (msg.type === 'worker-op') { + reply({ type: 'worker-res', id: msg.id, ok: true, value: { key: null, exists: true, value: 1, size: 1 } }); + } + }); + }); + const stop = async (): Promise => { + for (const client of server.clients) client.terminate(); + server.close(); + http.closeAllConnections(); + await new Promise((resolve) => http.close(() => resolve())); + }; + return { url: `http://127.0.0.1:${(http.address() as AddressInfo).port}`, pings: () => pings, stop }; +} + +/** Attach, run one op, stay idle long enough for several heartbeats, and end without closing. */ +const IDLE_SCRIPT = ` +const { setHeartbeatForTesting } = await import(new URL('host-liveness.js', process.argv[1]).href); +setHeartbeatForTesting({ intervalMs: 50, timeoutMs: 45_000 }); +const { connectRemoteSandbox } = await import(process.argv[1]); +const remote = await connectRemoteSandbox({ url: process.argv[2] }); +await remote.rtdb.get('a'); +await new Promise((resolve) => setTimeout(resolve, 400)); +process.stdout.write('idle'); +`; + +describe('remote client — heartbeat and the event loop (#973)', () => { + it('an idle attached process keeps pinging and still exits when its script ends', async () => { + const host = await startPingCountingHost(); + try { + const entry = new URL('../../dist/remote/index.js', import.meta.url).href; + const child = spawn( + process.env.PYRIC_TEST_NODE ?? 'node', + ['--input-type=module', '-e', IDLE_SCRIPT, entry, host.url], + { stdio: ['ignore', 'pipe', 'pipe'] }, + ); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => (stdout += chunk)); + child.stderr.on('data', (chunk) => (stderr += chunk)); + const exited = once(child, 'exit').then(([code]) => code as number | null); + const deadline = new Promise<'hung'>((resolve) => setTimeout(() => resolve('hung'), 10_000)); + const outcome = await Promise.race([exited, deadline]); + if (outcome === 'hung') child.kill('SIGKILL'); + expect(outcome, stderr).toBe(0); + expect(stdout).toBe('idle'); + expect(host.pings()).toBeGreaterThanOrEqual(3); + } finally { + await host.stop(); + } + }, 20_000); +}); diff --git a/packages/cli/test/remote/reconnect.test.ts b/packages/cli/test/remote/reconnect.test.ts index a103ff1c7c..8f38aaa737 100644 --- a/packages/cli/test/remote/reconnect.test.ts +++ b/packages/cli/test/remote/reconnect.test.ts @@ -4,13 +4,14 @@ * stopped sandbox: later ops reconnect, and live listeners are resubscribed * once the host answers again (#949). */ -import { afterEach, describe, expect, it } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; import { once } from 'node:events'; import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; import { WebSocketServer } from 'ws'; import type { BridgeMessage } from '../../src/bridge/protocol.js'; import { + connectRemoteSandbox, createLazyRemoteSandbox, createRemoteSandboxHandle, remoteSandbox, @@ -18,12 +19,16 @@ import { type RemoteSandbox, type RemoteSandboxChannel, } from '../../src/remote/index.js'; +import { setHeartbeatForTesting } from '../../src/remote/host-liveness.js'; /** * A bridge host that acknowledges attach, answers every op with `generation` - * (or none, with `answersOps: false`), and sends one snap per subscription. - * With `refusesAttach`, it refuses every attach with a policy close (1008), - * as the bridge does when it declines a hosted session. + * (or none, with `answersOps: false`), sends one snap per subscription, and + * answers `ping` with `pong`, as the bridge does. With `refusesAttach`, it + * refuses every attach with a policy close (1008), as the bridge does when it + * declines a hosted session. `muteClients` makes the sockets open now go + * silent without closing, as a paused host does; later sockets answer + * `generation`, which `setGeneration` changes. */ async function startFakeHost( port: number, @@ -34,6 +39,8 @@ async function startFakeHost( port: number; stop: () => Promise; closeClients: (code: number, reason: string) => void; + muteClients: () => void; + setGeneration: (next: string) => void; subs: string[]; ops: string[]; attaches: () => number; @@ -45,8 +52,10 @@ async function startFakeHost( const subs: string[] = []; const ops: string[] = []; let attaches = 0; + const muted = new WeakSet(); server.on('connection', socket => { socket.on('message', raw => { + if (muted.has(socket)) return; const msg = JSON.parse(raw.toString()) as BridgeMessage; const reply = (frame: BridgeMessage): void => socket.send(JSON.stringify(frame)); if (msg.type === 'attach') { @@ -59,6 +68,8 @@ async function startFakeHost( } else if (msg.type === 'worker-op') { ops.push(msg.id); if (answersOps) reply({ type: 'worker-res', id: msg.id, ok: true, value: { key: null, exists: true, value: generation, size: 1 } }); + } else if (msg.type === 'ping') { + reply({ type: 'pong', id: msg.id }); } else if (msg.type === 'worker-sub') { subs.push(msg.subId); reply({ type: 'worker-snap', subId: msg.subId, value: { key: null, exists: true, value: generation, size: 1 } }); @@ -74,7 +85,22 @@ async function startFakeHost( const closeClients = (code: number, reason: string): void => { for (const client of server.clients) client.close(code, reason); }; - return { port: (http.address() as AddressInfo).port, stop, closeClients, subs, ops, attaches: () => attaches }; + const muteClients = (): void => { + for (const client of server.clients) muted.add(client); + }; + const setGeneration = (next: string): void => { + generation = next; + }; + return { + port: (http.address() as AddressInfo).port, + stop, + closeClients, + muteClients, + setGeneration, + subs, + ops, + attaches: () => attaches, + }; } const cleanups: Array<() => unknown> = []; @@ -233,6 +259,87 @@ describe('remoteSandbox after its host restarts on the same url', () => { }); }); +/** A heartbeat short enough for a test: ping every 50 ms, 300 ms of silence is a drop. */ +const fastHeartbeat = { intervalMs: 50, timeoutMs: 300 }; + +describe('remoteSandbox when its host stops answering without closing the socket (#973)', () => { + beforeEach(() => setHeartbeatForTesting(fastHeartbeat)); + afterEach(() => setHeartbeatForTesting(undefined)); + + it('stays attached past the silence timeout while the host answers its pings', async () => { + const host = await startFakeHost(0, 'first'); + cleanups.push(host.stop); + const warnings: string[] = []; + const lazy = remoteSandbox({ url: `http://127.0.0.1:${host.port}`, warn: message => warnings.push(message) }); + cleanups.push(() => lazy.close()); + const values: unknown[] = []; + lazy.rtdb.onValue('ticks', snapshot => values.push(snapshot.value)); + await waitFor(() => values.length === 1); + + await Bun.sleep(3 * fastHeartbeat.timeoutMs); + expect(warnings).toEqual([]); + expect(host.attaches()).toBe(1); + }); + + it('reports one loss, reconnects, and resubscribes a live listener', async () => { + const host = await startFakeHost(0, 'first'); + cleanups.push(host.stop); + const warnings: string[] = []; + const lazy = remoteSandbox({ url: `http://127.0.0.1:${host.port}`, warn: message => warnings.push(message) }); + cleanups.push(() => lazy.close()); + const values: unknown[] = []; + const errors: unknown[] = []; + lazy.rtdb.onValue('ticks', snapshot => values.push(snapshot.value), error => errors.push(error)); + await waitFor(() => values.length === 1); + + host.setGeneration('second'); + host.muteClients(); + await waitFor(() => values.length === 2); + expect(values).toEqual(['first', 'second']); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain('the remote sandbox sent nothing for 0.3s'); + expect(host.attaches()).toBe(2); + expect(host.subs).toHaveLength(2); + expect(errors).toEqual([]); + }); + + it('fails an op sent on the silent socket once and runs an op issued while reconnecting once', async () => { + const host = await startFakeHost(0, 'first'); + cleanups.push(host.stop); + const warnings: string[] = []; + const lazy = remoteSandbox({ url: `http://127.0.0.1:${host.port}`, warn: message => warnings.push(message) }); + cleanups.push(() => lazy.close()); + expect(await lazy.rtdb.get('a')).toBe('first'); + + host.muteClients(); + const unanswered = await lazy.rtdb.set('a', 1).catch((error: Error & { code?: string }) => error); + expect((unanswered as Error & { code?: string }).code).toBe('unavailable'); + expect(warnings).toHaveLength(1); + + host.setGeneration('second'); + const opsBefore = host.ops.length; + expect(await lazy.rtdb.get('a')).toBe('second'); + expect(host.ops.length - opsBefore).toBe(1); + expect(host.attaches()).toBe(2); + }); + + it('ends the eager handle\'s listeners with unavailable', async () => { + const host = await startFakeHost(0, 'first'); + cleanups.push(host.stop); + const remote = await connectRemoteSandbox({ url: `http://127.0.0.1:${host.port}` }); + cleanups.push(() => remote.close()); + const values: unknown[] = []; + const errors: Array<{ code?: string }> = []; + remote.rtdb.onValue('ticks', snapshot => values.push(snapshot.value), error => errors.push(error)); + await waitFor(() => values.length === 1); + + host.muteClients(); + await waitFor(() => errors.length === 1); + expect(errors[0]!.code).toBe('unavailable'); + expect(host.attaches()).toBe(1); + }); +}); + describe('createLazyRemoteSandbox when the connection is lost', () => { function fakeConnection(serveUrl = 'http://127.0.0.1:5000'): { handle: RemoteSandbox; subscriptions: () => number } { let subscriptions = 0;