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
102 changes: 102 additions & 0 deletions scripts/repro-retry-after.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Minimal reproduction: a review wait rejects with the server's 503 instead of
// honoring a Retry-After that fits inside its own deadline.
//
// pnpm build && node scripts/repro-retry-after.mjs
//
// Pass a different build as the first argument:
// node scripts/repro-retry-after.mjs /path/to/dist/index.js
//
// The server answers the first review read with 503 + Retry-After: 90, and the
// second with a completed review. The caller allows ten minutes. Documented
// behavior (proofline.sh/docs/sdks): the wait stops early only when the retry
// delay would reach or pass the remaining budget, so it should wait 90 seconds
// and finish COMPLETED after two reads.
import { once } from "node:events";
import { createServer } from "node:http";

const entry =
process.argv[2] ?? new URL("../dist/index.js", import.meta.url).href;
const { ProoflineClient } = await import(entry);

const orgId = "00000000-0000-7000-8000-000000000001";
const reviewId = "00000000-0000-7000-8000-000000000002";
const token = "plp_customer_canary_3331";

// Compress the retry sleep so the repro finishes in a second, and record what
// the client asked for. Shorter timers, such as the server's keep-alive, pass
// through untouched.
const original = globalThis.setTimeout;
const slept = [];
globalThis.setTimeout = (callback, delay, ...rest) => {
if (delay < 30_000) return original(callback, delay, ...rest);
slept.push(delay);
return original(callback, 0, ...rest);
};

const review = {
id: reviewId,
public_key: "review-3331",
kind: "PULL_REQUEST",
status: "COMPLETED",
assessment_count: 1,
environment_display_names: ["production"],
finding_count: 0,
trigger_origin: "MANUAL",
publication: "WITHHELD",
created_at: "2026-09-30T12:00:00Z",
stoppable: false,
related_reviews: [],
subjects: [],
assessments: [
{
id: "00000000-0000-7000-8000-000000000003",
environment_display_name: "production",
status: "COMPLETED",
domains: [],
findings: [],
release_evidence_gap: null,
checks: { receipt_recorded: true, status: "READY", families: [] },
},
],
actions: {
promote_findings: false,
rerun: false,
publish: false,
stop: false,
validate_findings: false,
},
};

let reads = 0;
const http = createServer((request, response) => {
reads += 1;
const headers = { "Content-Type": "application/json" };
if (reads === 1) headers["Retry-After"] = "90";
response.writeHead(reads === 1 ? 503 : 200, headers);
response.end(
JSON.stringify(
reads === 1
? { type: "urn:proofline:unavailable", detail: "try again shortly" }
: review,
),
);
});
http.listen(0, "127.0.0.1");
await once(http, "listening");
const baseUrl = `http://127.0.0.1:${http.address().port}`;

try {
const outcome = await new ProoflineClient({ baseUrl, token }).waitForReview(
orgId,
reviewId,
{ timeoutMs: 10 * 60_000 },
);
console.log(`outcome ${outcome.status} after ${reads} reads, slept ${slept}`);
} catch (error) {
console.log(
`threw ${error.constructor.name}${error.status === undefined ? "" : ` ${error.status}`}: ${error.message} after ${reads} reads, slept ${slept}`,
);
} finally {
globalThis.setTimeout = original;
http.close();
}
12 changes: 10 additions & 2 deletions src/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -480,12 +480,13 @@ function problem(
function retryDelay(
header: string | null,
attempt: number,
maximum: number,
): number | undefined {
if (header === null) return Math.min(2 ** attempt, MAX_RETRY_SECONDS) * 1000;
const seconds = /^\d+$/.test(header.trim())
? Number(header)
: Math.max(0, (httpDate(header.trim()) - Date.now()) / 1000);
return Number.isFinite(seconds) && seconds <= MAX_RETRY_SECONDS
return Number.isFinite(seconds) && seconds <= maximum
? seconds * 1000
: undefined;
}
Expand Down Expand Up @@ -666,7 +667,14 @@ export class Transport {
);
if (response.ok) return value as T;
const error = problem(response.status, value, this.#token);
const delay = retryDelay(response.headers.get("Retry-After"), attempt);
// A read without a caller deadline waits at most a minute for a retry. A
// review wait spends its own deadline, so it honors a longer hint that fits
// inside that deadline instead of ending the wait with the refusal.
const delay = retryDelay(
response.headers.get("Retry-After"),
attempt,
deadline === undefined ? MAX_RETRY_SECONDS : Number.POSITIVE_INFINITY,
);
if (
method !== "GET" ||
![429, 503].includes(response.status) ||
Expand Down
52 changes: 52 additions & 0 deletions tests/http.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1333,6 +1333,58 @@ test("review waits recover from invalid UTF-8 refusals and retain retry deadline
}
});

test("a review wait honors a Retry-After longer than one read does", async (t) => {
// A read without a caller deadline waits at most a minute for a retry. A review
// wait spends its own deadline, so it honors a longer hint that fits inside it
// instead of ending the wait with the server's refusal.
const waits = [];
const original = globalThis.setTimeout;
t.mock.method(globalThis, "setTimeout", (callback, delay, ...rest) => {
if (delay !== 90_000) return original(callback, delay, ...rest);
waits.push(delay);
return original(callback, 0, ...rest);
});
const held = await server(t, (_, response, calls) =>
calls.length === 1
? json(
response,
503,
{ type: "urn:proofline:unavailable", detail: responseCanary },
{ "Retry-After": "90" },
)
: json(response, 200, review()),
);
const client = new ProoflineClient({ baseUrl: held.baseUrl, token });
const waited = await client.waitForReview(orgId, reviewId, {
timeoutMs: 10 * 60_000,
});
assert.equal(waited.status, "COMPLETED");
assert.equal(held.calls.length, 2);
assert.deepEqual(waits, [90_000]);

// The same hint cannot fit inside a shorter wait, which times out instead of
// throwing the refusal, and one read still refuses a hint it cannot spend.
const late = await server(t, (_, response) =>
json(
response,
503,
{ type: "urn:proofline:unavailable", detail: responseCanary },
{ "Retry-After": "90" },
),
);
const short = new ProoflineClient({ baseUrl: late.baseUrl, token });
const outcome = await short.waitForReview(orgId, reviewId, {
timeoutMs: 60_000,
});
assert.equal(outcome.status, "TIMED_OUT");
assert.equal(late.calls.length, 1);
await assert.rejects(
short.getReview({ path: { org_id: orgId, review_id: reviewId } }),
(error) => error instanceof ProoflineError && error.status === 503,
);
assert.equal(late.calls.length, 2);
});

test("export reads retry non-JSON refusals independently of the successful format", async (t) => {
for (const format of ["csv", "ndjson"]) {
for (const [name, body, contentType] of refusalBodies) {
Expand Down