Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/contracts/src/daemon-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ export const DAEMON_HTTP_TENANT_HEADER = 'x-agent-device-tenant';
// as RPC calls name it in their body. The daemon reads it for lease admission and a gateway
// can route the request to the daemon holding the lease. The header is caller-declared.
export const DAEMON_HTTP_LEASE_HEADER = 'x-agent-device-lease-id';
/** Why an upload is refused before its staging directory is created. */
export const UPLOAD_CAPACITY_REASONS = {
// A new upload would exceed the active upload count or reserved byte budget.
exceeded: { reason: 'UPLOAD_CAPACITY_EXCEEDED' },
} as const satisfies ReasonTable<'uploads'>;
export const DAEMON_HTTP_RUN_HEADER = 'x-agent-device-run-id';
export const DAEMON_HTTP_NETWORK_ACCESS_HEADER = 'x-agent-device-network-access';
export const DAEMON_HTTP_PUBLIC_NETWORK_ACCESS = 'public-only';
Expand Down
59 changes: 57 additions & 2 deletions packages/daemon/src/resources/artifact-tracking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ type ArtifactEntry = {
type ArtifactTrackingState = {
artifacts: Map<string, ArtifactEntry>;
uploads: Map<string, UploadEntry>;
onStagedUploadCleanupDeferred?: (tempDir: string, error: unknown, retryDelayMs: number) => void;
};

const ARTIFACT_TRACKING_SLOT = Symbol('artifactTracking');
Expand All @@ -94,13 +95,19 @@ const artifactTracking = (): ArtifactTrackingState =>
}
for (const entry of state.uploads.values()) {
clearTimeout(entry.timer);
removeBestEffort(entry.tempDir);
removeStagedUpload(entry.tempDir, entry.releaseReservation);
}
},
);
const pendingArtifacts = () => artifactTracking().artifacts;
const pendingUploads = () => artifactTracking().uploads;

export function setStagedUploadCleanupDiagnostic(
emit: NonNullable<ArtifactTrackingState['onStagedUploadCleanupDeferred']>,
): void {
artifactTracking().onStagedUploadCleanupDeferred = emit;
}

