diff --git a/node/src/server.ts b/node/src/server.ts index 2d59aba..c63c2e3 100644 --- a/node/src/server.ts +++ b/node/src/server.ts @@ -145,26 +145,30 @@ export async function buildServer(cfg: DaemonConfig, store: MailboxStore): Promi } const ac = new AbortController(); - req.raw.on("close", () => ac.abort()); + const onClose = (): void => ac.abort(); + req.raw.once("close", onClose); + try { + const result = await store.waitForMessage(name, timeoutS * 1000, ac.signal); - const result = await store.waitForMessage(name, timeoutS * 1000, ac.signal); - - if (result.kind === "message") { - const msg = rowToMessage(result.message); - reply.code(200); - return { ...msg, sentAt: msg.sentAt.toISOString() }; + if (result.kind === "message") { + const msg = rowToMessage(result.message); + reply.code(200); + return { ...msg, sentAt: msg.sentAt.toISOString() }; + } + if (result.kind === "renamed") { + reply.code(409); + return { reason: "renamed", to: result.to }; + } + if (result.kind === "timeout") { + reply.code(204); + return reply.send(); + } + // aborted — client gone; hand control to Fastify without writing to the dead socket. + reply.hijack(); + return; + } finally { + req.raw.off("close", onClose); } - if (result.kind === "renamed") { - reply.code(409); - return { reason: "renamed", to: result.to }; - } - if (result.kind === "timeout") { - reply.code(204); - return reply.send(); - } - // aborted — client gone, no response needed (Fastify will swallow). - reply.code(499); - return reply.send(); }, );