Compare commits

...
10 changed files with 213 additions and 31 deletions

No files matched your search

+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@expo/explore",
"version": "0.20.0",
"version": "0.20.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@expo/explore",
"version": "0.20.0",
"version": "0.20.1",
"license": "MIT",
"dependencies": {
"@expo/repack-app": "0.10.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@expo/explore",
"version": "0.20.0",
"version": "0.20.1",
"description": "Source-driven mobile app maps, deterministic CI capture, and visual reviews",
"license": "MIT",
"type": "module",
+7 -5
View File
@@ -454,6 +454,8 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
// `eas simulator:control` names the session by id, from the session's own project directory.
const sessionEas: EasCommand = (args, commandOptions) => runner({ command: options.easCommand, args, cwd: simulatorProject, environment: easEnvironment,
timeoutMs: commandOptions?.timeoutMs ?? 5 * 60_000, ...(commandOptions?.allowFailure ? { allowFailure: true } : {}) });
// A failed simulator:control action is sent again after a pause, which a test's clock replaces.
const controlOptions = { sleep: options.sleep };
// What the EAS session's host can do through simulator:control (iOS sessions on serve-sim 0.10.0 or later).
let controlActions = new Set<string>();
const configResult = eas(["config", "--platform", options.platform, "--profile", options.easProfile, "--json", "--non-interactive"]);
@@ -785,7 +787,7 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
"--platform", options.platform, "--json"], cwd: simulatorProject, environment: controllerEnvironment, timeoutMs: 15 * 60_000 });
// Before any link opens, as a local capture does with simctl: the app's own links then open without the prompt.
if (sessionId && scheme) {
const approved = approveSessionUrlSchemes(sessionEas, sessionId, controlActions, options.bundleId, [scheme]);
const approved = approveSessionUrlSchemes(sessionEas, sessionId, controlActions, options.bundleId, [scheme], controlOptions);
if (approved.length) say(`approved ${approved.map(item => `${item}://`).join(", ")} links on session ${sessionId}`);
}
}
@@ -844,7 +846,7 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
if (!controlActions.has("springboard.restart")) throw new CiError({ code: "CONTROLLER_FOLD_UNVERIFIED", stage: "session",
message: `${options.device} did not show the ${options.devicePose} display after folding.`, nextAction: "Rerun the capture on a new session." });
say(`${options.device} did not draw the ${options.devicePose} display after the fold; restarting SpringBoard and folding ${options.devicePose} again`);
simulatorControl(sessionEas, sessionId, "springboard.restart");
simulatorControl(sessionEas, sessionId, "springboard.restart", [], controlOptions);
pause(8_000);
open(true);
fold();
@@ -859,7 +861,7 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
catch (error) {
if (toCiError(error).code !== "CONTROLLER_FOLD_UNVERIFIED") throw error;
say(`Argent kept reading the other panel after the fold; restarting SpringBoard and folding ${options.devicePose} again`);
simulatorControl(sessionEas, sessionId, "springboard.restart");
simulatorControl(sessionEas, sessionId, "springboard.restart", [], controlOptions);
pause(8_000);
try { fold(); }
catch (retry) {
@@ -892,7 +894,7 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
nextAction: "Rerun the capture; if it keeps happening, report it to Explore: this session's Argent tool-server needs a restart that EAS cannot do yet.", cause: error });
if (recovery === 1) {
say("Argent still did not read the app; restarting SpringBoard, then resetting Argent's device helpers and opening the app again");
simulatorControl(sessionEas, sessionId, "springboard.restart");
simulatorControl(sessionEas, sessionId, "springboard.restart", [], controlOptions);
// SpringBoard takes a moment to come back, and sends the app to the background; the next open brings it back.
(options.sleep ?? (milliseconds => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds); }))(8_000);
} else say("Argent did not read the app after starting it; resetting Argent's device helpers and opening the app again");
@@ -944,7 +946,7 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
// machine and serve-sim on an EAS iOS session; elsewhere its single pass runs as the device starts.
if (controller !== "argent") runner({ command: controllerCommand, args: [...appearanceArgs(colorScheme), "--session", CONTROLLER_SESSION, ...deviceArgs(runtime), "--platform", options.platform],
cwd: simulatorProject, environment: controllerEnvironment, timeoutMs: 60_000 });
else if (sessionId && controlActions.has("appearance.set")) simulatorControl(sessionEas, sessionId, "appearance.set", [colorScheme]);
else if (sessionId && controlActions.has("appearance.set")) simulatorControl(sessionEas, sessionId, "appearance.set", [colorScheme], controlOptions);
else if (localSimulator) setLocalSimulatorAppearance({ runner, udid: localSimulator, scheme: colorScheme, cwd: simulatorProject, environment: restrictedEnvironment });
else if (localEmulator) setLocalEmulatorAppearance({ runner, serial: localEmulator, scheme: colorScheme, cwd: simulatorProject, environment: restrictedEnvironment });
// A scheme change recreates the Android activity in place, and the sheets it re-presents lose their inset; a
+35 -5
View File
@@ -20,23 +20,53 @@ export function simulatorControlActions(eas: EasCommand, sessionId: string): Set
} catch { return new Set(); }
}
/** Runs one `eas simulator:control` action on the session; eas-cli fills in the device. Throws with EAS's reason. */
export function simulatorControl(eas: EasCommand, sessionId: string, action: string, values: readonly string[] = []): void {
/**
* Pauses before each resend of a failed action. Every action Explore runs is idempotent, and the session's host can fail
* one once: in brentvatne/euxy's baseline run 39348933440, `app.approveUrlScheme` failed in its `simctl spawn … defaults
* write`, which failed the dark-appearance session and with it the target's whole baseline.
*/
const SIMULATOR_CONTROL_RETRY_DELAYS_MS = [3_000, 6_000] as const;
/** Lets a test replace the pause between resends of a failed action. */
export type SimulatorControlOptions = { sleep?: ((milliseconds: number) => void) | undefined };
/**
* Runs one `eas simulator:control` action on the session; eas-cli fills in the device. A failed action is sent again
* after a pause; one that still fails throws with EAS's reason.
*/
export function simulatorControl(eas: EasCommand, sessionId: string, action: string, values: readonly string[] = [], options: SimulatorControlOptions = {}): void {
const sleep = options.sleep ?? (milliseconds => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds); });
// Values follow `--` so one that starts with a dash is never read as a flag.
eas(["simulator:control", action, "--id", sessionId, "--json", "--non-interactive", "--", ...values], { timeoutMs: 2 * 60_000 });
const args = ["simulator:control", action, "--id", sessionId, "--json", "--non-interactive", "--", ...values];
for (let retry = 0; ; retry += 1) {
try { eas(args, { timeoutMs: 2 * 60_000 }); return; }
catch (error) {
const delayMs = SIMULATOR_CONTROL_RETRY_DELAYS_MS[retry];
if (delayMs === undefined) throw error;
// A resend that succeeds would otherwise leave no trace of the failure in the job log.
process.stderr.write(`simulator:control ${action} failed (${firstLine(error)}); sending it again in ${delayMs / 1000} s\n`);
sleep(delayMs);
}
}
}
/**
* Lets the app open its own links without iOS asking "Open in “App”?" first, like local captures do with simctl. A
* session without the action keeps the controllers' prompt handling; http and https never prompt and are skipped.
*/
export function approveSessionUrlSchemes(eas: EasCommand, sessionId: string, actions: ReadonlySet<string>, bundleId: string, schemes: readonly string[]): string[] {
export function approveSessionUrlSchemes(eas: EasCommand, sessionId: string, actions: ReadonlySet<string>, bundleId: string, schemes: readonly string[],
options: SimulatorControlOptions = {}): string[] {
if (!actions.has("app.approveUrlScheme")) return [];
const approved: string[] = [];
for (const scheme of new Set(schemes.map(value => value.toLowerCase()))) {
if (scheme === "http" || scheme === "https" || !/^[a-z][a-z0-9+.-]*$/.test(scheme)) continue;
simulatorControl(eas, sessionId, "app.approveUrlScheme", [bundleId, scheme]);
simulatorControl(eas, sessionId, "app.approveUrlScheme", [bundleId, scheme], options);
approved.push(scheme);
}
return approved;
}
/** The first line of a failure, for a log line. */
function firstLine(error: unknown): string {
return (error instanceof Error ? error.message : String(error)).split("\n", 1)[0]!.slice(0, 300);
}
+11 -3
View File
@@ -8,6 +8,7 @@ import { compareTitleMarkdown, projectReviewPresentation, type CompareReviewPres
import { renderPublicComment, platformSectionMerge, reviewChangeCount, type PublicCommentState } from "./pr-comment-body.js";
import { isTargetId, type ExplorePlatform } from "../config/explore-config.js";
import { upsertStickyComment } from "./pr-comment.js";
import { retryGitHubLookup } from "./github-lookup.js";
import { previewLinks, viewerLinks } from "./viewer-links.js";
import type { PublicReview } from "../contracts/capture.js";
import { CiError, toCiError } from "../shared/ci-errors.js";
@@ -136,6 +137,8 @@ export async function publishCiReportComment(options: {
preview?: { url: string; expiresAt: number | null };
/** Set by `ci:deploy` when the hosted preview failed: the comment falls back to the central Viewer and the ZIP. */
previewFailed?: boolean;
/** Pause between GitHub lookups that may succeed later; tests replace it so retries take no real time. */
sleep?: (milliseconds: number) => Promise<void>;
}) {
const environment = options.environment ?? process.env; const transport = options.transport ?? fetch;
const input = await readInput(options.inputPath); const review = input.publicReview; const pr = review.pullRequest;
@@ -186,16 +189,21 @@ export async function publishCiReportComment(options: {
catch (error) { throw new CiError({ code: "GITHUB_RESPONSE_INVALID", stage: "publication",
message: "GitHub returned invalid report metadata.", nextAction: "Rerun publication; if the response remains invalid, inspect the GitHub metadata request.", cause: error }); }
};
const artifact = await api(`actions/artifacts/${new URL(options.artifactUrl).pathname.split("/").at(-1)}`);
// A lookup is made again when GitHub may answer it later: no answer, a 5xx, or a 404 from the Actions API, which may
// not list a just-uploaded artifact yet. A bad token, a missing permission or a rate limit fails at once, as before.
const lookup = (path: string) => retryGitHubLookup(() => api(path), error => error instanceof CiError
&& (error.code === "GITHUB_NETWORK_FAILED" || error.code === "GITHUB_REQUEST_FAILED" && error.retryable
|| error.code === "GITHUB_RESOURCE_NOT_FOUND" && path.startsWith("actions/")), options.sleep);
const artifact = await lookup(`actions/artifacts/${new URL(options.artifactUrl).pathname.split("/").at(-1)}`);
if (artifact.expired || artifact.name !== `explore-review-${review.runId}-${review.runAttempt}${target ? `-${target}` : ""}` || String(artifact.workflow_run?.id) !== review.runId) {
throw new CiError({ code: artifact.expired ? "REPORT_ARTIFACT_EXPIRED" : "REPORT_ARTIFACT_MISMATCH", stage: "publication",
message: "The uploaded report artifact is unavailable or belongs to another run",
nextAction: artifact.expired ? "Rerun Explore to upload a fresh report artifact." : "Pass the final report artifact from this workflow run and attempt." });
}
const attempt = await api(`actions/runs/${review.runId}/attempts/${review.runAttempt}`);
const attempt = await lookup(`actions/runs/${review.runId}/attempts/${review.runAttempt}`);
if (String(attempt.id) !== review.runId || String(attempt.run_attempt) !== review.runAttempt) throw new CiError({ code: "REPORT_RUN_MISMATCH", stage: "publication",
message: "Report run attempt mismatch", nextAction: "Publish the artifact and report input from the same current workflow attempt." });
const current = await api(`pulls/${pr.number}`);
const current = await lookup(`pulls/${pr.number}`);
if (current.state !== "open" || current.head?.repo?.full_name !== pr.repository || current.head?.ref !== pr.head.ref) {
throw new CiError({ code: "PR_CHANGED", stage: "publication", message: "PR closed or changed branches before the report artifact was ready",
nextAction: "Run Explore for the current PR head and base before publishing a ready report." });
+25
View File
@@ -0,0 +1,25 @@
/**
* Pauses between attempts of a GitHub lookup that may succeed later, 45 seconds in all. GitHub's Actions API is
* eventually consistent just after an upload: in brentvatne/euxy's review run 39348956443, the duo-closed report job's
* `actions/artifacts/<id>` answered 404 for the artifact that job had just uploaded, while the other four targets'
* jobs found theirs.
*/
const GITHUB_LOOKUP_RETRY_DELAYS_MS = [3_000, 6_000, 12_000, 24_000] as const;
/**
* Runs a read-only GitHub lookup again after each pause while `transient` says its failure may clear on its own. The
* caller decides what is transient; any other failure, or the last one, is thrown as it is.
*/
export async function retryGitHubLookup<T>(lookup: () => Promise<T>, transient: (error: unknown) => boolean,
sleep: (milliseconds: number) => Promise<void> = milliseconds => new Promise<void>(done => setTimeout(done, milliseconds))): Promise<T> {
for (let retry = 0; ; retry += 1) {
try { return await lookup(); }
catch (error) {
const delayMs = GITHUB_LOOKUP_RETRY_DELAYS_MS[retry];
if (delayMs === undefined || !transient(error)) throw error;
// A lookup that succeeds later would otherwise leave no trace of the failure in the job log.
process.stderr.write(`GitHub lookup failed (${(error instanceof Error ? error.message : String(error)).split("\n", 1)[0]}); trying again in ${delayMs / 1000} s\n`);
await sleep(delayMs);
}
}
}
+23 -12
View File
@@ -7,6 +7,7 @@ import { Uint8ArrayReader, Uint8ArrayWriter, ZipWriter, configure } from "@zip.j
import { loadReport, MAX_METADATA_BYTES } from "./agent-api.js";
import { MAX_ASSET_BYTES, manifestBody, PREVIEW_ASSET } from "./preview-manifest.js";
import { publishCiReportComment, readCiReportInput, type CiReportInput } from "./artifact.js";
import { retryGitHubLookup } from "./github-lookup.js";
import { readZipDirectory, readZipEntry } from "./zip-reader.js";
import { reviewChangeCount, reviewDevice } from "./pr-comment-body.js";
import { isTargetId, warnIgnoredExpiry, type ExplorePlatform } from "../config/explore-config.js";
@@ -54,7 +55,7 @@ export type PreviewDeployOptions = (PreviewReportInput | {
environment?: NodeJS.ProcessEnv;
transport?: typeof fetch;
run?: CommandRunner;
/** Pause between `eas deploy` attempts; tests replace it so retries take no real time. */
/** Pause between `eas deploy` attempts and between GitHub lookups that may succeed later; tests replace it so retries take no real time. */
sleep?: (milliseconds: number) => Promise<void>;
/** The preview export (client/ and server/); defaults to the one shipped in this package. */
exportPath?: string;
@@ -386,7 +387,7 @@ export async function deployPreview(options: PreviewDeployOptions): Promise<Prev
if (pr.origin !== "compare") for (const report of reports) {
try {
await publishCiReportComment({ inputPath: report.entry.inputPath, artifactUrl: report.entry.artifactUrl, environment, transport,
...commentTarget(report), previewFailed: true });
...commentTarget(report), previewFailed: true, ...(options.sleep ? { sleep: options.sleep } : {}) });
} catch { /* the deployment failure is the one to report */ }
}
throw error;
@@ -398,7 +399,7 @@ export async function deployPreview(options: PreviewDeployOptions): Promise<Prev
let headSha = pr.head.sha;
if (pr.origin !== "compare") for (const report of reports) {
const published = await publishCiReportComment({ inputPath: report.entry.inputPath, artifactUrl: report.entry.artifactUrl, environment, transport,
...commentTarget(report), preview: { url: previewUrl, expiresAt: null } });
...commentTarget(report), preview: { url: previewUrl, expiresAt: null }, ...(options.sleep ? { sleep: options.sleep } : {}) });
headSha = published.headSha;
}
return { previewUrl, expiresAt: null, deploymentId: hosted.deploymentId, deploymentUrl: hosted.deploymentUrl,
@@ -766,7 +767,9 @@ const ARTIFACT_DIRECTORY = /^explore-(capture|review)-\d+-\d+-([a-z][a-z0-9-]{0,
* configs without targets). Pairs them by target, in the order the run's review lists its targets, and looks up each
* report artifact's URL on the run, since matrix jobs cannot hand their artifact URLs forward.
*/
export async function collectPlatformReports(options: { inputsPath: string; reportsPath: string; environment?: NodeJS.ProcessEnv; transport?: typeof fetch }): Promise<PreviewReportInput[]> {
export async function collectPlatformReports(options: { inputsPath: string; reportsPath: string; environment?: NodeJS.ProcessEnv; transport?: typeof fetch;
/** Pause between artifact lookups that may succeed later; tests replace it so retries take no real time. */
sleep?: (milliseconds: number) => Promise<void> }): Promise<PreviewReportInput[]> {
const environment = options.environment ?? process.env; const transport = options.transport ?? fetch;
const directories = async (root: string, kind: "capture" | "review") => {
const found = new Map<string, string>();
@@ -812,14 +815,22 @@ export async function collectPlatformReports(options: { inputsPath: string; repo
for (const entry of entries) {
const name = `explore-review-${review.runId}-${review.runAttempt}-${entry.target!.id}`;
const url = `https://api.github.com/repos/${repository}/actions/runs/${review.runId}/artifacts?per_page=100&name=${encodeURIComponent(name)}`;
const response = await transport(url, { headers: { accept: "application/vnd.github+json", authorization: `Bearer ${environment.GITHUB_TOKEN ?? ""}`,
"x-github-api-version": "2022-11-28" }, signal: AbortSignal.timeout(60_000) });
const body = response.ok ? await response.json() as { artifacts?: Array<{ id?: unknown; name?: unknown; expired?: unknown }> } : undefined;
const artifact = body?.artifacts?.find(candidate => candidate.name === name && candidate.expired !== true);
if (!artifact || typeof artifact.id !== "number" || !Number.isSafeInteger(artifact.id) || artifact.id <= 0) {
throw deployError("REPORT_ARTIFACT_MISSING", `The run has no artifact named ${name} (HTTP ${response.status}).`,
"Rerun the workflow so every target's report job uploads its artifact before the deploy job runs.", { retryable: true });
}
// The run's artifact list can lag an upload, as the artifact lookup of a report job's publication does, so an
// empty list, a 404, a 5xx or no answer is looked up again; a bad token or a missing permission fails at once.
const artifact = await retryGitHubLookup(async () => {
const response = await transport(url, { headers: { accept: "application/vnd.github+json", authorization: `Bearer ${environment.GITHUB_TOKEN ?? ""}`,
"x-github-api-version": "2022-11-28" }, signal: AbortSignal.timeout(60_000) });
const body = response.ok ? await response.json() as { artifacts?: Array<{ id?: unknown; name?: unknown; expired?: unknown }> } : undefined;
const found = body?.artifacts?.find(candidate => candidate.name === name && candidate.expired !== true);
if (!found || typeof found.id !== "number" || !Number.isSafeInteger(found.id) || found.id <= 0) {
throw deployError("REPORT_ARTIFACT_MISSING", `The run has no artifact named ${name} (HTTP ${response.status}).`,
"Rerun the workflow so every target's report job uploads its artifact before the deploy job runs.", { retryable: true, details: { status: response.status } });
}
return found;
}, error => {
const status = error instanceof CiError ? error.details?.status : undefined;
return !(error instanceof CiError) || typeof status === "number" && (status === 200 || status === 404 || status >= 500);
}, options.sleep);
entry.artifactUrl = `https://github.com/${repository}/actions/runs/${review.runId}/artifacts/${artifact.id}`;
}
return entries;
+39 -1
View File
@@ -392,6 +392,42 @@ test("collectPlatformReports pairs downloaded artifact directories by platform a
error => error.code === "PREVIEW_REPORTS_INCOMPLETE");
});
test("collectPlatformReports looks up a report artifact the run does not list yet again, but not one its token cannot read", async t => {
const ios = await exportFixture(t);
const root = await mkdtemp(join(tmpdir(), "explore-fanin-late-")); t.after(() => rm(root, { recursive: true, force: true }));
const { cp } = await import("node:fs/promises");
await mkdir(join(root, "inputs", "explore-capture-10-1-ios"), { recursive: true }); await cp(ios.inputPath, join(root, "inputs", "explore-capture-10-1-ios", "report-input.json"));
await cp(ios.reportPath, join(root, "reports", "explore-review-10-1-ios"), { recursive: true });
const eas = easFixture();
const listing = answers => {
const lookups = [];
const transport = async (input, options) => {
const url = new URL(input);
if (!url.pathname.endsWith("/actions/runs/10/artifacts")) return eas.transport(input, options);
lookups.push(url);
const answer = answers[Math.min(lookups.length, answers.length) - 1];
return answer ? new Response(JSON.stringify(answer.body ?? {}), { status: answer.status }) : eas.transport(input, options);
};
return { lookups, transport };
};
const pauses = [];
const sleep = async milliseconds => { pauses.push(milliseconds); };
// The list lags the report job's upload: empty, then a 404, then the artifact.
const late = listing([{ status: 200, body: { artifacts: [] } }, { status: 404 }, undefined]);
const [entry] = await collectPlatformReports({ inputsPath: join(root, "inputs"), reportsPath: join(root, "reports"), environment: deployEnvironment, transport: late.transport, sleep });
assert.equal(entry.artifactUrl, artifactUrl.replace(/20$/, "21"));
assert.equal(late.lookups.length, 3);
assert.equal(pauses.length, 2);
const denied = listing([{ status: 403 }]);
await assert.rejects(collectPlatformReports({ inputsPath: join(root, "inputs"), reportsPath: join(root, "reports"), environment: deployEnvironment, transport: denied.transport, sleep }),
error => error.code === "REPORT_ARTIFACT_MISSING" && /HTTP 403/.test(error.message));
assert.equal(denied.lookups.length, 1);
const never = listing([{ status: 200, body: { artifacts: [] } }]);
await assert.rejects(collectPlatformReports({ inputsPath: join(root, "inputs"), reportsPath: join(root, "reports"), environment: deployEnvironment, transport: never.transport, sleep }),
error => error.code === "REPORT_ARTIFACT_MISSING");
assert.equal(never.lookups.length, 5);
});
const now = Date.UTC(2026, 8, 11, 3, 7);
const STALE_COMMENT = `<!-- expo-explore-ci -->
Explore review for abc · Managed via config
@@ -789,7 +825,9 @@ test("ci:deploy pairs target-named artifacts, deploys them in config order, and
const entries = await collectPlatformReports({ inputsPath: join(root, "inputs"), reportsPath: join(root, "reports"), environment: deployEnvironment, transport });
assert.deepEqual(entries.map(entry => [entry.target.id, entry.platform, entry.artifactUrl.split("/").at(-1)]),
[["iphone", undefined, "31"], ["duo-closed", undefined, "32"], ["duo-open", undefined, "33"], ["android", "android", "34"]], "config order, not directory order");
const sealed = await deployPreview({ reports: entries.map(({ platform: _platform, ...entry }) => entry), exportPath: fixtures[0].exportPath, environment: deployEnvironment, transport, run: eas.run, now: () => now, verifyTimeoutMs: 1 })
// The fixture serves none of these artifacts by id, so each comment's artifact lookup answers 404 through all its retries.
const sealed = await deployPreview({ reports: entries.map(({ platform: _platform, ...entry }) => entry), exportPath: fixtures[0].exportPath, environment: deployEnvironment, transport, run: eas.run, now: () => now, verifyTimeoutMs: 1,
sleep: async () => {} })
.catch(error => error);
// Publishing each target's comment section after the deployment is the comment code's (publishCiReportComment, which needs
// the target to name the artifact); the deployment itself must have been written per target either way.
+37
View File
@@ -38,3 +38,40 @@ test("link schemes are approved once each, lowercased, never http or https, and
assert.deepEqual(approveSessionUrlSchemes(none.eas, "session-1", new Set(), "dev.example.app", ["example"]), []);
assert.equal(none.calls.length, 0);
});
// The host can fail an action once, as `app.approveUrlScheme` did in its `simctl spawn … defaults write` (euxy run 39348933440).
function flakyEas(failures) {
const calls = [];
const eas = args => {
calls.push(args);
if (calls.length <= failures) throw new Error("eas simulator:control exited with status 1: The simulator could not run app.approveUrlScheme");
return { stdout: "{}" };
};
return { calls, eas };
}
test("an action that fails once is sent again after a pause", () => {
const { calls, eas } = flakyEas(1);
const pauses = [];
simulatorControl(eas, "session-1", "app.approveUrlScheme", ["dev.example.app", "example"], { sleep: milliseconds => pauses.push(milliseconds) });
assert.equal(calls.length, 2);
assert.deepEqual(calls[1], calls[0]);
assert.equal(pauses.length, 1);
});
test("an action that keeps failing throws EAS's reason after its last attempt, with no pause after it", () => {
const { calls, eas } = flakyEas(Infinity);
const pauses = [];
assert.throws(() => simulatorControl(eas, "session-1", "app.approveUrlScheme", ["dev.example.app", "example"], { sleep: milliseconds => pauses.push(milliseconds) }),
/could not run app\.approveUrlScheme/);
assert.equal(calls.length, 3);
assert.equal(pauses.length, calls.length - 1);
assert.ok(pauses.every(milliseconds => milliseconds > 0 && milliseconds <= 10_000));
});
test("a link scheme the host fails to approve once is approved on the next attempt", () => {
const { calls, eas } = flakyEas(1);
const approved = approveSessionUrlSchemes(eas, "session-1", new Set(["app.approveUrlScheme"]), "dev.example.app", ["example"], { sleep: () => {} });
assert.deepEqual(approved, ["example"]);
assert.equal(calls.length, 2);
});
+33 -2
View File
@@ -133,11 +133,14 @@ test("report export rejects path traversal and symlink images from downloaded ev
});
function transportFixture({ stale = false, expired = false, artifactName = "explore-review-10-1", artifactRun = 10, attempt = 1,
status, headers } = {}) {
status, headers, artifactNotFound = 0 } = {}) {
const calls = [];
let artifactLookups = 0;
const transport = async (input, options = {}) => {
const url = new URL(input); calls.push({ url, options });
if (status) return new Response("private-upstream-error", { status, headers });
// GitHub can answer 404 for an artifact its run uploaded moments ago (euxy run 39348956443).
if (url.pathname.endsWith("/actions/artifacts/20") && (artifactLookups += 1) <= artifactNotFound) return new Response("Not Found", { status: 404 });
if (url.pathname.endsWith("/actions/artifacts/20")) return Response.json({ id: 20, name: artifactName, expired, workflow_run: { id: artifactRun } });
if (url.pathname.endsWith("/actions/runs/10/attempts/1")) return Response.json({ id: 10, run_attempt: attempt, status: "in_progress", conclusion: null });
if (url.pathname.endsWith("/pulls/1")) return Response.json({ state: "open", base: pr.base,
@@ -191,7 +194,8 @@ test("report publication separates credential, permission, rate limit, and servi
[503, {}, "GITHUB_REQUEST_FAILED", true, /service status/],
]) {
const { transport, calls } = transportFixture({ status, headers });
await assert.rejects(publishCiReportComment({ inputPath, artifactUrl, environment, transport }), error => {
const pauses = [];
await assert.rejects(publishCiReportComment({ inputPath, artifactUrl, environment, transport, sleep: async milliseconds => { pauses.push(milliseconds); } }), error => {
assert.equal(error.code, code);
assert.equal(error.stage, "publication");
assert.equal(error.retryable, retryable);
@@ -200,9 +204,36 @@ test("report publication separates credential, permission, rate limit, and servi
return true;
});
assert.equal(calls.some(call => call.options.method === "POST"), false);
// Only a 5xx is looked up again; a bad token, a missing permission and a rate limit fail on the first answer.
assert.equal(calls.length, status >= 500 ? 5 : 1, `${status} ${JSON.stringify(headers)}`);
assert.equal(pauses.length, calls.length - 1);
}
});
test("an artifact GitHub does not list yet is looked up again, and one it never lists keeps the not-found failure", async t => {
const { inputPath } = await fixture(t);
const late = transportFixture({ artifactNotFound: 1 });
const pauses = [];
await publishCiReportComment({ inputPath, artifactUrl, environment, transport: late.transport, sleep: async milliseconds => { pauses.push(milliseconds); } });
assert.equal(late.calls.filter(call => call.url.pathname.endsWith("/actions/artifacts/20")).length, 2);
assert.equal(pauses.length, 1);
assert.ok(late.calls.some(call => call.options.method === "POST"), "the comment is published once the artifact is found");
const missing = transportFixture({ artifactNotFound: Infinity });
const waited = [];
await assert.rejects(publishCiReportComment({ inputPath, artifactUrl, environment, transport: missing.transport, sleep: async milliseconds => { waited.push(milliseconds); } }), error => {
assert.equal(error.code, "GITHUB_RESOURCE_NOT_FOUND");
assert.equal(error.message, "Report publication GitHub check failed (404)");
assert.match(error.nextAction, /artifact ID/);
return true;
});
assert.equal(missing.calls.length, 5);
assert.equal(waited.length, 4, "no pause after the last lookup");
const total = waited.reduce((sum, milliseconds) => sum + milliseconds, 0);
assert.ok(total >= 30_000 && total <= 60_000, `${total} ms of pauses`);
assert.equal(missing.calls.some(call => call.options.method === "POST"), false);
});
test("stale PRs, expired artifacts, foreign artifacts, and replayed attempts cannot announce Ready", async t => {
const { inputPath } = await fixture(t);
const moved = transportFixture({ stale: true });