Skip to content
Open
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
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,23 @@ try {
}
```

## Waiting for a review of a specific commit

A review request targets a pull request, and the review runs on whichever commit is its head when the request lands. If the branch moves first, the result describes other code. Pass the commit you are about to ship as `headCommitSha`, and `waitForReview` reports `COMPLETED` only for a review of that commit.

```typescript
const { review_id } = await client.requestReview({
path: { org_id: organizationId, repo_id: repositoryId, number: 12 },
});
const outcome = await client.waitForReview(organizationId, review_id, {
headCommitSha: commitUnderTest,
});
if (outcome.status !== "COMPLETED")
console.error(outcome.status, outcome.reason, outcome.reviewUrl);
```

The value must be 40 or 64 hexadecimal characters, upper or lower case. Anything else, `null` included, throws a `TypeError` before the first request. Leaving the option out or passing `undefined` turns the check off. If a read shows the review on a different commit, polling stops there and the result is `INCOMPLETE`, even when the review is still running or has failed, with `HEAD_COMMIT_MISMATCH` as the final gap. A finished review that records no head commit gets `HEAD_COMMIT_UNAVAILABLE` as its final gap and is never `COMPLETED`, while a pending one is polled as usual. A wait that runs out of time keeps its timeout reason and still lists the head gap. For a GitHub Actions run triggered by `pull_request`, `GITHUB_SHA` points at a temporary merge commit rather than the branch head, so pass `github.event.pull_request.head.sha` instead.

## Coverage uploads

Upload CI coverage reports with a repository-restricted token that holds `coverage:write`. The token holder must have current GitHub write access to that repository. Set `PROOFLINE_TOKEN` to that token and pass the full commit SHA that the tests ran on. The server refuses branch names and abbreviated SHAs.
Expand Down
67 changes: 65 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ export interface ReviewOutcome {

export interface WaitOptions {
timeoutMs?: number;
/**
* The commit the result must describe, as 40 or 64 hexadecimal characters.
* A review of a different commit stops polling and returns INCOMPLETE, and
* a finished review that records no head commit cannot be COMPLETED.
*/
headCommitSha?: string;
}

export class ProoflineClient extends Operations {
Expand Down Expand Up @@ -178,6 +184,15 @@ export class ProoflineClient extends Operations {
const timeout = options.timeoutMs ?? 20 * 60_000;
if (!Number.isFinite(timeout) || timeout < 0)
throw new TypeError("timeoutMs must be finite and nonnegative");
const { headCommitSha } = options;
// Branch names move and short SHAs can turn ambiguous, so accept only a full SHA.
if (
headCommitSha !== undefined &&
(typeof headCommitSha !== "string" || !FULL_SHA.test(headCommitSha))
)
throw new TypeError(
"headCommitSha must be a full 40 or 64 character hexadecimal SHA",
);
const deadline = performance.now() + timeout;
const url = this.#transport.reviewUrl(orgId, reviewId);
let review: Review | null = null;
Expand All @@ -189,6 +204,7 @@ export class ProoflineClient extends Operations {
url,
review,
"the review did not finish before timeoutMs",
headCommitSha,
);
try {
review = await this.#transport.request<Review>(
Expand All @@ -207,6 +223,7 @@ export class ProoflineClient extends Operations {
url,
review,
"the review did not finish before timeoutMs",
headCommitSha,
);
if (
error instanceof ProoflineError &&
Expand All @@ -218,11 +235,17 @@ export class ProoflineClient extends Operations {
url,
review,
"the review did not finish before timeoutMs",
headCommitSha,
);
throw error;
}
validateReview(review, reviewId);
const status = terminal(review);
// A review never moves to another commit, so once a read shows a
// different one there is nothing left to wait for.
const status =
headGap(review, headCommitSha) === "HEAD_COMMIT_MISMATCH"
? "INCOMPLETE"
: terminal(review);
if (status !== null)
return outcome(
status,
Expand All @@ -235,6 +258,7 @@ export class ProoflineClient extends Operations {
? "one or more assessment results are unavailable or unknown"
: null
: null,
headCommitSha,
);
await sleep(
Math.min(interval, Math.max(0, deadline - performance.now())),
Expand Down Expand Up @@ -279,6 +303,12 @@ const KNOWN_ASSESSMENTS = new Set([
"EXCLUDED",
]);
const WITHHELD_MARKER = "[withheld: environment value]";
const FULL_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
const HEAD_REASONS = {
HEAD_COMMIT_MISMATCH: "the review is pinned to another head commit",
HEAD_COMMIT_UNAVAILABLE: "the review names no head commit",
} as const;
type HeadGap = keyof typeof HEAD_REASONS;

function isObject(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
Expand Down Expand Up @@ -428,6 +458,21 @@ function codeAssessment(review: Review): CodeAssessment | null {
return code;
}

// Compares the commit a review ran on with the one the caller expects. A
// missing, empty or non-string head reads as no head rather than a malformed
// response, so callers who leave the option out never see an error for it.
function headGap(
review: Review,
headCommitSha: string | undefined,
): HeadGap | null {
if (headCommitSha === undefined) return null;
const head: unknown = review.head_commit_sha;
if (typeof head !== "string" || !head) return "HEAD_COMMIT_UNAVAILABLE";
return head.toLowerCase() === headCommitSha.toLowerCase()
? null
: "HEAD_COMMIT_MISMATCH";
}

function optionalTexts(value: unknown): boolean {
return (
value === undefined ||
Expand Down Expand Up @@ -463,6 +508,7 @@ function outcome(
reviewUrl: string,
review: Review | null,
reason: string | null,
headCommitSha: string | undefined,
): ReviewOutcome {
const gaps: AssessmentGaps[] = (review?.assessments ?? [])
.filter(
Expand Down Expand Up @@ -559,5 +605,22 @@ function outcome(
checks: [],
});
}
return { status, reviewUrl, review, gaps, reason };
const head = review && headGap(review, headCommitSha);
if (!head) return { status, reviewUrl, review, gaps, reason };
gaps.push({
assessmentId: "",
status: "UNKNOWN",
incompletenessKind: null,
reasonCodes: [head],
releaseEvidenceGap: null,
checks: [],
});
// A timeout keeps its own reason: the head gap is in gaps either way.
return {
status: status === "COMPLETED" ? "INCOMPLETE" : status,
reviewUrl,
review,
gaps,
reason: status === "TIMED_OUT" ? reason : HEAD_REASONS[head],
};
}
229 changes: 229 additions & 0 deletions tests/http.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1507,6 +1507,235 @@ test("the wait timeout includes an in-flight request and returns the retained re
}
});

const headSha = "a".repeat(40);
const otherHeadSha = "c".repeat(40);

function headGap(code) {
return {
assessmentId: "",
status: "UNKNOWN",
incompletenessKind: null,
reasonCodes: [code],
releaseEvidenceGap: null,
checks: [],
};
}

const mismatchGap = headGap("HEAD_COMMIT_MISMATCH");
const missingHeadGap = headGap("HEAD_COMMIT_UNAVAILABLE");

function reviewOn(head, status = "COMPLETED") {
return { ...review(status), head_commit_sha: head };
}

// Poll sleeps are recorded and taken at once on a held clock, so a wait runs
// its whole schedule without real time passing. No sleep in these tests is
// shorter than the first 5,000 ms interval; shorter timers, such as the HTTP
// client's keep-alive, run as set.
function pollClock(t) {
let now = performance.now();
const waits = [];
const original = globalThis.setTimeout;
t.mock.method(performance, "now", () => now);
t.mock.method(globalThis, "setTimeout", (callback, delay, ...rest) => {
if (!(delay >= 5_000)) return original(callback, delay, ...rest);
waits.push(delay);
now += delay;
return original(callback, 0, ...rest);
});
return waits;
}

test("headCommitSha accepts only a review of that commit", async (t) => {
const waits = pollClock(t);
const fixture = await server(t, (_, response) =>
json(response, 200, reviewOn(headSha)),
);
const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token });
for (const held of [headSha, headSha.toUpperCase()]) {
const result = await client.waitForReview(orgId, reviewId, {
headCommitSha: held,
});
assert.deepEqual(
[result.status, result.gaps, result.reason],
["COMPLETED", [], null],
);
}
const result = await client.waitForReview(orgId, reviewId, {
headCommitSha: otherHeadSha,
});
assert.equal(result.status, "INCOMPLETE");
assert.deepEqual(result.gaps, [mismatchGap]);
assert.equal(result.reason, "the review is pinned to another head commit");
assert.equal(result.review.head_commit_sha, headSha);
assert.equal(
result.reviewUrl,
`${fixture.baseUrl}/orgs/by-id/${orgId}/reviews/${reviewId}`,
);
// Leaving the option out, or passing undefined (Python's None), keeps the
// old behaviour.
for (const options of [undefined, { headCommitSha: undefined }]) {
const plain = await client.waitForReview(orgId, reviewId, options);
assert.deepEqual(
[plain.status, plain.gaps, plain.reason],
["COMPLETED", [], null],
);
}
assert.equal(fixture.calls.length, 5);
assert.deepEqual(waits, []);
});

test("headCommitSha stops polling as soon as a read shows another commit", async (t) => {
const waits = pollClock(t);
const responses = [
review("PENDING"),
reviewOn(headSha, "RUNNING"),
reviewOn(headSha),
];
let reads = 0;
const fixture = await server(t, (_, response) =>
json(response, 200, responses[reads++]),
);
const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token });
const held = await client.waitForReview(orgId, reviewId, {
timeoutMs: 100_000,
headCommitSha: headSha,
});
assert.deepEqual(
[held.status, held.gaps, held.reason],
["COMPLETED", [], null],
);
assert.equal(reads, 3);
assert.deepEqual(waits.splice(0), [5_000, 10_000]);
reads = 0;
const other = await client.waitForReview(orgId, reviewId, {
timeoutMs: 100_000,
headCommitSha: otherHeadSha,
});
assert.equal(other.status, "INCOMPLETE");
assert.equal(other.review.status, "RUNNING");
assert.deepEqual(other.gaps, [mismatchGap]);
assert.equal(other.reason, "the review is pinned to another head commit");
// The second read already shows the other commit, so the completed third
// record is never fetched.
assert.equal(reads, 2);
assert.deepEqual(waits, [5_000]);
});

test("a review of another commit is INCOMPLETE even if it failed or stopped, with the head gap last", async (t) => {
pollClock(t);
let body;
const fixture = await server(t, (_, response) => json(response, 200, body));
const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token });
for (const status of ["FAILED", "STOPPED", "SUPERSEDED"]) {
body = reviewOn(headSha, status);
const other = await client.waitForReview(orgId, reviewId, {
headCommitSha: otherHeadSha,
});
assert.deepEqual([other.status, other.gaps], ["INCOMPLETE", [mismatchGap]]);
assert.equal(other.review.status, status);
const held = await client.waitForReview(orgId, reviewId, {
headCommitSha: headSha,
});
assert.equal(held.status, status === "FAILED" ? "FAILED" : "STOPPED");
assert.deepEqual([held.gaps, held.reason], [[], null]);
}
// The head gap comes after the review's own gaps.
body = { ...reviewOn(headSha), assessment_count: 2 };
const both = await client.waitForReview(orgId, reviewId, {
headCommitSha: otherHeadSha,
});
assert.deepEqual(both.gaps.at(-1), mismatchGap);
assert.deepEqual(
both.gaps.map((gap) => gap.reasonCodes),
[["ASSESSMENT_HISTORY_UNAVAILABLE"], ["HEAD_COMMIT_MISMATCH"]],
);
assert.equal(fixture.calls.length, 7);
});

test("a review with no head commit cannot complete while headCommitSha is set", async (t) => {
const waits = pollClock(t);
let body;
const fixture = await server(t, (_, response) => json(response, 200, body));
const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token });
const cases = [
[review(), "INCOMPLETE"],
[reviewOn(null), "INCOMPLETE"],
[reviewOn(""), "INCOMPLETE"],
[reviewOn(7), "INCOMPLETE"],
[reviewOn(null, "FAILED"), "FAILED"],
[reviewOn(null, "SUPERSEDED"), "STOPPED"],
];
for (const [record, status] of cases) {
body = record;
const result = await client.waitForReview(orgId, reviewId, {
headCommitSha: headSha,
});
assert.equal(result.status, status);
assert.deepEqual(result.gaps, [missingHeadGap]);
assert.equal(result.reason, "the review names no head commit");
}
assert.equal(fixture.calls.length, cases.length);
assert.deepEqual(waits, []);
// Without the option nobody gets an error over a field they don't use.
body = reviewOn(7);
assert.equal(
(await client.waitForReview(orgId, reviewId)).status,
"COMPLETED",
);
// A pending review may record its head later, so polling continues to the deadline.
body = review("PENDING");
const pending = await client.waitForReview(orgId, reviewId, {
timeoutMs: 12_000,
headCommitSha: headSha,
});
assert.equal(pending.status, "TIMED_OUT");
assert.deepEqual(pending.gaps, [missingHeadGap]);
// The wait ran out of time, so the reason says that; the head gap stays in gaps.
assert.equal(pending.reason, "the review did not finish before timeoutMs");
assert.equal(fixture.calls.length, cases.length + 3);
assert.deepEqual(waits, [5_000, 7_000]);
});

test("headCommitSha refuses anything but a full SHA before sending a request", async (t) => {
const fixture = await server(t, (_, response) =>
json(response, 200, reviewOn("d".repeat(64))),
);
const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token });
for (const value of [
"main",
"a".repeat(7),
"a".repeat(39),
"a".repeat(41),
"g".repeat(40),
"١".repeat(40),
`${headSha}\n`,
` ${headSha.slice(1)}`,
"",
7,
Buffer.from(headSha),
// The type allows no null. One comes from data with no commit in it, so the
// caller is not holding the commit they think they hold.
null,
]) {
await assert.rejects(
client.waitForReview(orgId, reviewId, { headCommitSha: value }),
(error) =>
error instanceof TypeError &&
/full 40 or 64 character/.test(error.message),
);
}
assert.equal(fixture.calls.length, 0);
const result = await client.waitForReview(orgId, reviewId, {
headCommitSha: "D".repeat(64),
});
assert.deepEqual(
[result.status, result.gaps, result.reason],
["COMPLETED", [], null],
);
assert.equal(fixture.calls.length, 1);
});

test("pagination keeps filters and refuses cycles, incomplete metadata and resource bounds", async (t) => {
let mode = "normal";
const fixture = await server(t, (request, response) => {
Expand Down