Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([issue-905]): extract awaitWritableDrain backpressure helper
Adam Eivy3de0048ffe6d
diff --git a/server/lib/README.md b/server/lib/README.mdindex 0b005ff670..8491cf0095 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -202,6 +202,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). || `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. || `sseUtils.js` | Per-job SSE stream helpers (imageGen + others). |+| `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). || `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. || `zodCompat.js` | Zod 4 compatibility helpers. `partialWithoutDefaults(objectSchema)` — like `.partial()` but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. |diff --git a/server/lib/index.js b/server/lib/index.jsindex f12bca5497..7024225689 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -168,6 +168,7 @@ export * from './errorHandler.js';export * from './mapWithConcurrency.js';export * from './objects.js';export * from './singleFlight.js';+export * from './streamBackpressure.js';export * from './sseUtils.js';export * from './uuid.js';export * from './zodCompat.js';diff --git a/server/lib/streamBackpressure.js b/server/lib/streamBackpressure.jsnew file mode 100644index 0000000000..0f0c6fdd88--- /dev/null+++ b/server/lib/streamBackpressure.js@@ -0,0 +1,24 @@+// Socket backpressure helper for streaming HTTP responses (SSE / NDJSON).+//+// `res.write()` returns false when the kernel/send buffer is full. A producer+// that ignores that return value buffers the whole response in memory when the+// reader is slower than the writer (a fast local model streaming to a slow+// client). Awaiting `awaitWritableDrain(res)` parks the producer until the+// socket drains — or the client disconnects — so writes stay bounded.+//+// Both listeners are torn down on settle so a client that hangs up mid-drain+// can't leak a `drain`/`close` listener. Resolves immediately when the response+// is already finished (nothing left to drain). Shared by the SSE `send` helper+// in routes/ask.js and the NDJSON `write` helper in routes/localLlm.js.+export const awaitWritableDrain = (res) => {+ if (res.writableEnded || res.destroyed) return Promise.resolve();+ return new Promise((resolve) => {+ const settle = () => {+ res.off('drain', settle);+ res.off('close', settle);+ resolve();+ };+ res.once('drain', settle);+ res.once('close', settle);+ });+};diff --git a/server/lib/streamBackpressure.test.js b/server/lib/streamBackpressure.test.jsnew file mode 100644index 0000000000..c84e681afd--- /dev/null+++ b/server/lib/streamBackpressure.test.js@@ -0,0 +1,48 @@+import { describe, it, expect, vi } from 'vitest';+import { EventEmitter } from 'node:events';+import { awaitWritableDrain } from './streamBackpressure.js';++// A minimal `res` stand-in: an EventEmitter with the writable-state flags the+// helper reads. `once`/`off` come from EventEmitter.+const makeRes = (over = {}) => Object.assign(new EventEmitter(), {+ writableEnded: false,+ destroyed: false,+}, over);++describe('awaitWritableDrain', () => {+ it('resolves immediately when the response is already ended', async () => {+ await expect(awaitWritableDrain(makeRes({ writableEnded: true }))).resolves.toBeUndefined();+ });++ it('resolves immediately when the response is destroyed', async () => {+ await expect(awaitWritableDrain(makeRes({ destroyed: true }))).resolves.toBeUndefined();+ });++ it('waits for `drain` and tears down both listeners on settle', async () => {+ const res = makeRes();+ let settled = false;+ const p = awaitWritableDrain(res).then(() => { settled = true; });++ expect(res.listenerCount('drain')).toBe(1);+ expect(res.listenerCount('close')).toBe(1);+ expect(settled).toBe(false);++ res.emit('drain');+ await p;++ expect(settled).toBe(true);+ expect(res.listenerCount('drain')).toBe(0);+ expect(res.listenerCount('close')).toBe(0);+ });++ it('also settles (and cleans up) when the client disconnects mid-drain', async () => {+ const res = makeRes();+ const p = awaitWritableDrain(res);++ res.emit('close');+ await p;++ expect(res.listenerCount('drain')).toBe(0);+ expect(res.listenerCount('close')).toBe(0);+ });+});diff --git a/server/routes/ask.js b/server/routes/ask.jsindex 07cb115c26..3469f4b4a9 100644--- a/server/routes/ask.js+++ b/server/routes/ask.js@@ -22,6 +22,7 @@ import { Router } from 'express';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';+import { awaitWritableDrain } from '../lib/streamBackpressure.js';import * as convs from '../services/askConversations.js';import { runAsk, VALID_MODES } from '../services/askService.js';import { ID_RE as CONV_ID_RE } from '../services/askConversations.js';@@ -171,10 +172,8 @@ router.post('/', asyncHandler(async (req, res) => {// Honour socket backpressure — for long answers with many delta frames,// a slow reader could otherwise force Node to buffer unbounded SSE data- // in memory. If `res.write` returns false, await the next `drain` (or- // `close`) before queuing more frames. Both listeners are torn down on- // settle so a slow client that disconnects mid-drain doesn't leak- // listeners.+ // in memory. If `res.write` returns false, `awaitWritableDrain` parks on+ // the next `drain` (or `close`) before we queue more frames.//// Guard the write itself: between the `aborted` check and the syscall,// the socket can transition to destroyed, in which case `res.write` would@@ -191,17 +190,7 @@ router.post('/', asyncHandler(async (req, res) => {onClose();return;}- if (!writeOk) {- await new Promise((resolve) => {- const settle = () => {- res.off('drain', settle);- res.off('close', settle);- resolve();- };- res.once('drain', settle);- res.once('close', settle);- });- }+ if (!writeOk) await awaitWritableDrain(res);};// Tell the client the conversation id up-front so it can deep-link the URLdiff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex d1b97d347f..ff4ba570a2 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -30,6 +30,7 @@ import {} from '../services/localLlm.js'import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js'import { abortSignalFromResponse } from '../lib/requestAbort.js'+import { awaitWritableDrain } from '../lib/streamBackpressure.js'import { getLoadedModels as getLoadedOllamaModels, unloadModel as unloadOllamaModel } from '../services/ollamaManager.js'const router = Router()@@ -252,27 +253,17 @@ router.post('/test/stream', asyncHandler(async (req, res) => {// here. A write after the client disconnected can throw ERR_STREAM_WRITE_AFTER_END;// treat any failure as a dead socket and drop the frame.//- // Honour socket backpressure (mirrors ask.js): when `res.write` returns false the- // kernel/send buffer is full, so await the next `drain` (or `close`) before letting- // the producer queue more NDJSON. A fast local model writing to a slow reader would- // otherwise buffer the whole response in memory. The producer awaits `onToken`, so- // returning this promise actually pauses the upstream read until the socket catches- // up. Both listeners are torn down on settle so a disconnect mid-drain can't leak them.+ // Honour socket backpressure: when `res.write` returns false the kernel/send+ // buffer is full, so await the next `drain` before letting the producer queue+ // more NDJSON. A fast local model writing to a slow reader would otherwise+ // buffer the whole response in memory. The producer awaits `onToken`, so+ // returning this promise actually pauses the upstream read until the socket+ // catches up. (`awaitWritableDrain` is the same helper routes/ask.js uses.)const write = async (frame) => {if (res.writableEnded || res.destroyed) returnlet writeOktry { writeOk = res.write(`${JSON.stringify(frame)}\n`) } catch { return /* client gone */ }- if (!writeOk) {- await new Promise((resolve) => {- const settle = () => {- res.off('drain', settle)- res.off('close', settle)- resolve()- }- res.once('drain', settle)- res.once('close', settle)- })- }+ if (!writeOk) await awaitWritableDrain(res)}// `runLocalLlmTest` resolves for in-stream failures, but can still THROW before