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
69 changes: 51 additions & 18 deletions src/gateways/api-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,24 @@ interface BundleDownloadOptions {
* tells an API that applied the filter from an older one that ignored it.
*/
requiredFilenamePrefix?: string;
/**
* Throws the error the inline route gives for the same answer. Called for a
* manifest status in {@link FINAL_MANIFEST_STATUSES} instead of falling
* back, so the caller's message is the one the user saw before.
*/
throwFinalError?: (res: Response) => Promise<never>;
unsupportedMessage?: string;
}

/**
* Manifest answers the inline route would only repeat: a bad request, a key
* that can't reach the run, a run that isn't there. Falling back on them cost
* a second request for the same error. 413 (too many files for the bundle)
* and 501 (no bundle delivery here) still fall back, since the inline route
* can serve those.
*/
const FINAL_MANIFEST_STATUSES: ReadonlySet<number> = new Set([400, 403, 404]);

/** What went wrong in a bundle attempt, minus the route/timing added later. */
type BundleFailure = Omit<
BundleFallbackTelemetry,
Expand Down Expand Up @@ -300,8 +315,8 @@ export const ApiGateway = {
* the bundle path is unavailable or anything about it doesn't pan out — a
* `501` (deployment doesn't offer it), a non-OK manifest response, a body
* that isn't a manifest, or a delivery-service error — so the caller can fall
* back to the inline download endpoint. Definitive errors (e.g. not found)
* surface through that inline path instead.
* back to the inline download endpoint. A manifest 400, 403 or 404 throws
* `throwFinalError`'s error instead, without a fallback.
*/
async tryBundleDownload(
baseUrl: string,
Expand Down Expand Up @@ -357,9 +372,16 @@ export const ApiGateway = {
return failure('manifest_request_failed', errorDetail(error));
}

// 501 => this deployment has no bundle delivery; any other non-OK => let
// the inline path re-request and surface the real error.
// 400/403/404 => the inline route would answer the same, so throw its
// error now. 501 => this deployment has no bundle delivery; any other
// non-OK (413, 5xx) => the inline path may still deliver.
if (!manifestRes.ok) {
if (
options.throwFinalError &&
FINAL_MANIFEST_STATUSES.has(manifestRes.status)
) {
await options.throwFinalError(manifestRes);
}
return failure(
manifestRes.status === 501 ? 'manifest_unavailable' : 'manifest_http_error',
{ status: manifestRes.status },
Expand Down Expand Up @@ -558,14 +580,18 @@ export const ApiGateway = {
(filtered ? `&resultId=${resultId}` : ''),
artifactsPath,
'Failed to download artifacts',
filtered
? {
// What the API names a bundle it narrowed to one result.
requiredFilenamePrefix: 'artifacts-result-',
unsupportedMessage:
'Failed to download artifacts: this API does not support downloading one result yet. Download without --result-id or --flow.',
}
: {},
{
throwFinalError: (res) =>
this.handleApiError(res, 'Failed to download artifacts'),
...(filtered
? {
// What the API names a bundle it narrowed to one result.
requiredFilenamePrefix: 'artifacts-result-',
unsupportedMessage:
'Failed to download artifacts: this API does not support downloading one result yet. Download without --result-id or --flow.',
}
: {}),
},
)
) {
return;
Expand Down Expand Up @@ -1153,6 +1179,17 @@ export const ApiGateway = {
const finalReportPath = reportPath || path.resolve(process.cwd(), defaultFilename);
const url = `${baseUrl}${endpoint}`;

// The error for a non-OK answer, from the inline route or, for the html
// report, a final answer from its bundle route.
const throwHttpError = async (res: Response): Promise<never> => {
const errorText = await res.text();
if (res.status === 404) {
throw new Error(notFoundMessage);
}

throw new Error(`${errorPrefix}: ${res.status} ${errorText}`);
};

// The HTML report is a ZIP bundle; prefer bundle delivery when available.
// (junit is a single small file and allure has its own endpoint — both stay
// on the inline path.)
Expand All @@ -1164,6 +1201,7 @@ export const ApiGateway = {
`/results/${uploadId}/report-bundle`,
finalReportPath,
errorPrefix,
{ throwFinalError: throwHttpError },
))
) {
return;
Expand All @@ -1179,12 +1217,7 @@ export const ApiGateway = {
});

if (!res.ok) {
const errorText = await res.text();
if (res.status === 404) {
throw new Error(notFoundMessage);
}

throw new Error(`${errorPrefix}: ${res.status} ${errorText}`);
await throwHttpError(res);
}

await this.streamResponseToFile(res, finalReportPath, errorPrefix);
Expand Down
96 changes: 96 additions & 0 deletions test/unit/report-download.service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,102 @@ describe('ReportDownloadService', () => {
expect(fs.readFileSync(outPath).equals(INLINE_ZIP)).to.be.true;
});

// The inline route gives these answers too, so asking it again only cost
// a second request for the same error.
describe('a manifest answer the inline route would repeat', () => {
const cases = [
{
expected: 'Invalid request: resultId must be a positive whole number',
message: 'resultId must be a positive whole number',
status: 400,
},
{
expected: 'Access denied. This upload belongs to another team',
message: 'This upload belongs to another team',
status: 403,
},
{
expected: 'Resource not found. No results found for uploadId=run-42',
message: 'No results found for uploadId=run-42',
status: 404,
},
];

for (const { expected, message, status } of cases) {
it(`shows an artifacts ${status} without asking the inline route`, async () => {
mockBundleFetch({
manifestBody: { message, statusCode: status },
manifestStatus: status,
});
const warnings: string[] = [];

const result = await service.downloadArtifacts({
...BASE,
artifactsPath: path.join(tempDir, `final-${status}.zip`),
downloadType: 'ALL',
warnLogger: (msg) => warnings.push(msg),
});

expect(result.ok).to.be.false;
expect(warnings[0]).to.equal(`Failed to download artifacts: ${expected}`);
expect(calls).to.have.length(1);
expect(calls.some((c) => c.url.endsWith('/download'))).to.be.false;
expect(fallbacks).to.deep.equal([]);
});

it(`shows an html report ${status} without asking the inline route`, async () => {
mockBundleFetch({
manifestBody: { message, statusCode: status },
manifestStatus: status,
});
const warnings: string[] = [];

await service.downloadReports({
...BASE,
htmlPath: path.join(tempDir, `final-report-${status}.zip`),
reportType: 'html',
warnLogger: (msg) => warnings.push(msg),
});

// The same text the inline route's answer gave.
expect(warnings[0]).to.equal(
status === 404
? "Failed to download HTML report: Upload ID 'run-42' not found or no HTML report available for this upload"
: `Failed to download HTML report: Failed to download HTML report: ${status} ${JSON.stringify({ message, statusCode: status })}`,
);
expect(calls).to.have.length(1);
expect(calls.some((c) => c.url.endsWith('/html-report'))).to.be.false;
expect(fallbacks).to.deep.equal([]);
});
}

for (const status of [413, 500]) {
it(`still falls back on a manifest ${status}`, async () => {
mockBundleFetch({
manifestBody: { message: 'no' },
manifestStatus: status,
});
const outPath = path.join(tempDir, `fallback-${status}.zip`);

const result = await service.downloadArtifacts({
...BASE,
artifactsPath: outPath,
downloadType: 'ALL',
});

expect(result.ok).to.be.true;
expect(fallbacks[0]).to.include({
reason: 'manifest_http_error',
status,
});
expect(
calls.some((c) => c.method === 'POST' && c.url.endsWith('/download')),
).to.be.true;
expect(fs.readFileSync(outPath).equals(INLINE_ZIP)).to.be.true;
});
}
});

// A folder as the artifacts path failed with EISDIR, which the
// CLI took for a broken stream, so it fell back to the inline download
// (the API building the whole ZIP) and then failed the same way.
Expand Down
Loading