/** What a finished request registers for each artifact it hands back to the client. */
export type DownloadableArtifactRegistration = {
artifactPath: string;
Expand Down Expand Up @@ -532,6 +539,7 @@ function cleanupDirectoryArchive(entry: ArtifactEntry): void {
// --- Upload artifact tracking ---

const UPLOAD_CLEANUP_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
const STAGED_UPLOAD_RETRY_DELAY_MS = 30_000;

const UPLOADED_ARTIFACT_RESOURCE: TenantOwnedResourceKind = {
label: 'Uploaded artifact',
Expand All @@ -543,6 +551,7 @@ type UploadEntry = {
tempDir: string;
tenantId?: string;
leaseId?: string;
releaseReservation?: () => void;
timer: ReturnType<typeof setTimeout>;
};

Expand All @@ -551,6 +560,7 @@ export function trackUploadedArtifact(params: {
tempDir: string;
tenantId?: string;
leaseId?: string;
releaseReservation?: () => void;
}): string {
const uploadId = crypto.randomUUID();
const timer = setTimeout(() => {
Expand All @@ -562,6 +572,7 @@ export function trackUploadedArtifact(params: {
tempDir: params.tempDir,
tenantId: params.tenantId,
leaseId: normalizeLeaseId(params.leaseId) ?? params.leaseId,
releaseReservation: params.releaseReservation,
timer,
});
return uploadId;
Expand Down Expand Up @@ -592,5 +603,49 @@ export function cleanupUploadedArtifact(uploadId: string): void {
if (!entry) return;
clearTimeout(entry.timer);
pendingUploads().delete(uploadId);
fs.rmSync(entry.tempDir, { recursive: true, force: true });
removeStagedUpload(entry.tempDir, entry.releaseReservation);
}

export function removeStagedUpload(tempDir: string, releaseReservation?: () => void): void {
removeStagedUploadSync(tempDir, releaseReservation, true);
}

function removeStagedUploadSync(
tempDir: string,
releaseReservation: (() => void) | undefined,
firstAttempt: boolean,
): void {
try {
fs.rmSync(tempDir, { recursive: true, force: true });
} catch (error) {
retryRemoval(tempDir, releaseReservation);
if (firstAttempt) reportStagedUploadCleanupDeferred(tempDir, error);
return;
}
releaseReservation?.();
}

export async function removeStagedUploadAsync(
tempDir: string,
releaseReservation: () => void,
): Promise<void> {
try {
await fs.promises.rm(tempDir, { recursive: true, force: true });
} catch (error) {
retryRemoval(tempDir, releaseReservation);
reportStagedUploadCleanupDeferred(tempDir, error);
throw error;
}
releaseReservation();
}

function retryRemoval(tempDir: string, releaseReservation?: () => void): void {
setTimeout(
() => removeStagedUploadSync(tempDir, releaseReservation, false),
STAGED_UPLOAD_RETRY_DELAY_MS,
).unref();
}
Comment thread
thymikee marked this conversation as resolved.
Resolved

function reportStagedUploadCleanupDeferred(tempDir: string, error: unknown): void {
artifactTracking().onStagedUploadCleanupDeferred?.(tempDir, error, STAGED_UPLOAD_RETRY_DELAY_MS);
}
84 changes: 84 additions & 0 deletions packages/daemon/src/server/__tests__/resumable-upload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,43 @@ test('expiry aborts an active receive and invalidates the ticket after rollback'
}
});

test('expiry owns staged removal when active receive rollback fails', async () => {
vi.useFakeTimers();
const accepted = acceptedWrite();
const truncate = vi.spyOn(fs.promises, 'truncate').mockRejectedValueOnce(new Error('busy'));
const remove = vi.spyOn(fs.promises, 'rm').mockRejectedValueOnce(new Error('busy'));
const retry = vi.spyOn(fs, 'rmSync');
const uploadId = beginUpload(Buffer.from('AB')).uploadId;
const body = requestStream();
const receiving = receiveResumableUploadChunk({
uploadId,
req: body,
onAcceptedBytes: accepted.resolve,
});
const rolledBack = assert.rejects(
receiving,
(error: unknown) =>
error instanceof AppError && error.details?.reason === 'UPLOAD_ROLLBACK_FAILED',
);
try {
body.write('A');
await accepted.promise;
await vi.advanceTimersByTimeAsync(5 * 60 * 1000);
await rolledBack;
await vi.advanceTimersByTimeAsync(0);
assert.equal(truncate.mock.calls.length, 1);
assert.equal(remove.mock.calls.length, 1);
assert.equal(retry.mock.calls.length, 0);
await vi.advanceTimersByTimeAsync(30_000);
assert.equal(retry.mock.calls.length, 1);
} finally {
body.destroy();
await vi.advanceTimersByTimeAsync(30_000);
vi.restoreAllMocks();
vi.useRealTimers();
}
});

test('an ignored out-of-order chunk does not extend upload expiry', async () => {
vi.useFakeTimers();
try {
Expand Down Expand Up @@ -610,6 +647,7 @@ test('upload preflights reserve tenant capacity and preserve idempotent tickets'
};
const first = beginResumableUpload(options);
beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() });
beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() });
assert.equal(beginResumableUpload(options).uploadId, first.uploadId);
assert.throws(
() => beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() }),
Expand All @@ -622,6 +660,52 @@ test('upload preflights reserve tenant capacity and preserve idempotent tickets'
}
});

