Skip to content

Build your personal knowledge base with Trilium Notes

perf(desktop): apply backpressure in the protocol streaming bridge

Elian Doran6799ab3563bd
diff --git a/apps/desktop/src/protocol.spec.ts b/apps/desktop/src/protocol.spec.ts
index 8b489ac804..23a1772acf 100644
--- a/apps/desktop/src/protocol.spec.ts
+++ b/apps/desktop/src/protocol.spec.ts
@@ -1,3 +1,5 @@
+import { once } from "node:events";
+
import express from "express";
import multer from "multer";
import { describe, expect, it, vi } from "vitest";
@@ -213,6 +215,78 @@ describe("trilium-app protocol dispatcher", () => {
await expect(reader.read()).rejects.toThrow();
});
+ it("applies backpressure: res.write() returns false once the unread queue exceeds the high-water mark", async () => {
+ const app = express();
+ const writeResults: boolean[] = [];
+ app.get("/bp", (_req, res) => {
+ res.setHeader("Content-Type", "application/octet-stream");
+ res.flushHeaders();
+ // Write several 1 MiB chunks synchronously while nothing reads the
+ // body. Without backpressure these would all be buffered and return
+ // true; with it, the queue fills and writes start returning false.
+ for (let i = 0; i < 6; i++) {
+ writeResults.push(res.write(Buffer.alloc(1024 * 1024, i)));
+ }
+ res.end();
+ });
+
+ const response = await dispatch(app, new Request("trilium-app://app/bp"));
+ expect(writeResults).toContain(false);
+
+ // Backpressure is advisory: every chunk is still delivered intact.
+ const body = response.body;
+ if (!body) throw new Error("expected a streaming body");
+ const reader = body.getReader();
+ let total = 0;
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value?.length ?? 0;
+ }
+ expect(total).toBe(6 * 1024 * 1024);
+ });
+
+ it("emits 'drain' to resume a producer that paused on backpressure", async () => {
+ const app = express();
+ const order: string[] = [];
+ let routeFinished: () => void = () => {};
+ const routeDone = new Promise<void>((resolve) => { routeFinished = resolve; });
+
+ app.get("/bp2", async (_req, res) => {
+ res.setHeader("Content-Type", "application/octet-stream");
+ res.flushHeaders();
+ // Fill until backpressure. Capped so an implementation that never
+ // signals backpressure can't loop forever (it would just fail below).
+ let paused = false;
+ for (let i = 0; i < 64 && !paused; i++) {
+ paused = res.write(Buffer.alloc(1024 * 1024, i)) === false;
+ }
+ order.push(paused ? "paused" : "no-backpressure");
+ // Wait to be resumed, but never hang the suite if 'drain' never comes.
+ const outcome = await Promise.race([
+ once(res, "drain").then(() => "drained" as const),
+ new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), 3000))
+ ]);
+ order.push(outcome);
+ res.end();
+ routeFinished();
+ });
+
+ const response = await dispatch(app, new Request("trilium-app://app/bp2"));
+ const body = response.body;
+ if (!body) throw new Error("expected a streaming body");
+ const reader = body.getReader();
+ // Draining the queue frees capacity, which pulls the stream and must emit
+ // 'drain' so the paused producer continues.
+ while (true) {
+ const { done } = await reader.read();
+ if (done) break;
+ }
+ await routeDone;
+
+ expect(order).toEqual(["paused", "drained"]);
+ });
+
it("returns a 500 Response when dispatch throws inside the protocol handler", async () => {
electronMock.handle.mockReset();
setupTriliumAppProtocol(express());
diff --git a/apps/desktop/src/protocol.ts b/apps/desktop/src/protocol.ts
index 2cc057b278..0e0f02c7b4 100644
--- a/apps/desktop/src/protocol.ts
+++ b/apps/desktop/src/protocol.ts
@@ -282,15 +282,33 @@ function installStreamingBridge(
): StreamingBridge {
let streaming = false;
let controller: ReadableStreamDefaultController<Uint8Array> | null = null;
+ // Set when write() signalled backpressure (returned false). The producer
+ // (e.g. archiver's pipe) then pauses until we emit a 'drain' event.
+ let producerPaused = false;
const origWrite = res.write.bind(res);
const origEnd = res.end.bind(res);
+ // Bound how much streamed-but-unread data sits in the queue. Without this a
+ // consumer slower than the producer — e.g. Electron writing a multi-GB
+ // export to disk — would let the whole payload pile up in memory.
+ const HIGH_WATER_MARK = 1024 * 1024; // 1 MiB
+
+ function resumeProducerIfReady() {
+ if (producerPaused && controller && controller.desiredSize !== null && controller.desiredSize > 0) {
+ producerPaused = false;
+ res.emit("drain");
+ }
+ }
+
function commit() {
if (streaming) return;
streaming = true;
const body = new ReadableStream<Uint8Array>({
- start(c) { controller = c; }
- });
+ start(c) { controller = c; },
+ // The consumer pulled (queue has capacity again) → release a producer
+ // that paused on backpressure.
+ pull() { resumeProducerIfReady(); }
+ }, new ByteLengthQueuingStrategy({ highWaterMark: HIGH_WATER_MARK }));
try {
onCommit(new Response(body, {
/* v8 ignore next -- defensive: statusCode is always set before flushHeaders */
@@ -332,6 +350,12 @@ function installStreamingBridge(
write(chunk: unknown, ...rest: unknown[]): boolean {
if (streaming) {
enqueue(chunk);
+ // Honour backpressure: once the queue is full, tell the producer
+ // to pause until the consumer drains it (pull → 'drain').
+ if (controller && controller.desiredSize !== null && controller.desiredSize <= 0) {
+ producerPaused = true;
+ return false;
+ }
return true;
}
return (origWrite as (...a: unknown[]) => boolean)(chunk, ...rest);