Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

A routed request knows its connection, and its service is told when that connection closes (#927)

Dee389b22964142
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index b9c79e905..f52de5757 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -274,7 +274,12 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {
// Then at 75,456 in 344, from 75,746 in 345: the web dashboard (webui.ts, `GET /`, its log tail and stop
// button, and its port in `e2e_status`) is deleted. Nothing opened it: no app, website, script or the
// backend, and the web client that linked to it retired with the browser setup links (#348).
-const CORE_CLOSURE_BUDGET = 75_560
+//
+// Grew by 37 to 75,493 in 344, from 75,456, for the notice that the connection a routed request came over closed
+// (core/serviceHost.ts, core/serviceLinks.ts, the socket's close paths), held requests for an experiment
+// still starting included: what lets a service keep work per connection and stop it when its asker goes,
+// which held the command bar's two doors in the core (step 4).
+const CORE_CLOSURE_BUDGET = 75_590
/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */
const EDGE: RegExp[] = [
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 65337f911..352433f26 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -992,6 +992,25 @@ describe('BackendSocket outbound queue', () => {
await socket.stop()
})
+ it('tells the services when a connection that may have asked them closes: a window, a remote client, the relay and its clients', async () => {
+ const socket = relaySocket('token')
+ const closed: string[] = []
+ socket.onConnectionClosed = (connId) => { closed.push(connId) }
+ socket.registerLocalClient('local:window', { sendFrame: () => true, sendBinary: () => true })
+ await socket.unregisterLocalClient('local:window')
+ const client = { role: 'web' as const, label: null, identity: 'id', direct: false }
+ for (const connId of ['web-1', 'web-2', 'web-3']) socket.fromGateway.client(connId, client)
+ socket.fromGateway.client('web-1', null)
+ // One the gateway never announced is no connection of the socket's.
+ socket.fromGateway.client('web-unknown', null)
+ await socket.fromGateway.disconnected('web-2')
+ // The relay gone: every remote client it still had went with it, and no window on this computer did.
+ socket.registerLocalClient('local:stays', { sendFrame: () => true, sendBinary: () => true })
+ socket.fromGateway.linkDown()
+ expect(closed).toEqual(['local:window', 'web-1', 'web-2', 'web-3'])
+ await socket.stop()
+ })
+
it('answers a request whose service is unavailable SERVICE_UNAVAILABLE, retryable, and goes on', async () => {
const socket = relaySocket('token')
// A request whose work reaches a service through its port, whose fallback is to fail (core/serviceHost.ts).
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 81ccc4f49..b831a8d11 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -341,13 +341,13 @@ export class BackendSocket {
this.wifi?.session(connId, client)
if (client) { this.remoteClients.set(connId, client); return }
if (!this.remoteClients.delete(connId)) return
- this.viewerForwarder.closeConnection(connId); this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId)
+ this.viewerForwarder.closeConnection(connId); this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId); this.onConnectionClosed?.(connId)
},
disconnected: async (connId) => {
this.wifi?.dropped(connId)
this.remoteClients.delete(connId)
this.viewerForwarder.closeConnection(connId)
- this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId)
+ this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId); this.onConnectionClosed?.(connId)
await this.terminalStreams?.closeConnection(
connId,
'client connection closed',
@@ -366,7 +366,7 @@ export class BackendSocket {
linkDown: () => {
this.observers?.closeAll()
this.viewerForwarder.closeAll()
- this.interactiveViewers.closeAll(); this.ownerCommands.closeAll()
+ this.interactiveViewers.closeAll(); this.ownerCommands.closeAll(); for (const connId of this.remoteClients.keys()) this.onConnectionClosed?.(connId)
void this.terminalStreams?.closeConnectionsWhere(
(connId) => !isLocalClientId(connId),
'backend disconnected',
@@ -623,6 +623,8 @@ export class BackendSocket {
/** Routes a request to the service that answers it, in its own process (core/serviceLinks.ts) or in
* this one (core/serviceHost.ts): false when none does and the socket answers it itself. */
serviceRouter: ((type: string, payload: Record<string, unknown>, asker: Asker, reply: (result: Record<string, unknown>) => void) => boolean) | null = null
+ /** A connection that asked the services something closed: they abort what it asked (`Asker.connection`). */
+ onConnectionClosed: ((connId: string) => void) | null = null
/** A window (or `hn`) on this computer attached or went away — the pair brain thinks only while one is here. */
onLocalClient: ((connId: string, attached: boolean) => void) | null = null
@@ -632,7 +634,7 @@ export class BackendSocket {
if (!this.toolClients.delete(connId)) this.onLocalClient?.(connId, false)
this.rowStateWindows.delete(connId)
this.viewerForwarder.closeConnection(connId)
- this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId)
+ this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId); this.onConnectionClosed?.(connId)
// The last one leaving before any link could hear it attach: nothing happened, as far as the backend
// is concerned, and the gateway does not tell a later link otherwise.
this.gatewayPort?.localClients(this.localClients.size)
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index a9e269e0f..1720e526f 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -358,16 +358,25 @@ export interface Asker {
/** Whether it may act as this machine's owner: a local process, or the owner's paired app over the
* relay. A device or an observer may not. */
owner: boolean
- /** The connection it came over, as the core names it, and the id it asked under: what a service keys
- * work by that belongs to one connection's request (the Model Manager's grid commands, which a cancel
- * on the same connection stops). Absent when the core itself asks. */
+ /** The connection it came over (a window's, a remote client's), as the core names it, and the id it
+ * asked under: what a service keys work by that belongs to one connection (the Model Manager's grid
+ * commands, which a cancel on the same connection stops; a limit on how many at once per connection).
+ * The handler hears that connection close through `closed`. Absent when the core itself asks, and from
+ * a core from before it was given: then the request is its own connection. */
connection?: string
requestId?: string
}
-/** A request a service answers for the apps: the reply, or a promise of it. A throw or a rejection is
- * answered `SERVICE_FAILED` by the host and counted against the service. */
-export type ServiceRequest = (payload: Record<string, unknown>, asker: Asker) => Record<string, unknown> | Promise<Record<string, unknown>>
+/**
+ * A request a service answers for the apps: the reply, or a promise of it. A throw or a rejection is
+ * answered `SERVICE_FAILED` by the host and counted against the service.
+ *
+ * `closed` is aborted when the connection that asked closes (`Asker.connection`), or when the core that
+ * routed it goes: nobody is left to read the answer, so the work for it may stop. A handler that ignores
+ * it runs to the end, as every one did before it was given; one called without it (a spec, a wrapper)
+ * is never told.
+ */
+export type ServiceRequest = (payload: Record<string, unknown>, asker: Asker, closed?: AbortSignal) => Record<string, unknown> | Promise<Record<string, unknown>>
/** The requests a service answers, by frame type: what its start returns. */
export type ServiceRequests = Readonly<Record<string, ServiceRequest>>
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index d47b6d4b2..04c3af53f 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -1223,6 +1223,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// A request a service declared goes to it: in its own process, or in this one (core/serviceHost.ts).
backend.serviceRouter = (type, payload, asker, reply) => (teamsOut && teamsLink.route(type, payload, asker, reply))
|| serviceLinks.route(type, payload, asker, reply) || serviceHost.route(type, payload, asker, reply)
+ // The connection that asked closed: the services abort what it asked, wherever they run.
+ backend.onConnectionClosed = (connId) => { serviceLinks.closeConnection(connId); serviceHost.closeConnection(connId) }
// Session search (services/search.ts): in this process, or in its own (services/searchProcess.ts),
// where the core tells it what changed. A purge's forgetting waits for it if it is down.
if (outOfProcess.has('search')) {
diff --git a/cli/src/core/serviceHost.spec.ts b/cli/src/core/serviceHost.spec.ts
index 7e916384a..56039c668 100644
--- a/cli/src/core/serviceHost.spec.ts
+++ b/cli/src/core/serviceHost.spec.ts
@@ -238,6 +238,31 @@ describe('hosting services so one that fails cannot take the core down', () => {
expect(h.services.route('agents_list', {}, ASKER, reply)).toBe(false)
})
+ it('tells a handler when the connection that asked closes, and no other connection\'s', async () => {
+ const h = host()
+ const asked = new Map<string, { closed: AbortSignal; answer: () => void }>()
+ h.services.serve('commands', () => ({
+ command: (payload, _asker, closed) => new Promise((resolve) => {
+ asked.set(String(payload.id), { closed: closed!, answer: () => resolve({ id: payload.id }) })
+ }),
+ }), fakeCore(), ['command'])
+ const { got, reply } = collect()
+ h.services.route('command', { id: 'a1' }, { ...ASKER, connection: 'conn-a' }, reply)
+ h.services.route('command', { id: 'a2' }, { ...ASKER, connection: 'conn-a' }, reply)
+ h.services.route('command', { id: 'b1' }, { ...ASKER, connection: 'conn-b' }, reply)
+ // The core's own asking, with no connection: never closed.
+ h.services.route('command', { id: 'core' }, ASKER, reply)
+ // A request already answered is forgotten: closing its connection reaches nothing.
+ asked.get('b1')!.answer()
+ await vi.waitFor(() => expect(got).toEqual([{ id: 'b1' }]))
+ h.services.closeConnection('conn-b')
+ h.services.closeConnection('conn-a')
+ expect([...asked.values()].map((one) => one.closed.aborted)).toEqual([true, true, false, false])
+ // Aborted or not, what the handler answers is replied: the socket drops what nobody can read.
+ asked.get('a1')!.answer()
+ await vi.waitFor(() => expect(got).toEqual([{ id: 'b1' }, { id: 'a1' }]))
+ })
+
it('returns at once, and replies when a promised answer comes', async () => {
const h = host()
let answer!: (value: Record<string, unknown>) => void
diff --git a/cli/src/core/serviceHost.ts b/cli/src/core/serviceHost.ts
index 8cad8a9aa..6b0272939 100644
--- a/cli/src/core/serviceHost.ts
+++ b/cli/src/core/serviceHost.ts
@@ -93,6 +93,8 @@ export function createServiceHost(ports: CorePorts, options: ServiceHostOptions
const stoppers = new Map<string, () => void>()
/** The service that answers each request type, and its handler once it has started. */
const owners = new Map<string, { service: string; answer: ServiceRequest | null }>()
+ /** The requests still being answered, each with the connection that asked: what its closing aborts. */
+ const answering = new Map<AbortController, string | undefined>()
const inject = (target: string): void => {
if (faults.has(target)) throw new Error(`injected fault: ${target}`)
@@ -245,20 +247,29 @@ export function createServiceHost(ports: CorePorts, options: ServiceHostOptions
failed(service, type, error)
reply({ error: 'SERVICE_FAILED', service })
}
+ // Aborted when its connection closes (`closeConnection`); a request with none is its own, never closed.
+ const closed = new AbortController()
+ answering.set(closed, asker.connection)
+ const settled = (): void => { answering.delete(closed) }
let result: ReturnType<ServiceRequest>
try {
inject(`${service}.${type}`)
- result = answer(payload, asker)
+ result = answer(payload, asker, closed.signal)
} catch (error) {
+ settled()
failedWith(error)
return true
}
void Promise.resolve(result).then((value) => {
if (typeof value === 'object' && value !== null) reply(value)
else failedWith(new Error(`${type} was answered with no reply`))
- }, failedWith)
+ }, failedWith).finally(settled)
return true
},
+ /** A connection closed: abort what it asked that is still being answered. Its answers go nowhere. */
+ closeConnection(connection: string): void {
+ for (const [closed, asked] of answering) if (asked === connection) closed.abort()
+ },
/** Run `handler` once, when `name` is switched off. */
onOff(name: string, handler: () => void): void {
offHandlers.set(name, [...offHandlers.get(name) ?? [], handler])
diff --git a/cli/src/core/serviceLinks.spec.ts b/cli/src/core/serviceLinks.spec.ts
index 020080020..495185858 100644
--- a/cli/src/core/serviceLinks.spec.ts
+++ b/cli/src/core/serviceLinks.spec.ts
@@ -98,6 +98,29 @@ describe('service links', () => {
expect(want).toHaveBeenCalledTimes(2)
})
+ it('carries the connection through an experiment\'s start, and never sends what a connection that closed meanwhile asked', () => {
+ const links = make({ owned: { orchestrator: ['orchestrator'] }, onDemand: new Set(['orchestrator']), want: vi.fn() })
+ const gone = vi.fn(), stays = vi.fn(), core = vi.fn()
+ links.route('orchestrator', { action: 'list' }, { ...ASKER, connection: 'gone' }, gone)
+ links.route('orchestrator', { action: 'catalog' }, { ...ASKER, connection: 'stays' }, stays)
+ links.route('orchestrator', { action: 'status' }, ASKER, core)
+ links.closeConnection('gone')
+ // Answered where nobody is left to read it, and never sent.
+ expect(gone).toHaveBeenCalledWith({ error: 'SERVICE_UNAVAILABLE', service: 'orchestrator', retryable: true })
+ const orchestrator = sink()
+ links.accept('orchestrator', TOKEN, orchestrator, vi.fn())
+ expect(orchestrator.sent).toEqual([
+ { type: 'orchestrator', payload: { action: 'catalog', requestId: 'route-2' }, asker: { ...ASKER, connection: 'stays' } },
+ { type: 'orchestrator', payload: { action: 'status', requestId: 'route-3' }, asker: ASKER },
+ ])
+ expect(stays).not.toHaveBeenCalled()
+ expect(core).not.toHaveBeenCalled()
+ // Sent, it is the process's to abort when its connection closes.
+ links.closeConnection('stays')
+ expect(orchestrator.sent.at(-1)).toEqual({ type: 'service_connection_closed', payload: { connection: 'stays' } })
+ expect(stays).not.toHaveBeenCalled()
+ })
+
it('answers SERVICE_UNAVAILABLE for an experiment that does not come in time, or will not take the request', () => {
const links = make({ owned: { orchestrator: ['orchestrator'], search: ['session_search'] }, onDemand: new Set(['orchestrator']) })
const late = vi.fn()
@@ -149,6 +172,23 @@ describe('service links', () => {
expect(links.route('agents_list', {}, ASKER, reply)).toBe(false)
})
+ it('routes with the connection that asked, and tells every service connected when a connection closes', () => {
+ const links = make({ owned: { search: ['session_search'], store: ['dsh_list'], viewers: [] } })
+ const search = sink(), store = sink()
+ links.accept('search', TOKEN, search, vi.fn())
+ links.accept('store', TOKEN, store, vi.fn())
+ links.route('session_search', { query: 'q' }, { ...ASKER, connection: 'conn-1' }, vi.fn())
+ expect(search.sent).toEqual([{ type: 'session_search', payload: { query: 'q', requestId: 'route-1' }, asker: { local: false, owner: true, connection: 'conn-1' } }])
+ links.closeConnection('conn-1')
+ const closed = { type: 'service_connection_closed', payload: { connection: 'conn-1' } }
+ expect(search.sent.at(-1)).toEqual(closed)
+ expect(store.sent).toEqual([closed])
+ // A service down when it closed is not told later: what it was answering went with it.
+ const viewers = sink()
+ links.accept('viewers', TOKEN, viewers, vi.fn())
+ expect(viewers.sent).toEqual([])
+ })
+
it('asks a service what the core itself needs, as the core, and settles every way a routed request does', async () => {
const links = make({ owned: { monitor: ['machine_resources'] } })
// Down: unavailable at once, never a rejection.
diff --git a/cli/src/core/serviceLinks.ts b/cli/src/core/serviceLinks.ts
index 6a5061ecf..891198207 100644
--- a/cli/src/core/serviceLinks.ts
+++ b/cli/src/core/serviceLinks.ts
@@ -6,8 +6,10 @@
* alike, so no other local process can stand in for one. The core then routes the requests the service
* answers to it and relays each answer back to the client that asked; a request that finds the service
* down, or not answering in time, is answered SERVICE_UNAVAILABLE with `retryable: true` — the core never
- * waits on a service in line. The core tells a service what it needs to know with `notify`, and answers
- * the few questions a service may ask it (`service_query`), nothing more.
+ * waits on a service in line. A routed request carries the connection it came over (`Asker.connection`),
+ * and the core says when that connection closes (`closeConnection`). The core tells a service what it
+ * needs to know with `notify`, and answers the few questions a service may ask it (`service_query`),
+ * nothing more.
*/
import { randomUUID, timingSafeEqual } from 'node:crypto'
import type { Asker } from './api.js'
@@ -210,6 +212,17 @@ export function createServiceLinks(options: ServiceLinksOptions) {
return new Promise((resolve) => { ask(service, type, payload, THE_CORE, resolve, waitMs) })
},
+ /** A connection closed: every service connected is told (`service_connection_closed`), and aborts what
+ * that connection asked it that it is still answering (services/process.ts). Not held for a service
+ * that is down: what it was answering went with it. What it asked of an experiment still starting is
+ * never sent: nobody is left to read the answer, and the work would run for no one. */
+ closeConnection(connection: string): void {
+ for (const [id, entry] of waiting) {
+ if (entry.frame && (entry.frame.asker as Asker | undefined)?.connection === connection) settle(id, entry, unavailable(entry.service))
+ }
+ for (const link of links.values()) link.sink.sendFrame({ type: 'service_connection_closed', payload: { connection } })
+ },
+
/** Bytes for a service that carries terminals; false when it is not connected or would not take them. */
notifyBinary(service: string, bytes: Uint8Array): boolean {
return links.get(service)?.sink.sendBinary?.(bytes) ?? false
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index d39b4b113..0c8ed42d6 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -20,6 +20,11 @@ let several people build features at once without touching the core or each othe
- While the service is off, its requests are answered `SERVICE_UNAVAILABLE`, never `UNSUPPORTED`
(the apps read that as "update the CLI"). That is why the types are declared up front.
- A handler that throws or rejects is answered `SERVICE_FAILED` and counts against the service.
+ - Work that belongs to the connection that asked (a limit on how many at once per connection, work to
+ stop when the asker goes) is keyed by `asker.connection` and stops on `closed`, the handler's third
+ argument: it is aborted when that connection closes, or when the core that routed it goes, wherever
+ the service runs (`serviceHost.closeConnection`, `serviceLinks.closeConnection`, `process.ts`). A
+ request held while an experiment's process starts is never sent once its connection has closed.
3. **If the core must call the service, give it a port.** Add `<Name>Port` and its fallbacks
(`<NAME>_FALLBACKS`) to `src/core/api.ts`. A fallback is what the core does while the service is
off or failing: `undefined` for nothing, a value, or `FAIL` to answer that one request
diff --git a/cli/src/services/process.spec.ts b/cli/src/services/process.spec.ts
index 400c41932..44b49b4e5 100644
--- a/cli/src/services/process.spec.ts
+++ b/cli/src/services/process.spec.ts
@@ -216,6 +216,41 @@ describe('a service in its own process', () => {
])
})
+ it('tells a handler when the connection that asked closes, and when the core that routed it goes', async () => {
+ const asked: Array<{ asker: unknown; closed: AbortSignal; answer: () => void }> = []
+ run({ requests: { command: (payload: Record<string, unknown>, asker: unknown, closed?: AbortSignal) => new Promise((resolve) => {
+ asked.push({ asker, closed: closed!, answer: () => resolve({ id: payload.id }) })
+ }) } })
+ socket().open()
+ const ask = (id: string, connection?: unknown) => socket().say({ type: 'command', payload: { id, requestId: id }, asker: { local: false, owner: true, connection } })
+ ask('a1', 'conn-a')
+ ask('a2', 'conn-a')
+ ask('b1', 'conn-b')
+ // Not a string: read as no connection, as from a core from before connections were given.
+ ask('none', 7)
+ await vi.waitFor(() => expect(asked).toHaveLength(4))
+ expect(asked.map((one) => one.asker)).toEqual([
+ { local: false, owner: true, connection: 'conn-a' },
+ { local: false, owner: true, connection: 'conn-a' },
+ { local: false, owner: true, connection: 'conn-b' },
+ { local: false, owner: true },
+ ])
+ // A request already answered is forgotten: closing its connection reaches nothing.
+ asked[2].answer()
+ await vi.waitFor(() => expect(socket().sent.at(-1)).toEqual({ type: 'command_result', payload: { id: 'b1', requestId: 'b1' } }))
+ socket().say({ type: 'service_connection_closed', payload: { connection: 'conn-b' } })
+ expect(asked[2].closed.aborted).toBe(false)
+ // Only the connection that closed: its two, not another's, not one with none.
+ socket().say({ type: 'service_connection_closed', payload: { connection: 'conn-a' } })
+ expect(asked.map((one) => one.closed.aborted)).toEqual([true, true, false, false])
+ // Aborted or not, what a handler answers still goes back: the core drops what nobody can read.
+ asked[0].answer()
+ await vi.waitFor(() => expect(socket().sent.at(-1)).toEqual({ type: 'command_result', payload: { id: 'a1', requestId: 'a1' } }))
+ // The core gone: nobody is left to read any answer, so all that is left is aborted.
+ socket().drop()
+ expect(asked[3].closed.aborted).toBe(true)
+ })
+
it('hears what the core tells it, and asks the core what it needs to know', async () => {
const onEvent = vi.fn()
let core: Parameters<NonNullable<ServiceProcessOptions['onConnected']>>[0] | null = null
diff --git a/cli/src/services/process.ts b/cli/src/services/process.ts
index 51ebc90dd..3e70b5711 100644
--- a/cli/src/services/process.ts
+++ b/cli/src/services/process.ts
@@ -185,6 +185,9 @@ export function runServiceProcess(options: ServiceProcessOptions): ServiceProces
/** The core took this connection (`connected`): only then does its end mean the service was cut off. */
let opened = false
const pending = new Map<string, { resolve: (payload: Payload) => void; reject: (error: Error) => void }>()
+ /** The requests being answered, each with the connection that asked (`Asker.connection`): what that
+ * connection closing aborts, and what the core going aborts all of, since nobody is left to answer. */
+ const answering = new Map<AbortController, string | undefined>()
const send = (frame: { type: string; payload: Payload }): void => {
try { socket?.send(JSON.stringify(frame)) } catch { /* the socket is going; the core answers for us */ }
@@ -231,6 +234,10 @@ export function runServiceProcess(options: ServiceProcessOptions): ServiceProces
} catch (error) { failed(error) }
return
}
+ if (frame.type === 'service_connection_closed') {
+ for (const [closed, asked] of answering) if (asked === payload.connection) closed.abort()
+ return
+ }
if (frame.type === 'service_query_result') {
const waiting = pending.get(String(payload.requestId))
if (!waiting) return
@@ -251,18 +258,24 @@ export function runServiceProcess(options: ServiceProcessOptions): ServiceProces
...(typeof frame.asker?.connection === 'string' ? { connection: frame.asker.connection } : {}),
...(typeof frame.asker?.requestId === 'string' ? { requestId: frame.asker.requestId } : {}),
}
+ // Aborted when that connection closes (`service_connection_closed`), or when the core goes.
+ const closed = new AbortController()
+ answering.set(closed, asker.connection)
// A request that fails here is answered as failed, never left for the core's timeout, and in the
// words the core's host uses: what went wrong goes to the log, not to whoever asked.
void Promise.resolve()
.then(() => {
if (faults.calls.has(type)) throw new Error(`injected fault: ${options.name}.${type}`)
- return handle(payload, asker)
+ return handle(payload, asker, closed.signal)
})
.catch((error: unknown) => {
log(`[service ${options.name}] ${type} failed · ${describe(error)}`)
return { error: 'SERVICE_FAILED', service: options.name }
})
- .then((result) => send({ type: `${type}_result`, payload: { ...result, requestId } }))
+ .then((result) => {
+ answering.delete(closed)
+ send({ type: `${type}_result`, payload: { ...result, requestId } })
+ })
}
// Only ever run at start and from the reconnect timer, which `stop` clears.
@@ -283,6 +296,8 @@ export function runServiceProcess(options: ServiceProcessOptions): ServiceProces
socket = null
opened = false
for (const [id, waiting] of pending) { pending.delete(id); waiting.reject(new Error('the core went away')) }
+ // The core that asked is gone, and every connection it routed with it: nobody can read these answers.
+ for (const closed of answering.keys()) closed.abort()
if (wasOpen) {
try { options.onDisconnected?.() } catch (error) { log(`[service ${options.name}] disconnect failed · ${describe(error)}`) }
}