Skip to content
Merged
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
10 changes: 7 additions & 3 deletions src/commands/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { apiFlags } from '../config/flags/api.flags.js';
import { jsonFlag } from '../config/flags/output.flags.js';
import {
type DownloadResult,
downloadsSucceeded,
ReportDownloadService,
reportFormatDeprecation,
} from '../services/report-download.service.js';
Expand Down Expand Up @@ -140,12 +141,15 @@ export const artifactsCommand = defineCommand({
if (result) downloads.push(result);
}

// Downloading is this command's only job, so a failed or incomplete
// download exits 1, with or without --json. Its warning is already
// printed, and fail() prints nothing more (no second JSON object).
const ok = downloadsSucceeded(downloads);
if (json) {
const ok = downloads.some((d) => d.ok);
logger.json({ status: ok ? 'SUCCESS' : 'FAILED', uploadId, downloads });
// Same exit code a thrown error would give, without a second JSON object.
if (!ok) logger.fail('Every download failed', 1);
}

if (!ok) logger.fail('Download failed', 1);
},
});

Expand Down
60 changes: 60 additions & 0 deletions src/gateways/api-gateway.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createWriteStream, mkdirSync } from 'node:fs';
import { rm } from 'node:fs/promises';
import { homedir } from 'node:os';
import * as path from 'node:path';
import { Readable } from 'node:stream';
Expand All @@ -19,6 +20,7 @@ import type {
} from '../types/domain/live.types.js';
import type { TeamSettings } from '../types/domain/team-settings.types.js';
import { components, paths } from '../types/generated/schema.types.js';
import { assertCompleteZip, IncompleteZipError } from '../utils/zip-integrity.js';

/** Expand a leading `~` to the home directory, as the download paths allow. */
function expandHome(p: string): string {
Expand Down Expand Up @@ -402,9 +404,52 @@ export const ApiGateway = {
bytes_received: bytesReceived,
});
}

// A bundle that fails after its 200 headers still ends cleanly, so the
// stream above succeeds and leaves a ZIP with no central directory. Check
// before calling it done; the inline path then overwrites the file.
try {
await assertCompleteZip(expandHome(destinationPath));
} catch (error) {
return failure('bundle_truncated', {
...errorDetail(error),
bytes_received: bytesReceived,
});
}

return true;
},

/**
* Fail an inline ZIP download that ended before its central directory: the
* API streams the ZIP as it builds it, so a failure after the headers can
* still close the response cleanly. Deletes the partial file, so nothing
* downstream (a CI artifact upload, say) picks up a corrupt ZIP.
*/
async assertInlineZipComplete(
destinationPath: string,
operation: string,
route: string,
uploadId: string,
) {
const file = expandHome(destinationPath);
try {
await assertCompleteZip(file);
} catch (error) {
if (!(error instanceof IncompleteZipError)) throw error;
await rm(file, { force: true }).catch(() => {});
telemetry.recordDownloadIncomplete({
bytes: error.bytes,
route,
upload_id: uploadId,
});
throw new Error(
`${operation}: the download ended early and ${error.message}. Please retry.`,
{ cause: error },
);
}
},

/**
* Look for an already-uploaded binary to skip re-uploading.
*
Expand Down Expand Up @@ -492,6 +537,12 @@ export const ApiGateway = {
}

await this.streamResponseToFile(res, artifactsPath, 'Failed to download artifacts');
await this.assertInlineZipComplete(
artifactsPath,
'Failed to download artifacts',
'download',
uploadId,
);
} catch (error) {
if (error instanceof TypeError && error.message === 'fetch failed') {
throw this.enhanceFetchError(error, `${baseUrl}/results/${uploadId}/download`);
Expand Down Expand Up @@ -1089,6 +1140,15 @@ export const ApiGateway = {
}

await this.streamResponseToFile(res, finalReportPath, errorPrefix);
// Only the HTML report is a ZIP; junit is XML and allure is one HTML file.
if (reportType === 'html') {
await this.assertInlineZipComplete(
finalReportPath,
errorPrefix,
'html-report',
uploadId,
);
}
} catch (error) {
if (error instanceof TypeError && error.message === 'fetch failed') {
throw this.enhanceFetchError(error, url);
Expand Down
8 changes: 8 additions & 0 deletions src/services/report-download.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ export interface DownloadResult {
type: 'allure' | 'artifacts' | 'html' | 'junit';
}

/**
* Whether every requested download succeeded. `dcd artifacts` exits 1 when
* not; `dcd cloud` only warns, so a download never changes a test-run exit.
*/
export function downloadsSucceeded(downloads: DownloadResult[]): boolean {
return downloads.length > 0 && downloads.every((d) => d.ok);
}

