diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index 84a3170300..ba2b80e738 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -5,16 +5,128 @@ import { buffer } from 'node:stream/consumers'; import { gunzipSync } from 'node:zlib'; import { expect, test, vi } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { AppError, isRequestCanceledError, normalizeError } from '@agent-device/kernel/errors'; import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; import * as command from '@agent-device/host-kit/command'; import { cleanupDownloadableArtifact, + listDownloadableArtifacts, openDownloadableArtifact, trackDownloadableArtifact, trackUploadedArtifact, type OpenedDownloadableArtifact, } from './artifact-tracking.ts'; +test.each(['cleanup', 'expiry'] as const)( + '%s aborts an inventory-only archive and removes its source after tar settles', + async (trigger) => { + const root = mkdtempForTestSync('fu-art-inventory-expiry-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), 'pending inventory archive'); + const runtime = createRuntimeStateHandle(); + let start!: () => void; + const started = new Promise((resolve) => { + start = resolve; + }); + let finish!: () => void; + const stopped = new Promise((resolve) => { + finish = resolve; + }); + let archivePath = ''; + let signal: AbortSignal | undefined; + const runCmd = command.runCmd; + const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + archivePath = String(args[1]?.[1]); + signal = args[2]?.signal; + fs.writeFileSync(archivePath, 'partial tar output'); + start(); + await stopped; + return await runCmd(...args); + }); + let listing: ReturnType | undefined; + try { + const timers = vi.spyOn(globalThis, 'setTimeout'); + let id: string; + let expire: (() => void) | undefined; + try { + id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + expire = timers.mock.calls.find(([, delay]) => delay === 15 * 60 * 1000)?.[0]; + } finally { + timers.mockRestore(); + } + listing = runtime.run(() => listDownloadableArtifacts(undefined, process.env)); + await started; + expect(fs.existsSync(archivePath)).toBe(true); + if (trigger === 'expiry') { + expect(expire).toBeTypeOf('function'); + runtime.run(() => expire!()); + } else { + runtime.run(() => cleanupDownloadableArtifact(id)); + } + expect(signal?.aborted).toBe(true); + expect(signal?.reason).toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'RESOURCE_EXPIRED' }, + }); + expect(fs.existsSync(artifactPath)).toBe(true); + expect(fs.existsSync(archivePath)).toBe(true); + finish(); + expect(await listing).toEqual([]); + expect(fs.existsSync(artifactPath)).toBe(false); + expect(fs.existsSync(path.dirname(archivePath))).toBe(false); + expect(archive).toHaveBeenCalledTimes(1); + } finally { + finish(); + if (listing) await listing; + runtime.dispose(); + archive.mockRestore(); + } + }, +); + +test('a missing cached directory archive is rebuilt from the live source', async () => { + const root = mkdtempForTestSync('fu-art-cache-rebuild-'); + const artifactPath = path.join(root, 'capture.trace'); + const expected = Buffer.from('live source after cached archive disappears'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), expected); + const runtime = createRuntimeStateHandle(); + const downloads: OpenedDownloadableArtifact[] = []; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + const first = await runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + downloads.push(first); + expect(gunzipSync(await buffer(first.stream)).includes(expected)).toBe(true); + await vi.waitFor(() => expect(first.stream.closed).toBe(true)); + first.release(); + const oldArchive = String(first.stream.path); + fs.unlinkSync(oldArchive); + expect(fs.existsSync(artifactPath)).toBe(true); + const second = await runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + downloads.push(second); + expect(gunzipSync(await buffer(second.stream)).includes(expected)).toBe(true); + await vi.waitFor(() => expect(second.stream.closed).toBe(true)); + second.release(); + expect(String(second.stream.path)).not.toBe(oldArchive); + expect(fs.existsSync(path.dirname(oldArchive))).toBe(false); + runtime.run(() => cleanupDownloadableArtifact(id)); + expect(fs.existsSync(artifactPath)).toBe(false); + expect(fs.existsSync(path.dirname(String(second.stream.path)))).toBe(false); + } finally { + for (const download of downloads) { + download.stream.destroy(); + await vi.waitFor(() => expect(download.stream.closed).toBe(true)); + download.release(); + } + runtime.dispose(); + } +}); + test('cancelling the archive builder preserves a second download waiting for its full archive', async () => { const root = mkdtempForTestSync('fu-art-shared-build-'); const artifactPath = path.join(root, 'capture.trace'); @@ -84,6 +196,143 @@ test('cancelling the archive builder preserves a second download waiting for its } }); +test.each(['deadline-aborted', 'late-aborted'] as const)( + 'a live artifact starts a fresh archive while a %s build is settling', + async (failure) => { + const root = mkdtempForTestSync('fu-art-retry-build-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + const expected = Buffer.from('fresh archive payload'); + fs.writeFileSync(path.join(artifactPath, 'payload'), expected); + const runtime = createRuntimeStateHandle(); + let finishAborted!: () => void; + const settling = new Promise((resolve) => { + finishAborted = resolve; + }); + let aborted!: () => void; + const cancelled = new Promise((resolve) => { + aborted = resolve; + }); + let tarSucceeded!: () => void; + const succeeded = new Promise((resolve) => { + tarSucceeded = resolve; + }); + let firstArchiveDir = ''; + const runCmd = command.runCmd; + const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + firstArchiveDir = path.dirname(String(args[1]?.[1])); + args[2]?.signal?.addEventListener('abort', aborted, { once: true }); + if (failure === 'late-aborted') { + const result = await runCmd(...args); + tarSucceeded(); + await settling; + return result; + } + await settling; + return await runCmd(...args); + }); + const openings: Array> = []; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + const timers = vi.spyOn(globalThis, 'setTimeout'); + const first = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + openings.push(first); + void first.catch(() => {}); + const deadline = timers.mock.calls.find(([, delay]) => delay === 15 * 60 * 1000)?.[0]; + timers.mockRestore(); + if (failure === 'late-aborted') await succeeded; + expect(deadline).toBeTypeOf('function'); + runtime.run(() => deadline!()); + await cancelled; + const second = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + openings.push(second); + void second.catch(() => {}); + finishAborted(); + await expect(first).rejects.toMatchObject({ details: { reason: 'RESOURCE_EXPIRED' } }); + expect(fs.existsSync(firstArchiveDir)).toBe(false); + const download = await second; + const closed = once(download.stream, 'close'); + const bytes = await buffer(download.stream); + await closed; + download.release(); + expect(gunzipSync(bytes).includes(expected)).toBe(true); + expect(archive).toHaveBeenCalledTimes(2); + if (failure === 'late-aborted') runtime.dispose(); + else runtime.run(() => cleanupDownloadableArtifact(id)); + expect(fs.existsSync(artifactPath)).toBe(false); + expect(fs.existsSync(path.dirname(String(download.stream.path)))).toBe(false); + } finally { + finishAborted(); + for (const result of await Promise.allSettled(openings)) { + if (result.status !== 'fulfilled') continue; + const download = result.value; + if (!download.stream.closed) { + const closed = once(download.stream, 'close'); + download.stream.destroy(); + await closed; + } + download.release(); + } + runtime.dispose(); + archive.mockRestore(); + } + }, +); + +test.each(['before opening', 'while archiving'] as const)( + 'caller cancellation %s has a typed reason without forwarding caller data', + async (phase) => { + const root = mkdtempForTestSync('fu-art-client-cancel-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), 'cancelled payload'); + const runtime = createRuntimeStateHandle(); + const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + const signal = args[2]!.signal!; + await new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => reject(signal.reason), { once: true }); + }); + throw new Error('aborted tar cannot complete'); + }); + const caller = new AbortController(); + const reason = new AppError('COMMAND_FAILED', 'private caller cancellation data', { + reason: 'RESOURCE_EXPIRED', + }); + let opening: Promise | undefined; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + if (phase === 'before opening') caller.abort(reason); + opening = runtime.run(() => + openDownloadableArtifact(id, undefined, process.env, caller.signal), + ); + void opening.catch(() => {}); + if (phase === 'while archiving') caller.abort(reason); + const error = await opening.catch((error: unknown) => error); + expect(isRequestCanceledError(error)).toBe(true); + const normalized = normalizeError(error); + expect(normalized).toMatchObject({ + code: 'COMMAND_FAILED', + message: 'request canceled', + details: { reason: 'request_canceled' }, + }); + expect(JSON.stringify(normalized)).not.toContain('private caller cancellation data'); + expect(JSON.stringify(normalized)).not.toContain('RESOURCE_EXPIRED'); + expect(fs.existsSync(artifactPath)).toBe(true); + runtime.run(() => cleanupDownloadableArtifact(id)); + expect(fs.existsSync(artifactPath)).toBe(false); + } finally { + caller.abort(); + if (opening) await Promise.allSettled([opening]); + runtime.dispose(); + archive.mockRestore(); + } + }, +); + test('disposing every archive waiter aborts the shared build and removes its temporary directory', async () => { const root = mkdtempForTestSync('fu-art-cancel-all-'); const artifactPath = path.join(root, 'capture.trace'); @@ -118,7 +367,7 @@ test('disposing every archive waiter aborts the shared build and removes its tem openings.push(runtime.run(() => openDownloadableArtifact(id, undefined, process.env))); for (const opening of openings) void opening.catch(() => {}); runtime.dispose(); - expect(archiveSignal?.aborted).toBe(true); + await vi.waitFor(() => expect(archiveSignal?.aborted).toBe(true)); expect(fs.existsSync(artifactPath)).toBe(true); expect(fs.existsSync(archiveDir)).toBe(true); continueArchive(); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 4bc868a76f..4af16a65a2 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -4,7 +4,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { finished } from 'node:stream/promises'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; import type { DaemonArtifactType } from '@agent-device/kernel/contracts'; import type { DeviceRotation } from '@agent-device/contracts/device'; import type { DaemonArtifactInventoryEntry } from '@agent-device/contracts/observability'; @@ -34,6 +34,12 @@ type DirectoryArchive = { sizeBytes: number; }; +type DirectoryArchiveBuild = { + promise: Promise; + controller: AbortController; + waiters: number; +}; + type ArtifactSourceCleanup = { remainingEntries: number; deleteAfterDownload: boolean; @@ -55,8 +61,7 @@ type ArtifactEntry = { sourceCleanup: ArtifactSourceCleanup; createdAt: number; directoryArchive?: DirectoryArchive; - directoryArchivePromise?: Promise; - archiveAbortController?: AbortController; + directoryArchiveBuild?: DirectoryArchiveBuild; activeDownloads: Set; cleanupRequested: boolean; timer: ReturnType; @@ -176,7 +181,9 @@ export async function openDownloadableArtifact( artifactId: string, tenantId: string | undefined, hostEnv: NodeJS.ProcessEnv, + signal?: AbortSignal, ): Promise { + if (signal?.aborted) throw createRequestCanceledError(); const artifacts = pendingArtifacts(); const { entry, stat } = readDownloadableArtifactEntry(artifactId, tenantId); const download: ArtifactDownload = { @@ -184,6 +191,7 @@ export async function openDownloadableArtifact( release: () => { if (!entry.activeDownloads.delete(download)) return; clearTimeout(deadline); + signal?.removeEventListener('abort', cancel); if (entry.cleanupRequested) requestArtifactCleanup(artifacts, artifactId, entry); }, }; @@ -193,8 +201,18 @@ export async function openDownloadableArtifact( ARTIFACT_DOWNLOAD_MAX_LIFETIME_MS, ); deadline.unref(); + const cancel = () => + cancelArtifactDownload(artifactId, entry, download, createRequestCanceledError()); + signal?.addEventListener('abort', cancel, { once: true }); try { - const payload = await prepareArtifactPayload(artifactId, entry, stat, hostEnv); + download.controller.signal.throwIfAborted(); + const payload = await prepareArtifactPayload( + artifactId, + entry, + stat, + hostEnv, + download.controller.signal, + ); download.controller.signal.throwIfAborted(); if (!payload) { throw new AppError( @@ -215,16 +233,11 @@ function cancelArtifactDownload( artifactId: string, entry: ArtifactEntry, download: ArtifactDownload, + reason: unknown = expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId), ): void { if (!entry.activeDownloads.has(download)) return; - const reason = expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); download.controller.abort(reason); - if (!download.stream) { - if ([...entry.activeDownloads].every(({ controller }) => controller.signal.aborted)) { - entry.archiveAbortController?.abort(reason); - } - return; - } + if (!download.stream) return; const closed = finished(download.stream, { cleanup: true }).catch(() => {}); download.stream.destroy(); void closed.then(download.release); @@ -303,6 +316,7 @@ async function prepareArtifactPayload( entry: ArtifactEntry, stat: fs.Stats, hostEnv: NodeJS.ProcessEnv, + signal?: AbortSignal, ): Promise { if (stat.isFile()) { return { @@ -314,7 +328,7 @@ async function prepareArtifactPayload( } if (!stat.isDirectory()) return null; - const directoryArchive = await ensureDirectoryArchive(artifactId, entry, hostEnv); + const directoryArchive = await ensureDirectoryArchive(artifactId, entry, hostEnv, signal); return { artifactPath: directoryArchive.archivePath, fileName: directoryArchive.fileName, @@ -327,21 +341,44 @@ async function ensureDirectoryArchive( artifactId: string, entry: ArtifactEntry, hostEnv: NodeJS.ProcessEnv, + signal?: AbortSignal, ): Promise { + signal?.throwIfAborted(); if (entry.directoryArchive && fs.existsSync(entry.directoryArchive.archivePath)) { return entry.directoryArchive; } - if (entry.directoryArchivePromise) { - return await entry.directoryArchivePromise; + const artifacts = pendingArtifacts(); + let build = entry.directoryArchiveBuild; + if (!build || build.controller.signal.aborted) { + const controller = new AbortController(); + build = { + promise: createDirectoryArchive(artifactId, entry, hostEnv, controller), + controller, + waiters: 0, + }; + entry.directoryArchiveBuild = build; } - - const archivePromise = createDirectoryArchive(artifactId, entry, hostEnv); - entry.directoryArchivePromise = archivePromise; + build.waiters += 1; + let onAbort: (() => void) | undefined; + const aborted = + signal && + new Promise((_resolve, reject) => { + onAbort = () => reject(signal.reason); + signal.addEventListener('abort', onAbort, { once: true }); + if (signal.aborted) onAbort(); + }); try { - return await archivePromise; + return await (aborted ? Promise.race([build.promise, aborted]) : build.promise); } finally { - if (entry.directoryArchivePromise === archivePromise) { - entry.directoryArchivePromise = undefined; + if (signal && onAbort) signal.removeEventListener('abort', onAbort); + build.waiters -= 1; + if (build.waiters === 0) { + if (signal?.aborted) { + build.controller.abort(signal.reason); + await build.promise.catch(() => {}); + } + if (entry.directoryArchiveBuild === build) entry.directoryArchiveBuild = undefined; + if (entry.cleanupRequested) requestArtifactCleanup(artifacts, artifactId, entry); } } } @@ -350,21 +387,21 @@ async function createDirectoryArchive( artifactId: string, entry: ArtifactEntry, hostEnv: NodeJS.ProcessEnv, + controller: AbortController, ): Promise { - cleanupDirectoryArchive(entry); - - const sourceName = safeArtifactFilename( - entry.fileName, - path.basename(entry.artifactPath) || artifactId, - ); - const fileName = archiveFilename(sourceName); - const tempDir = fs.mkdtempSync( - path.join(os.tmpdir(), `agent-device-download-${crypto.randomUUID()}-`), - ); - const archivePath = path.join(tempDir, fileName); - const controller = new AbortController(); - entry.archiveAbortController = controller; + let tempDir: string | undefined; try { + cleanupDirectoryArchive(entry); + + const sourceName = safeArtifactFilename( + entry.fileName, + path.basename(entry.artifactPath) || artifactId, + ); + const fileName = archiveFilename(sourceName); + tempDir = fs.mkdtempSync( + path.join(os.tmpdir(), `agent-device-download-${crypto.randomUUID()}-`), + ); + const archivePath = path.join(tempDir, fileName); await runCmd( 'tar', [ @@ -391,24 +428,21 @@ async function createDirectoryArchive( fileName, sizeBytes: fs.statSync(archivePath).size, }; - // Inventory can expire while tar is still archiving. - if (entry.cleanupRequested && entry.activeDownloads.size === 0) { - throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); - } entry.directoryArchive = archive; return archive; } catch (error) { - fs.rmSync(tempDir, { recursive: true, force: true }); - if (controller.signal.aborted) throw controller.signal.reason; - if (error instanceof AppError) throw error; - throw new AppError( - 'COMMAND_FAILED', - `Failed to archive downloadable artifact: ${entry.artifactPath}`, - { artifactPath: entry.artifactPath }, - error instanceof Error ? error : undefined, - ); - } finally { - if (entry.archiveAbortController === controller) entry.archiveAbortController = undefined; + const failure = controller.signal.aborted + ? controller.signal.reason + : error instanceof AppError + ? error + : new AppError( + 'COMMAND_FAILED', + `Failed to archive downloadable artifact: ${entry.artifactPath}`, + { artifactPath: entry.artifactPath }, + error instanceof Error ? error : undefined, + ); + if (tempDir) fs.rmSync(tempDir, { recursive: true, force: true }); + throw failure; } } @@ -452,9 +486,12 @@ function requestArtifactCleanup( entry.cleanupRequested = true; clearTimeout(entry.timer); if (entry.activeDownloads.size > 0 || artifacts.get(artifactId) !== entry) return; - entry.archiveAbortController?.abort( - expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId), - ); + if (entry.directoryArchiveBuild) { + entry.directoryArchiveBuild.controller.abort( + expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId), + ); + return; + } artifacts.delete(artifactId); cleanupDirectoryArchive(entry); entry.sourceCleanup.remainingEntries -= 1; diff --git a/packages/daemon/src/server/__tests__/request-diagnostics-http.test.ts b/packages/daemon/src/server/__tests__/request-diagnostics-http.test.ts index d8a9352e83..e546f319dc 100644 --- a/packages/daemon/src/server/__tests__/request-diagnostics-http.test.ts +++ b/packages/daemon/src/server/__tests__/request-diagnostics-http.test.ts @@ -1,6 +1,6 @@ import { resolveSessionRequestLogPath } from '@agent-device/daemon-contracts/session-artifact-paths'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import { test } from 'vitest'; +import { expect, test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import http from 'node:http'; @@ -94,6 +94,37 @@ test('request diagnostics route serves one record as ndjson to an authorized cal }); }); +test('request diagnostics returns complete JSON when its stream fails before headers', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + + await withDiagnosticsServer(async ({ baseUrl, sessionsDir }) => { + writeRecord(sessionsDir, 'default', 'abc123'); + const createReadStream = fs.createReadStream; + const streams = vi.spyOn(fs, 'createReadStream').mockImplementation((file, options) => + createReadStream(file, { + ...(typeof options === 'object' ? options : {}), + fs: { + ...fs, + open: (_file, _flags, _mode, callback) => callback(new Error('record read failed')), + }, + }), + ); + let response: Response | undefined; + try { + response = await fetch(diagnosticsUrl(baseUrl, 'default', 'abc123'), { + headers: { authorization: 'Bearer daemon-secret' }, + }); + expect(response.status).toBe(500); + expect(response.headers.get('content-type')).toBe('application/json'); + expect(response.headers.get('content-length')).toBeNull(); + expect(await response.json()).toMatchObject({ ok: false, error: 'record read failed' }); + } finally { + await response?.body?.cancel().catch(() => {}); + streams.mockRestore(); + } + }); +}); + test('request diagnostics route refuses an unauthenticated caller', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; diff --git a/packages/daemon/src/server/downloadable-artifact-http.test.ts b/packages/daemon/src/server/downloadable-artifact-http.test.ts index aa8e14bccc..b4453b9c25 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.test.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.test.ts @@ -3,10 +3,15 @@ import fs from 'node:fs'; import http from 'node:http'; import path from 'node:path'; import { gunzipSync } from 'node:zlib'; -import { expect, test, vi } from 'vitest'; +import { expect, test, vi, type MockInstance } from 'vitest'; import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; import * as command from '@agent-device/host-kit/command'; -import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; +import { + closeLoopbackServer, + listenOnLoopback, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; import * as artifactTracking from '../resources/artifact-tracking.ts'; import { createDaemonHttpServer } from './http/http-server.ts'; @@ -28,6 +33,9 @@ type DownloadFixture = { failResponse(): void; outcome(): 'pending' | 'complete' | 'failed'; cleanupCount(): number; + closedResponses(): number; + receivedRequests(): number; + responseDestroys(): number; expire(): void; expiryPending(): boolean; fireDeadlines(): void; @@ -52,8 +60,14 @@ async function withDownloadFixture( ); const port = await listenOnLoopback(server); let activeResponse: http.ServerResponse | undefined; + let closedResponses = 0; + let receivedRequests = 0; + const responseDestroySpies: Array> = []; server.on('request', (_request, response) => { + responseDestroySpies.push(vi.spyOn(response, 'destroy')); + receivedRequests++; activeResponse = response; + response.once('close', () => closedResponses++); }); const timers = vi.spyOn(globalThis, 'setTimeout'); const clearedTimers = vi.spyOn(globalThis, 'clearTimeout'); @@ -107,6 +121,10 @@ async function withDownloadFixture( abortClient: () => request?.destroy(), failResponse: () => activeResponse?.destroy(new Error('injected response failure')), outcome: () => outcome, + closedResponses: () => closedResponses, + receivedRequests: () => receivedRequests, + responseDestroys: () => + responseDestroySpies.reduce((count, spy) => count + spy.mock.calls.length, 0), cleanupCount: () => removed.mock.calls.filter(([target]) => target === source).length, expire: () => runtime.run(expire), expiryPending: () => !clearedTimers.mock.calls.some(([timer]) => timer === expiryTimer), @@ -137,49 +155,137 @@ async function withDownloadFixture( await closeLoopbackServer(server); runtime.dispose(); removed.mockRestore(); + for (const spy of responseDestroySpies) spy.mockRestore(); } } -test('a client abort during a shared archive build preserves the other HTTP download', async () => { - const started = deferred(); - const proceed = deferred(); - const runCmd = command.runCmd; - const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { - started.resolve(); - await proceed.promise; - return await runCmd(...args); - }); - const opens = vi.spyOn(artifactTracking, 'openDownloadableArtifact'); +test('a completed download is not destroyed or cleaned up twice after its 200 response', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + + await withDownloadFixture( + async (fixture) => { + const expected = fs.readFileSync(path.join(fixture.source, 'payload')); + const response = await fetch(fixture.url, { + headers: { authorization: 'Bearer fu-art-secret' }, + }); + expect(response.status).toBe(200); + const bytes = Buffer.from(await response.arrayBuffer()); + expect(bytes).toHaveLength(Number(response.headers.get('content-length'))); + expect(gunzipSync(bytes).includes(expected)).toBe(true); + await vi.waitFor(() => expect(fixture.closedResponses()).toBe(1)); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + expect(fixture.responseDestroys()).toBe(0); + expect(fixture.cleanupCount()).toBe(1); + fixture.expire(); + fixture.runtime.dispose(); + expect(fixture.cleanupCount()).toBe(1); + expect(fixture.responseDestroys()).toBe(0); + }, + () => {}, + ); +}); + +test.each(['lone', 'shared', 'inventory'] as const)( + 'a client abort cancels its preparation during a %s archive build', + async (kind) => { + const started = deferred(); + const proceed = deferred(); + let archiveSignal: AbortSignal | undefined; + let archiveDir = ''; + const runCmd = command.runCmd; + const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + archiveSignal = args[2]?.signal; + archiveDir = path.dirname(String(args[1]?.[1])); + started.resolve(); + await proceed.promise; + return await runCmd(...args); + }); + try { + await withDownloadFixture( + async (fixture) => { + const expected = fs.readFileSync(path.join(fixture.source, 'payload')); + let second: Promise | undefined; + try { + fixture.start(); + await started.promise; + if (kind !== 'lone') { + const url = + kind === 'inventory' + ? fixture.url.slice(0, fixture.url.lastIndexOf('/')) + : fixture.url; + second = fetch(url, { headers: { authorization: 'Bearer fu-art-secret' } }); + void second.catch(() => {}); + await vi.waitFor(() => expect(fixture.receivedRequests()).toBe(2)); + } + fixture.abortClient(); + await vi.waitFor(() => expect(fixture.closedResponses()).toBe(1)); + if (kind !== 'inventory') expect(archiveSignal?.aborted).toBe(kind === 'lone'); + proceed.resolve(); + if (second) { + let response = await second; + expect(response.status).toBe(200); + if (kind === 'inventory') { + expect(await response.json()).toMatchObject({ + artifacts: [ + { id: fixture.url.split('/').at(-1), filename: 'capture.trace.tar.gz' }, + ], + }); + expect(archiveSignal?.aborted).toBe(false); + expect(fs.existsSync(fixture.source)).toBe(true); + response = await fetch(fixture.url, { + headers: { authorization: 'Bearer fu-art-secret' }, + }); + expect(response.status).toBe(200); + } + const bytes = Buffer.from(await response.arrayBuffer()); + expect(bytes).toHaveLength(Number(response.headers.get('content-length'))); + expect(gunzipSync(bytes).includes(expected)).toBe(true); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + } else { + await vi.waitFor(() => expect(fs.existsSync(archiveDir)).toBe(false)); + expect(fs.existsSync(fixture.source)).toBe(true); + } + expect(fixture.streams).toHaveLength(kind !== 'lone' ? 1 : 0); + expect(archive).toHaveBeenCalledTimes(1); + } finally { + proceed.resolve(); + await Promise.allSettled(second ? [second] : []); + } + }, + () => {}, + ); + } finally { + proceed.resolve(); + archive.mockRestore(); + } + }, +); + +test('a failed archive build permits a later HTTP download to retry', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + + const archive = vi + .spyOn(command, 'runCmd') + .mockRejectedValueOnce(new Error('injected tar failure')); try { await withDownloadFixture( async (fixture) => { + const headers = { authorization: 'Bearer fu-art-secret' }; + const failed = await fetch(fixture.url, { headers }); + expect(failed.status).toBe(500); + expect(await failed.json()).toMatchObject({ ok: false, code: 'COMMAND_FAILED' }); + expect(fs.existsSync(fixture.source)).toBe(true); const expected = fs.readFileSync(path.join(fixture.source, 'payload')); - fixture.start(); - await started.promise; - const second = fetch(fixture.url, { headers: { authorization: 'Bearer fu-art-secret' } }); - void second.catch(() => {}); - try { - await vi.waitFor(() => expect(opens).toHaveBeenCalledTimes(2)); - fixture.abortClient(); - await vi.waitFor(() => expect(fixture.outcome()).toBe('failed')); - proceed.resolve(); - const response = await second; - expect(response.status).toBe(200); - const bytes = Buffer.from(await response.arrayBuffer()); - expect(bytes).toHaveLength(Number(response.headers.get('content-length'))); - expect(gunzipSync(bytes).includes(expected)).toBe(true); - expect(archive).toHaveBeenCalledTimes(1); - await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); - } finally { - proceed.resolve(); - await Promise.allSettled([second]); - } + const response = await fetch(fixture.url, { headers }); + expect(response.status).toBe(200); + const bytes = Buffer.from(await response.arrayBuffer()); + expect(gunzipSync(bytes).includes(expected)).toBe(true); + expect(archive).toHaveBeenCalledTimes(2); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); }, () => {}, ); } finally { - proceed.resolve(); - opens.mockRestore(); archive.mockRestore(); } }); diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index c6b4238783..59fce82a46 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -9,8 +9,9 @@ import { listDownloadableArtifacts, openDownloadableArtifact, } from '../resources/artifact-tracking.ts'; -import { sendRestJsonError } from './http-errors.ts'; +import { failStreamedHttpResponse, sendRestJsonError } from './http-errors.ts'; import { decodeUriSegment } from './http-request-target.ts'; +import { responseDisconnectSignal } from './http/response-disconnect-signal.ts'; type DownloadableArtifactHttpRoute = | { kind: 'inventory' } @@ -83,6 +84,7 @@ async function handleArtifactDownload( return; } + const signal = responseDisconnectSignal(req, res); try { const auth = await authorize({ req, @@ -94,7 +96,12 @@ async function handleArtifactDownload( }); if (!auth) return; - const artifact = await openDownloadableArtifact(artifactId, auth.tenantId, options.hostEnv); + const artifact = await openDownloadableArtifact( + artifactId, + auth.tenantId, + options.hostEnv, + signal, + ); const { stream } = artifact; const closed = finished(stream, { cleanup: true }).catch(() => {}); try { @@ -141,14 +148,7 @@ async function handleArtifactDownload( artifact.release(); } } catch (error) { - if (res.destroyed) return; - if (res.headersSent) { - res.destroy(error instanceof Error ? error : undefined); - return; - } - res.removeHeader('content-length'); - res.removeHeader('content-disposition'); - sendRestJsonError(res, normalizeError(error)); + failStreamedHttpResponse(res, error); } } diff --git a/packages/daemon/src/server/http-errors.ts b/packages/daemon/src/server/http-errors.ts index 60c264aba0..ea1726178f 100644 --- a/packages/daemon/src/server/http-errors.ts +++ b/packages/daemon/src/server/http-errors.ts @@ -50,12 +50,13 @@ export function sendRestJsonError(res: http.ServerResponse, normalized: Normaliz * destroying the connection, so the client sees a truncated body rather than a * complete one. */ -export function failStreamedHttpResponse(res: http.ServerResponse, error: Error): void { +export function failStreamedHttpResponse(res: http.ServerResponse, error: unknown): void { + if (res.destroyed) return; if (res.headersSent) { - res.destroy(error); + res.destroy(error instanceof Error ? error : undefined); return; } - const normalized = normalizeError(error); - res.statusCode = statusCodeForNormalizedError(normalized); - res.end(normalized.message); + res.removeHeader('content-length'); + res.removeHeader('content-disposition'); + sendRestJsonError(res, normalizeError(error)); } diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 12d7893ff1..2856a340c6 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -5,6 +5,7 @@ // request's cancellation lifetime, and invocation. The envelope framing lives // in `http-rpc-envelope.ts`, the authorization decisions in // `http-authorization.ts`, and the RPC method vocabulary in `http-rpc-methods.ts`. +import { responseDisconnectSignal } from './response-disconnect-signal.ts'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { AsyncResource } from 'node:async_hooks'; import http from 'node:http'; @@ -453,12 +454,11 @@ function beginRpcRequestLifetime(params: { let abortRegistration: ReturnType; let handlerCompleted = false; let canceledInFlight = false; + let disconnectSignal: AbortSignal | undefined; + let onClientGone: (() => void) | undefined; - // `res` close fires for a finished response too, so the completion guard is what separates a - // real disconnect from an ordinary end. `markRequestCanceled` aborts only this request's - // signal, leaving other requests, other devices, and non-Apple work alone. const markCanceledIfResponseIncomplete = () => { - if (handlerCompleted || res.writableFinished || canceledInFlight) return; + if (handlerCompleted || canceledInFlight) return; canceledInFlight = true; markRequestCanceled(requestId); emitDiagnostic({ @@ -482,10 +482,10 @@ function beginRpcRequestLifetime(params: { }; }, watchForClientDisconnect() { - const onClientGone = AsyncResource.bind(markCanceledIfResponseIncomplete); - req.on('aborted', onClientGone); - res.on('close', onClientGone); - if (req.aborted || res.destroyed) { + onClientGone = AsyncResource.bind(markCanceledIfResponseIncomplete); + disconnectSignal = responseDisconnectSignal(req, res); + disconnectSignal.addEventListener('abort', onClientGone, { once: true }); + if (disconnectSignal.aborted) { markCanceledIfResponseIncomplete(); } }, @@ -493,6 +493,7 @@ function beginRpcRequestLifetime(params: { handlerCompleted = true; }, release() { + if (onClientGone) disconnectSignal?.removeEventListener('abort', onClientGone); clearRequestAbortRegistration(abortRegistration); }, }; diff --git a/packages/daemon/src/server/http/response-disconnect-signal.test.ts b/packages/daemon/src/server/http/response-disconnect-signal.test.ts new file mode 100644 index 0000000000..050f1b6ddb --- /dev/null +++ b/packages/daemon/src/server/http/response-disconnect-signal.test.ts @@ -0,0 +1,59 @@ +import http from 'node:http'; +import net from 'node:net'; +import { expect, test } from 'vitest'; +import { + closeLoopbackServer, + listenOnLoopback, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { isRequestCanceledError } from '@agent-device/kernel/errors'; +import { responseDisconnectSignal } from './response-disconnect-signal.ts'; + +test.each(['request abort', 'response close', 'already aborted', 'already destroyed'] as const)( + '%s produces a typed disconnect signal and removes its listeners', + (event) => { + const socket = new net.Socket(); + const req = new http.IncomingMessage(socket); + const res = new http.ServerResponse(req); + try { + if (event === 'already aborted') req.destroy(); + if (event === 'already destroyed') res.destroy(); + const signal = responseDisconnectSignal(req, res); + if (event === 'request abort') req.destroy(); + if (event === 'response close') res.emit('close'); + expect(signal.aborted).toBe(true); + expect(isRequestCanceledError(signal.reason)).toBe(true); + expect(req.listenerCount('aborted')).toBe(0); + expect(res.listenerCount('close')).toBe(0); + } finally { + req.destroy(); + res.destroy(); + socket.destroy(); + } + }, +); + +test('a completed response does not abort its disconnect signal', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + + let signal: AbortSignal | undefined; + let responseClosed!: () => void; + const closed = new Promise((resolve) => { + responseClosed = resolve; + }); + const server = http.createServer((req, res) => { + signal = responseDisconnectSignal(req, res); + res.once('close', responseClosed); + res.end('complete'); + }); + try { + const port = await listenOnLoopback(server); + const response = await fetch(`http://127.0.0.1:${port}`); + expect(response.status).toBe(200); + expect(await response.text()).toBe('complete'); + await closed; + expect(signal?.aborted).toBe(false); + } finally { + await closeLoopbackServer(server); + } +}); diff --git a/packages/daemon/src/server/http/response-disconnect-signal.ts b/packages/daemon/src/server/http/response-disconnect-signal.ts new file mode 100644 index 0000000000..23f1e842df --- /dev/null +++ b/packages/daemon/src/server/http/response-disconnect-signal.ts @@ -0,0 +1,20 @@ +import type http from 'node:http'; +import { createRequestCanceledError } from '@agent-device/kernel/errors'; + +/** Cancels work when the HTTP client abandons an unfinished response. */ +export function responseDisconnectSignal( + req: http.IncomingMessage, + res: http.ServerResponse, +): AbortSignal { + const controller = new AbortController(); + function cancelIfDisconnected(): void { + // A finished response also emits close. + if (!res.writableFinished) controller.abort(createRequestCanceledError()); + req.off('aborted', cancelIfDisconnected); + res.off('close', cancelIfDisconnected); + } + req.once('aborted', cancelIfDisconnected); + res.once('close', cancelIfDisconnected); + if (req.aborted || res.destroyed) cancelIfDisconnected(); + return controller.signal; +} diff --git a/packages/daemon/src/server/human-control-http.ts b/packages/daemon/src/server/human-control-http.ts index 60a701b582..f668997596 100644 --- a/packages/daemon/src/server/human-control-http.ts +++ b/packages/daemon/src/server/human-control-http.ts @@ -1,7 +1,8 @@ import type http from 'node:http'; -import { AppError, createRequestCanceledError, normalizeError } from '@agent-device/kernel/errors'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { readNodeHttpRequestBody, timingSafeStringEqual } from '@agent-device/host-kit/transport'; import { sendRestJsonError } from './http-errors.ts'; +import { responseDisconnectSignal } from './http/response-disconnect-signal.ts'; import { HUMAN_CONTROL_HTTP_PREFIX, parseHumanControlHoldInput, @@ -75,26 +76,10 @@ async function upsertHumanControlHold( params: HumanControlHttpParams, ): Promise { const { req, res } = params; - const controller = new AbortController(); - const cancelIfDisconnected = () => { - if (!res.writableFinished) controller.abort(createRequestCanceledError()); - }; - req.once('aborted', cancelIfDisconnected); - res.once('close', cancelIfDisconnected); - if (req.aborted || res.destroyed) cancelIfDisconnected(); - try { - const input = await readHoldInput(req); - const hold = await params.registry.putHumanControlHold( - { kind: 'host' }, - holdId, - input, - controller.signal, - ); - sendJson(res, { ok: true, hold, state: 'active' }); - } finally { - req.off('aborted', cancelIfDisconnected); - res.off('close', cancelIfDisconnected); - } + const signal = responseDisconnectSignal(req, res); + const input = await readHoldInput(req); + const hold = await params.registry.putHumanControlHold({ kind: 'host' }, holdId, input, signal); + sendJson(res, { ok: true, hold, state: 'active' }); } function removeHumanControlHold(holdId: string, params: HumanControlHttpParams): void { diff --git a/packages/daemon/src/server/request-diagnostics-http.ts b/packages/daemon/src/server/request-diagnostics-http.ts index 4261cc4922..84540ad98d 100644 --- a/packages/daemon/src/server/request-diagnostics-http.ts +++ b/packages/daemon/src/server/request-diagnostics-http.ts @@ -161,7 +161,7 @@ async function handleRequestDiagnostics( }); stream.pipe(res); } catch (error) { - sendRestJsonError(res, normalizeError(error)); + failStreamedHttpResponse(res, error); } } diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index cb7b48b017..b1c1bda441 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -71,20 +71,20 @@ "packages/daemon-client/src/daemon-client-transport.ts#readRemoteDaemonHealth": "sha256:df174d1ccf73851ca58bd75533fb4660424003b98bd9e41fe942cf3ab3698e5f", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpAuthorizer": "sha256:1b2702a929ca9170db2ca97c08e3ab67e17edb3ee75325a576c4c1b9cdbebb44", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpRoute": "sha256:e63c4581ccde668913914149c9092d16ecf8a5cbd7ab33c6eb8617e77fc1015e", - "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:54b5a8817237d38502f8ae56d8e754217c811520110deb3f2637264e68534f98", + "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:fbb1ffa587ffb8b2975936fd35113c1970da16c58a713014df2c6ba885eecdd5", "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory": "sha256:651806eabbd78d51d4bb21dab0b8a28847fb6087941f73dee735c24d9c2a79fa", "packages/daemon/src/server/downloadable-artifact-http.ts#readArtifactId": "sha256:3472ee52d951fdf7ef00ee500298602c68f0e1e3b8c44ff51b09981efabf348c", "packages/daemon/src/server/downloadable-artifact-http.ts#readRequestPathname": "sha256:6b3a49c72365cf7da4552abef59862c073461f746025e28d409048815dd586f2", "packages/daemon/src/server/downloadable-artifact-http.ts#resolveDownloadableArtifactHttpRoute": "sha256:9fcdc9619e8d378e8f04ef7b3584863af446e855702ddce83a16ec194a6d98af", "packages/daemon/src/server/http-errors.ts#NormalizedHttpError": "sha256:2c2111802fe5f193acbeacc454de9cfab82bc8e4274b896f485e19a14f5518cf", - "packages/daemon/src/server/http-errors.ts#failStreamedHttpResponse": "sha256:e4f4dbb80a2213395220dfe448ff4453cc0402a755a66fe4203a7adf6fda4948", + "packages/daemon/src/server/http-errors.ts#failStreamedHttpResponse": "sha256:3e6b642cb41b88ab1e6f3269ebd14918f912cbecf09f40e9b591fdd28a2ba489", "packages/daemon/src/server/http-errors.ts#sendRestJsonError": "sha256:aef588e77ea73eb3cf6e94ec2f2c98a434fcaaeb96de6973a43c442b704694ad", "packages/daemon/src/server/http-errors.ts#statusCodeForNormalizedError": "sha256:39aa61eed8459527d7077e31e23be4fe0275021ed99c70ad692538091db91125", "packages/daemon/src/server/http-request-target.ts#decodeUriSegment": "sha256:b37622771ea4e61d1a9820169dbdc5809b5c38889bfad79277d7b22f3c3f1ef1", "packages/daemon/src/server/request-diagnostics-http.ts#REQUEST_DIAGNOSTICS_CONTENT_TYPE": "sha256:16bbd9ae7eaeaaa8c8cbd6e65c4ce786a6c5230c5351288228bbf1a6f11bdcdc", "packages/daemon/src/server/request-diagnostics-http.ts#RequestDiagnosticsHttpAuthorizer": "sha256:24b0fa6b1d965e5cf6503a4665148dc6360c56bf5a0ae710eeaa76a73a62c52a", "packages/daemon/src/server/request-diagnostics-http.ts#RequestDiagnosticsHttpOptions": "sha256:cd2c0dda77d2bc434857aea07206a5491ce5f0b82cb86628569f607d6c2cebcf", - "packages/daemon/src/server/request-diagnostics-http.ts#handleRequestDiagnostics": "sha256:32c3d100176dd99ecbb61f8050d05b1cda64b7be1944a2cd16633e83fa78660b", + "packages/daemon/src/server/request-diagnostics-http.ts#handleRequestDiagnostics": "sha256:08d3fd203cd7e47814cf8c50f710e86bee28ac2818dbf93910ae49725b97468a", "packages/daemon/src/server/request-diagnostics-http.ts#resolveRequestDiagnosticsHttpRoute": "sha256:4ff07623b27a6f7461e1addb87aabd149904da63f7462149ae4114d14336cde0", "packages/daemon-contracts/src/request-progress-protocol.ts#DaemonProgressEnvelope": "sha256:16162d01cfc43fc6a0198dbba3358981c1a278a70f7494ebe70d051f517cfb22", "packages/daemon-contracts/src/request-progress-protocol.ts#DaemonResponseEnvelope": "sha256:202ae64836af890549a1d95963903f9a506294b80bd0862c1b708e72d7f286d0", @@ -257,8 +257,8 @@ }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload", - "digest": "sha256:54b5a8817237d38502f8ae56d8e754217c811520110deb3f2637264e68534f98", - "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 uses a bounded, abortable Node pipeline and validates the declared byte length, with idempotent reader release after completion or failed setup. The handler waits for file readiness before setting headers and starting the pipeline, so open errors use the existing JSON error response. Setup errors clear artifact-only headers first. Successful status codes, headers and artifact bytes retain their existing contracts. Failed or incomplete streaming reads close the HTTP transfer instead of hanging; released clients already treat an interrupted download as failure. Routes, authorization and error JSON shapes are unchanged, so no peer must parse a new payload or send a new field." + "digest": "sha256:fbb1ffa587ffb8b2975936fd35113c1970da16c58a713014df2c6ba885eecdd5", + "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 uses a bounded, abortable Node pipeline and validates the declared byte length, with idempotent reader release after completion or failed setup. The handler waits for file readiness before setting headers and starting the pipeline, so open errors use the existing JSON error response. Setup errors clear artifact-only headers first. Successful status codes, headers and artifact bytes retain their existing contracts. Failed or incomplete streaming reads close the HTTP transfer instead of hanging; released clients already treat an interrupted download as failure. Routes, authorization and error JSON shapes are unchanged, so no peer must parse a new payload or send a new field. Implementation-only follow-up to #4165 under ADR 0006: response close cancels artifact preparation and streaming through an internal AbortSignal. Shared builds continue for other downloads. The existing streamed failure helper now owns the same pre-header JSON error and post-header connection destruction. Successful status, headers, bytes, routes and authorization retain their existing contracts; disconnected clients receive no new payload. A response that has finished writing is not cancelled by its normal close event, so successful pipeline completion keeps its existing success semantics. Caller cancellation is normalized to the existing request_canceled error instead of forwarding caller-supplied reasons. Artifact expiry and download deadlines keep their existing reasons. The shared HTTP disconnect helper preserves typed cancellation on aborted requests and unfinished response closes. Directory preparation counts inventory and download callers together, so one disconnected download cannot abort an inventory caller's build; successful response fields and authorization stay unchanged." }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory", @@ -297,8 +297,8 @@ }, { "declaration": "packages/daemon/src/server/request-diagnostics-http.ts#handleRequestDiagnostics", - "digest": "sha256:32c3d100176dd99ecbb61f8050d05b1cda64b7be1944a2cd16633e83fa78660b", - "rationale": "#2198 context: asks isTenantAddressableSessionName instead of applying the prefix rule locally. Same UNAUTHORIZED code, same 'Session is outside this tenant' message and same 401 body for the attested-tenant case the rule still refuses; the only difference a peer can observe is that an unattested tenant now gets the 200 + ndjson record it already knows how to read instead of a 401 it could not act on." + "digest": "sha256:08d3fd203cd7e47814cf8c50f710e86bee28ac2818dbf93910ae49725b97468a", + "rationale": "#2198 context: asks isTenantAddressableSessionName instead of applying the prefix rule locally. Same UNAUTHORIZED code, same 'Session is outside this tenant' message and same 401 body for the attested-tenant case the rule still refuses; the only difference a peer can observe is that an unattested tenant now gets the 200 + ndjson record it already knows how to read instead of a 401 it could not act on. Implementation-only HTTP error repair under ADR 0006: setup failures use the shared streamed failure helper. Before headers, it emits the existing REST JSON error shape with an error status; after headers, it destroys the incomplete transfer. Successful diagnostics remain 200 with the same NDJSON bytes. Released clients reject error statuses before reading diagnostic records, so no successful response parser or request requirement changes." }, { "declaration": "packages/kernel/src/contracts.ts#LEASE_BACKENDS", @@ -497,8 +497,8 @@ }, { "declaration": "packages/daemon/src/server/http-errors.ts#failStreamedHttpResponse", - "digest": "sha256:e4f4dbb80a2213395220dfe448ff4453cc0402a755a66fe4203a7adf6fda4948", - "rationale": "Passes the whole normalized error to the details-aware status mapper instead of its code; the plain-text body is unchanged. A gone resource now answers 404 instead of 500: COMMAND_FAILED with details.reason RESOURCE_EXPIRED (an artifact, upload ticket, uploaded artifact or materialized path id the TTL registry no longer holds) maps to 404. The mapper also takes over the DEVICE_IN_USE human_control_active 423 rule, which statusCodeForDaemonError applied only to a failed response a /rpc handler returned. The rule now also reaches the REST routes and thrown /rpc failures, which answered 500: a PUT /admin/leases/ refused during a human-control hold, or a non-streamed /rpc call whose handler throws human_control_active, now answers 423. /admin/* is host-only on the loopback port and the proxy never forwards it, and the host already reads 423 for the same refusal on a returned /rpc failure. No released client branches on 404 versus 500 for these routes: downloadRemoteArtifactFromUrl treats any status >= 400 alike, the upload client fails any non-2xx and decides retries from a typed stream detail rather than the status, the /rpc client parses the JSON-RPC error envelope whatever the status and only special-cases 409, and the proxy passes the status through. The error code, message and JSON-RPC error data a peer parses are unchanged, so a protocol 2 peer reports the same failure it did before." + "digest": "sha256:3e6b642cb41b88ab1e6f3269ebd14918f912cbecf09f40e9b591fdd28a2ba489", + "rationale": "Compatible HTTP error repair under ADR 0006. Status: the helper passes the whole normalized error to the details-aware status mapper instead of its code. A gone resource now answers 404 instead of 500: COMMAND_FAILED with details.reason RESOURCE_EXPIRED (an artifact, upload ticket, uploaded artifact or materialized path id the TTL registry no longer holds) maps to 404. The mapper also takes over the DEVICE_IN_USE human_control_active 423 rule, which statusCodeForDaemonError applied only to a failed response a /rpc handler returned. The rule now also reaches the REST routes and thrown /rpc failures, which answered 500: a PUT /admin/leases/ refused during a human-control hold, or a non-streamed /rpc call whose handler throws human_control_active, now answers 423. /admin/* is host-only on the loopback port and the proxy never forwards it, and the host already reads 423 for the same refusal on a returned /rpc failure. Body: before headers, the helper no longer writes the plain-text error message. It removes stale content-length and content-disposition headers and sends the existing REST JSON error shape ({ ok: false, error, code, reason?, hint? }) that the other REST routes already use. Previously a diagnostics stream open failure could keep its successful-response length and leave the error body incomplete. After headers, it still destroys the incomplete transfer, and it ignores an already destroyed response. No released client branches on 404 versus 500 or parses this body: downloadRemoteArtifactFromUrl treats any status >= 400 alike and keeps the body only as an opaque details.body string, the diagnostics client rejects non-success statuses before reading records, the upload client fails any non-2xx and decides retries from a typed stream detail rather than the status, the /rpc client parses the JSON-RPC error envelope whatever the status and only special-cases 409, and the proxy passes the status through. Routes, successful responses and authorization are unchanged, so a protocol 2 peer reports the same failure it did before." } ] } diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 43d3a764f6..4f7819c217 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -90,6 +90,9 @@ destination on your machine. Direct RPC callers receive artifact IDs and downloa By default, artifacts leave the inventory after download or after 15 minutes. `AGENT_DEVICE_RETAIN_ARTIFACTS` keeps downloaded artifacts in inventory until expiry. Downloads already in progress can finish before their files are removed, including overlapping downloads of a directory archive. +Closing the HTTP connection cancels that download, including directory archive preparation. +Other downloads waiting for the same archive can still finish. You can retry a cancelled download +while the artifact remains in inventory. Each download has a 15-minute maximum lifetime. When it reaches that limit, the daemon cancels it and cleans up after its pipeline stops.