diff --git a/packages/daemon/src/server/__tests__/upload-http-deadline.test.ts b/packages/daemon/src/server/__tests__/upload-http-deadline.test.ts index 8ae44ae0ff..c08d70ea6b 100644 --- a/packages/daemon/src/server/__tests__/upload-http-deadline.test.ts +++ b/packages/daemon/src/server/__tests__/upload-http-deadline.test.ts @@ -7,6 +7,11 @@ import net from 'node:net'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { createDaemonHttpServer } from '../http/http-server.ts'; import { cleanupUploadedArtifact } from '../../resources/artifact-tracking.ts'; +import { + readResponses, + watchAcceptedArtifactBytes, + watchServer, +} from './upload-loopback.fixtures.ts'; import { closeLoopbackServer, listenOnLoopback, @@ -45,19 +50,6 @@ async function flushIO(): Promise { for (let i = 0; i < 100; i += 1) await new Promise((r) => setImmediate(r)); } -/** Settles on the socket data that completes the text, however long the server's real IO takes. */ -function receivedText(socket: net.Socket, isComplete: () => boolean): Promise { - return new Promise((resolve) => { - const check = () => { - if (!isComplete()) return; - socket.off('data', check); - resolve(); - }; - socket.on('data', check); - check(); - }); -} - function routeRequest(port: number, options: http.RequestOptions, body?: string | Buffer) { return new Promise((resolve, reject) => { const req = http.request({ host: '127.0.0.1', port, agent: false, ...options }, (res) => { @@ -241,6 +233,7 @@ test('a finalize whose hash crosses the deadline never publishes success', async test('a queued 308 behind a long finalize never closes the socket under the earlier answer', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const { server, port } = await startServer(); + const watch = watchServer(server); const reads = holdPayloadReads((path) => String(path).endsWith('/payload')); try { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); @@ -278,12 +271,9 @@ test('a queued 308 behind a long finalize never closes the socket under the earl // One keep-alive socket: a complete finalize for A, then a stale-offset PUT for B whose // body stays unfinished. B's 308 queues behind A's long hash. const socket = net.connect(port, '127.0.0.1'); - let received = ''; + const client = readResponses(socket); const closed = new Promise((resolve) => socket.once('close', () => resolve())); - socket.on('data', (data: Buffer) => { - received += data.toString('latin1'); - }); - socket.on('error', () => {}); + const bAnswered = watch.answered(`/upload/direct/${uploadB}`); const finalizeBody = JSON.stringify({ uploadId: uploadA }); socket.write( `POST /upload/finalize HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + @@ -292,17 +282,18 @@ test('a queued 308 behind a long finalize never closes the socket under the earl `Transfer-Encoding: chunked\r\n\r\n1\r\na\r\n`, ); await withIO(reads.started.promise, 'the held finalize hash'); - await flushIO(); + // B's 308 is committed (queued behind A) before the clock moves. + await withIO(bAnswered, "B's queued 308"); // B's inactivity ceiling passes while A's in-budget hash still owns the socket. await vi.advanceTimersByTimeAsync(150_000); await flushIO(); assert.equal(socket.destroyed, false, 'the socket survives B timing out behind A'); reads.release.resolve(); + const [answerA, answerB] = await withIO(client.responses(2), 'both answers'); await withIO(closed, 'the socket close after both answers'); - const statuses = [...received.matchAll(/HTTP\/1\.1 (\d+)/g)].map((match) => match[1]); - assert.equal(statuses[0], '200', 'A finalizes with its own answer'); - assert.equal(statuses[1], '308', "B's queued answer follows"); - const artifact = received.match(/"uploadId":"([^"]+)"/)?.[1]; + assert.equal(answerA?.status, 200, 'A finalizes with its own answer'); + assert.equal(answerB?.status, 308, "B's queued answer follows"); + const artifact = answerA?.body.match(/"uploadId":"([^"]+)"/)?.[1]; if (artifact) cleanupUploadedArtifact(artifact); } finally { reads.release.resolve(); @@ -630,6 +621,7 @@ function pipelinedFinalizeThenStreamingPut(port: number, uploadA: string, upload test('an expired queued request with an unread body never resets the earlier answer', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const { server, port } = await startServer(); + const watch = watchServer(server); try { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); // A reset on close with unread body bytes is timing dependent, so the case repeats. @@ -665,10 +657,12 @@ test('an expired queued request with an unread body never resets the earlier ans ), 'seed B', ); + const bAnswered = watch.answered(`/upload/direct/${uploadB}`); const pipelined = pipelinedFinalizeThenStreamingPut(port, uploadA, uploadB); void pipelined.outcome.catch(() => {}); await withIO(reads.started.promise, 'the held finalize hash'); - await flushIO(); + // B's 308 is committed (queued behind A) before the clock moves. + await withIO(bAnswered, "B's queued 308"); // B's inactivity ceiling passes while queued behind A's in-budget hash. await vi.advanceTimersByTimeAsync(150_000); reads.release.resolve(); @@ -695,6 +689,7 @@ test('an expired queued request with an unread body never resets the earlier ans test('guard: a single-shot upload expiring behind a long finalize keeps the earlier answer first', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const { server, port } = await startServer(); + const watch = watchServer(server); const reads = holdPayloadReads((path) => String(path).endsWith('/payload')); try { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); @@ -717,11 +712,9 @@ test('guard: a single-shot upload expiring behind a long finalize keeps the earl // One keep-alive socket: a finalize for A (hash held), then a single-shot upload B // whose body stalls after its first bytes. const socket = net.connect(port, '127.0.0.1'); - let received = ''; - socket.on('data', (data: Buffer) => { - received += data.toString('latin1'); - }); - socket.on('error', () => {}); + const client = readResponses(socket); + const bAdmitted = watch.admitted('/upload'); + const bAnswered = watch.answered('/upload'); const finalizeBody = JSON.stringify({ uploadId: uploadA }); socket.write( `POST /upload/finalize HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + @@ -730,18 +723,21 @@ test('guard: a single-shot upload expiring behind a long finalize keeps the earl `X-Artifact-Type: file\r\nX-Artifact-Filename: single.bin\r\nContent-Length: 1000\r\n\r\n0123456789`, ); await withIO(reads.started.promise, 'the held finalize hash'); - await flushIO(); + // B's ingress is admitted, so its own 120 s ceiling runs on the fake clock. + await withIO(bAdmitted, 'B admitted'); // B's 120 s inactivity ceiling passes while A's in-budget hash still owns the socket. await vi.advanceTimersByTimeAsync(150_000); - await flushIO(); + await withIO(bAnswered, "B's typed expiry, queued behind A"); assert.equal(socket.destroyed, false, "B's expiry does not close the socket under A"); reads.release.resolve(); - const answers = receivedText(socket, () => (received.match(/HTTP\/1\.1 /g) ?? []).length >= 2); - await withIO(answers, 'both answers'); - const statuses = [...received.matchAll(/HTTP\/1\.1 (\d+)/g)].map((match) => match[1]); - assert.deepEqual(statuses, ['200', '500'], 'A finalizes, then B answers its typed expiry'); - assert.match(received, /"reason":"transfer_phase_timeout"/); - const artifact = received.match(/"uploadId":"([^"]+)"/)?.[1]; + const responses = await withIO(client.responses(2), 'both answers'); + assert.deepEqual( + responses.map((response) => response.status), + [200, 500], + 'A finalizes, then B answers its typed expiry', + ); + assert.equal(JSON.parse(responses[1]?.body ?? '{}').reason, 'transfer_phase_timeout'); + const artifact = responses[0]?.body.match(/"uploadId":"([^"]+)"/)?.[1]; if (artifact) cleanupUploadedArtifact(artifact); socket.destroy(); } finally { @@ -759,56 +755,32 @@ test('a single-shot upload that expires mid-body answers a client that is still vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); // A reset on close with unread body bytes is timing dependent, so the case repeats. for (let attempt = 0; attempt < 5; attempt += 1) { + const watch = watchServer(server); + const accepted = watchAcceptedArtifactBytes(`single-${attempt}.bin`); const socket = net.connect({ port, host: '127.0.0.1', allowHalfOpen: true }); - let received = ''; - let answered = false; - const socketErrors: unknown[] = []; - socket.on('error', (error) => socketErrors.push(error)); - // Resolves once the typed answer is read completely; rejects on a reset before it. - const answer = new Promise((resolve, reject) => { - socket.on('data', (data: Buffer) => { - received += data.toString('latin1'); - if (!answered && /\r\n\r\n\{.*\}$/s.test(received)) { - answered = true; - resolve(received); - } - }); - socket.on('error', (error) => { - if (!answered) reject(error); - }); - }); - void answer.catch(() => {}); - socket.write( - `POST /upload HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + - `X-Artifact-Type: file\r\nX-Artifact-Filename: single.bin\r\nContent-Length: ${64 * 1024 * 1024}\r\n\r\n`, - ); - const chunk = Buffer.alloc(64 * 1024, 0x61); - // The body keeps making progress, so only the 600 s aggregate can end it. The last - // step stops 1 s past the aggregate, inside the expired request's lingering grace. - for (let step = 0; step < 10 && !answered; step += 1) { - socket.write(chunk); - await flushIO(); - await vi.advanceTimersByTimeAsync(step < 9 ? 61_000 : 52_000); - } - // The client is still sending when its typed answer arrives, as the remote upload - // client does until it reads the answer. - let sent = 0; - const pump = () => { - while (!answered && sent < 16 * 1024 * 1024 && socket.writable) { - sent += chunk.length; - if (!socket.write(chunk)) { - socket.once('drain', pump); - return; - } - } - }; - pump(); + const client = readResponses(socket); try { - const read = await withIO(answer, 'the typed answer to a client still sending'); - assert.match(read, /^HTTP\/1\.1 500 /); - // Under load a progress write can land after the 120 s ceiling; either typed - // expiry is the owner's answer. - assert.match(read, /"reason":"transfer_(ingress_deadline_exceeded|phase_timeout)"/); + const admitted = watch.admitted('/upload'); + socket.write( + `POST /upload HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + + `X-Artifact-Type: file\r\nX-Artifact-Filename: single-${attempt}.bin\r\n` + + `Content-Length: ${64 * 1024 * 1024}\r\n\r\n`, + ); + await withIO(admitted, 'the upload admitted'); + const chunk = Buffer.alloc(64 * 1024, 0x61); + // The body keeps making progress: each step's bytes are accepted before the clock + // moves 61 s, so only the 600 s aggregate can end it. The last step lands 1 s past + // the aggregate, inside the expired request's lingering grace. + for (let step = 0; step < 10; step += 1) { + socket.write(chunk); + await withIO(accepted.reached((step + 1) * chunk.length), 'the step accepted'); + await vi.advanceTimersByTimeAsync(step < 9 ? 61_000 : 52_000); + } + // The client is still sending when its typed answer arrives, as the remote upload + // client does until it reads the answer. + const [answer] = await withIO(client.responses(1), 'the typed answer'); + assert.equal(answer?.status, 500); + assert.equal(JSON.parse(answer?.body ?? '{}').reason, 'transfer_ingress_deadline_exceeded'); // The expiry did not destroy the connection: the server lingers and discards, so a // client that has not read its answer yet keeps sending without a reset. const sentAfterAnswer = new Promise((resolve, reject) => { @@ -828,15 +800,14 @@ test('a single-shot upload that expires mid-body answers a client that is still pumpMore(); }); await withIO(sentAfterAnswer, 'the body bytes sent after the answer'); - await flushIO(); - assert.equal(socket.destroyed, false, 'the server did not reset the connection'); - // The server closes cleanly: it half-closed with a FIN after the answer, and its - // lingering grace ends the connection without a reset. + // The server half-closed with a FIN after its answer, and its lingering grace then + // ends the connection without a reset. + await withIO(client.ended, "the server's FIN"); await vi.advanceTimersByTimeAsync(5_000); - await flushIO(); - assert.equal(socket.readableEnded, true, 'the server sent a FIN, not a reset'); - assert.deepEqual(socketErrors, [], 'no reset reached the client'); + await withIO(watch.connectionsClosed(), 'the server close after the grace'); + assert.deepEqual(client.errors, [], 'no reset reached the client'); } finally { + accepted.restore(); socket.destroy(); } } @@ -892,16 +863,12 @@ test('a hash mismatch found past the deadline answers the deadline expiry', asyn test('a chunk refused by its byte cap lingers only for the grace, not the inactivity ceiling', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const { server, port } = await startServer(); + const watch = watchServer(server); try { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); const uploadId = await withIO(preflight(port, Buffer.alloc(0), 4), 'the preflight'); const socket = net.connect({ port, host: '127.0.0.1', allowHalfOpen: true }); - let received = ''; - socket.on('data', (data: Buffer) => { - received += data.toString('latin1'); - }); - socket.on('error', () => {}); - const ended = new Promise((resolve) => socket.once('end', () => resolve())); + const client = readResponses(socket); // A chunked body that overruns its 2-byte range: the limiter refuses it mid-body. const chunk = Buffer.alloc(64 * 1024, 0x61); socket.write( @@ -911,19 +878,18 @@ test('a chunk refused by its byte cap lingers only for the grace, not the inacti socket.write( Buffer.concat([Buffer.from(`${chunk.length.toString(16)}\r\n`), chunk, Buffer.from('\r\n')]), ); - const answer = receivedText(socket, () => /\r\n\r\n\{.*\}$/s.test(received)); - await withIO(answer, 'the byte-cap answer'); - assert.match(received, /^HTTP\/1\.1 400 /); + const [answer] = await withIO(client.responses(1), 'the byte-cap answer'); + assert.equal(answer?.status, 400); // The rest of the refused body is discarded for at most the grace, then the server // closes its side of the connection, long before the 120 s inactivity ceiling. - await withIO(ended, "the server's half-close after its answer"); + await withIO(client.ended, "the server's half-close after its answer"); const openConnections = () => new Promise((resolve, reject) => server.getConnections((error, count) => (error ? reject(error) : resolve(count))), ); - assert.equal(await openConnections(), 1); + assert.equal(await openConnections(), 1, 'the connection lingers until the grace'); await vi.advanceTimersByTimeAsync(5_000); - await flushIO(); + await withIO(watch.connectionsClosed(), 'the server close after the grace'); assert.equal(await openConnections(), 0, 'the grace closed the connection'); socket.destroy(); } finally { @@ -936,15 +902,11 @@ for (const route of ['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/upload/preflight', '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/upload/finalize']) { test(`an oversized JSON body on ${route} gets its 400 and a clean close while the client keeps sending`, async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const { server, port } = await startServer(); + const watch = watchServer(server); try { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); const socket = net.connect({ port, host: '127.0.0.1', allowHalfOpen: true }); - let received = ''; - const socketErrors: unknown[] = []; - socket.on('error', (error) => socketErrors.push(error)); - socket.on('data', (data: Buffer) => { - received += data.toString('latin1'); - }); + const client = readResponses(socket); // A chunked body declares no length, so the reader refuses it as it passes 64 KiB. socket.write( `POST ${route} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + @@ -975,19 +937,19 @@ for (const route of ['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/upload/preflight', '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/upload/finalize']) { pump(); }); await withIO(sent, 'the oversized body sent past the refusal'); - await flushIO(); - assert.match(received, /^HTTP\/1\.1 400 /, 'the client reads its typed refusal'); - assert.equal(socket.readableEnded, true, 'the server half-closed with a FIN'); - assert.deepEqual(socketErrors, [], 'no reset reached the client'); + const [answer] = await withIO(client.responses(1), 'the typed refusal'); + assert.equal(answer?.status, 400, 'the client reads its typed refusal'); + await withIO(client.ended, 'the server half-close with a FIN'); + assert.deepEqual(client.errors, [], 'no reset reached the client'); // After its lingering grace the server closes the connection. const openConnections = () => new Promise((resolve, reject) => server.getConnections((error, count) => (error ? reject(error) : resolve(count))), ); await vi.advanceTimersByTimeAsync(5_000); - await flushIO(); + await withIO(watch.connectionsClosed(), 'the server close after the grace'); assert.equal(await openConnections(), 0); - assert.deepEqual(socketErrors, []); + assert.deepEqual(client.errors, []); socket.destroy(); } finally { vi.useRealTimers(); diff --git a/packages/daemon/src/server/__tests__/upload-http-socket-ownership.test.ts b/packages/daemon/src/server/__tests__/upload-http-socket-ownership.test.ts index a025fcf971..77b5dd728c 100644 --- a/packages/daemon/src/server/__tests__/upload-http-socket-ownership.test.ts +++ b/packages/daemon/src/server/__tests__/upload-http-socket-ownership.test.ts @@ -32,10 +32,6 @@ async function withIO(pending: Promise, label: string): Promise { } } -async function flushIO(): Promise { - for (let i = 0; i < 100; i += 1) await new Promise((r) => setImmediate(r)); -} - async function startServer(env: NodeJS.ProcessEnv = process.env) { const server = await createDaemonHttpServer({ token: TOKEN, @@ -138,10 +134,13 @@ test('the second of two pipelined uploads reads its early 308 while it is still type HeldHookCall = { signal?: AbortSignal }; const HELD_HOOK_CALLS = '__agentDeviceHeldUploadAuthHook'; -function heldHookCalls(): HeldHookCall[] { +/** The held hook reports each call here, so a test waits on the call, not on loop turns. */ +type HeldHookLog = { calls: HeldHookCall[]; onCall?: (call: HeldHookCall) => void }; + +function heldHookLog(): HeldHookLog { const store = globalThis as Record; - store[HELD_HOOK_CALLS] ??= []; - return store[HELD_HOOK_CALLS] as HeldHookCall[]; + store[HELD_HOOK_CALLS] ??= { calls: [] }; + return store[HELD_HOOK_CALLS] as HeldHookLog; } async function startHeldHookServer() { @@ -151,20 +150,37 @@ async function startHeldHookServer() { fs.writeFileSync( hookPath, `export default (context) => { - const calls = (globalThis[${JSON.stringify(HELD_HOOK_CALLS)}] ??= []); - calls.push({ signal: context.signal }); + const log = (globalThis[${JSON.stringify(HELD_HOOK_CALLS)}] ??= { calls: [] }); + const call = { signal: context.signal }; + log.calls.push(call); + log.onCall?.(call); return new Promise(() => {}); };\n`, ); - heldHookCalls().length = 0; + const log = heldHookLog(); + log.calls.length = 0; + log.onCall = undefined; return await startServer({ ...process.env, AGENT_DEVICE_HTTP_AUTH_HOOK: hookPath }); } async function waitForHookCall(): Promise { - for (let i = 0; i < 50 && heldHookCalls().length === 0; i += 1) await flushIO(); - const [call] = heldHookCalls(); - assert.ok(call, 'the auth hook was called'); - return call; + const log = heldHookLog(); + const [first] = log.calls; + if (first) return first; + return await withIO( + new Promise((resolve) => { + log.onCall = resolve; + }), + 'the auth hook call', + ); +} + +/** Resolves when the signal aborts. */ +function aborted(signal: AbortSignal | undefined): Promise { + if (!signal || signal.aborted) return Promise.resolve(); + return new Promise((resolve) => + signal.addEventListener('abort', () => resolve(), { once: true }), + ); } test('a held auth hook sees the upload ingress deadline through its signal', async (t) => { @@ -224,7 +240,7 @@ test('a held auth hook sees a client disconnect through its signal', async (t) = req.end('{}'); const call = await waitForHookCall(); req.destroy(); - for (let i = 0; i < 50 && !call.signal?.aborted; i += 1) await flushIO(); + await withIO(aborted(call.signal), 'the hook signal abort on disconnect'); assert.equal(call.signal?.aborted, true, 'the hook signal aborts on disconnect'); const reason = call.signal?.reason as AppError | undefined; assert.equal(reason?.details?.reason, 'request_canceled'); diff --git a/packages/daemon/src/server/__tests__/upload-loopback.fixtures.ts b/packages/daemon/src/server/__tests__/upload-loopback.fixtures.ts new file mode 100644 index 0000000000..53a9c5f3b8 --- /dev/null +++ b/packages/daemon/src/server/__tests__/upload-loopback.fixtures.ts @@ -0,0 +1,207 @@ +import fs from 'node:fs'; +import type http from 'node:http'; +import type net from 'node:net'; +import { vi } from 'vitest'; + +/** + * Observes the server's own answers, so a test waits on the server's state instead of + * counting event-loop turns: `admitted(path)` resolves when the next request for exactly + * that path (query aside) reaches the route callback, and `answered(path)` when the server + * has ended its response (written, or queued behind an earlier pipelined answer). + */ +export function watchServer(server: http.Server) { + const admitted = new Map void>>(); + const answered = new Map void>>(); + const seen = { admitted: [] as string[], answered: [] as string[] }; + const notify = (map: Map void>>, list: string[], url: string) => { + list.push(url); + for (const [path, waiters] of map) { + if (url.split('?')[0] !== path || waiters.length === 0) continue; + waiters.shift()?.(); + return; + } + }; + const closed: Array> = []; + server.on('connection', (socket: net.Socket) => { + closed.push(new Promise((resolve) => socket.once('close', () => resolve()))); + }); + server.prependListener('request', (req: http.IncomingMessage, res: http.ServerResponse) => { + const url = req.url ?? ''; + notify(admitted, seen.admitted, url); + const end = res.end.bind(res) as (...args: unknown[]) => http.ServerResponse; + let ended = false; + res.end = ((...args: unknown[]) => { + const result = end(...args); + if (!ended) { + ended = true; + notify(answered, seen.answered, url); + } + return result; + }) as typeof res.end; + }); + const waitFor = (map: Map void>>, path: string) => + new Promise((resolve) => { + const waiters = map.get(path) ?? []; + waiters.push(resolve); + map.set(path, waiters); + }); + return { + admitted: (path: string) => waitFor(admitted, path), + answered: (path: string) => waitFor(answered, path), + /** Resolves when every server-side connection accepted so far has closed. */ + connectionsClosed: () => Promise.all(closed).then(() => undefined), + }; +} + +export type ParsedResponse = { status: number; headers: Record; body: string }; + +/** + * Collects the HTTP/1.1 responses a raw client socket receives. `responses(count)` resolves + * once that many responses are complete (headers plus a Content-Length body), whatever the + * TCP chunking, and rejects when a reset or the server's FIN arrives first; `ended` resolves on + * the server's FIN; `errors` records any reset. + */ +export function readResponses(socket: net.Socket) { + let buffer = ''; + const parsed: ParsedResponse[] = []; + const waiters: Array<{ + count: number; + resolve: (responses: ParsedResponse[]) => void; + reject: (reason: unknown) => void; + }> = []; + const errors: unknown[] = []; + let finished: Error | undefined; + // A reset or a FIN before the awaited responses is the failure to report, not a 3 s wait. + const fail = (reason: Error): void => { + finished ??= reason; + for (const waiter of waiters.splice(0)) waiter.reject(reason); + }; + const parse = () => { + for (;;) { + const next = parseOneResponse(buffer); + if (!next) return; + parsed.push(next.response); + buffer = buffer.slice(next.consumed); + } + }; + socket.on('data', (data: Buffer) => { + buffer += data.toString('latin1'); + parse(); + for (const waiter of waiters.slice()) { + if (parsed.length < waiter.count) continue; + waiters.splice(waiters.indexOf(waiter), 1); + waiter.resolve(parsed.slice(0, waiter.count)); + } + }); + socket.on('error', (error) => { + errors.push(error); + fail(error); + }); + const ended = new Promise((resolve) => socket.once('end', () => resolve())); + socket.once('end', () => + fail(new Error(`the connection ended after ${parsed.length} complete response(s)`)), + ); + return { + errors, + ended, + responses: (count: number) => { + if (parsed.length >= count) return Promise.resolve(parsed.slice(0, count)); + if (finished) return Promise.reject(finished); + return new Promise((resolve, reject) => + waiters.push({ count, resolve, reject }), + ); + }, + }; +} + +/** + * Counts the body bytes a single-shot upload has written to its artifact file, so a test + * moves the fake clock only after the server accepted the progress it just sent. + */ +export function watchAcceptedArtifactBytes(fileName: string) { + let accepted = 0; + const waiters: Array<{ bytes: number; resolve: () => void }> = []; + const createWriteStream = fs.createWriteStream; + const spy = vi.spyOn(fs, 'createWriteStream').mockImplementation((path, options) => { + if (!String(path).endsWith(`/${fileName}`)) return createWriteStream(path, options); + return createWriteStream(path, { + ...(typeof options === 'object' ? options : {}), + fs: { + open: fs.open, + close: fs.close, + write(fd, buffer, offset, length, position, callback) { + fs.write(fd, buffer, offset, length, position, (error, written, data) => { + if (!error) { + accepted += written; + for (const waiter of waiters.slice()) { + if (accepted < waiter.bytes) continue; + waiters.splice(waiters.indexOf(waiter), 1); + waiter.resolve(); + } + } + callback(error, written, data); + }); + }, + }, + }); + }); + return { + reached: (bytes: number) => + accepted >= bytes + ? Promise.resolve() + : new Promise((resolve) => waiters.push({ bytes, resolve })), + restore: () => spy.mockRestore(), + }; +} + +/** Parses one complete response from the front of `buffer`, or undefined while it is partial. */ +function parseOneResponse( + buffer: string, +): { response: ParsedResponse; consumed: number } | undefined { + const headerEnd = buffer.indexOf('\r\n\r\n'); + if (headerEnd === -1) return undefined; + const [statusLine = '', ...lines] = buffer.slice(0, headerEnd).split('\r\n'); + const headers = parseHeaderLines(lines); + const bodyStart = headerEnd + 4; + const body = + headers['transfer-encoding'] === 'chunked' + ? readChunkedBody(buffer, bodyStart) + : readLengthBody(buffer, bodyStart, Number(headers['content-length'] ?? '0')); + if (!body) return undefined; + return { + response: { status: Number(statusLine.split(' ')[1]), headers, body: body.text }, + consumed: body.end, + }; +} + +function parseHeaderLines(lines: string[]): Record { + const headers: Record = {}; + for (const line of lines) { + const colon = line.indexOf(':'); + headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim(); + } + return headers; +} + +function readLengthBody( + buffer: string, + start: number, + length: number, +): { text: string; end: number } | undefined { + if (buffer.length < start + length) return undefined; + return { text: buffer.slice(start, start + length), end: start + length }; +} + +function readChunkedBody(buffer: string, start: number): { text: string; end: number } | undefined { + let text = ''; + let cursor = start; + for (;;) { + const sizeEnd = buffer.indexOf('\r\n', cursor); + if (sizeEnd === -1) return undefined; + const size = Number.parseInt(buffer.slice(cursor, sizeEnd), 16); + if (buffer.length < sizeEnd + 2 + size + 2) return undefined; + text += buffer.slice(sizeEnd + 2, sizeEnd + 2 + size); + cursor = sizeEnd + 2 + size + 2; + if (size === 0) return { text, end: cursor }; + } +}