A desktop coding agent with free access to frontier models.
TypeScript
fix: stream box tars to disk with backpressure
ogsamrat70214b3f63b3
diff --git a/apps/server/src/box/client-tar.test.ts b/apps/server/src/box/client-tar.test.tsnew file mode 100644index 00000000..b8ac0603--- /dev/null+++ b/apps/server/src/box/client-tar.test.ts@@ -0,0 +1,80 @@+import { afterEach, describe, expect, test } from "bun:test";+import { createHash } from "node:crypto";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import net from "node:net";+import os from "node:os";+import path from "node:path";++import { request, tarTo, type BoxEndpoint } from "./client.js";++// The box client's tar stream (tarTo): a large tar goes to disk with+// backpressure, and the connection waits while the consumer catches up.+// A fake boxd speaks the wire format over TCP.++const frame = (kind: number, payload: Buffer) => {+ const head = Buffer.alloc(5);+ head[0] = kind;+ head.writeUInt32BE(payload.length, 1);+ return Buffer.concat([head, payload]);+};++const cleanup: Array<() => void> = [];+afterEach(() => {+ for (const fn of cleanup.splice(0)) fn();+});++/** A boxd that answers any op with `count` data frames of `size` bytes, then exit 0, as fast as the socket lets it. */+async function streamingBoxd(count: number, size: number): Promise<{ box: BoxEndpoint; sent: { frames: number } }> {+ const sent = { frames: 0 };+ const server = net.createServer((socket) => {+ socket.on("error", () => undefined);+ socket.once("data", async () => {+ for (let index = 0; index < count; index += 1) {+ sent.frames += 1;+ if (!socket.write(frame(0x64, Buffer.alloc(size, index % 251)))) await new Promise((resolve) => socket.once("drain", resolve));+ if (socket.destroyed) return;+ }+ socket.end(frame(0x78, Buffer.from(JSON.stringify({ code: 0, ms: 1 }))));+ });+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ cleanup.push(() => server.close());+ const address = server.address();+ return { box: { host: "127.0.0.1", port: typeof address === "object" && address ? address.port : 0, token: "t" }, sent };+}++describe("box client tar", () => {+ test("tarTo streams a large tar to disk, whole and hashed", async () => {+ const count = 256;+ const size = 256 * 1024;+ const { box } = await streamingBoxd(count, size);+ const dir = mkdtempSync(path.join(os.tmpdir(), "omnirush-tar-"));+ cleanup.push(() => rmSync(dir, { recursive: true, force: true }));+ const file = path.join(dir, "turn.tar");+ const result = await tarTo(box, ["/opt"], file);+ const written = readFileSync(file);+ expect(result.bytes).toBe(count * size);+ expect(written.length).toBe(count * size);+ expect(result.sha256).toBe(createHash("sha256").update(written).digest("hex"));+ });++ test("an onData promise holds the connection until it settles", async () => {+ const { box, sent } = await streamingBoxd(400, 64 * 1024);+ let calls = 0;+ let release: () => void = () => undefined;+ const held = new Promise<void>((resolve) => (release = resolve));+ const done = request(box, { op: "tar", paths: [] }, { onData: () => ((calls += 1) === 1 ? held : undefined) });+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(calls).toBeLessThan(400);+ expect(sent.frames).toBeLessThan(400);+ release();+ const result = await done;+ expect(result.exit.code).toBe(0);+ expect(calls).toBe(400);+ });++ test("tarTo fails with the file's error when the file cannot be written", async () => {+ const { box } = await streamingBoxd(4, 1024);+ await expect(tarTo(box, ["/opt"], path.join(os.tmpdir(), "omnirush-no-such-dir", "x", "turn.tar"))).rejects.toThrow(/ENOENT/);+ });+});diff --git a/apps/server/src/box/client.ts b/apps/server/src/box/client.tsindex db17e747..15f4dcf2 100644--- a/apps/server/src/box/client.ts+++ b/apps/server/src/box/client.ts@@ -7,6 +7,7 @@// launcher: readiness, the snapshot's stat/walk/tar, and toolchain probes.import { createHash } from "node:crypto";+import { once } from "node:events";import { createWriteStream } from "node:fs";import net from "node:net";@@ -30,12 +31,13 @@ function frame(kind: number, payload = Buffer.alloc(0)): Buffer {/*** One operation: resolves { exit, stdout, stderr, data } where data is the* concatenated Data frames (unless onData takes them). Rejects when the box- * cannot be reached or closes early.+ * cannot be reached or closes early. An onData that returns a promise holds+ * the connection (backpressure) until it settles; a rejection fails the call.*/export function request(box: BoxEndpoint,req: BoxRequest,- { onData, onStdout, onStderr, timeoutMs = 30_000, signal }: { onData?: (chunk: Buffer) => void; onStdout?: (chunk: Buffer) => void; onStderr?: (chunk: Buffer) => void; timeoutMs?: number; signal?: AbortSignal } = {},+ { onData, onStdout, onStderr, timeoutMs = 30_000, signal }: { onData?: (chunk: Buffer) => Promise<unknown> | null | void; onStdout?: (chunk: Buffer) => void; onStderr?: (chunk: Buffer) => void; timeoutMs?: number; signal?: AbortSignal } = {},): Promise<BoxReply> {return new Promise((resolve, reject) => {const socket = net.connect({ host: box.host || "127.0.0.1", port: box.port });@@ -74,7 +76,12 @@ export function request(else if (kind === T.stderr || kind === T.fail) (onStderr ? onStderr(payload) : err.push(Buffer.from(payload)));else if (kind === T.data) {if (onData) {- try { onData(payload); } catch (error) { finish(reject, error); return; }+ let wait: Promise<unknown> | null | void;+ try { wait = onData(payload); } catch (error) { finish(reject, error); return; }+ if (wait && typeof wait.then === "function" && !socket.isPaused()) {+ socket.pause();+ wait.then(() => { if (!settled) socket.resume(); }, (error: unknown) => finish(reject, error));+ }} else data.push(Buffer.from(payload));} else if (kind === T.exit) {let exit: BoxExit = { code: 0 };@@ -137,29 +144,45 @@ export async function walk(box: BoxEndpoint, roots: string[], { max = 400_000, treturn JSON.parse(result.data.toString("utf8"));}-/** Tar exactly these paths into `file`: { bytes, sha256, ms, warning }. */+/**+ * Tar exactly these paths into `file`: { bytes, sha256, ms, warning }. The+ * tar streams to disk: the box's connection waits while the file catches up.+ */export async function tarTo(box: BoxEndpoint, paths: string[], file: string, { timeoutMs = 15 * 60_000 }: { timeoutMs?: number } = {}): Promise<{ bytes: number; sha256: string; ms?: number; warning: string | null }> {const stream = createWriteStream(file, { mode: 0o600 });const hash = createHash("sha256");+ const controller = new AbortController();let bytes = 0;- let pending: Promise<unknown> = Promise.resolve();- const opened = new Promise((resolve, reject) => { stream.once("open", resolve); stream.once("error", reject); });- await opened;+ let draining: Promise<unknown> | null = null;+ let failed: Error | null = null;+ stream.on("error", (error) => {+ failed ??= error;+ controller.abort();+ });+ await once(stream, "open");let result: BoxReply;try {result = await request(box, { op: "tar", paths }, {timeoutMs,+ signal: controller.signal,onData: (chunk) => {const copy = Buffer.from(chunk);hash.update(copy);bytes += copy.length;- if (!stream.write(copy)) pending = new Promise<void>((resolve) => stream.once("drain", () => resolve()));+ // One drain wait at a time, however many frames arrive before it.+ if (!stream.write(copy) && !draining) {+ draining = once(stream, "drain").finally(() => { draining = null; });+ draining.catch(() => undefined); // a write error is `failed`+ }+ return draining;},});+ } catch (error) {+ throw failed ?? error;} finally {- await pending;await new Promise<void>((resolve) => stream.end(() => resolve()));}+ if (failed) throw failed;if (result.exit.code !== 0) throw new Error(`box tar failed: ${result.stderr.trim() || result.exit.code}`);return { bytes, sha256: hash.digest("hex"), ms: result.exit.ms, warning: result.stderr.trim() || null };}