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
49 changes: 49 additions & 0 deletions src/commands/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ export const artifactsCommand = defineCommand({
description:
'Custom file path for downloaded artifacts (default: ./artifacts.zip). Requires --download-artifacts.',
},
'result-id': {
type: 'string',
description:
"Download only this result's artifacts: its flow's attempts on that one device. Requires --download-artifacts.",
},
flow: {
type: 'string',
description:
'Download only the artifacts of the flow with this file path or name (e.g. flows/login.yaml or login). Fails, listing the result ids, when it matches more than one result, e.g. one per device. Requires --download-artifacts.',
},
report: {
type: 'string',
description:
Expand Down Expand Up @@ -76,6 +86,8 @@ export const artifactsCommand = defineCommand({
'download-artifacts',
);
const artifactsPath = args['artifacts-path'] as string | undefined;
const resultIdArg = args['result-id'] as string | undefined;
const flow = args.flow as string | undefined;
const report = validateEnum(
args.report as string | undefined,
REPORT_OPTIONS,
Expand Down Expand Up @@ -109,6 +121,8 @@ export const artifactsCommand = defineCommand({
);
}

const resultId = parseResultFilter(resultIdArg, flow, Boolean(downloadArtifacts));

const service = new ReportDownloadService();
const downloads: DownloadResult[] = [];

Expand All @@ -119,7 +133,9 @@ export const artifactsCommand = defineCommand({
artifactsPath: artifactsPath ?? './artifacts.zip',
debug,
downloadType: downloadArtifacts,
flow,
logger: log,
resultId,
uploadId,
warnLogger: (m: string) => logger.warn(m),
}));
Expand Down Expand Up @@ -153,4 +169,37 @@ export const artifactsCommand = defineCommand({
},
});

/**
* Check --result-id and --flow: at most one, only with --download-artifacts,
* and a result id that is a positive whole number. Returns the parsed id.
*/
export function parseResultFilter(
resultIdArg: string | undefined,
flow: string | undefined,
downloadingArtifacts: boolean,
): number | undefined {
if (resultIdArg !== undefined && flow !== undefined) {
throw new CliError(
'--result-id cannot also be provided when using --flow (flags are mutually exclusive).',
);
}

const flag = resultIdArg === undefined ? (flow === undefined ? undefined : '--flow') : '--result-id';
if (flag && !downloadingArtifacts) {
throw new CliError(`${flag} requires --download-artifacts.`);
}

if (flow !== undefined && flow.trim() === '') {
throw new CliError('--flow needs a flow file path or name.');
}

if (resultIdArg === undefined) return undefined;
const resultId = Number(resultIdArg);
if (!/^\d+$/.test(resultIdArg.trim()) || !Number.isSafeInteger(resultId) || resultId <= 0) {
throw new CliError(`--result-id must be a positive whole number, got '${resultIdArg}'.`);
}

return resultId;
}

export default artifactsCommand;
43 changes: 41 additions & 2 deletions src/gateways/api-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ function expandHome(p: string): string {
return p.replace(/^~(?=$|\/|\\)/, homedir());
}

/** Extra checks a bundle download makes before it trusts the manifest. */
interface BundleDownloadOptions {
/**
* The manifest's `filename` must start with this, or the download throws
* `unsupportedMessage` instead of falling back: how a filtered request
* tells an API that applied the filter from an older one that ignored it.
*/
requiredFilenamePrefix?: string;
unsupportedMessage?: string;
}

/** What went wrong in a bundle attempt, minus the route/timing added later. */
type BundleFailure = Omit<
BundleFallbackTelemetry,
Expand Down Expand Up @@ -293,6 +304,7 @@ export const ApiGateway = {
manifestEndpoint: string,
destinationPath: string,
operation: string,
options: BundleDownloadOptions = {},
): Promise<boolean> {
const startedAt = Date.now();
const outcome = await this.attemptBundleDownload(
Expand All @@ -301,6 +313,7 @@ export const ApiGateway = {
manifestEndpoint,
destinationPath,
operation,
options,
);
if (outcome === true) return true;

Expand All @@ -327,6 +340,7 @@ export const ApiGateway = {
manifestEndpoint: string,
destinationPath: string,
operation: string,
options: BundleDownloadOptions = {},
): Promise<BundleFailure | true> {
let manifestRes: Response;
try {
Expand All @@ -349,6 +363,7 @@ export const ApiGateway = {

let bundle: {
bundleUrl?: string;
filename?: string;
manifest?: string;
sig?: string;
};
Expand All @@ -361,6 +376,14 @@ export const ApiGateway = {
return failure('manifest_incomplete');
}

// An API that predates a filter ignores it and bundles the whole upload,
// named as such. Thrown, not a fallback: the inline route would ignore the
// filter just the same and save the wrong ZIP.
const prefix = options.requiredFilenamePrefix;
if (prefix !== undefined && !bundle.filename?.startsWith(prefix)) {
throw new Error(options.unsupportedMessage ?? `${operation}: the API ignored the request filter`);
}

let zipRes: Response;
try {
zipRes = await fetch(bundle.bundleUrl, {
Expand Down Expand Up @@ -503,29 +526,45 @@ export const ApiGateway = {
},


/**
* Download an upload's artifacts ZIP. With `resultId`, only the attempts of
* the flow run that result belongs to; the parameter is sent only when set,
* so an unfiltered request is exactly what it always was.
*/
async downloadArtifactsZip(
baseUrl: string,
auth: AuthContext,
uploadId: string,
results: 'ALL' | 'FAILED',
artifactsPath: string = './artifacts.zip',
resultId?: number,
) {
const filtered = resultId !== undefined;
// Prefer bundle delivery; fall back to the inline download below.
if (
await this.tryBundleDownload(
baseUrl,
auth,
`/results/${uploadId}/artifacts-bundle?results=${results}`,
`/results/${uploadId}/artifacts-bundle?results=${results}` +
(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.',
}
: {},
)
) {
return;
}

try {
const res = await fetch(`${baseUrl}/results/${uploadId}/download`, {
body: JSON.stringify({ results }),
body: JSON.stringify(filtered ? { results, resultId } : { results }),
headers: {
'content-type': 'application/json',
...auth.headers,
Expand Down
21 changes: 21 additions & 0 deletions src/mcp/tools/download-artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,21 @@ export function registerDownloadArtifacts(server: McpServer): void {
.string()
.optional()
.describe('Local path to write the artifacts zip (default ./artifacts.zip)'),
resultId: z
.number()
.int()
.positive()
.optional()
.describe(
"Only this result's artifacts: its flow's attempts on that one device. Leave unset with flow.",
),
flow: z
.string()
.min(1)
.optional()
.describe(
'Only the artifacts of the flow with this file path or name (e.g. flows/login.yaml or login). A name matching several results (one per device) gives a warning listing their ids; pass one as resultId.',
),
report: z
.enum(['junit', 'allure', 'html'])
.optional()
Expand All @@ -51,6 +66,10 @@ export function registerDownloadArtifacts(server: McpServer): void {
},
async (args) =>
runTool('dcd_download_artifacts', async () => {
if (args.resultId !== undefined && args.flow !== undefined) {
throw new Error('Pass resultId or flow, not both');
}

const { apiUrl, auth } = await getContext();
const service = new ReportDownloadService();
const warnings: string[] = [];
Expand All @@ -66,6 +85,8 @@ export function registerDownloadArtifacts(server: McpServer): void {
uploadId: args.uploadId,
downloadType: args.type ?? 'ALL',
artifactsPath,
flow: args.flow,
resultId: args.resultId,
logger: logStderr,
warnLogger,
});
Expand Down
76 changes: 75 additions & 1 deletion src/services/report-download.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as path from 'node:path';
import { ApiGateway } from '../gateways/api-gateway.js';
import type { AuthContext } from '../types/domain/auth.types.js';
import { refreshAuth } from '../utils/auth.js';
import { deviceFromResultRow } from './results-polling.service.js';

export interface DownloadOptions {
auth: AuthContext;
Expand All @@ -16,6 +17,60 @@ export interface DownloadOptions {
export interface ArtifactsDownloadOptions extends DownloadOptions {
artifactsPath?: string;
downloadType: 'ALL' | 'FAILED';
/**
* Only this flow's artifacts, by its file path or name: resolved to one
* result with {@link matchFlowResult}. Leave unset with `resultId`.
*/
flow?: string;
/**
* Only the artifacts of the flow run this result belongs to: its first
* attempt and every retry, on that one device.
*/
resultId?: number;
}

/** A result row as the flow lookup needs it. */
export interface FlowResultRow {
config?: unknown;
id: number;
retry_of?: null | number;
simulator_name?: null | string;
test_file_name: string;
}

/** `./flows/login.yaml` -> `flows/login.yaml`, so the forms compare equal. */
const normaliseFlowPath = (p: string) => p.trim().replace(/^(\.\/)+/, '');

/**
* The one run in an upload whose flow file matches `flow`: its full path as
* submitted (`flows/login.yaml`, with or without `./`), its file name
* (`login.yaml`) or its name without the extension (`login`). Only first
* attempts are candidates; the API adds the retries. Throws when nothing
* matches, or when several runs do (a device matrix runs one flow per
* device), listing the result ids to pick from with --result-id.
*/
export function matchFlowResult(rows: FlowResultRow[], flow: string): number {
const wanted = normaliseFlowPath(flow);
const roots = rows.filter((r) => r.retry_of === null || r.retry_of === undefined);
const matches = roots.filter((r) => {
const file = normaliseFlowPath(r.test_file_name);
const base = file.split('/').pop() ?? file;
return file === wanted || base === wanted || base.replace(/\.ya?ml$/i, '') === wanted;
});

if (matches.length === 1) return matches[0].id;
if (matches.length === 0) {
throw new Error(`No flow matching '${flow}' in this upload`);
}

const candidates = matches.map((r) => {
const device = deviceFromResultRow(r);
const label = [device?.name, device?.osVersion].filter(Boolean).join(' ');
return `${r.id} (${r.test_file_name}${label ? `, ${label}` : ''})`;
});
throw new Error(
`'${flow}' matches ${matches.length} results in this upload; pick one with --result-id: ${candidates.join(', ')}`,
);
}

export interface ReportDownloadOptions extends DownloadOptions {
Expand Down Expand Up @@ -84,6 +139,7 @@ export class ReportDownloadService {
downloadType,
artifactsPath = './artifacts.zip',
debug = false,
flow,
logger,
warnLogger,
} = options;
Expand All @@ -95,12 +151,30 @@ export class ReportDownloadService {

// `dcd cloud` downloads after polling, which can outlast a `dcd login`
// token; a failed refresh lands in the warning below like any failure.
const freshAuth = await refreshAuth(auth);

// A flow name becomes the result id the API filters on. A name that
// matches nothing, or several runs, lands in the warning below.
let { resultId } = options;
if (flow !== undefined) {
const { results } = (await ApiGateway.getResultsForUpload(
apiUrl,
freshAuth,
uploadId,
)) as { results?: FlowResultRow[] };
resultId = matchFlowResult(results ?? [], flow);
if (debug && logger) {
logger(`[DEBUG] Flow '${flow}' is result ${resultId}`);
}
}

await ApiGateway.downloadArtifactsZip(
apiUrl,
await refreshAuth(auth),
freshAuth,
uploadId,
downloadType,
artifactsPath,
resultId,
);

if (logger) {
Expand Down
43 changes: 43 additions & 0 deletions test/unit/artifacts-result-filter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { expect } from 'chai';

import { parseResultFilter } from '../../src/commands/artifacts.js';

describe('dcd artifacts --result-id / --flow', () => {
it('passes nothing through when neither is given', () => {
expect(parseResultFilter(undefined, undefined, true)).to.equal(undefined);
expect(parseResultFilter(undefined, undefined, false)).to.equal(undefined);
});

it('parses a result id', () => {
expect(parseResultFilter('4446290', undefined, true)).to.equal(4446290);
});

it('leaves a flow for the service to resolve', () => {
expect(parseResultFilter(undefined, 'login', true)).to.equal(undefined);
});

for (const bad of ['0', '-3', '1.5', 'abc', '12abc', '', '9007199254740993']) {
it(`rejects --result-id '${bad}'`, () => {
expect(() => parseResultFilter(bad, undefined, true)).to.throw(
/--result-id must be a positive whole number/,
);
});
}

it('rejects both at once', () => {
expect(() => parseResultFilter('1', 'login', true)).to.throw(/mutually exclusive/);
});

it('needs --download-artifacts', () => {
expect(() => parseResultFilter('1', undefined, false)).to.throw(
'--result-id requires --download-artifacts.',
);
expect(() => parseResultFilter(undefined, 'login', false)).to.throw(
'--flow requires --download-artifacts.',
);
});

it('rejects an empty --flow', () => {
expect(() => parseResultFilter(undefined, ' ', true)).to.throw(/--flow needs/);
});
});
Loading
Loading