test('expired upload keeps staged capacity through a failed removal and retry', async () => {
vi.useFakeTimers();
const cleanupStarted = acceptedWrite();
const cleanupAllowed = acceptedWrite();
const cleanupFinished = acceptedWrite();
vi.spyOn(fs.promises, 'rm').mockImplementationOnce(async () => {
cleanupStarted.resolve();
await cleanupAllowed.promise;
cleanupFinished.resolve();
throw Object.assign(new Error('staging directory is busy'), { code: 'EBUSY' });
});
try {
const options = {
...uploadOptions(Buffer.alloc(0)),
tenantId: 'expiry-capacity-tenant',
sizeBytes: 2 * 1024 * 1024 * 1024,
};
beginResumableUpload(options);
await vi.advanceTimersByTimeAsync(60 * 1000);
beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() });
beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() });
await vi.advanceTimersByTimeAsync(4 * 60 * 1000);
await cleanupStarted.promise;
const beginNext = () =>
beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() });
const assertCapacityHeld = () =>
assert.throws(
beginNext,
(error: unknown) =>
error instanceof AppError && error.details?.reason === 'UPLOAD_CAPACITY_EXCEEDED',
);
assertCapacityHeld();
cleanupAllowed.resolve();
await cleanupFinished.promise;
await vi.advanceTimersByTimeAsync(0);
assertCapacityHeld();
await vi.advanceTimersByTimeAsync(30_000);
beginNext();
} finally {
cleanupAllowed.resolve();
vi.restoreAllMocks();
await vi.advanceTimersByTimeAsync(5 * 60 * 1000);
vi.useRealTimers();
}
});

function beginUpload(bytes: Buffer): ReturnType<typeof beginResumableUpload> {
return beginResumableUpload(uploadOptions(bytes));
}
Expand Down
113 changes: 113 additions & 0 deletions packages/daemon/src/server/__tests__/upload-http-capacity.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import assert from 'node:assert/strict';
import { createHash, randomUUID } from 'node:crypto';
import { test } from 'vitest';
import {
MAX_ARCHIVE_EXPANDED_BYTES,
MAX_ARTIFACT_COMPRESSED_BYTES,
} from '@agent-device/host-kit/archive';
import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots';
import { createDaemonProxyServer } from '@agent-device/proxy';
import {
closeLoopbackServer,
listenOnLoopback,
skipWhenLoopbackUnavailable,
} from '@agent-device/test-kit';
import { cleanupUploadedArtifact } from '../../resources/artifact-tracking.ts';
import { createDaemonHttpServer } from '../http/http-server.ts';
import { reserveUploadCapacity } from '../upload-capacity.ts';

test('the staging budget admits one maximum-size archive and its expanded contents', () => {
const reservation = reserveUploadCapacity('archive-tenant', MAX_ARTIFACT_COMPRESSED_BYTES);
try {
assert.doesNotThrow(() => reservation.addBytes(MAX_ARCHIVE_EXPANDED_BYTES));
} finally {
reservation.release();
}
});

