diff --git a/src/gateways/api-gateway.ts b/src/gateways/api-gateway.ts index d08eb1d..1714f1d 100644 --- a/src/gateways/api-gateway.ts +++ b/src/gateways/api-gateway.ts @@ -4,6 +4,11 @@ import * as path from 'node:path'; import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; +import { + type BundleFallbackReason, + type BundleFallbackTelemetry, + telemetry, +} from '../services/telemetry.service.js'; import { TAppMetadata } from '../types.js'; import type { AuthContext } from '../types/domain/auth.types.js'; import type { @@ -14,6 +19,39 @@ import type { } from '../types/domain/live.types.js'; import { components, paths } from '../types/generated/schema.types.js'; +/** Expand a leading `~` to the home directory, as the download paths allow. */ +function expandHome(p: string): string { + return p.replace(/^~(?=$|\/|\\)/, homedir()); +} + +/** What went wrong in a bundle attempt, minus the route/timing added later. */ +type BundleFailure = Omit< + BundleFallbackTelemetry, + 'duration_ms' | 'route' | 'upload_id' +>; + +/** Name, message and low-level code (e.g. ECONNRESET) of a thrown error. */ +function errorDetail(error: unknown): Pick< + BundleFallbackTelemetry, + 'error_code' | 'error_message' | 'error_name' +> { + const err = error instanceof Error ? error : new Error(String(error)); + const cause = (err as { cause?: { code?: unknown } }).cause; + const code = cause?.code ?? (err as { code?: unknown }).code; + return { + error_code: typeof code === 'string' ? code : undefined, + error_message: err.message.slice(0, 300), + error_name: err.name, + }; +} + +function failure( + reason: BundleFallbackReason, + extra: Omit = {}, +): BundleFailure { + return { reason, ...extra }; +} + /** * Error thrown for non-OK API responses, carrying the HTTP status so callers * can branch on auth failures etc. without string matching. @@ -180,7 +218,7 @@ export const ApiGateway = { } // Handle tilde expansion for home directory - const expandedPath = destinationPath.replace(/^~(?=$|\/|\\)/, homedir()); + const expandedPath = expandHome(destinationPath); // Create directory structure if it doesn't exist const directory = path.dirname(expandedPath); @@ -219,20 +257,57 @@ export const ApiGateway = { destinationPath: string, operation: string, ): Promise { + const startedAt = Date.now(); + const outcome = await this.attemptBundleDownload( + baseUrl, + auth, + manifestEndpoint, + destinationPath, + operation, + ); + if (outcome === true) return true; + + // The fallback is silent to the user (the inline download still delivers + // the file), so this event is the only record of why the bundle path was + // skipped. + const route = /\/results\/([^/?]+)\/([a-z-]+)/.exec(manifestEndpoint); + telemetry.recordBundleFallback({ + ...outcome, + duration_ms: Date.now() - startedAt, + route: route?.[2] ?? manifestEndpoint.split('?')[0], + upload_id: route?.[1], + }); + return false; + }, + + /** + * One bundle-download attempt. Resolves `true` once the ZIP is on disk, or + * with the reason it fell through, for {@link tryBundleDownload} to record. + */ + async attemptBundleDownload( + baseUrl: string, + auth: AuthContext, + manifestEndpoint: string, + destinationPath: string, + operation: string, + ): Promise { let manifestRes: Response; try { manifestRes = await fetch(`${baseUrl}${manifestEndpoint}`, { headers: { ...auth.headers }, method: 'GET', }); - } catch { - return false; + } catch (error) { + 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. if (!manifestRes.ok) { - return false; + return failure( + manifestRes.status === 501 ? 'manifest_unavailable' : 'manifest_http_error', + { status: manifestRes.status }, + ); } let bundle: { @@ -242,11 +317,11 @@ export const ApiGateway = { }; try { bundle = (await manifestRes.json()) as typeof bundle; - } catch { - return false; + } catch (error) { + return failure('manifest_invalid_json', errorDetail(error)); } if (!bundle?.bundleUrl || !bundle?.manifest || !bundle?.sig) { - return false; + return failure('manifest_incomplete'); } let zipRes: Response; @@ -257,21 +332,40 @@ export const ApiGateway = { headers: { 'content-type': 'application/json' }, method: 'POST', }); - } catch { - return false; + } catch (error) { + return failure('bundle_request_failed', errorDetail(error)); } if (!zipRes.ok) { - return false; + return failure('bundle_http_error', { status: zipRes.status }); } // A mid-stream failure (dropped/truncated connection) or a null body on an // otherwise-OK response throws here — fall back to the inline path rather // than let it escape past the caller's fallback. The inline path re-opens // the destination with flags: 'w', truncating any partial file left behind. + // Count bytes as they arrive, so a broken stream records how far it got. + // (The file's size on disk understates it: the write stream is torn down + // with buffered bytes still unflushed.) + let bytesReceived = 0; + const counted = zipRes.body?.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + bytesReceived += chunk.byteLength; + controller.enqueue(chunk); + }, + }), + ); try { - await this.streamResponseToFile(zipRes, destinationPath, operation); - } catch { - return false; + await this.streamResponseToFile( + counted ? new Response(counted) : zipRes, + destinationPath, + operation, + ); + } catch (error) { + return failure('bundle_stream_failed', { + ...errorDetail(error), + bytes_received: bytesReceived, + }); } return true; }, diff --git a/src/services/telemetry.service.ts b/src/services/telemetry.service.ts index 6e3df8e..8bb51ea 100644 --- a/src/services/telemetry.service.ts +++ b/src/services/telemetry.service.ts @@ -40,6 +40,37 @@ export interface EncryptionTelemetry { source: EncryptionSource; } +/** + * Why a bundle download fell back to the inline endpoint. `manifest_unavailable` + * (a 501) is the expected answer from a deployment without bundle delivery; + * the rest are failures worth counting. + */ +export type BundleFallbackReason = + | 'bundle_http_error' + | 'bundle_request_failed' + | 'bundle_stream_failed' + | 'manifest_http_error' + | 'manifest_incomplete' + | 'manifest_invalid_json' + | 'manifest_request_failed' + | 'manifest_unavailable'; + +export interface BundleFallbackTelemetry { + /** Bytes of the ZIP received before the stream failed. */ + bytes_received?: number; + duration_ms: number; + /** Low-level error code from the cause, e.g. `ECONNRESET`. */ + error_code?: string; + error_message?: string; + error_name?: string; + reason: BundleFallbackReason; + /** The manifest route, e.g. `artifacts-bundle`. */ + route: string; + /** HTTP status, for the `*_http_error` / `manifest_unavailable` reasons. */ + status?: number; + upload_id?: string; +} + interface TelemetryConfig { apiUrl: string; auth: AuthContext; @@ -150,6 +181,20 @@ class Telemetry { this.submitAttempts = attempts; } + /** + * Record that a bundle download fell back to the inline endpoint, and why. + * The user never sees the fallback (the inline download still delivers the + * file), so without this the reason is lost. + */ + recordBundleFallback(detail: BundleFallbackTelemetry) { + this.enqueue( + detail.reason === 'manifest_unavailable' ? 'info' : 'warn', + 'cli.download', + 'bundle download fell back', + { ...detail }, + ); + } + recordCommandSuccess() { this.enqueue('info', 'cli.lifecycle', 'command completed', { duration_ms: Date.now() - this.startedAt, diff --git a/test/unit/report-download.service.test.ts b/test/unit/report-download.service.test.ts index 5077afb..eba68ee 100644 --- a/test/unit/report-download.service.test.ts +++ b/test/unit/report-download.service.test.ts @@ -8,6 +8,10 @@ import { ReportDownloadService, reportFormatDeprecation, } from '../../src/services/report-download.service.js'; +import { + type BundleFallbackTelemetry, + telemetry, +} from '../../src/services/telemetry.service.js'; import type { AuthContext } from '../../src/types/domain/auth.types.js'; const TEST_AUTH: AuthContext = { @@ -360,9 +364,27 @@ describe('ReportDownloadService', () => { * flow (manifest GET, then bundle POST, no inline call) can be asserted. */ function mockBundleFetch( - opts: { manifestStatus?: number; zipBody?: string } = {}, + opts: { + manifestBody?: Record; + manifestStatus?: number; + zipBody?: string; + zipBreaksAfter?: string; + zipStatus?: number; + } = {}, ) { - const { manifestStatus = 200, zipBody = 'bundle-zip' } = opts; + const { + manifestBody = { + bundleUrl: 'https://cdn.example.com/bundle', + entryCount: 3, + filename: 'artifacts-all.zip', + manifest: '{"version":1}', + sig: 'SIG', + }, + manifestStatus = 200, + zipBody = 'bundle-zip', + zipBreaksAfter, + zipStatus = 200, + } = opts; const encoder = new TextEncoder(); const stream = (s: string) => new ReadableStream({ @@ -387,15 +409,7 @@ describe('ReportDownloadService', () => { if (url.includes('artifacts-bundle') || url.includes('report-bundle')) { return new Response( - stream( - JSON.stringify({ - bundleUrl: 'https://cdn.example.com/bundle', - entryCount: 3, - filename: 'artifacts-all.zip', - manifest: '{"version":1}', - sig: 'SIG', - }), - ), + stream(JSON.stringify(manifestBody)), { headers: { 'content-type': 'application/json' }, status: manifestStatus, @@ -403,15 +417,42 @@ describe('ReportDownloadService', () => { ); } if (url === 'https://cdn.example.com/bundle') { - return new Response(stream(zipBody), { status: 200 }); + if (zipBreaksAfter !== undefined) { + // Sends some bytes, then the connection drops. + const broken = new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode(zipBreaksAfter)); + }, + pull(controller) { + controller.error( + Object.assign(new TypeError('terminated'), { + cause: { code: 'UND_ERR_SOCKET' }, + }), + ); + }, + }); + return new Response(broken, { status: 200 }); + } + return new Response(stream(zipBody), { status: zipStatus }); } return new Response(stream('inline-zip'), { status: 200 }); }; globalThis.fetch = impl as typeof fetch; } + let fallbacks: BundleFallbackTelemetry[]; + const realRecordBundleFallback = telemetry.recordBundleFallback; + beforeEach(() => { calls = []; + fallbacks = []; + telemetry.recordBundleFallback = (detail) => { + fallbacks.push(detail); + }; + }); + + afterEach(() => { + telemetry.recordBundleFallback = realRecordBundleFallback; }); it('streams from the bundle URL and skips the inline endpoint', async () => { @@ -471,6 +512,77 @@ describe('ReportDownloadService', () => { expect(fs.readFileSync(outPath, 'utf8')).to.equal('inline-zip'); }); + describe('records why it fell back', () => { + const download = (name: string) => + service.downloadArtifacts({ + ...BASE, + artifactsPath: path.join(tempDir, name), + downloadType: 'ALL', + }); + + it('records nothing when the bundle download succeeds', async () => { + mockBundleFetch(); + await download('ok.zip'); + expect(fallbacks).to.deep.equal([]); + }); + + it('records a 501 as manifest_unavailable, with route and upload id', async () => { + mockBundleFetch({ manifestStatus: 501 }); + await download('unavailable.zip'); + + expect(fallbacks).to.have.length(1); + expect(fallbacks[0]).to.include({ + reason: 'manifest_unavailable', + route: 'artifacts-bundle', + status: 501, + upload_id: 'run-42', + }); + expect(fallbacks[0].duration_ms).to.be.a('number'); + }); + + it('records a manifest missing its fields as manifest_incomplete', async () => { + mockBundleFetch({ manifestBody: { bundleUrl: 'https://cdn.example.com/bundle' } }); + await download('incomplete.zip'); + expect(fallbacks[0]).to.include({ reason: 'manifest_incomplete' }); + }); + + it('records a non-OK bundle response with its status', async () => { + mockBundleFetch({ zipStatus: 502 }); + const outPath = path.join(tempDir, 'bundle-502.zip'); + await service.downloadArtifacts({ + ...BASE, + artifactsPath: outPath, + downloadType: 'ALL', + }); + + expect(fallbacks[0]).to.include({ + reason: 'bundle_http_error', + status: 502, + }); + expect(fs.readFileSync(outPath, 'utf8')).to.equal('inline-zip'); + }); + + it('records a stream that breaks partway, with the error and bytes received', async () => { + mockBundleFetch({ zipBreaksAfter: 'partial' }); + const outPath = path.join(tempDir, 'bundle-broken.zip'); + await service.downloadArtifacts({ + ...BASE, + artifactsPath: outPath, + downloadType: 'ALL', + }); + + expect(fallbacks[0]).to.include({ + bytes_received: 'partial'.length, + error_code: 'UND_ERR_SOCKET', + error_message: 'terminated', + error_name: 'TypeError', + reason: 'bundle_stream_failed', + }); + // The inline download still replaced the partial file. + expect(fs.readFileSync(outPath, 'utf8')).to.equal('inline-zip'); + }); + }); + it('uses bundle delivery for the html report', async () => { mockBundleFetch();