/**
* Service for downloading test artifacts and reports
*/
Expand Down
15 changes: 15 additions & 0 deletions src/services/telemetry.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ export type BundleFallbackReason =
| 'bundle_http_error'
| 'bundle_request_failed'
| 'bundle_stream_failed'
/** The stream ended cleanly but the ZIP has no complete central directory. */
| 'bundle_truncated'
| 'manifest_http_error'
| 'manifest_incomplete'
| 'manifest_invalid_json'
Expand Down Expand Up @@ -195,6 +197,19 @@ class Telemetry {
);
}

/**
* Record an inline ZIP download that ended before its central directory.
* The user sees the failure; this keeps a count of how often it happens.
*/
recordDownloadIncomplete(detail: {
bytes: number;
/** The inline route, e.g. `download` or `html-report`. */
route: string;
upload_id?: string;
}) {
this.enqueue('warn', 'cli.download', 'download incomplete', { ...detail });
}

recordCommandSuccess() {
this.enqueue('info', 'cli.lifecycle', 'command completed', {
duration_ms: Date.now() - this.startedAt,
Expand Down
50 changes: 50 additions & 0 deletions src/utils/zip-integrity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { stat } from 'node:fs/promises';
import StreamZip from 'node-stream-zip';

/**
* A downloaded ZIP that ends before its central directory, so `unzip` and most
* tools reject it. A server streams a ZIP's entries first and its central
* directory last, so a response that stops early, but still closes cleanly,
* leaves exactly this behind.
*/
export class IncompleteZipError extends Error {
constructor(
readonly bytes: number,
readonly detail?: string,
) {
super(`the ZIP is incomplete (${bytes} bytes, no valid central directory)`);
this.name = 'IncompleteZipError';
}
}

/**
* Check that the file at `filePath` is a complete ZIP: its end-of-central-
* directory record (or the ZIP64 one) is there and every central directory
* header after it is intact. Only the central directory is read, never the
* entries' data, so this costs about its size even for a multi-GB archive.
*
* Throws {@link IncompleteZipError} when the file is not a complete ZIP,
* including when it is empty or missing.
*/
export async function assertCompleteZip(filePath: string): Promise<void> {
const bytes = await stat(filePath).then(
(s) => s.size,
() => 0,
);
const zip = new StreamZip.async({
file: filePath,
skipEntryNameValidation: true,
storeEntries: false,
});
try {
// Resolves only once every central directory header has been read.
await zip.entriesCount;
} catch (error) {
throw new IncompleteZipError(
bytes,
error instanceof Error ? error.message : String(error),
);
} finally {
await zip.close().catch(() => {});
}
}
19 changes: 19 additions & 0 deletions test/helpers/zip-fixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import * as yazl from 'yazl';

/**
* A stored (uncompressed) ZIP holding `count` entries of `size` bytes, each
* filled with `fill + i` so two fixtures with different fills differ.
*/
export async function zipBuffer(count = 20, size = 4096, fill = 0): Promise<Buffer> {
const zip = new yazl.ZipFile();
for (let i = 0; i < count; i++) {
zip.addBuffer(Buffer.alloc(size, (fill + i) % 256), `${i}/logs/file-${i}.log`, {
compress: false,
});
}

zip.end();
const chunks: Buffer[] = [];
for await (const chunk of zip.outputStream) chunks.push(chunk as Buffer);
return Buffer.concat(chunks);
}
Loading
Loading