test('legacy uploads use the same staged capacity over direct and proxied HTTP', async (t) => {
if (await skipWhenLoopbackUnavailable(t, 'upload capacity')) return;
const env = { ...process.env };
delete env.AGENT_DEVICE_HTTP_AUTH_HOOK;
const runtime = createRuntimeStateHandle();
const server = await runtime.run(() =>
createDaemonHttpServer({
token: 'test-token',
env,
cwd: process.cwd(),
handleRequest: async () => ({ ok: true, data: {} }),
}),
);
try {
const port = await listenOnLoopback(server);
const base = `http://127.0.0.1:${port}`;
const auth = { authorization: 'Bearer test-token', 'x-agent-device-tenant': 'tenant-a' };
const emptyHash = createHash('sha256').update('').digest('hex');
const declaredBytes = Buffer.byteLength('new-app');
for (const [index, sizeBytes] of [
Comment thread
thymikee marked this conversation as resolved.
Resolved
MAX_ARTIFACT_COMPRESSED_BYTES,
MAX_ARTIFACT_COMPRESSED_BYTES,
MAX_ARTIFACT_COMPRESSED_BYTES - declaredBytes,
].entries()) {
const preflight = await fetch(`${base}/upload/preflight`, {
method: 'POST',
headers: { ...auth, 'content-type': 'application/json' },
body: JSON.stringify({
sha256: emptyHash,
uploadAttemptId: randomUUID(),
fileName: `empty-${index}.apk`,
sizeBytes,
artifactType: 'file',
}),
});
assert.equal(preflight.status, 200);
await preflight.json();
}

const uploadLegacy = (origin: string, token: string) =>
fetch(`${origin}/upload`, {
method: 'POST',
headers: {
...auth,
authorization: `Bearer ${token}`,
'x-artifact-type': 'file',
'x-artifact-filename': 'new.apk',
'content-length': String(declaredBytes),
},
body: 'new-app',
});
const admittedWithDeclaredLength = await uploadLegacy(base, 'test-token');
assert.equal(admittedWithDeclaredLength.status, 200);
const retainedId = ((await admittedWithDeclaredLength.json()) as { uploadId: string }).uploadId;

const full = await uploadLegacy(base, 'test-token');
assert.equal(full.status, 503);
const refusal = (await full.json()) as { reason?: string };
assert.equal(refusal.reason, 'UPLOAD_CAPACITY_EXCEEDED');

runtime.run(() => cleanupUploadedArtifact(retainedId));
const proxy = createDaemonProxyServer({
upstreamBaseUrl: base,
upstreamToken: 'test-token',
clientToken: 'proxy-token',
});
try {
const proxyPort = await listenOnLoopback(proxy);
const admittedThroughProxy = await uploadLegacy(
`http://127.0.0.1:${proxyPort}`,
'proxy-token',
);
assert.equal(admittedThroughProxy.status, 200);
const uploaded = (await admittedThroughProxy.json()) as { uploadId: string };
assert.ok(uploaded.uploadId);
} finally {
await closeLoopbackServer(proxy);
}
} finally {
try {
await closeLoopbackServer(server);
} finally {
runtime.dispose();
}
}
});
4 changes: 4 additions & 0 deletions packages/daemon/src/server/artifact-archive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export async function extractTarInstallableArtifact(params: {
platform: 'ios' | 'android';
expectedRootName?: string;
signal?: AbortSignal;
reserveExpandedBytes?: (bytes: number) => void;
}): Promise<string> {
params.signal?.throwIfAborted();
const outputRoot = path.join(params.tempDir, 'extracted');
Expand All @@ -23,6 +24,9 @@ export async function extractTarInstallableArtifact(params: {
signal: params.signal,
validateManifest: (manifest) => {
rootName = resolveArchiveRootName(manifest, params.platform, params.expectedRootName);
params.reserveExpandedBytes?.(
manifest.reduce((bytes, entry) => bytes + (entry.kind === 'file' ? entry.size : 0), 0),
);
},
Comment thread
thymikee marked this conversation as resolved.
Resolved
});
params.signal?.throwIfAborted();
Expand Down
5 changes: 4 additions & 1 deletion packages/daemon/src/server/artifact-download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ export function createArtifactTempDir(requestId?: string): string {
return fs.mkdtempSync(path.join(os.tmpdir(), `${TEMP_PREFIX}${scope}-`));
}

export function validateArtifactContentLength(rawLength: string | number | undefined): void {
export function validateArtifactContentLength(
rawLength: string | number | undefined,
): number | undefined {
if (rawLength === undefined) return;
const raw = String(rawLength);
if (!/^\d+$/.test(raw)) {
Expand All @@ -36,6 +38,7 @@ export function validateArtifactContentLength(rawLength: string | number | undef
`Upload exceeds maximum size of ${MAX_ARTIFACT_COMPRESSED_BYTES} bytes`,
);
}
return parsed;
}

function sanitizeRequestId(raw: string | undefined): string {
Expand Down
Loading
Loading