diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index c0c013e4f1..84a3170300 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -1,9 +1,295 @@ import fs from 'node:fs'; +import { once } from 'node:events'; import path from 'node:path'; -import { expect, test } from 'vitest'; +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 { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; -import { trackDownloadableArtifact, trackUploadedArtifact } from './artifact-tracking.ts'; +import * as command from '@agent-device/host-kit/command'; +import { + cleanupDownloadableArtifact, + openDownloadableArtifact, + trackDownloadableArtifact, + trackUploadedArtifact, + type OpenedDownloadableArtifact, +} from './artifact-tracking.ts'; + +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'); + fs.mkdirSync(artifactPath); + const expected = 'complete shared capture payload\n'.repeat(4096); + fs.writeFileSync(path.join(artifactPath, 'payload'), expected); + const runtime = createRuntimeStateHandle(); + let continueArchive!: () => void; + const blocked = new Promise((resolve) => { + continueArchive = resolve; + }); + let archiveStarted!: () => void; + const started = new Promise((resolve) => { + archiveStarted = resolve; + }); + const runCmd = command.runCmd; + const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + archiveStarted(); + await blocked; + return await runCmd(...args); + }); + const timers = vi.spyOn(globalThis, 'setTimeout'); + const openings: Array> = []; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + const timerIndex = timers.mock.calls.length; + const first = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + openings.push(first); + void first.catch(() => {}); + const cancelFirst = timers.mock.calls[timerIndex]![0]; + await started; + const second = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + openings.push(second); + void second.catch(() => {}); + runtime.run(cancelFirst); + continueArchive(); + const download = await second; + const closed = once(download.stream, 'close'); + const bytes = await buffer(download.stream); + await closed; + download.release(); + expect(bytes).toHaveLength(download.sizeBytes); + expect(gunzipSync(bytes).includes(Buffer.from(expected))).toBe(true); + await expect(first).rejects.toMatchObject({ details: { reason: 'RESOURCE_EXPIRED' } }); + expect(archive).toHaveBeenCalledTimes(1); + runtime.run(() => cleanupDownloadableArtifact(id)); + expect(fs.existsSync(artifactPath)).toBe(false); + expect(fs.existsSync(path.dirname(String(download.stream.path)))).toBe(false); + } finally { + continueArchive(); + const results = await Promise.allSettled(openings); + for (const result of results) { + 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(); + timers.mockRestore(); + 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'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), 'cancelled archive payload'); + const runtime = createRuntimeStateHandle(); + let continueArchive!: () => void; + const blocked = new Promise((resolve) => { + continueArchive = resolve; + }); + let archiveStarted!: () => void; + const started = new Promise((resolve) => { + archiveStarted = resolve; + }); + let archiveDir = ''; + let archiveSignal: AbortSignal | undefined; + const runCmd = command.runCmd; + const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + archiveDir = path.dirname(String(args[1]?.[1])); + archiveSignal = args[2]?.signal; + archiveStarted(); + await blocked; + return await runCmd(...args); + }); + const openings: Array> = []; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + openings.push(runtime.run(() => openDownloadableArtifact(id, undefined, process.env))); + await started; + openings.push(runtime.run(() => openDownloadableArtifact(id, undefined, process.env))); + for (const opening of openings) void opening.catch(() => {}); + runtime.dispose(); + expect(archiveSignal?.aborted).toBe(true); + expect(fs.existsSync(artifactPath)).toBe(true); + expect(fs.existsSync(archiveDir)).toBe(true); + continueArchive(); + for (const opening of openings) { + await expect(opening).rejects.toMatchObject({ details: { reason: 'RESOURCE_EXPIRED' } }); + } + expect(archive).toHaveBeenCalledTimes(1); + expect(fs.existsSync(artifactPath)).toBe(false); + expect(fs.existsSync(archiveDir)).toBe(false); + } finally { + continueArchive(); + await Promise.allSettled(openings); + runtime.dispose(); + archive.mockRestore(); + } +}); + +function holdArtifactReads() { + const pending: Array<{ file: string; complete: () => void }> = []; + const createReadStream = fs.createReadStream; + let held = true; + const spy = vi.spyOn(fs, 'createReadStream').mockImplementation((file, options) => + createReadStream(file, { + ...(typeof options === 'string' ? { encoding: options } : options), + fs: { + open: fs.open, + close: fs.close, + read(fd, buffer, offset, length, position, callback) { + fs.read(fd, buffer, offset, length, position, (error, bytesRead, readBuffer) => { + const complete = () => callback(error, bytesRead, readBuffer); + if (held) pending.push({ file: String(file), complete }); + else complete(); + }); + }, + }, + }), + ); + return { + pending, + release: () => { + held = false; + for (const { complete } of pending.splice(0)) complete(); + }, + restore: () => spy.mockRestore(), + }; +} + +test.each(['old-first', 'new-first'] as const)( + 'disposing two deferred registrations cleans their shared source after pending reads close (%s)', + async (order) => { + const root = mkdtempForTestSync('fu-art-shared-dispose-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), 'shared source marker'); + const runtime = createRuntimeStateHandle(); + const reads = holdArtifactReads(); + const removed = vi.spyOn(fs, 'rmSync'); + const downloads: OpenedDownloadableArtifact[] = []; + const track = () => + runtime.run(() => trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' })); + try { + const firstId = track(); + downloads.push( + await runtime.run(() => openDownloadableArtifact(firstId, undefined, process.env)), + ); + runtime.run(() => cleanupDownloadableArtifact(firstId)); + const secondId = track(); + expect(secondId).not.toBe(firstId); + downloads.push( + await runtime.run(() => openDownloadableArtifact(secondId, undefined, process.env)), + ); + runtime.run(() => cleanupDownloadableArtifact(secondId)); + for (const download of downloads) download.stream.resume(); + await vi.waitFor(() => expect(reads.pending).toHaveLength(2)); + runtime.dispose(); + expect(fs.existsSync(artifactPath)).toBe(true); + for (const download of downloads) expect(download.stream.closed).toBe(false); + const firstToClose = downloads[order === 'old-first' ? 0 : 1]!; + const pendingIndex = reads.pending.findIndex( + ({ file }) => file === String(firstToClose.stream.path), + ); + expect(pendingIndex).toBeGreaterThanOrEqual(0); + reads.pending.splice(pendingIndex, 1)[0]!.complete(); + await vi.waitFor(() => + expect(downloads.filter(({ stream }) => stream.closed)).toHaveLength(1), + ); + expect(firstToClose.stream.closed).toBe(true); + expect(fs.existsSync(artifactPath)).toBe(true); + reads.release(); + await vi.waitFor(() => expect(fs.existsSync(artifactPath)).toBe(false)); + for (const download of downloads) { + expect(download.stream.closed).toBe(true); + const archiveDir = path.dirname(String(download.stream.path)); + expect(fs.existsSync(archiveDir)).toBe(false); + expect(removed.mock.calls.filter(([target]) => target === archiveDir)).toHaveLength(1); + } + expect(removed.mock.calls.filter(([target]) => target === artifactPath)).toHaveLength(1); + } finally { + reads.release(); + runtime.dispose(); + for (const { stream } of downloads) { + if (!stream.closed) await once(stream, 'close'); + } + reads.restore(); + removed.mockRestore(); + } + }, +); + +test.each(['expiry-first', 'deadline-first'] as const)( + 'a stalled directory read cleans up after registration expiry and its own deadline (%s)', + async (order) => { + const root = mkdtempForTestSync('fu-art-stalled-expiry-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), 'stalled source marker'); + const runtime = createRuntimeStateHandle(); + const reads = holdArtifactReads(); + const timers = vi.spyOn(globalThis, 'setTimeout'); + const clearedTimers = vi.spyOn(globalThis, 'clearTimeout'); + const removed = vi.spyOn(fs, 'rmSync'); + let download: OpenedDownloadableArtifact | undefined; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + const expire = timers.mock.calls.at(-1)![0]; + const expiryTimer = timers.mock.results.at(-1)!.value; + const timerIndex = timers.mock.calls.length; + const opening = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + const deadline = timers.mock.calls[timerIndex]![0]; + download = await opening; + const archiveDir = path.dirname(String(download.stream.path)); + download.stream.resume(); + await vi.waitFor(() => expect(reads.pending).toHaveLength(1)); + if (order === 'expiry-first') runtime.run(expire); + expect(download.stream.destroyed).toBe(false); + expect(fs.existsSync(artifactPath)).toBe(true); + expect(fs.existsSync(archiveDir)).toBe(true); + runtime.run(deadline); + expect(download.signal.aborted).toBe(true); + expect(download.stream.destroyed).toBe(true); + expect(download.stream.closed).toBe(false); + expect(fs.existsSync(artifactPath)).toBe(true); + reads.release(); + await vi.waitFor(() => expect(download!.stream.closed).toBe(true)); + if (order === 'deadline-first') { + expect(fs.existsSync(artifactPath)).toBe(true); + expect(fs.existsSync(archiveDir)).toBe(true); + expect(clearedTimers.mock.calls.some(([timer]) => timer === expiryTimer)).toBe(false); + runtime.run(expire); + } + await vi.waitFor(() => expect(fs.existsSync(artifactPath)).toBe(false)); + expect(download.stream.closed).toBe(true); + expect(fs.existsSync(archiveDir)).toBe(false); + for (const target of [artifactPath, archiveDir]) { + expect(removed.mock.calls.filter(([removedPath]) => removedPath === target)).toHaveLength( + 1, + ); + } + } finally { + reads.release(); + runtime.dispose(); + if (download && !download.stream.closed) await once(download.stream, 'close'); + timers.mockRestore(); + clearedTimers.mockRestore(); + reads.restore(); + removed.mockRestore(); + } + }, +); test('disposing a runtime removes the temporary files it still tracks', () => { const root = mkdtempForTestSync('agent-device-artifact-dispose-'); @@ -49,3 +335,76 @@ test('a file tracked twice for one tenant keeps one id, and another tenant gets expect(again).toBe(first); expect(otherTenant).not.toBe(first); }); + +test.each( + (['old-first', 'new-first'] as const).flatMap((order) => + [true, false].map((deleteAfterDownload) => ({ order, deleteAfterDownload })), + ), +)( + 're-registering a directory during deferred cleanup keeps both downloads alive ($order, deleteAfterDownload=$deleteAfterDownload)', + async ({ order, deleteAfterDownload }) => { + const root = mkdtempForTestSync('fu-art-register-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + const payloadPath = path.join(artifactPath, 'payload'); + fs.writeFileSync(payloadPath, 'original capture marker'); + const runtime = createRuntimeStateHandle(); + const downloads: OpenedDownloadableArtifact[] = []; + const track = (deleteAfterDownload = true) => + runtime.run(() => + trackDownloadableArtifact({ + artifactPath, + artifactType: 'trace-log', + tenantId: 'tenant-a', + deleteAfterDownload, + }), + ); + const open = async (id: string) => { + const artifact: OpenedDownloadableArtifact = await runtime.run(() => + openDownloadableArtifact(id, 'tenant-a', process.env), + ); + downloads.push(artifact); + return artifact; + }; + const read = async (download: OpenedDownloadableArtifact, expected: string) => { + const { stream } = download; + const closed = once(stream, 'close'); + const bytes = await buffer(stream); + await closed; + download.release(); + download.release(); + expect(gunzipSync(bytes).includes(Buffer.from(expected))).toBe(true); + expect(fs.existsSync(path.dirname(String(stream.path)))).toBe(false); + }; + try { + const firstId = track(); + const first = await open(firstId); + runtime.run(() => cleanupDownloadableArtifact(firstId)); + fs.writeFileSync(payloadPath, 'replacement capture marker'); + const nextId = track(deleteAfterDownload); + expect(nextId).not.toBe(firstId); + if (order === 'old-first') { + await read(first, 'original capture marker'); + expect(fs.existsSync(artifactPath)).toBe(true); + } + const next = await open(nextId); + runtime.run(() => cleanupDownloadableArtifact(nextId)); + await read(next, 'replacement capture marker'); + if (order === 'new-first') { + expect(fs.existsSync(artifactPath)).toBe(true); + await read(first, 'original capture marker'); + } + expect(fs.existsSync(artifactPath)).toBe(!deleteAfterDownload); + } finally { + for (const download of downloads) { + if (!download.stream.closed) { + const closed = once(download.stream, 'close'); + download.stream.destroy(); + await closed; + } + download.release(); + } + runtime.dispose(); + } + }, +); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 16db460766..4bc868a76f 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -3,6 +3,7 @@ import crypto from 'node:crypto'; 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 type { DaemonArtifactType } from '@agent-device/kernel/contracts'; import type { DeviceRotation } from '@agent-device/contracts/device'; @@ -17,6 +18,7 @@ import { // --- Downloadable artifact tracking --- const ARTIFACT_CLEANUP_TIMEOUT_MS = 15 * 60 * 1000; +const ARTIFACT_DOWNLOAD_MAX_LIFETIME_MS = 15 * 60 * 1000; const DOWNLOADABLE_ARTIFACT_RESOURCE: TenantOwnedResourceKind = { label: 'Artifact', @@ -32,6 +34,17 @@ type DirectoryArchive = { sizeBytes: number; }; +type ArtifactSourceCleanup = { + remainingEntries: number; + deleteAfterDownload: boolean; +}; + +type ArtifactDownload = { + controller: AbortController; + stream?: fs.ReadStream; + release: () => void; +}; + type ArtifactEntry = { artifactPath: string; tenantId?: string; @@ -39,10 +52,13 @@ type ArtifactEntry = { fileName?: string; displayRotation?: DeviceRotation; sessionName?: string; - deleteAfterDownload: boolean; + sourceCleanup: ArtifactSourceCleanup; createdAt: number; directoryArchive?: DirectoryArchive; directoryArchivePromise?: Promise; + archiveAbortController?: AbortController; + activeDownloads: Set; + cleanupRequested: boolean; timer: ReturnType; }; @@ -57,10 +73,9 @@ const artifactTracking = (): ArtifactTrackingState => ARTIFACT_TRACKING_SLOT, (): ArtifactTrackingState => ({ artifacts: new Map(), uploads: new Map() }), (state) => { - for (const entry of state.artifacts.values()) { - clearTimeout(entry.timer); - cleanupDirectoryArchive(entry); - if (entry.deleteAfterDownload) removeBestEffort(entry.artifactPath); + for (const [id, entry] of state.artifacts) { + requestArtifactCleanup(state.artifacts, id, entry); + for (const download of entry.activeDownloads) cancelArtifactDownload(id, entry, download); } for (const entry of state.uploads.values()) { clearTimeout(entry.timer); @@ -85,13 +100,20 @@ export type DownloadableArtifactRegistration = { export type TrackDownloadableArtifact = (registration: DownloadableArtifactRegistration) => string; -export type PreparedDownloadableArtifact = { +type PreparedDownloadableArtifact = { artifactPath: string; fileName?: string; mimeType: string; sizeBytes: number; }; +export type OpenedDownloadableArtifact = PreparedDownloadableArtifact & { + stream: fs.ReadStream; + signal: AbortSignal; + /** Release ownership after the download pipeline settles, including failure. */ + release: () => void; +}; + /** * Registers one file for download and returns its id. A file the same tenant can already download * returns its existing entry unchanged: two ids for one file would each delete it after their own @@ -106,6 +128,12 @@ export function trackDownloadableArtifact(params: DownloadableArtifactRegistrati cleanupDownloadableArtifact(artifactId); }, ARTIFACT_CLEANUP_TIMEOUT_MS); timer.unref(); + const sourceCleanup = findArtifactSourceCleanup(params.artifactPath) ?? { + remainingEntries: 0, + deleteAfterDownload: true, + }; + sourceCleanup.remainingEntries += 1; + sourceCleanup.deleteAfterDownload &&= params.deleteAfterDownload !== false; pendingArtifacts().set(artifactId, { artifactPath: params.artifactPath, tenantId: params.tenantId, @@ -113,7 +141,9 @@ export function trackDownloadableArtifact(params: DownloadableArtifactRegistrati fileName: params.fileName, ...(params.displayRotation !== undefined ? { displayRotation: params.displayRotation } : {}), ...(params.sessionName !== undefined ? { sessionName: params.sessionName } : {}), - deleteAfterDownload: params.deleteAfterDownload !== false, + sourceCleanup, + activeDownloads: new Set(), + cleanupRequested: false, createdAt, timer, }); @@ -125,25 +155,79 @@ function findTrackedArtifactId( tenantId: string | undefined, ): string | undefined { for (const [artifactId, entry] of pendingArtifacts()) { - if (entry.artifactPath === artifactPath && entry.tenantId === tenantId) return artifactId; + if ( + !entry.cleanupRequested && + entry.artifactPath === artifactPath && + entry.tenantId === tenantId + ) + return artifactId; } return undefined; } -export async function prepareDownloadableArtifact( +function findArtifactSourceCleanup(artifactPath: string): ArtifactSourceCleanup | undefined { + for (const entry of pendingArtifacts().values()) { + if (entry.artifactPath === artifactPath) return entry.sourceCleanup; + } + return undefined; +} + +export async function openDownloadableArtifact( artifactId: string, tenantId: string | undefined, hostEnv: NodeJS.ProcessEnv, -): Promise { +): Promise { + const artifacts = pendingArtifacts(); const { entry, stat } = readDownloadableArtifactEntry(artifactId, tenantId); - const payload = await prepareArtifactPayload(artifactId, entry, stat, hostEnv); - if (!payload) { - throw new AppError( - 'COMMAND_FAILED', - `Artifact path is not a regular file or directory: ${entry.artifactPath}`, - ); + const download: ArtifactDownload = { + controller: new AbortController(), + release: () => { + if (!entry.activeDownloads.delete(download)) return; + clearTimeout(deadline); + if (entry.cleanupRequested) requestArtifactCleanup(artifacts, artifactId, entry); + }, + }; + entry.activeDownloads.add(download); + const deadline = setTimeout( + () => cancelArtifactDownload(artifactId, entry, download), + ARTIFACT_DOWNLOAD_MAX_LIFETIME_MS, + ); + deadline.unref(); + try { + const payload = await prepareArtifactPayload(artifactId, entry, stat, hostEnv); + download.controller.signal.throwIfAborted(); + if (!payload) { + throw new AppError( + 'COMMAND_FAILED', + `Artifact path is not a regular file or directory: ${entry.artifactPath}`, + ); + } + const stream = fs.createReadStream(payload.artifactPath); + download.stream = stream; + return { ...payload, stream, signal: download.controller.signal, release: download.release }; + } catch (error) { + download.release(); + throw error; + } +} + +function cancelArtifactDownload( + artifactId: string, + entry: ArtifactEntry, + download: ArtifactDownload, +): 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; } - return payload; + const closed = finished(download.stream, { cleanup: true }).catch(() => {}); + download.stream.destroy(); + void closed.then(download.release); } export async function listDownloadableArtifacts( @@ -161,7 +245,7 @@ export async function listDownloadableArtifacts( continue; } const payload = await prepareArtifactPayloadForInventory(id, entry, stat, hostEnv); - if (!payload) continue; + if (!payload || entry.cleanupRequested) continue; artifacts.push({ id, ...(entry.artifactType !== undefined ? { artifactType: entry.artifactType } : {}), @@ -201,6 +285,9 @@ function readDownloadableArtifactEntry( tenantId, DOWNLOADABLE_ARTIFACT_RESOURCE, ); + if (entry.cleanupRequested) { + throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); + } let stat: fs.Stats; try { stat = fs.statSync(entry.artifactPath); @@ -275,6 +362,8 @@ async function createDirectoryArchive( path.join(os.tmpdir(), `agent-device-download-${crypto.randomUUID()}-`), ); const archivePath = path.join(tempDir, fileName); + const controller = new AbortController(); + entry.archiveAbortController = controller; try { await runCmd( 'tar', @@ -287,27 +376,30 @@ async function createDirectoryArchive( path.basename(entry.artifactPath), ], { + signal: controller.signal, + timeoutMs: ARTIFACT_DOWNLOAD_MAX_LIFETIME_MS, env: { ...hostEnv, COPYFILE_DISABLE: '1', }, }, ); + controller.signal.throwIfAborted(); const archive = { archivePath, tempDir, fileName, sizeBytes: fs.statSync(archivePath).size, }; - // The artifact may be consumed or expire while tar is still archiving. - if (pendingArtifacts().get(artifactId) !== entry) { - fs.rmSync(tempDir, { recursive: true, force: true }); + // 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', @@ -315,6 +407,8 @@ async function createDirectoryArchive( { artifactPath: entry.artifactPath }, error instanceof Error ? error : undefined, ); + } finally { + if (entry.archiveAbortController === controller) entry.archiveAbortController = undefined; } } @@ -325,8 +419,7 @@ function archiveFilename(fileName: string): string { } function canReadArtifact(entry: ArtifactEntry, tenantId: string | undefined): boolean { - if (!entry.tenantId) return true; - return entry.tenantId === tenantId; + return !entry.cleanupRequested && (!entry.tenantId || entry.tenantId === tenantId); } function safeArtifactFilename(fileName: string | undefined, fallback: string): string { @@ -345,12 +438,29 @@ function hasUnsafeFilenameCharacter(fileName: string): boolean { } export function cleanupDownloadableArtifact(artifactId: string): void { - const entry = pendingArtifacts().get(artifactId); + const artifacts = pendingArtifacts(); + const entry = artifacts.get(artifactId); if (!entry) return; + requestArtifactCleanup(artifacts, artifactId, entry); +} + +function requestArtifactCleanup( + artifacts: Map, + artifactId: string, + entry: ArtifactEntry, +): void { + entry.cleanupRequested = true; clearTimeout(entry.timer); - pendingArtifacts().delete(artifactId); + if (entry.activeDownloads.size > 0 || artifacts.get(artifactId) !== entry) return; + entry.archiveAbortController?.abort( + expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId), + ); + artifacts.delete(artifactId); cleanupDirectoryArchive(entry); - if (entry.deleteAfterDownload) removeBestEffort(entry.artifactPath); + entry.sourceCleanup.remainingEntries -= 1; + if (entry.sourceCleanup.remainingEntries === 0 && entry.sourceCleanup.deleteAfterDownload) { + removeBestEffort(entry.artifactPath); + } } function removeBestEffort(targetPath: string): void { diff --git a/packages/daemon/src/server/downloadable-artifact-http.test.ts b/packages/daemon/src/server/downloadable-artifact-http.test.ts new file mode 100644 index 0000000000..aa8e14bccc --- /dev/null +++ b/packages/daemon/src/server/downloadable-artifact-http.test.ts @@ -0,0 +1,475 @@ +import crypto from 'node:crypto'; +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 { 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 * as artifactTracking from '../resources/artifact-tracking.ts'; +import { createDaemonHttpServer } from './http/http-server.ts'; + +function deferred() { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +type DownloadFixture = { + url: string; + source: string; + runtime: ReturnType; + streams: fs.ReadStream[]; + start(): void; + abortClient(): void; + failResponse(): void; + outcome(): 'pending' | 'complete' | 'failed'; + cleanupCount(): number; + expire(): void; + expiryPending(): boolean; + fireDeadlines(): void; +}; + +async function withDownloadFixture( + run: (fixture: DownloadFixture) => Promise, + configureStream: (stream: fs.ReadStream) => void, +): Promise { + const root = mkdtempForTestSync('fu-art-pipeline-'); + const source = path.join(root, 'capture.trace'); + fs.mkdirSync(source); + fs.writeFileSync(path.join(source, 'payload'), crypto.randomBytes(256 * 1024)); + const runtime = createRuntimeStateHandle(); + const server = await runtime.run(() => + createDaemonHttpServer({ + token: 'fu-art-secret', + handleRequest: async () => ({ ok: true, data: {} }), + env: process.env, + cwd: process.cwd(), + }), + ); + const port = await listenOnLoopback(server); + let activeResponse: http.ServerResponse | undefined; + server.on('request', (_request, response) => { + activeResponse = response; + }); + const timers = vi.spyOn(globalThis, 'setTimeout'); + const clearedTimers = vi.spyOn(globalThis, 'clearTimeout'); + const id = runtime.run(() => + artifactTracking.trackDownloadableArtifact({ artifactPath: source, artifactType: 'trace-log' }), + ); + const expire = timers.mock.calls[0]![0]; + const expiryTimer = timers.mock.results[0]!.value; + const removed = vi.spyOn(fs, 'rmSync'); + const streams: fs.ReadStream[] = []; + const createReadStream = fs.createReadStream; + const reads = vi.spyOn(fs, 'createReadStream').mockImplementation((file, options) => { + const stream = createReadStream(file, options); + streams.push(stream); + configureStream(stream); + return stream; + }); + const agent = new http.Agent({ keepAlive: true }); + let request: http.ClientRequest | undefined; + let outcome: 'pending' | 'complete' | 'failed' = 'pending'; + try { + await run({ + url: `http://127.0.0.1:${port}/artifacts/${id}`, + source, + runtime, + streams, + start: () => { + request = http.get( + `http://127.0.0.1:${port}/artifacts/${id}`, + { + agent, + headers: { authorization: 'Bearer fu-art-secret' }, + }, + (response) => { + response.on('end', () => { + outcome = 'complete'; + }); + response.on('aborted', () => { + outcome = 'failed'; + }); + response.on('error', () => { + outcome = 'failed'; + }); + response.resume(); + }, + ); + request.on('error', () => { + outcome = 'failed'; + }); + }, + abortClient: () => request?.destroy(), + failResponse: () => activeResponse?.destroy(new Error('injected response failure')), + outcome: () => outcome, + cleanupCount: () => removed.mock.calls.filter(([target]) => target === source).length, + expire: () => runtime.run(expire), + expiryPending: () => !clearedTimers.mock.calls.some(([timer]) => timer === expiryTimer), + fireDeadlines: () => { + for (const [index, [callback, delay]] of timers.mock.calls.entries()) { + const handle = timers.mock.results[index]!.value; + if ( + delay !== 15 * 60 * 1000 || + clearedTimers.mock.calls.some(([cleared]) => cleared === handle) + ) + continue; + runtime.run(callback); + } + }, + }); + } finally { + request?.destroy(); + agent.destroy(); + for (const stream of streams) { + if (stream.closed) continue; + const closed = new Promise((resolve) => stream.once('close', resolve)); + stream.destroy(); + await closed; + } + reads.mockRestore(); + timers.mockRestore(); + clearedTimers.mockRestore(); + await closeLoopbackServer(server); + runtime.dispose(); + removed.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'); + try { + await withDownloadFixture( + async (fixture) => { + 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]); + } + }, + () => {}, + ); + } finally { + proceed.resolve(); + opens.mockRestore(); + archive.mockRestore(); + } +}); + +test.each(['destroyed', 'truncated', 'errored'] as const)( + 'a %s artifact read terminates the HTTP response', + async (failure) => { + await withDownloadFixture( + async (fixture) => { + fixture.start(); + await vi.waitFor(() => expect(fixture.outcome()).toBe('failed')); + fixture.expire(); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + expect(fixture.cleanupCount()).toBe(1); + }, + (stream) => { + if (failure === 'truncated') { + stream.once('open', () => + fs.truncateSync(String(stream.path), fs.statSync(String(stream.path)).size - 1), + ); + } else { + let chunks = 0; + stream.on('data', () => { + if (++chunks === 2) + stream.destroy( + failure === 'errored' ? new Error('injected read failure') : undefined, + ); + }); + } + }, + ); + }, +); + +test('an artifact open failure returns a complete JSON error before streaming starts', async () => { + await withDownloadFixture( + async (fixture) => { + const response = await fetch(fixture.url, { + headers: { authorization: 'Bearer fu-art-secret' }, + }); + expect(response.status).toBe(500); + expect(response.headers.get('content-type')).toBe('application/json'); + expect(await response.json()).toMatchObject({ ok: false }); + fixture.expire(); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + }, + (stream) => fs.unlinkSync(String(stream.path)), + ); +}); + +test('a truncated directory archive preserves the source and expires without leaking its cached archive', async () => { + await withDownloadFixture( + async (fixture) => { + const payloadPath = path.join(fixture.source, 'payload'); + const expected = fs.readFileSync(payloadPath); + fixture.start(); + await vi.waitFor(() => expect(fixture.outcome()).toBe('failed')); + const stream = fixture.streams[0]!; + await vi.waitFor(() => expect(stream.closed).toBe(true)); + const archiveDir = path.dirname(String(stream.path)); + expect(fs.readFileSync(payloadPath)).toEqual(expected); + expect(fs.existsSync(archiveDir)).toBe(true); + expect(fixture.expiryPending()).toBe(true); + const inventory = await fetch(fixture.url.slice(0, fixture.url.lastIndexOf('/')), { + headers: { authorization: 'Bearer fu-art-secret' }, + }); + expect(await inventory.json()).toMatchObject({ + artifacts: [{ id: fixture.url.split('/').at(-1) }], + }); + fixture.expire(); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + expect(fs.existsSync(archiveDir)).toBe(false); + expect(fixture.cleanupCount()).toBe(1); + }, + (stream) => + stream.once('open', () => + fs.truncateSync(String(stream.path), fs.statSync(String(stream.path)).size - 1), + ), + ); +}); + +test.each(['deadline', 'runtime disposal'] as const)( + '%s cancels an active download and removes its files', + async (trigger) => { + const started = deferred(); + await withDownloadFixture( + async (fixture) => { + fixture.start(); + await started.promise; + if (trigger === 'deadline') fixture.fireDeadlines(); + else fixture.runtime.dispose(); + await vi.waitFor(() => expect(fixture.outcome()).toBe('failed')); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + expect(fixture.streams.every((stream) => stream.closed)).toBe(true); + expect(fixture.cleanupCount()).toBe(1); + for (const stream of fixture.streams) { + expect(fs.existsSync(path.dirname(String(stream.path)))).toBe(false); + } + }, + (stream) => + stream.once('data', () => { + stream.pause(); + started.resolve(); + }), + ); + }, +); + +test.each(['client abort', 'response error'] as const)( + '%s releases an active download before expiry cleanup', + async (failure) => { + const started = deferred(); + await withDownloadFixture( + async (fixture) => { + fixture.start(); + await started.promise; + if (failure === 'client abort') fixture.abortClient(); + else fixture.failResponse(); + await vi.waitFor(() => expect(fixture.outcome()).toBe('failed')); + fixture.expire(); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + expect(fixture.cleanupCount()).toBe(1); + }, + (stream) => + stream.once('data', () => { + stream.pause(); + started.resolve(); + }), + ); + }, +); + +test('a directory artifact expires after download header setup throws', async () => { + const root = mkdtempForTestSync('fu-art-header-error-'); + const source = path.join(root, 'profile.trace'); + fs.mkdirSync(source); + fs.writeFileSync(path.join(source, 'payload'), 'trace payload'); + const runtime = createRuntimeStateHandle(); + const server = await runtime.run(() => + createDaemonHttpServer({ + token: 'fu-art-secret', + handleRequest: async () => ({ ok: true, data: {} }), + env: process.env, + cwd: process.cwd(), + }), + ); + const port = await listenOnLoopback(server); + const timer = vi.spyOn(globalThis, 'setTimeout'); + const artifactId = runtime.run(() => + artifactTracking.trackDownloadableArtifact({ + artifactPath: source, + artifactType: 'trace-log', + fileName: 'trace-💥', + }), + ); + const expire = timer.mock.calls[0]![0]; + timer.mockRestore(); + const streams = vi.spyOn(fs, 'createReadStream'); + const controller = new AbortController(); + try { + const response = await fetch(`http://127.0.0.1:${port}/artifacts/${artifactId}`, { + headers: { authorization: 'Bearer fu-art-secret' }, + signal: controller.signal, + }); + expect(response.status).toBe(500); + let body: unknown; + const consumed = response.json().then((value: unknown) => { + body = value; + }); + void consumed.catch(() => {}); + await vi.waitFor(() => expect(body).toMatchObject({ ok: false })); + await consumed; + const stream = streams.mock.results[0]!.value as fs.ReadStream; + const archiveDir = path.dirname(String(stream.path)); + runtime.run(expire); + await vi.waitFor(() => expect(fs.existsSync(source)).toBe(false)); + expect(stream.closed).toBe(true); + expect(fs.existsSync(archiveDir)).toBe(false); + } finally { + controller.abort(); + for (const result of streams.mock.results) { + const stream = result.value as fs.ReadStream; + if (stream.closed) continue; + const closed = new Promise((resolve) => stream.once('close', resolve)); + stream.destroy(); + await closed; + } + streams.mockRestore(); + await closeLoopbackServer(server); + runtime.dispose(); + } +}); + +test.each(['another download completes', 'expiry fires'] as const)( + 'a directory download keeps its archive until its delayed file open finishes when %s', + async (trigger) => { + const root = mkdtempForTestSync('fu-art-download-'); + const source = path.join(root, 'profile.trace'); + fs.mkdirSync(source); + const expected = crypto.randomBytes(64 * 1024).toString('hex'); + fs.writeFileSync(path.join(source, 'payload'), expected); + const runtime = createRuntimeStateHandle(); + const server = await runtime.run(() => + createDaemonHttpServer({ + token: 'fu-art-secret', + handleRequest: async () => ({ ok: true, data: {} }), + env: process.env, + cwd: process.cwd(), + }), + ); + const port = await listenOnLoopback(server); + const headers = { authorization: 'Bearer fu-art-secret' }; + const timer = vi.spyOn(globalThis, 'setTimeout'); + const artifactId = runtime.run(() => + artifactTracking.trackDownloadableArtifact({ + artifactPath: source, + artifactType: 'trace-log', + }), + ); + const expire = timer.mock.calls[0]![0]; + timer.mockRestore(); + const url = `http://127.0.0.1:${port}/artifacts/${artifactId}`; + const opened = deferred(); + const release = deferred(); + const createReadStream = fs.createReadStream; + const cleanup = vi.spyOn(fs, 'rmSync'); + let archivePath = ''; + const streams: fs.ReadStream[] = []; + const spy = vi.spyOn(fs, 'createReadStream').mockImplementation((file, options) => { + archivePath = String(file); + const stream = createReadStream(file, { + ...(typeof options === 'object' ? options : {}), + fs: { + ...fs, + open: (filePath, flags, mode, callback) => { + opened.resolve(); + void release.promise.then(() => fs.open(filePath, flags, mode, callback)); + }, + }, + }); + streams.push(stream); + return stream; + }); + const download = () => + fetch(url, { headers }).then(async (response) => { + if (response.status !== 200) { + await response.body?.cancel(); + return { status: response.status, bytes: Buffer.alloc(0) }; + } + return { status: response.status, bytes: Buffer.from(await response.arrayBuffer()) }; + }); + const pending = download(); + try { + await opened.promise; + spy.mockRestore(); + let first: Awaited> | undefined; + if (trigger === 'another download completes') { + first = await download(); + expect(first.status).toBe(200); + } else { + runtime.run(expire); + } + const archiveDir = path.dirname(archivePath); + expect(fs.existsSync(archivePath)).toBe(true); + expect(fs.existsSync(source)).toBe(true); + expect((await fetch(url, { headers })).status).toBe(404); + const inventory = await fetch(`http://127.0.0.1:${port}/artifacts`, { headers }); + expect(await inventory.json()).toEqual({ artifacts: [] }); + release.resolve(); + const delayed = await pending; + expect(delayed.status).toBe(200); + if (first) expect(delayed.bytes).toEqual(first.bytes); + const downloaded = path.join(root, 'download.tar.gz'); + fs.writeFileSync(downloaded, delayed.bytes); + expect(command.runCmdSync('tar', ['-xOzf', downloaded, 'profile.trace/payload']).stdout).toBe( + expected, + ); + await vi.waitFor(() => expect(fs.existsSync(archiveDir)).toBe(false)); + expect(fs.existsSync(source)).toBe(false); + for (const target of [source, archiveDir]) { + expect(cleanup.mock.calls.filter(([removed]) => removed === target)).toHaveLength(1); + } + } finally { + release.resolve(); + spy.mockRestore(); + cleanup.mockRestore(); + for (const stream of streams) stream.destroy(); + await Promise.allSettled([pending]); + await closeLoopbackServer(server); + runtime.dispose(); + } + }, +); diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index 854afe1a5a..c6b4238783 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -1,13 +1,15 @@ -import fs from 'node:fs'; import http from 'node:http'; -import { normalizeError } from '@agent-device/kernel/errors'; +import { once } from 'node:events'; +import { Transform } from 'node:stream'; +import { finished, pipeline } from 'node:stream/promises'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; import type { DaemonRequest } from '../core/daemon-request.ts'; import { cleanupDownloadableArtifact, listDownloadableArtifacts, - prepareDownloadableArtifact, + openDownloadableArtifact, } from '../resources/artifact-tracking.ts'; -import { failStreamedHttpResponse, sendRestJsonError } from './http-errors.ts'; +import { sendRestJsonError } from './http-errors.ts'; import { decodeUriSegment } from './http-request-target.ts'; type DownloadableArtifactHttpRoute = @@ -92,44 +94,60 @@ async function handleArtifactDownload( }); if (!auth) return; - const artifact = await prepareDownloadableArtifact(artifactId, auth.tenantId, options.hostEnv); - const retainArtifactAfterDownload = options.retainArtifacts === true; - const stream = fs.createReadStream(artifact.artifactPath); - res.statusCode = 200; - res.setHeader('content-type', artifact.mimeType); - res.setHeader('content-length', String(artifact.sizeBytes)); - if (artifact.fileName) { - res.setHeader( - 'content-disposition', - `attachment; filename="${artifact.fileName.replace(/"/g, '')}"`, - ); - } - stream.on('error', (error) => { - failStreamedHttpResponse(res, error); - }); - let didCleanupArtifact = false; - const cleanupCompletedDownload = () => { - if (didCleanupArtifact || retainArtifactAfterDownload) return; - didCleanupArtifact = true; - cleanupDownloadableArtifact(artifactId); - }; - // Consume before the final chunk is written to the client: fetch treats a - // download as complete once content-length bytes arrive, which can happen - // before this stream emits 'end' (that needs one more threadpool read). - let bytesSent = 0; - stream.on('data', (chunk: string | Buffer) => { - bytesSent += chunk.length; - if (bytesSent >= artifact.sizeBytes) cleanupCompletedDownload(); - }); - stream.on('end', cleanupCompletedDownload); - res.on('finish', cleanupCompletedDownload); - res.on('close', () => { - if (res.writableFinished) { - cleanupCompletedDownload(); + const artifact = await openDownloadableArtifact(artifactId, auth.tenantId, options.hostEnv); + const { stream } = artifact; + const closed = finished(stream, { cleanup: true }).catch(() => {}); + try { + artifact.signal.throwIfAborted(); + if (stream.errored) throw stream.errored; + if (stream.pending) await once(stream, 'ready', { signal: artifact.signal }); + res.statusCode = 200; + res.setHeader('content-type', artifact.mimeType); + res.setHeader('content-length', String(artifact.sizeBytes)); + if (artifact.fileName) { + res.setHeader( + 'content-disposition', + `attachment; filename="${artifact.fileName.replace(/"/g, '')}"`, + ); } - }); - stream.pipe(res); + let bytesRead = 0; + const checked = new Transform({ + transform(chunk: Buffer, _encoding, callback) { + bytesRead += chunk.length; + if (bytesRead >= artifact.sizeBytes && options.retainArtifacts !== true) { + cleanupDownloadableArtifact(artifactId); + } + callback(null, chunk); + }, + flush(callback) { + if (bytesRead !== artifact.sizeBytes) { + callback( + new AppError('COMMAND_FAILED', 'Artifact read did not match its declared size', { + reason: 'artifact_size_mismatch', + expectedBytes: artifact.sizeBytes, + actualBytes: bytesRead, + }), + ); + return; + } + if (options.retainArtifacts !== true) cleanupDownloadableArtifact(artifactId); + callback(); + }, + }); + await pipeline(stream, checked, res, { signal: artifact.signal }); + } finally { + stream.destroy(); + await closed; + 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)); } } diff --git a/packages/daemon/src/server/http/http-server-remote-output.test.ts b/packages/daemon/src/server/http/http-server-remote-output.test.ts index 5a67b854fb..3762f2e7d1 100644 --- a/packages/daemon/src/server/http/http-server-remote-output.test.ts +++ b/packages/daemon/src/server/http/http-server-remote-output.test.ts @@ -688,7 +688,7 @@ test.each( ); expect(reportDownload.status).toBe(200); expect(await reportDownload.text()).toBe('generated-report'); - } else expect(fs.existsSync(output)).toBe(false); + } else await vi.waitFor(() => expect(fs.existsSync(output)).toBe(false)); }); }, ); @@ -837,7 +837,7 @@ test.each(['./capture.log', undefined])( }); expect(download.status).toBe(200); expect(await download.text()).toContain('generated-trace'); - expect(fs.existsSync(output)).toBe(false); + await vi.waitFor(() => expect(fs.existsSync(output)).toBe(false)); }); }, ); @@ -930,7 +930,7 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite expect(download.status).toBe(200); const archive = gunzipSync(Buffer.from(await download.arrayBuffer())); expect(archive.includes(Buffer.from('tenant-a-private-marker'))).toBe(false); - expect(fs.existsSync(secondPath)).toBe(false); + await vi.waitFor(() => expect(fs.existsSync(secondPath)).toBe(false)); expect(fs.readFileSync(path.join(firstPath, 'private-a.txt'), 'utf8')).toBe( 'tenant-a-private-marker', ); @@ -947,8 +947,10 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite expect(own.status).toBe(200); await own.arrayBuffer(); } - expect(fs.existsSync(firstPath)).toBe(false); - expect(fs.existsSync(registrations[2]!.path)).toBe(false); + await vi.waitFor(() => { + expect(fs.existsSync(firstPath)).toBe(false); + expect(fs.existsSync(registrations[2]!.path)).toBe(false); + }); }, env, ); diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 7eb63460e7..cb7b48b017 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -71,7 +71,7 @@ "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:9f51e86c19cd4f5d8097f1c5ce38dc1daa795b803a6afc89d16cd556371ea037", + "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:54b5a8817237d38502f8ae56d8e754217c811520110deb3f2637264e68534f98", "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", @@ -257,8 +257,8 @@ }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload", - "digest": "sha256:9f51e86c19cd4f5d8097f1c5ce38dc1daa795b803a6afc89d16cd556371ea037", - "rationale": "#3753 threads the daemon runtime's host environment into the directory-archive spawn instead of the module reading process.env. Request parsing, authorization, response framing, headers, and cleanup are unchanged; no peer-visible field moves." + "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." }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory", diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 18975a9141..c27d1a11f6 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -84,6 +84,12 @@ the daemon. When you specify an output path through the CLI, SDK, or MCP, it sel destination on your machine. Direct RPC callers receive artifact IDs and download each result with `GET /artifacts/` using the same authentication. +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. +Each download has a 15-minute maximum lifetime. When it reaches that limit, the daemon cancels it +and cleans up after its pipeline stops. + Remote requests ignore `meta.cwd`. They refuse host tooling paths, `--launch-console`, and script publication with reason `REMOTE_HOST_INPUT_DENIED`. They also refuse daemon host paths as `install` and `reinstall` binaries, `push` payload files, and xctrace template files. Upload binaries with the