From 9d66b050750ff767bc7396a7989853429caf0c8c Mon Sep 17 00:00:00 2001 From: Devnil434 Date: Thu, 3 Dec 2026 15:39:55 +0530 Subject: [PATCH 1/7] Add AbortSignal and onPoll support and fix decoded timeout classification --- src/index.ts | 92 ++++++++++++-- src/transport.ts | 103 +++++++++++++--- tests/http.test.mjs | 293 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 457 insertions(+), 31 deletions(-) diff --git a/src/index.ts b/src/index.ts index 0374a0e..fbe5d08 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,13 +28,20 @@ import { type UploadCoverageReportsParameters, } from "./operations.js"; import type { components } from "./schema.js"; -import { type ClientOptions, sleep, Transport } from "./transport.js"; +import { + aborted, + type ClientOptions, + type RequestOptions, + sleep, + Transport, +} from "./transport.js"; export type * from "./operations.js"; export type { components, operations, paths } from "./schema.js"; export type { ClientOptions, ProblemFields, + RequestOptions, RunNowRefusal, } from "./transport.js"; export { ProoflineError, SecretToken } from "./transport.js"; @@ -75,6 +82,8 @@ export interface ReviewOutcome { export interface WaitOptions { timeoutMs?: number; + signal?: AbortSignal; + onPoll?: (review: Review) => void | Promise; } export class ProoflineClient extends Operations { @@ -94,7 +103,10 @@ export class ProoflineClient extends Operations { this.fixes = new FixesClient(transport); } - async exportReviews(parameters: ExportParameters): Promise { + async exportReviews( + parameters: ExportParameters, + options: RequestOptions = {}, + ): Promise { const format = parameters.query.format ?? "ndjson"; if (format !== "csv" && format !== "ndjson") throw new TypeError("export format must be csv or ndjson"); @@ -107,6 +119,8 @@ export class ProoflineClient extends Operations { (text, headers) => decodeExport(text, headers, format, parameters.path.dataset), format === "csv" ? "text/csv" : "application/x-ndjson", + undefined, + options.signal, ); } @@ -118,22 +132,29 @@ export class ProoflineClient extends Operations { */ async *iterExportPages( parameters: ExportParameters, - options: { maxPages?: number } = {}, + options: { maxPages?: number; signal?: AbortSignal } = {}, ): AsyncGenerator { const maxPages = options.maxPages ?? 100; if (!Number.isSafeInteger(maxPages) || maxPages < 1 || maxPages > 1_000) throw new TypeError("maxPages must be an integer from 1 to 1000"); + if (options.signal?.aborted) throw aborted(); + const requestOptions: RequestOptions = + options.signal === undefined ? {} : { signal: options.signal }; // The caller's objects can change while a page is yielded. const path = { ...parameters.path }; const query = { ...parameters.query }; let cursor = query.cursor ?? null; const seen = new Set(cursor === null ? [] : [cursor]); for (let index = 0; index < maxPages; index += 1) { - const page = await this.exportReviews({ - ...parameters, - path, - query: { ...query, cursor }, - }); + if (options.signal?.aborted) throw aborted(); + const page = await this.exportReviews( + { + ...parameters, + path, + query: { ...query, cursor }, + }, + requestOptions, + ); if (page.nextCursor === null) { yield page; return; @@ -155,29 +176,58 @@ export class ProoflineClient extends Operations { async uploadCoverageFiles( parameters: UploadCoverageReportsParameters, upload: CoverageFilesUpload, + options: RequestOptions = {}, ): Promise { - return this.uploadCoverageReports( + if (options.signal?.aborted) throw aborted(); + const body = await readCoverageFiles(upload); + if (options.signal?.aborted) throw aborted(); + return this.#transport.request( + "POST", + "/api/v1/organizations/{org_id}/repositories/{repo_id}/coverage-reports", parameters, - await readCoverageFiles(upload), + undefined, + body, + undefined, + undefined, + undefined, + options.signal, ); } async *iterReviews( parameters: ListReviewsParameters, - options: { maxPages?: number; maxItems?: number } = {}, + options: { + maxPages?: number; + maxItems?: number; + signal?: AbortSignal; + } = {}, ): AsyncGenerator { const maxPages = integerLimit(options.maxPages ?? 100, "maxPages"); const maxItems = integerLimit(options.maxItems ?? 10_000, "maxItems"); + if (options.signal?.aborted) throw aborted(); const initialQuery = { ...parameters.query }; const seen = new Set(); let count = 0; let cursor = initialQuery.cursor; for (let index = 0; index < maxPages; index += 1) { + if (options.signal?.aborted) throw aborted(); const query = { ...initialQuery, ...(cursor === undefined ? {} : { cursor }), }; - const page = await this.listReviews({ ...parameters, query }); + const page = await this.#transport.request< + components["schemas"]["ReviewPage"] + >( + "GET", + "/api/v1/organizations/{org_id}/reviews", + { ...parameters, query }, + undefined, + undefined, + undefined, + undefined, + undefined, + options.signal, + ); if ( !isObject(page) || !Array.isArray(page.items) || @@ -220,11 +270,16 @@ 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"); + if (options.onPoll !== undefined && typeof options.onPoll !== "function") + throw new TypeError("onPoll must be a function"); + const signal = options.signal; + if (signal?.aborted) throw aborted(); const deadline = performance.now() + timeout; const url = this.#transport.reviewUrl(orgId, reviewId); let review: Review | null = null; let interval = 5_000; for (;;) { + if (signal?.aborted) throw aborted(); if (performance.now() >= deadline) return outcome( "TIMED_OUT", @@ -238,8 +293,19 @@ export class ProoflineClient extends Operations { "/api/v1/organizations/{org_id}/reviews/{review_id}", { path: { org_id: orgId, review_id: reviewId } }, deadline, + undefined, + undefined, + undefined, + undefined, + signal, ); } catch (error) { + if ( + signal?.aborted || + (error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted") + ) + throw error; if ( error instanceof ProoflineError && error.type === "urn:proofline:sdk:timeout" @@ -264,6 +330,7 @@ export class ProoflineClient extends Operations { throw error; } validateReview(review, reviewId); + if (options.onPoll) await options.onPoll(review); const status = terminal(review); if (status !== null) return outcome( @@ -280,6 +347,7 @@ export class ProoflineClient extends Operations { ); await sleep( Math.min(interval, Math.max(0, deadline - performance.now())), + signal, ); interval = Math.min(interval * 2, 60_000); } diff --git a/src/transport.ts b/src/transport.ts index 06795f0..0cfbc23 100644 --- a/src/transport.ts +++ b/src/transport.ts @@ -110,6 +110,10 @@ export interface ClientOptions { requestTimeoutMs?: number; } +export interface RequestOptions { + signal?: AbortSignal; +} + export interface Parameters { path?: object; query?: object; @@ -177,12 +181,21 @@ function positive(value: number, name: string): number { return value; } +export function aborted(): ProoflineError { + return new ProoflineError( + 0, + "urn:proofline:sdk:aborted", + "the request was aborted", + ); +} + async function decoded( response: Response, deadline: number, - signal: AbortSignal, + timeoutSignal: AbortSignal, waitTimeout: boolean, decode: (text: string, headers: Headers) => unknown, + callerSignal?: AbortSignal, ): Promise { const reader = response.body?.getReader(); if (!reader) { @@ -195,6 +208,7 @@ async function decoded( } const chunks: Uint8Array[] = []; let size = 0; + let data: Uint8Array; try { for (;;) { const { value, done } = await reader.read(); @@ -210,23 +224,16 @@ async function decoded( } chunks.push(value); } - const data = new Uint8Array(size); + data = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { data.set(chunk, offset); offset += chunk.length; } - const decoder = new TextDecoder("utf-8", { fatal: true }); - if (response.ok) return decode(decoder.decode(data), response.headers); - try { - return JSON.parse(decoder.decode(data)) as unknown; - } catch { - // A complete HTTP refusal need not carry a UTF-8 JSON Problem to be retryable. - return undefined; - } } catch (error) { if (error instanceof ProoflineError) throw error; - if (response.ok && (signal.aborted || performance.now() >= deadline)) + if (callerSignal?.aborted) throw aborted(); + if (response.ok && (timeoutSignal.aborted || performance.now() >= deadline)) throw new ProoflineError( 0, waitTimeout @@ -239,11 +246,41 @@ async function decoded( throw new ProoflineError( response.status, "urn:proofline:sdk:invalid-response", - "the response is not valid UTF-8 JSON", + "the response body stream ended before completion", ); } finally { reader.releaseLock(); } + let text: string; + try { + text = new TextDecoder("utf-8", { fatal: true }).decode(data); + } catch { + // A complete HTTP refusal need not carry valid UTF-8 to be retryable. + if (!response.ok) return undefined; + throw new ProoflineError( + response.status, + "urn:proofline:sdk:invalid-response", + "the response is not valid UTF-8", + ); + } + if (response.ok) { + try { + return decode(text, response.headers); + } catch (error) { + if (error instanceof ProoflineError) throw error; + throw new ProoflineError( + response.status, + "urn:proofline:sdk:invalid-response", + "the response is not valid UTF-8 JSON", + ); + } + } + try { + return JSON.parse(text) as unknown; + } catch { + // A complete HTTP refusal need not carry a UTF-8 JSON Problem to be retryable. + return undefined; + } } type Body = Record; @@ -400,8 +437,23 @@ function httpDate(value: string): number { : Number.NaN; } -export function sleep(milliseconds: number): Promise { - return new Promise((resolve) => setTimeout(resolve, milliseconds)); +export function sleep( + milliseconds: number, + signal?: AbortSignal, +): Promise { + if (signal?.aborted) return Promise.reject(aborted()); + if (milliseconds <= 0) return Promise.resolve(); + return new Promise((resolve, reject) => { + const onAbort = () => { + clearTimeout(timer); + reject(aborted()); + }; + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, milliseconds); + signal?.addEventListener("abort", onAbort, { once: true }); + }); } export class Transport { @@ -437,6 +489,7 @@ export class Transport { JSON.parse(text), accept = "application/json, application/problem+json", mcpPhase?: "initialize" | "notification" | "call", + callerSignal?: AbortSignal, ): Promise { const path = Object.entries(parameters.path ?? {}).reduce( (value, [key, coordinateValue]) => @@ -454,6 +507,7 @@ export class Transport { if (mcpPhase && new TextEncoder().encode(requestBody).length > 8192) throw new TypeError("MCP request exceeds 8192 bytes"); for (let attempt = 0; ; attempt += 1) { + if (callerSignal?.aborted) throw aborted(); const headers = new Headers({ Accept: accept, "User-Agent": `proofline-typescript/${VERSION}`, @@ -479,7 +533,10 @@ export class Transport { "the request deadline expired", ); const requestDeadline = now + remaining; - const signal = AbortSignal.timeout(Math.ceil(remaining)); + const timeoutSignal = AbortSignal.timeout(Math.ceil(remaining)); + const signal = callerSignal + ? AbortSignal.any([timeoutSignal, callerSignal]) + : timeoutSignal; let response: Response; try { response = await fetch(url, { @@ -491,16 +548,23 @@ export class Transport { signal, }); } catch { - if (signal.aborted && waitTimeout) + if (callerSignal?.aborted) throw aborted(); + if (timeoutSignal.aborted && waitTimeout) throw new ProoflineError( 0, "urn:proofline:sdk:timeout", "the review wait deadline expired", ); + if (timeoutSignal.aborted) + throw new ProoflineError( + 0, + "urn:proofline:sdk:transport", + "the request did not receive a response within its timeout", + ); throw new ProoflineError( 0, "urn:proofline:sdk:transport", - "the request did not receive a response within its timeout", + "the request failed due to a transport error", ); } if (mcpPhase && response.ok) { @@ -524,9 +588,10 @@ export class Transport { const value = await decoded( response, requestDeadline, - signal, + timeoutSignal, waitTimeout, decode, + callerSignal, ); if (response.ok) return value as T; const error = problem(response.status, value, this.#token); @@ -545,7 +610,7 @@ export class Transport { "the review timeout expires before the server permits a retry", ); } - await sleep(delay); + await sleep(delay, callerSignal); } } } diff --git a/tests/http.test.mjs b/tests/http.test.mjs index 0a189be..ea65726 100644 --- a/tests/http.test.mjs +++ b/tests/http.test.mjs @@ -2578,3 +2578,296 @@ export async function use(client: ProoflineClient): Promise { fixture, ]); }); + +test("completed corrupt 200 responses at the wait deadline remain invalid-response rather than TIMED_OUT", async (t) => { + let payload = '{"id":'; + const fixture = await server(t, (_, response) => { + response.writeHead(200, { "Content-Type": "application/json" }); + response.end(payload); + }); + const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token }); + const start = performance.now(); + let calls = 0; + // Advance past the 80ms wait deadline while the response body is decoded. + const clock = t.mock.method(performance, "now", () => { + calls += 1; + return calls <= 4 ? start : start + 500; + }); + try { + for (const next of ['{"id":', invalidUtf8Body]) { + payload = next; + calls = 0; + await assert.rejects( + client.waitForReview(orgId, reviewId, { timeoutMs: 80 }), + (error) => + error instanceof ProoflineError && + error.status === 200 && + error.type === "urn:proofline:sdk:invalid-response" && + !error.detail.includes(token) && + !error.detail.includes(responseCanary), + ); + } + } finally { + clock.mock.restore(); + } +}); + +test("immediate network failures report transport error without claiming timeout", async (t) => { + const original = globalThis.fetch; + globalThis.fetch = async () => { + throw new TypeError("fetch failed"); + }; + t.after(() => { + globalThis.fetch = original; + }); + const client = new ProoflineClient({ + baseUrl: "https://proofline.sh", + token, + }); + await assert.rejects( + client.getReview({ path: { org_id: orgId, review_id: reviewId } }), + (error) => + error instanceof ProoflineError && + error.status === 0 && + error.type === "urn:proofline:sdk:transport" && + !error.detail.includes("within its timeout") && + !error.detail.includes(token), + ); +}); + +test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and uploads", async (t) => { + let mode = "running"; + let pendingResponse; + const fixture = await server(t, (request, response) => { + if (mode === "retry") { + response.writeHead(503, { + "Content-Type": "application/json", + "Retry-After": "60", + }); + return response.end(JSON.stringify({ detail: "busy" })); + } + if (mode === "hang") { + pendingResponse = response; + response.writeHead(200, { "Content-Type": "application/json" }); + return; + } + if (request.url.includes("/exports/")) { + const url = new URL(request.url, "http://127.0.0.1"); + const cursor = url.searchParams.get("cursor"); + response.writeHead(200, { + "content-type": "application/x-ndjson", + "x-proofline-export-version": "1", + "x-proofline-export-settled-until": "2026-10-25T00:00:00Z", + ...(cursor ? {} : { "x-proofline-export-next-cursor": "page-2" }), + }); + return response.end('{"dataset_version":1,"page":"first"}\n'); + } + if (request.url.endsWith("/reviews") || request.url.includes("/reviews?")) { + return json(response, 200, { + items: [{ id: "first" }], + truncated: true, + next_cursor: "page-2", + filters: { repositories: [], environments: [], authors: [] }, + }); + } + return json(response, 200, review("RUNNING")); + }); + t.after(() => pendingResponse?.destroy()); + const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token }); + + // Pre-aborted signal rejects even when timeoutMs is 0. + const preAborted = new AbortController(); + preAborted.abort(); + await assert.rejects( + client.waitForReview(orgId, reviewId, { + timeoutMs: 0, + signal: preAborted.signal, + }), + (error) => + error instanceof ProoflineError && + error.status === 0 && + error.type === "urn:proofline:sdk:aborted", + ); + assert.equal(fixture.calls.length, 0); + + // Aborting during the 5s polling sleep rejects immediately. + const sleepAbort = new AbortController(); + const sleepStarted = performance.now(); + setTimeout(() => sleepAbort.abort(), 30); + await assert.rejects( + client.waitForReview(orgId, reviewId, { signal: sleepAbort.signal }), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + assert(performance.now() - sleepStarted < 1_000); + + // Aborting an in-flight request never collapses into TIMED_OUT. + mode = "hang"; + const flightAbort = new AbortController(); + setTimeout(() => flightAbort.abort(), 30); + await assert.rejects( + client.waitForReview(orgId, reviewId, { + timeoutMs: 40, + signal: flightAbort.signal, + }), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + + // Aborting during Retry-After backoff rejects promptly after one attempt. + mode = "retry"; + const retryBefore = fixture.calls.length; + const retryAbort = new AbortController(); + const retryStarted = performance.now(); + setTimeout(() => retryAbort.abort(), 30); + await assert.rejects( + client.exportReviews( + { + path: { org_id: orgId, dataset: "reviews" }, + query: { + from: "2026-10-01T00:00:00Z", + to: "2026-10-25T00:00:00Z", + }, + }, + { signal: retryAbort.signal }, + ), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + assert(performance.now() - retryStarted < 1_000); + assert.equal(fixture.calls.length - retryBefore, 1); + + // Aborting between pagination pages stops before fetching the next page. + mode = "normal"; + const reviewsAbort = new AbortController(); + const reviewsBefore = fixture.calls.length; + const reviewIter = client.iterReviews( + { path: { org_id: orgId } }, + { signal: reviewsAbort.signal }, + ); + assert.equal((await reviewIter.next()).value.id, "first"); + reviewsAbort.abort(); + await assert.rejects( + reviewIter.next(), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + assert.equal(fixture.calls.length - reviewsBefore, 1); + + const exportAbort = new AbortController(); + const exportBefore = fixture.calls.length; + const exportIter = client.iterExportPages( + { + path: { org_id: orgId, dataset: "reviews" }, + query: { + from: "2026-10-01T00:00:00Z", + to: "2026-10-25T00:00:00Z", + }, + }, + { signal: exportAbort.signal }, + ); + assert.equal((await exportIter.next()).value.nextCursor, "page-2"); + exportAbort.abort(); + await assert.rejects( + exportIter.next(), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + assert.equal(fixture.calls.length - exportBefore, 1); + + // Pre-aborted signal cancels uploadCoverageFiles before reading disk. + const uploadBefore = fixture.calls.length; + await assert.rejects( + client.uploadCoverageFiles( + { path: { org_id: orgId, repo_id: repoId } }, + { tested_sha: "c".repeat(40), files: ["absent.info"] }, + { signal: preAborted.signal }, + ), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + assert.equal(fixture.calls.length - uploadBefore, 0); +}); + +test("waitForReview invokes onPoll for each validated poll and supports public options types", async (t) => { + const states = ["PENDING", "RUNNING", "COMPLETED"]; + let index = 0; + const fixture = await server(t, (_, response) => { + const status = states[Math.min(index, states.length - 1)]; + index += 1; + json(response, 200, review(status)); + }); + const original = globalThis.setTimeout; + t.mock.method(globalThis, "setTimeout", (callback, delay, ...rest) => + delay === 5_000 || delay === 10_000 + ? original(callback, 0, ...rest) + : original(callback, delay, ...rest), + ); + const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token }); + const observed = []; + const result = await client.waitForReview(orgId, reviewId, { + onPoll: async (current) => { + observed.push(current.status); + }, + }); + assert.equal(result.status, "COMPLETED"); + assert.deepEqual(observed, ["PENDING", "RUNNING", "COMPLETED"]); + + await assert.rejects( + client.waitForReview(orgId, reviewId, { onPoll: "not-a-function" }), + TypeError, + ); + + // Verify consumer compilation with strict + exactOptionalPropertyTypes. + const work = await mkdtemp(join(tmpdir(), "sdk-wait-types-")); + t.after(() => rm(work, { recursive: true, force: true })); + const entry = fileURLToPath(new URL("../dist/index.js", import.meta.url)); + const typeFixture = join(work, "consumer.mts"); + await writeFile( + typeFixture, + ` +import type { ProoflineClient, RequestOptions, WaitOptions, Review } from ${JSON.stringify(entry)}; +export async function wait(client: ProoflineClient, signal: AbortSignal): Promise { + const req: RequestOptions = { signal }; + const opts: WaitOptions = { + timeoutMs: 1000, + signal, + onPoll: (r: Review) => { + console.log(r.status); + }, + }; + await client.waitForReview("org", "rev", opts); + await client.exportReviews( + { path: { org_id: "org", dataset: "reviews" }, query: { from: "2026-10-01T00:00:00Z", to: "2026-10-02T00:00:00Z" } }, + req, + ); + for await (const _ of client.iterReviews({ path: { org_id: "org" } }, { signal })) break; + for await (const _ of client.iterExportPages( + { path: { org_id: "org", dataset: "reviews" }, query: { from: "2026-10-01T00:00:00Z", to: "2026-10-02T00:00:00Z" } }, + { signal }, + )) break; +} +`, + ); + execFileSync(process.execPath, [ + fileURLToPath( + new URL("../node_modules/typescript/lib/tsc.js", import.meta.url), + ), + "--noEmit", + "--strict", + "--exactOptionalPropertyTypes", + "--target", + "ES2022", + "--module", + "NodeNext", + "--moduleResolution", + "NodeNext", + typeFixture, + ]); +}); From 95d8c3f58a653c573881c366c7486f4f06791d2c Mon Sep 17 00:00:00 2001 From: Devnil434 Date: Thu, 3 Dec 2026 15:47:16 +0530 Subject: [PATCH 2/7] Align onPoll with non-terminal polls and test abort/error paths --- src/index.ts | 3 ++- tests/http.test.mjs | 31 +++++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/index.ts b/src/index.ts index fbe5d08..546c2f9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -83,6 +83,7 @@ export interface ReviewOutcome { export interface WaitOptions { timeoutMs?: number; signal?: AbortSignal; + /** Invoked after each validated non-terminal poll while waiting. */ onPoll?: (review: Review) => void | Promise; } @@ -330,7 +331,6 @@ export class ProoflineClient extends Operations { throw error; } validateReview(review, reviewId); - if (options.onPoll) await options.onPoll(review); const status = terminal(review); if (status !== null) return outcome( @@ -345,6 +345,7 @@ export class ProoflineClient extends Operations { : null : null, ); + if (options.onPoll) await options.onPoll(review); await sleep( Math.min(interval, Math.max(0, deadline - performance.now())), signal, diff --git a/tests/http.test.mjs b/tests/http.test.mjs index ea65726..8b2f32b 100644 --- a/tests/http.test.mjs +++ b/tests/http.test.mjs @@ -2795,7 +2795,7 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up assert.equal(fixture.calls.length - uploadBefore, 0); }); -test("waitForReview invokes onPoll for each validated poll and supports public options types", async (t) => { +test("waitForReview invokes onPoll for non-terminal polls and supports public options types", async (t) => { const states = ["PENDING", "RUNNING", "COMPLETED"]; let index = 0; const fixture = await server(t, (_, response) => { @@ -2817,7 +2817,34 @@ test("waitForReview invokes onPoll for each validated poll and supports public o }, }); assert.equal(result.status, "COMPLETED"); - assert.deepEqual(observed, ["PENDING", "RUNNING", "COMPLETED"]); + assert.equal(result.review.status, "COMPLETED"); + assert.deepEqual(observed, ["PENDING", "RUNNING"]); + + // Aborting from onPoll stops waiting immediately without sleeping. + index = 0; + const pollAbort = new AbortController(); + await assert.rejects( + client.waitForReview(orgId, reviewId, { + signal: pollAbort.signal, + onPoll: () => pollAbort.abort(), + }), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + assert.equal(index, 1); + + // An error thrown by onPoll propagates immediately. + index = 0; + await assert.rejects( + client.waitForReview(orgId, reviewId, { + onPoll: () => { + throw new Error("stop polling"); + }, + }), + { message: "stop polling" }, + ); + assert.equal(index, 1); await assert.rejects( client.waitForReview(orgId, reviewId, { onPoll: "not-a-function" }), From 359fc41830a6eefbeaf90155aaf13b89b1a50b59 Mon Sep 17 00:00:00 2001 From: Devnil434 Date: Thu, 3 Dec 2026 18:40:18 +0530 Subject: [PATCH 3/7] Address Proofline review findings on waitForReview, pagination, and tests --- src/index.ts | 101 ++++++++++++++++++++++++--------- tests/http.test.mjs | 135 +++++++++++++++++++++++++++++++++++++++----- 2 files changed, 197 insertions(+), 39 deletions(-) diff --git a/src/index.ts b/src/index.ts index 546c2f9..4af52cb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -138,16 +138,17 @@ export class ProoflineClient extends Operations { const maxPages = options.maxPages ?? 100; if (!Number.isSafeInteger(maxPages) || maxPages < 1 || maxPages > 1_000) throw new TypeError("maxPages must be an integer from 1 to 1000"); - if (options.signal?.aborted) throw aborted(); + const signal = options.signal; + if (signal?.aborted) throw aborted(); const requestOptions: RequestOptions = - options.signal === undefined ? {} : { signal: options.signal }; + signal === undefined ? {} : { signal }; // The caller's objects can change while a page is yielded. const path = { ...parameters.path }; const query = { ...parameters.query }; let cursor = query.cursor ?? null; const seen = new Set(cursor === null ? [] : [cursor]); for (let index = 0; index < maxPages; index += 1) { - if (options.signal?.aborted) throw aborted(); + if (signal?.aborted) throw aborted(); const page = await this.exportReviews( { ...parameters, @@ -179,9 +180,12 @@ export class ProoflineClient extends Operations { upload: CoverageFilesUpload, options: RequestOptions = {}, ): Promise { - if (options.signal?.aborted) throw aborted(); + const signal = options.signal; + if (signal?.aborted) throw aborted(); const body = await readCoverageFiles(upload); - if (options.signal?.aborted) throw aborted(); + if (signal === undefined) + return this.uploadCoverageReports(parameters, body); + if (signal.aborted) throw aborted(); return this.#transport.request( "POST", "/api/v1/organizations/{org_id}/repositories/{repo_id}/coverage-reports", @@ -191,7 +195,7 @@ export class ProoflineClient extends Operations { undefined, undefined, undefined, - options.signal, + signal, ); } @@ -205,30 +209,32 @@ export class ProoflineClient extends Operations { ): AsyncGenerator { const maxPages = integerLimit(options.maxPages ?? 100, "maxPages"); const maxItems = integerLimit(options.maxItems ?? 10_000, "maxItems"); - if (options.signal?.aborted) throw aborted(); + const signal = options.signal; + if (signal?.aborted) throw aborted(); const initialQuery = { ...parameters.query }; const seen = new Set(); let count = 0; let cursor = initialQuery.cursor; for (let index = 0; index < maxPages; index += 1) { - if (options.signal?.aborted) throw aborted(); + if (signal?.aborted) throw aborted(); const query = { ...initialQuery, ...(cursor === undefined ? {} : { cursor }), }; - const page = await this.#transport.request< - components["schemas"]["ReviewPage"] - >( - "GET", - "/api/v1/organizations/{org_id}/reviews", - { ...parameters, query }, - undefined, - undefined, - undefined, - undefined, - undefined, - options.signal, - ); + const page = + signal === undefined + ? await this.listReviews({ ...parameters, query }) + : await this.#transport.request( + "GET", + "/api/v1/organizations/{org_id}/reviews", + { ...parameters, query }, + undefined, + undefined, + undefined, + undefined, + undefined, + signal, + ); if ( !isObject(page) || !Array.isArray(page.items) || @@ -239,6 +245,7 @@ export class ProoflineClient extends Operations { ) throw protocol("the review page has no typed collection metadata"); for (const item of page.items) { + if (signal?.aborted) throw aborted(); if (count >= maxItems) throw paginationLimit("the review collection exceeds maxItems"); count += 1; @@ -271,7 +278,8 @@ 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"); - if (options.onPoll !== undefined && typeof options.onPoll !== "function") + const onPoll = options.onPoll; + if (onPoll !== undefined && typeof onPoll !== "function") throw new TypeError("onPoll must be a function"); const signal = options.signal; if (signal?.aborted) throw aborted(); @@ -302,11 +310,11 @@ export class ProoflineClient extends Operations { ); } catch (error) { if ( - signal?.aborted || - (error instanceof ProoflineError && - error.type === "urn:proofline:sdk:aborted") + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted" ) throw error; + if (signal?.aborted) throw aborted(); if ( error instanceof ProoflineError && error.type === "urn:proofline:sdk:timeout" @@ -345,7 +353,21 @@ export class ProoflineClient extends Operations { : null : null, ); - if (options.onPoll) await options.onPoll(review); + if (onPoll) { + const settled = await awaitPollCallback( + onPoll, + review, + deadline, + signal, + ); + if (!settled) + return outcome( + "TIMED_OUT", + url, + review, + "the review did not finish before timeoutMs", + ); + } await sleep( Math.min(interval, Math.max(0, deadline - performance.now())), signal, @@ -357,6 +379,33 @@ export class ProoflineClient extends Operations { import { ProoflineError } from "./transport.js"; +async function awaitPollCallback( + callback: (review: Review) => void | Promise, + review: Review, + deadline: number, + signal?: AbortSignal, +): Promise { + const pending = Promise.resolve().then(() => + callback(structuredClone(review)), + ); + if (signal?.aborted) throw aborted(); + const remaining = deadline - performance.now(); + if (remaining <= 0) return false; + let timer: ReturnType | undefined; + let onAbort: (() => void) | undefined; + const bound = new Promise((resolve, reject) => { + onAbort = () => reject(aborted()); + timer = setTimeout(() => resolve(false), remaining); + signal?.addEventListener("abort", onAbort, { once: true }); + }); + try { + return await Promise.race([pending.then(() => true), bound]); + } finally { + if (timer !== undefined) clearTimeout(timer); + if (onAbort) signal?.removeEventListener("abort", onAbort); + } +} + function protocol(detail: string): ProoflineError { return new ProoflineError(0, "urn:proofline:sdk:invalid-response", detail); } diff --git a/tests/http.test.mjs b/tests/http.test.mjs index 8b2f32b..7a3dc3b 100644 --- a/tests/http.test.mjs +++ b/tests/http.test.mjs @@ -2664,7 +2664,7 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up } if (request.url.endsWith("/reviews") || request.url.includes("/reviews?")) { return json(response, 200, { - items: [{ id: "first" }], + items: [{ id: "first" }, { id: "second" }], truncated: true, next_cursor: "page-2", filters: { repositories: [], environments: [], authors: [] }, @@ -2690,31 +2690,40 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up ); assert.equal(fixture.calls.length, 0); - // Aborting during the 5s polling sleep rejects immediately. + // Aborting after the first poll completes (during the 5s sleep) rejects immediately. const sleepAbort = new AbortController(); - const sleepStarted = performance.now(); - setTimeout(() => sleepAbort.abort(), 30); + const sleepBefore = fixture.calls.length; + let sleepStarted = 0; await assert.rejects( - client.waitForReview(orgId, reviewId, { signal: sleepAbort.signal }), + client.waitForReview(orgId, reviewId, { + signal: sleepAbort.signal, + onPoll: () => { + sleepStarted = performance.now(); + setTimeout(() => sleepAbort.abort(), 20); + }, + }), (error) => error instanceof ProoflineError && error.type === "urn:proofline:sdk:aborted", ); + assert.equal(fixture.calls.length - sleepBefore, 1); assert(performance.now() - sleepStarted < 1_000); - // Aborting an in-flight request never collapses into TIMED_OUT. + // Aborting an in-flight request cancels fetch before a much longer timeoutMs. mode = "hang"; const flightAbort = new AbortController(); + const flightStarted = performance.now(); setTimeout(() => flightAbort.abort(), 30); await assert.rejects( client.waitForReview(orgId, reviewId, { - timeoutMs: 40, + timeoutMs: 5_000, signal: flightAbort.signal, }), (error) => error instanceof ProoflineError && error.type === "urn:proofline:sdk:aborted", ); + assert(performance.now() - flightStarted < 1_000); // Aborting during Retry-After backoff rejects promptly after one attempt. mode = "retry"; @@ -2740,15 +2749,18 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up assert(performance.now() - retryStarted < 1_000); assert.equal(fixture.calls.length - retryBefore, 1); - // Aborting between pagination pages stops before fetching the next page. + // Aborting mid-page stops iterReviews before yielding the next item, + // and mutating options.signal after start does not bypass cancellation. mode = "normal"; const reviewsAbort = new AbortController(); const reviewsBefore = fixture.calls.length; + const reviewOptions = { signal: reviewsAbort.signal }; const reviewIter = client.iterReviews( { path: { org_id: orgId } }, - { signal: reviewsAbort.signal }, + reviewOptions, ); assert.equal((await reviewIter.next()).value.id, "first"); + reviewOptions.signal = new AbortController().signal; reviewsAbort.abort(); await assert.rejects( reviewIter.next(), @@ -2760,6 +2772,7 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up const exportAbort = new AbortController(); const exportBefore = fixture.calls.length; + const exportOptions = { signal: exportAbort.signal }; const exportIter = client.iterExportPages( { path: { org_id: orgId, dataset: "reviews" }, @@ -2768,9 +2781,10 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up to: "2026-10-25T00:00:00Z", }, }, - { signal: exportAbort.signal }, + exportOptions, ); assert.equal((await exportIter.next()).value.nextCursor, "page-2"); + exportOptions.signal = new AbortController().signal; exportAbort.abort(); await assert.rejects( exportIter.next(), @@ -2780,7 +2794,8 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up ); assert.equal(fixture.calls.length - exportBefore, 1); - // Pre-aborted signal cancels uploadCoverageFiles before reading disk. + // Pre-aborted and mid-flight signals cancel uploadCoverageFiles, while + // calls without a signal still dispatch through uploadCoverageReports. const uploadBefore = fixture.calls.length; await assert.rejects( client.uploadCoverageFiles( @@ -2793,12 +2808,53 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up error.type === "urn:proofline:sdk:aborted", ); assert.equal(fixture.calls.length - uploadBefore, 0); + + const coverageRoot = await mkdtemp(join(tmpdir(), "proofline-upload-abort-")); + t.after(() => rm(coverageRoot, { recursive: true, force: true })); + await writeFile( + join(coverageRoot, "lcov.info"), + "SF:src/app.ts\nDA:1,1\nend_of_record\n", + ); + mode = "hang"; + const uploadAbort = new AbortController(); + const hangUploadBefore = fixture.calls.length; + const uploadStarted = performance.now(); + setTimeout(() => uploadAbort.abort(), 30); + await assert.rejects( + client.uploadCoverageFiles( + { path: { org_id: orgId, repo_id: repoId } }, + { tested_sha: "c".repeat(40), root: coverageRoot, files: ["lcov.info"] }, + { signal: uploadAbort.signal }, + ), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + assert.equal(fixture.calls.length - hangUploadBefore, 1); + assert(performance.now() - uploadStarted < 1_000); + + const spy = t.mock.method(client, "uploadCoverageReports", async () => ({ + report_id: findingId, + tested_sha: "c".repeat(40), + created: true, + formats: ["LCOV"], + instrumented_lines: 1, + covered_lines: 1, + })); + await client.uploadCoverageFiles( + { path: { org_id: orgId, repo_id: repoId } }, + { tested_sha: "c".repeat(40), root: coverageRoot, files: ["lcov.info"] }, + ); + assert.equal(spy.mock.callCount(), 1); }); -test("waitForReview invokes onPoll for non-terminal polls and supports public options types", async (t) => { +test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback waits and supports public options types", async (t) => { const states = ["PENDING", "RUNNING", "COMPLETED"]; let index = 0; + const observed = []; + const seenBeforePoll = []; const fixture = await server(t, (_, response) => { + seenBeforePoll.push([...observed]); const status = states[Math.min(index, states.length - 1)]; index += 1; json(response, 200, review(status)); @@ -2810,15 +2866,68 @@ test("waitForReview invokes onPoll for non-terminal polls and supports public op : original(callback, delay, ...rest), ); const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token }); - const observed = []; const result = await client.waitForReview(orgId, reviewId, { onPoll: async (current) => { + await new Promise((resolve) => original(resolve, 15)); observed.push(current.status); }, }); assert.equal(result.status, "COMPLETED"); assert.equal(result.review.status, "COMPLETED"); assert.deepEqual(observed, ["PENDING", "RUNNING"]); + // Poll 2 and Poll 3 only ran after the previous async onPoll settled. + assert.deepEqual(seenBeforePoll, [[], ["PENDING"], ["PENDING", "RUNNING"]]); + + // Mutating the review inside onPoll does not mutate the retained timeout review, + // and a hanging onPoll still respects both timeoutMs and signal. + index = 0; + const timedOut = await client.waitForReview(orgId, reviewId, { + timeoutMs: 60, + onPoll: (current) => { + current.status = "MUTATED"; + return new Promise(() => {}); + }, + }); + assert.equal(timedOut.status, "TIMED_OUT"); + assert.equal(timedOut.review.status, "PENDING"); + + index = 0; + const hangingPollAbort = new AbortController(); + const hangAbortStarted = performance.now(); + original(() => hangingPollAbort.abort(), 30); + await assert.rejects( + client.waitForReview(orgId, reviewId, { + timeoutMs: 5_000, + signal: hangingPollAbort.signal, + onPoll: () => new Promise(() => {}), + }), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + assert(performance.now() - hangAbortStarted < 1_000); + + // If the caller aborts just as transport rejects with a timeout, + // waitForReview reports urn:proofline:sdk:aborted rather than timeout. + const raceAbort = new AbortController(); + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => { + raceAbort.abort(); + throw new DOMException("The operation timed out.", "TimeoutError"); + }; + try { + await assert.rejects( + client.waitForReview(orgId, reviewId, { + timeoutMs: 5_000, + signal: raceAbort.signal, + }), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + } finally { + globalThis.fetch = originalFetch; + } // Aborting from onPoll stops waiting immediately without sleeping. index = 0; From 0071cadb21193fe55b001261a5514898300a05db Mon Sep 17 00:00:00 2001 From: Devnil434 Date: Thu, 3 Dec 2026 18:51:57 +0530 Subject: [PATCH 4/7] Fix awaitPollCallback early-exit handling, dependent signal listeners, and test determinism --- src/index.ts | 45 ++++++++--- src/transport.ts | 6 +- tests/http.test.mjs | 188 ++++++++++++++++++++++++++++++++++++-------- 3 files changed, 194 insertions(+), 45 deletions(-) diff --git a/src/index.ts b/src/index.ts index 4af52cb..053c022 100644 --- a/src/index.ts +++ b/src/index.ts @@ -25,6 +25,7 @@ export type { ExportPage, ExportParameters } from "./exports.js"; import { type ListReviewsParameters, Operations, + type UploadCoverageReportsBody, type UploadCoverageReportsParameters, } from "./operations.js"; import type { components } from "./schema.js"; @@ -171,6 +172,7 @@ export class ProoflineClient extends Operations { cursor = page.nextCursor; yield page; } + if (signal?.aborted) throw aborted(); throw paginationLimit("the export continues past maxPages"); } @@ -182,7 +184,13 @@ export class ProoflineClient extends Operations { ): Promise { const signal = options.signal; if (signal?.aborted) throw aborted(); - const body = await readCoverageFiles(upload); + let body: UploadCoverageReportsBody; + try { + body = await readCoverageFiles(upload); + } catch (error) { + if (signal?.aborted) throw aborted(); + throw error; + } if (signal === undefined) return this.uploadCoverageReports(parameters, body); if (signal.aborted) throw aborted(); @@ -267,6 +275,7 @@ export class ProoflineClient extends Operations { seen.add(page.next_cursor); cursor = page.next_cursor; } + if (signal?.aborted) throw aborted(); throw paginationLimit("the review collection exceeds maxPages"); } @@ -385,24 +394,42 @@ async function awaitPollCallback( deadline: number, signal?: AbortSignal, ): Promise { - const pending = Promise.resolve().then(() => - callback(structuredClone(review)), - ); if (signal?.aborted) throw aborted(); const remaining = deadline - performance.now(); if (remaining <= 0) return false; + const localSignal = signal ? AbortSignal.any([signal]) : undefined; + let settled = false; + const pending = Promise.resolve() + .then(() => callback(structuredClone(review))) + .then( + () => { + settled = true; + return true; + }, + (error: unknown) => { + if (!settled) throw error; + return false; + }, + ); let timer: ReturnType | undefined; let onAbort: (() => void) | undefined; const bound = new Promise((resolve, reject) => { - onAbort = () => reject(aborted()); - timer = setTimeout(() => resolve(false), remaining); - signal?.addEventListener("abort", onAbort, { once: true }); + onAbort = () => { + settled = true; + reject(aborted()); + }; + timer = setTimeout(() => { + settled = true; + resolve(false); + }, remaining); + localSignal?.addEventListener("abort", onAbort, { once: true }); }); try { - return await Promise.race([pending.then(() => true), bound]); + return await Promise.race([pending, bound]); } finally { + settled = true; if (timer !== undefined) clearTimeout(timer); - if (onAbort) signal?.removeEventListener("abort", onAbort); + if (onAbort) localSignal?.removeEventListener("abort", onAbort); } } diff --git a/src/transport.ts b/src/transport.ts index 0cfbc23..5774911 100644 --- a/src/transport.ts +++ b/src/transport.ts @@ -443,16 +443,18 @@ export function sleep( ): Promise { if (signal?.aborted) return Promise.reject(aborted()); if (milliseconds <= 0) return Promise.resolve(); + // Use a dependent signal so earlier listeners calling stopImmediatePropagation() cannot suppress sleep cancellation. + const localSignal = signal ? AbortSignal.any([signal]) : undefined; return new Promise((resolve, reject) => { const onAbort = () => { clearTimeout(timer); reject(aborted()); }; const timer = setTimeout(() => { - signal?.removeEventListener("abort", onAbort); + localSignal?.removeEventListener("abort", onAbort); resolve(); }, milliseconds); - signal?.addEventListener("abort", onAbort, { once: true }); + localSignal?.addEventListener("abort", onAbort, { once: true }); }); } diff --git a/tests/http.test.mjs b/tests/http.test.mjs index 7a3dc3b..ff7df41 100644 --- a/tests/http.test.mjs +++ b/tests/http.test.mjs @@ -2637,20 +2637,38 @@ test("immediate network failures report transport error without claiming timeout test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and uploads", async (t) => { let mode = "running"; - let pendingResponse; + let onServerResponse; + let hangOnCursor; + const pendingResponses = []; const fixture = await server(t, (request, response) => { if (mode === "retry") { response.writeHead(503, { "Content-Type": "application/json", "Retry-After": "60", }); - return response.end(JSON.stringify({ detail: "busy" })); + return response.end(JSON.stringify({ detail: "busy" }), () => + onServerResponse?.(), + ); } - if (mode === "hang") { - pendingResponse = response; + if ( + mode === "hang" || + (hangOnCursor && request.url.includes(`cursor=${hangOnCursor}`)) + ) { + pendingResponses.push(response); response.writeHead(200, { "Content-Type": "application/json" }); + onServerResponse?.(); return; } + if (request.url.includes("/coverage-reports")) { + return json(response, 201, { + report_id: findingId, + tested_sha: "c".repeat(40), + created: true, + formats: ["LCOV"], + instrumented_lines: 1, + covered_lines: 1, + }); + } if (request.url.includes("/exports/")) { const url = new URL(request.url, "http://127.0.0.1"); const cursor = url.searchParams.get("cursor"); @@ -2672,7 +2690,9 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up } return json(response, 200, review("RUNNING")); }); - t.after(() => pendingResponse?.destroy()); + t.after(() => { + for (const response of pendingResponses) response.destroy(); + }); const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token }); // Pre-aborted signal rejects even when timeoutMs is 0. @@ -2690,8 +2710,12 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up ); assert.equal(fixture.calls.length, 0); - // Aborting after the first poll completes (during the 5s sleep) rejects immediately. + // Aborting after the first poll completes (during the 5s sleep) rejects immediately, + // even when an earlier listener calls stopImmediatePropagation(). const sleepAbort = new AbortController(); + sleepAbort.signal.addEventListener("abort", (event) => + event.stopImmediatePropagation(), + ); const sleepBefore = fixture.calls.length; let sleepStarted = 0; await assert.rejects( @@ -2725,12 +2749,15 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up ); assert(performance.now() - flightStarted < 1_000); - // Aborting during Retry-After backoff rejects promptly after one attempt. + // Aborting during Retry-After backoff (after the 503 response arrives) rejects promptly. mode = "retry"; const retryBefore = fixture.calls.length; const retryAbort = new AbortController(); - const retryStarted = performance.now(); - setTimeout(() => retryAbort.abort(), 30); + let retryStarted = performance.now(); + onServerResponse = () => { + retryStarted = performance.now(); + setTimeout(() => retryAbort.abort(), 20); + }; await assert.rejects( client.exportReviews( { @@ -2746,6 +2773,7 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up error instanceof ProoflineError && error.type === "urn:proofline:sdk:aborted", ); + onServerResponse = undefined; assert(performance.now() - retryStarted < 1_000); assert.equal(fixture.calls.length - retryBefore, 1); @@ -2770,10 +2798,31 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up ); assert.equal(fixture.calls.length - reviewsBefore, 1); - const exportAbort = new AbortController(); - const exportBefore = fixture.calls.length; - const exportOptions = { signal: exportAbort.signal }; - const exportIter = client.iterExportPages( + // Both iterReviews and iterExportPages forward signal to subsequent page requests + // and check abort when resumed past maxPages / maxItems. + hangOnCursor = "page-2"; + const page2ReviewAbort = new AbortController(); + const page2ReviewBefore = fixture.calls.length; + onServerResponse = () => setTimeout(() => page2ReviewAbort.abort(), 20); + const page2ReviewIter = client.iterReviews( + { path: { org_id: orgId } }, + { signal: page2ReviewAbort.signal }, + ); + assert.equal((await page2ReviewIter.next()).value.id, "first"); + assert.equal((await page2ReviewIter.next()).value.id, "second"); + await assert.rejects( + page2ReviewIter.next(), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + onServerResponse = undefined; + assert.equal(fixture.calls.length - page2ReviewBefore, 2); + + const page2ExportAbort = new AbortController(); + const page2ExportBefore = fixture.calls.length; + onServerResponse = () => setTimeout(() => page2ExportAbort.abort(), 20); + const page2ExportIter = client.iterExportPages( { path: { org_id: orgId, dataset: "reviews" }, query: { @@ -2781,21 +2830,57 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up to: "2026-10-25T00:00:00Z", }, }, - exportOptions, + { signal: page2ExportAbort.signal }, ); - assert.equal((await exportIter.next()).value.nextCursor, "page-2"); - exportOptions.signal = new AbortController().signal; - exportAbort.abort(); + assert.equal((await page2ExportIter.next()).value.nextCursor, "page-2"); await assert.rejects( - exportIter.next(), + page2ExportIter.next(), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + onServerResponse = undefined; + hangOnCursor = undefined; + assert.equal(fixture.calls.length - page2ExportBefore, 2); + + const maxExportAbort = new AbortController(); + const maxExportIter = client.iterExportPages( + { + path: { org_id: orgId, dataset: "reviews" }, + query: { + from: "2026-10-01T00:00:00Z", + to: "2026-10-25T00:00:00Z", + }, + }, + { maxPages: 1, signal: maxExportAbort.signal }, + ); + assert.equal((await maxExportIter.next()).value.nextCursor, "page-2"); + maxExportAbort.abort(); + await assert.rejects( + maxExportIter.next(), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + + const maxReviewAbort = new AbortController(); + const maxReviewIter = client.iterReviews( + { path: { org_id: orgId } }, + { maxPages: 1, signal: maxReviewAbort.signal }, + ); + assert.equal((await maxReviewIter.next()).value.id, "first"); + assert.equal((await maxReviewIter.next()).value.id, "second"); + maxReviewAbort.abort(); + await assert.rejects( + maxReviewIter.next(), (error) => error instanceof ProoflineError && error.type === "urn:proofline:sdk:aborted", ); - assert.equal(fixture.calls.length - exportBefore, 1); // Pre-aborted and mid-flight signals cancel uploadCoverageFiles, while - // calls without a signal still dispatch through uploadCoverageReports. + // un-aborted signal uploads preserve route and body and omitted signal + // dispatches through uploadCoverageReports. const uploadBefore = fixture.calls.length; await assert.rejects( client.uploadCoverageFiles( @@ -2811,10 +2896,26 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up const coverageRoot = await mkdtemp(join(tmpdir(), "proofline-upload-abort-")); t.after(() => rm(coverageRoot, { recursive: true, force: true })); - await writeFile( - join(coverageRoot, "lcov.info"), - "SF:src/app.ts\nDA:1,1\nend_of_record\n", + const reportContent = "SF:src/app.ts\nDA:1,1\nend_of_record\n"; + await writeFile(join(coverageRoot, "lcov.info"), reportContent); + + const activeUploadAbort = new AbortController(); + const uploaded = await client.uploadCoverageFiles( + { path: { org_id: orgId, repo_id: repoId } }, + { tested_sha: "c".repeat(40), root: coverageRoot, files: ["lcov.info"] }, + { signal: activeUploadAbort.signal }, + ); + assert.equal(uploaded.created, true); + assert.equal(fixture.calls.at(-1).method, "POST"); + assert.equal( + fixture.calls.at(-1).url, + `/api/v1/organizations/${orgId}/repositories/${repoId}/coverage-reports`, ); + assert.deepEqual(JSON.parse(fixture.calls.at(-1).body), { + tested_sha: "c".repeat(40), + reports: [{ name: "lcov.info", content: reportContent }], + }); + mode = "hang"; const uploadAbort = new AbortController(); const hangUploadBefore = fixture.calls.length; @@ -2851,6 +2952,7 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback waits and supports public options types", async (t) => { const states = ["PENDING", "RUNNING", "COMPLETED"]; let index = 0; + const called = []; const observed = []; const seenBeforePoll = []; const fixture = await server(t, (_, response) => { @@ -2868,18 +2970,21 @@ test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token }); const result = await client.waitForReview(orgId, reviewId, { onPoll: async (current) => { + called.push(current.status); await new Promise((resolve) => original(resolve, 15)); observed.push(current.status); }, }); assert.equal(result.status, "COMPLETED"); assert.equal(result.review.status, "COMPLETED"); + assert.deepEqual(called, ["PENDING", "RUNNING"]); assert.deepEqual(observed, ["PENDING", "RUNNING"]); // Poll 2 and Poll 3 only ran after the previous async onPoll settled. assert.deepEqual(seenBeforePoll, [[], ["PENDING"], ["PENDING", "RUNNING"]]); // Mutating the review inside onPoll does not mutate the retained timeout review, - // and a hanging onPoll still respects both timeoutMs and signal. + // and a hanging onPoll still respects both timeoutMs and signal (even with + // stopImmediatePropagation() on the caller's signal). index = 0; const timedOut = await client.waitForReview(orgId, reviewId, { timeoutMs: 60, @@ -2893,13 +2998,19 @@ test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback index = 0; const hangingPollAbort = new AbortController(); - const hangAbortStarted = performance.now(); - original(() => hangingPollAbort.abort(), 30); + hangingPollAbort.signal.addEventListener("abort", (event) => + event.stopImmediatePropagation(), + ); + let hangAbortStarted = 0; await assert.rejects( client.waitForReview(orgId, reviewId, { timeoutMs: 5_000, signal: hangingPollAbort.signal, - onPoll: () => new Promise(() => {}), + onPoll: () => { + hangAbortStarted = performance.now(); + original(() => hangingPollAbort.abort(), 20); + return new Promise(() => {}); + }, }), (error) => error instanceof ProoflineError && @@ -2907,18 +3018,27 @@ test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback ); assert(performance.now() - hangAbortStarted < 1_000); - // If the caller aborts just as transport rejects with a timeout, - // waitForReview reports urn:proofline:sdk:aborted rather than timeout. + // If the caller aborts after transport rejects with urn:proofline:sdk:timeout + // but before waitForReview handles it, waitForReview still throws aborted. const raceAbort = new AbortController(); const originalFetch = globalThis.fetch; - globalThis.fetch = async () => { - raceAbort.abort(); - throw new DOMException("The operation timed out.", "TimeoutError"); - }; + globalThis.fetch = (_url, init) => + new Promise((_resolve, reject) => { + init.signal.addEventListener( + "abort", + () => { + Promise.resolve().then(() => + Promise.resolve().then(() => raceAbort.abort()), + ); + reject(new DOMException("The operation timed out.", "TimeoutError")); + }, + { once: true }, + ); + }); try { await assert.rejects( client.waitForReview(orgId, reviewId, { - timeoutMs: 5_000, + timeoutMs: 25, signal: raceAbort.signal, }), (error) => From 011f4c6e3d2ca21723173b0a9ca872e3e2eabb37 Mon Sep 17 00:00:00 2001 From: Devnil434 Date: Thu, 3 Dec 2026 19:04:36 +0530 Subject: [PATCH 5/7] Fix 32-bit timer overflow, post-await abort checks, and Run 6 test hardening --- src/index.ts | 35 +++++++---- src/transport.ts | 29 +++++++-- tests/http.test.mjs | 143 +++++++++++++++++++++++++++++++++----------- 3 files changed, 158 insertions(+), 49 deletions(-) diff --git a/src/index.ts b/src/index.ts index 053c022..1b5f0eb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -84,7 +84,7 @@ export interface ReviewOutcome { export interface WaitOptions { timeoutMs?: number; signal?: AbortSignal; - /** Invoked after each validated non-terminal poll while waiting. */ + /** Invoked after each validated non-terminal poll while waiting, unless the deadline has already elapsed or the signal is aborted. */ onPoll?: (review: Review) => void | Promise; } @@ -347,6 +347,7 @@ export class ProoflineClient extends Operations { ); throw error; } + if (signal?.aborted) throw aborted(); validateReview(review, reviewId); const status = terminal(review); if (status !== null) @@ -388,6 +389,8 @@ export class ProoflineClient extends Operations { import { ProoflineError } from "./transport.js"; +const MAX_TIMER_MS = 2_147_483_647; + async function awaitPollCallback( callback: (review: Review) => void | Promise, review: Review, @@ -395,16 +398,22 @@ async function awaitPollCallback( signal?: AbortSignal, ): Promise { if (signal?.aborted) throw aborted(); - const remaining = deadline - performance.now(); - if (remaining <= 0) return false; + const initialRemaining = deadline - performance.now(); + if (initialRemaining <= 0) return false; const localSignal = signal ? AbortSignal.any([signal]) : undefined; let settled = false; const pending = Promise.resolve() - .then(() => callback(structuredClone(review))) + .then(() => { + if (settled || signal?.aborted || performance.now() >= deadline) + return false; + return Promise.resolve(callback(structuredClone(review))).then( + () => true, + ); + }) .then( - () => { + (completed) => { settled = true; - return true; + return completed; }, (error: unknown) => { if (!settled) throw error; @@ -418,11 +427,17 @@ async function awaitPollCallback( settled = true; reject(aborted()); }; - timer = setTimeout(() => { - settled = true; - resolve(false); - }, remaining); + const schedule = () => { + const remaining = deadline - performance.now(); + if (remaining <= 0) { + settled = true; + resolve(false); + return; + } + timer = setTimeout(schedule, Math.min(remaining, MAX_TIMER_MS)); + }; localSignal?.addEventListener("abort", onAbort, { once: true }); + schedule(); }); try { return await Promise.race([pending, bound]); diff --git a/src/transport.ts b/src/transport.ts index 5774911..a184925 100644 --- a/src/transport.ts +++ b/src/transport.ts @@ -437,6 +437,8 @@ function httpDate(value: string): number { : Number.NaN; } +const MAX_TIMER_MS = 2_147_483_647; + export function sleep( milliseconds: number, signal?: AbortSignal, @@ -445,16 +447,33 @@ export function sleep( if (milliseconds <= 0) return Promise.resolve(); // Use a dependent signal so earlier listeners calling stopImmediatePropagation() cannot suppress sleep cancellation. const localSignal = signal ? AbortSignal.any([signal]) : undefined; + const target = performance.now() + milliseconds; return new Promise((resolve, reject) => { + let timer: ReturnType | undefined; const onAbort = () => { - clearTimeout(timer); + if (timer !== undefined) clearTimeout(timer); reject(aborted()); }; - const timer = setTimeout(() => { - localSignal?.removeEventListener("abort", onAbort); - resolve(); - }, milliseconds); + const schedule = (delay: number) => { + if (delay <= MAX_TIMER_MS) { + timer = setTimeout(() => { + localSignal?.removeEventListener("abort", onAbort); + resolve(); + }, delay); + return; + } + timer = setTimeout(() => { + const remaining = target - performance.now(); + if (remaining <= 0) { + localSignal?.removeEventListener("abort", onAbort); + resolve(); + } else { + schedule(remaining); + } + }, MAX_TIMER_MS); + }; localSignal?.addEventListener("abort", onAbort, { once: true }); + schedule(milliseconds); }); } diff --git a/tests/http.test.mjs b/tests/http.test.mjs index ff7df41..3b6b95b 100644 --- a/tests/http.test.mjs +++ b/tests/http.test.mjs @@ -2749,34 +2749,74 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up ); assert(performance.now() - flightStarted < 1_000); - // Aborting during Retry-After backoff (after the 503 response arrives) rejects promptly. + // Aborting during Retry-After backoff (only once sleep(60_000) is entered) rejects promptly. mode = "retry"; const retryBefore = fixture.calls.length; const retryAbort = new AbortController(); let retryStarted = performance.now(); - onServerResponse = () => { - retryStarted = performance.now(); - setTimeout(() => retryAbort.abort(), 20); - }; - await assert.rejects( - client.exportReviews( - { - path: { org_id: orgId, dataset: "reviews" }, - query: { - from: "2026-10-01T00:00:00Z", - to: "2026-10-25T00:00:00Z", - }, - }, - { signal: retryAbort.signal }, - ), - (error) => - error instanceof ProoflineError && - error.type === "urn:proofline:sdk:aborted", + const origSetTimeout = globalThis.setTimeout; + const sleepSpy = t.mock.method( + globalThis, + "setTimeout", + (callback, delay, ...rest) => { + if (delay === 60_000) { + retryStarted = performance.now(); + origSetTimeout(() => retryAbort.abort(), 15); + } + return origSetTimeout(callback, delay, ...rest); + }, ); - onServerResponse = undefined; + try { + await assert.rejects( + client.exportReviews( + { + path: { org_id: orgId, dataset: "reviews" }, + query: { + from: "2026-10-01T00:00:00Z", + to: "2026-10-25T00:00:00Z", + }, + }, + { signal: retryAbort.signal }, + ), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + } finally { + sleepSpy.mock.restore(); + } assert(performance.now() - retryStarted < 1_000); assert.equal(fixture.calls.length - retryBefore, 1); + // Page-1 requests also forward signal into fetch(). + mode = "hang"; + for (const startFirstPage of [ + (signal) => client.iterReviews({ path: { org_id: orgId } }, { signal }), + (signal) => + client.iterExportPages( + { + path: { org_id: orgId, dataset: "reviews" }, + query: { + from: "2026-10-01T00:00:00Z", + to: "2026-10-25T00:00:00Z", + }, + }, + { signal }, + ), + ]) { + const page1Abort = new AbortController(); + const page1Before = fixture.calls.length; + onServerResponse = () => setTimeout(() => page1Abort.abort(), 20); + await assert.rejects( + startFirstPage(page1Abort.signal).next(), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + onServerResponse = undefined; + assert.equal(fixture.calls.length - page1Before, 1); + } + // Aborting mid-page stops iterReviews before yielding the next item, // and mutating options.signal after start does not bypass cancellation. mode = "normal"; @@ -2798,6 +2838,19 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up ); assert.equal(fixture.calls.length - reviewsBefore, 1); + // Pre-aborted signal takes precedence even with maxItems: 1. + await assert.rejects( + client + .iterReviews( + { path: { org_id: orgId } }, + { maxItems: 1, signal: preAborted.signal }, + ) + .next(), + (error) => + error instanceof ProoflineError && + error.type === "urn:proofline:sdk:aborted", + ); + // Both iterReviews and iterExportPages forward signal to subsequent page requests // and check abort when resumed past maxPages / maxItems. hangOnCursor = "page-2"; @@ -2919,8 +2972,11 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up mode = "hang"; const uploadAbort = new AbortController(); const hangUploadBefore = fixture.calls.length; - const uploadStarted = performance.now(); - setTimeout(() => uploadAbort.abort(), 30); + let uploadStarted = performance.now(); + onServerResponse = () => { + uploadStarted = performance.now(); + setTimeout(() => uploadAbort.abort(), 20); + }; await assert.rejects( client.uploadCoverageFiles( { path: { org_id: orgId, repo_id: repoId } }, @@ -2931,6 +2987,7 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up error instanceof ProoflineError && error.type === "urn:proofline:sdk:aborted", ); + onServerResponse = undefined; assert.equal(fixture.calls.length - hangUploadBefore, 1); assert(performance.now() - uploadStarted < 1_000); @@ -2954,19 +3011,20 @@ test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback let index = 0; const called = []; const observed = []; - const seenBeforePoll = []; + const seenBeforeSleep = []; const fixture = await server(t, (_, response) => { - seenBeforePoll.push([...observed]); const status = states[Math.min(index, states.length - 1)]; index += 1; json(response, 200, review(status)); }); const original = globalThis.setTimeout; - t.mock.method(globalThis, "setTimeout", (callback, delay, ...rest) => - delay === 5_000 || delay === 10_000 - ? original(callback, 0, ...rest) - : original(callback, delay, ...rest), - ); + t.mock.method(globalThis, "setTimeout", (callback, delay, ...rest) => { + if (delay === 5_000 || delay === 10_000) { + seenBeforeSleep.push([...observed]); + return original(callback, 0, ...rest); + } + return original(callback, delay, ...rest); + }); const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token }); const result = await client.waitForReview(orgId, reviewId, { onPoll: async (current) => { @@ -2979,22 +3037,34 @@ test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback assert.equal(result.review.status, "COMPLETED"); assert.deepEqual(called, ["PENDING", "RUNNING"]); assert.deepEqual(observed, ["PENDING", "RUNNING"]); - // Poll 2 and Poll 3 only ran after the previous async onPoll settled. - assert.deepEqual(seenBeforePoll, [[], ["PENDING"], ["PENDING", "RUNNING"]]); + // sleep(5_000) and sleep(10_000) were only scheduled after the preceding async onPoll settled. + assert.deepEqual(seenBeforeSleep, [["PENDING"], ["PENDING", "RUNNING"]]); + + // timeoutMs larger than 2^31 - 1 does not overflow Node's 32-bit timer limit to 1 ms. + index = 0; + const longTimeoutResult = await client.waitForReview(orgId, reviewId, { + timeoutMs: 3_000_000_000, + onPoll: async () => { + await new Promise((resolve) => original(resolve, 15)); + }, + }); + assert.equal(longTimeoutResult.status, "COMPLETED"); - // Mutating the review inside onPoll does not mutate the retained timeout review, - // and a hanging onPoll still respects both timeoutMs and signal (even with - // stopImmediatePropagation() on the caller's signal). + // Mutating nested fields on the review inside onPoll does not mutate the retained + // timeout review, and a hanging onPoll still respects both timeoutMs and signal + // (even with stopImmediatePropagation() on the caller's signal). index = 0; const timedOut = await client.waitForReview(orgId, reviewId, { timeoutMs: 60, onPoll: (current) => { current.status = "MUTATED"; + current.assessments[0].status = "MUTATED"; return new Promise(() => {}); }, }); assert.equal(timedOut.status, "TIMED_OUT"); assert.equal(timedOut.review.status, "PENDING"); + assert.equal(timedOut.review.assessments[0].status, "COMPLETED"); index = 0; const hangingPollAbort = new AbortController(); @@ -3099,6 +3169,11 @@ export async function wait(client: ProoflineClient, signal: AbortSignal): Promis }, }; await client.waitForReview("org", "rev", opts); + await client.waitForReview("org", "rev", { + onPoll: async (r: Review) => { + await Promise.resolve(r.status); + }, + }); await client.exportReviews( { path: { org_id: "org", dataset: "reviews" }, query: { from: "2026-10-01T00:00:00Z", to: "2026-10-02T00:00:00Z" } }, req, From 08d8fda08505ec13ef1bf0cb15c253cf936fd715 Mon Sep 17 00:00:00 2001 From: Nilanjan Saha Date: Thu, 3 Dec 2026 13:57:25 +0000 Subject: [PATCH 6/7] Address Proofline feedback on polling and cancellation --- src/index.ts | 21 ++++- src/transport.ts | 18 +++-- tests/http.test.mjs | 182 ++++++++++++++++++++++++++++++++++++-------- 3 files changed, 180 insertions(+), 41 deletions(-) diff --git a/src/index.ts b/src/index.ts index 1b5f0eb..1d510fd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -158,6 +158,7 @@ export class ProoflineClient extends Operations { }, requestOptions, ); + if (signal?.aborted) throw aborted(); if (page.nextCursor === null) { yield page; return; @@ -243,6 +244,7 @@ export class ProoflineClient extends Operations { undefined, signal, ); + if (signal?.aborted) throw aborted(); if ( !isObject(page) || !Array.isArray(page.items) || @@ -406,6 +408,16 @@ async function awaitPollCallback( .then(() => { if (settled || signal?.aborted || performance.now() >= deadline) return false; + const actions = review.actions; + if ( + !isObject(actions) || + typeof actions.promote_findings !== "boolean" || + typeof actions.publish !== "boolean" || + typeof actions.rerun !== "boolean" || + typeof actions.stop !== "boolean" || + typeof actions.validate_findings !== "boolean" + ) + throw protocol("the review response has no valid action permissions"); return Promise.resolve(callback(structuredClone(review))).then( () => true, ); @@ -413,11 +425,14 @@ async function awaitPollCallback( .then( (completed) => { settled = true; - return completed; + if (signal?.aborted) throw aborted(); + return completed && performance.now() < deadline; }, (error: unknown) => { - if (!settled) throw error; - return false; + if (signal?.aborted) throw aborted(); + if (settled || performance.now() >= deadline) return false; + settled = true; + throw error; }, ); let timer: ReturnType | undefined; diff --git a/src/transport.ts b/src/transport.ts index a184925..7b93cd5 100644 --- a/src/transport.ts +++ b/src/transport.ts @@ -189,13 +189,21 @@ export function aborted(): ProoflineError { ); } +function callerAborted( + signal: AbortSignal, + timeoutSignal: AbortSignal, +): boolean { + // AbortSignal.any retains the first abort reason, even if both inputs abort. + return signal.aborted && signal.reason !== timeoutSignal.reason; +} + async function decoded( response: Response, deadline: number, timeoutSignal: AbortSignal, waitTimeout: boolean, decode: (text: string, headers: Headers) => unknown, - callerSignal?: AbortSignal, + signal: AbortSignal, ): Promise { const reader = response.body?.getReader(); if (!reader) { @@ -232,7 +240,7 @@ async function decoded( } } catch (error) { if (error instanceof ProoflineError) throw error; - if (callerSignal?.aborted) throw aborted(); + if (callerAborted(signal, timeoutSignal)) throw aborted(); if (response.ok && (timeoutSignal.aborted || performance.now() >= deadline)) throw new ProoflineError( 0, @@ -444,7 +452,7 @@ export function sleep( signal?: AbortSignal, ): Promise { if (signal?.aborted) return Promise.reject(aborted()); - if (milliseconds <= 0) return Promise.resolve(); + if (milliseconds <= 0 && !signal) return Promise.resolve(); // Use a dependent signal so earlier listeners calling stopImmediatePropagation() cannot suppress sleep cancellation. const localSignal = signal ? AbortSignal.any([signal]) : undefined; const target = performance.now() + milliseconds; @@ -569,7 +577,7 @@ export class Transport { signal, }); } catch { - if (callerSignal?.aborted) throw aborted(); + if (callerAborted(signal, timeoutSignal)) throw aborted(); if (timeoutSignal.aborted && waitTimeout) throw new ProoflineError( 0, @@ -612,7 +620,7 @@ export class Transport { timeoutSignal, waitTimeout, decode, - callerSignal, + signal, ); if (response.ok) return value as T; const error = problem(response.status, value, this.#token); diff --git a/tests/http.test.mjs b/tests/http.test.mjs index 3b6b95b..7d1927f 100644 --- a/tests/http.test.mjs +++ b/tests/http.test.mjs @@ -2580,35 +2580,32 @@ export async function use(client: ProoflineClient): Promise { }); test("completed corrupt 200 responses at the wait deadline remain invalid-response rather than TIMED_OUT", async (t) => { - let payload = '{"id":'; - const fixture = await server(t, (_, response) => { - response.writeHead(200, { "Content-Type": "application/json" }); - response.end(payload); + const client = new ProoflineClient({ + baseUrl: "https://example.test", + token, }); - const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token }); const start = performance.now(); - let calls = 0; - // Advance past the 80ms wait deadline while the response body is decoded. - const clock = t.mock.method(performance, "now", () => { - calls += 1; - return calls <= 4 ? start : start + 500; + let now = start; + let payload; + t.mock.method(performance, "now", () => now); + t.mock.method(globalThis, "fetch", async () => { + now = start + 500; + return new Response(payload, { + headers: { "Content-Type": "application/json" }, + }); }); - try { - for (const next of ['{"id":', invalidUtf8Body]) { - payload = next; - calls = 0; - await assert.rejects( - client.waitForReview(orgId, reviewId, { timeoutMs: 80 }), - (error) => - error instanceof ProoflineError && - error.status === 200 && - error.type === "urn:proofline:sdk:invalid-response" && - !error.detail.includes(token) && - !error.detail.includes(responseCanary), - ); - } - } finally { - clock.mock.restore(); + for (const next of ['{"id":', invalidUtf8Body]) { + payload = next; + now = start; + await assert.rejects( + client.waitForReview(orgId, reviewId, { timeoutMs: 80 }), + (error) => + error instanceof ProoflineError && + error.status === 200 && + error.type === "urn:proofline:sdk:invalid-response" && + !error.detail.includes(token) && + !error.detail.includes(responseCanary), + ); } }); @@ -2635,6 +2632,83 @@ test("immediate network failures report transport error without claiming timeout ); }); +test("transport preserves the first abort cause before headers and during body reads", async (t) => { + const client = new ProoflineClient({ + baseUrl: "https://example.test", + requestTimeoutMs: 25, + token, + }); + const parameters = { + path: { org_id: orgId, dataset: "reviews" }, + query: { from: "2026-10-01T00:00:00Z", to: "2026-10-25T00:00:00Z" }, + }; + for (const phase of ["headers", "body"]) { + for (const timeoutFirst of [true, false]) { + const caller = new AbortController(); + const keepAlive = setTimeout(() => {}, 1_000); + const fetch = t.mock.method( + globalThis, + "fetch", + async (_, { signal }) => { + const fail = (reject) => { + signal.addEventListener( + "abort", + () => { + if (timeoutFirst) caller.abort(); + reject(signal.reason); + }, + { once: true }, + ); + if (!timeoutFirst) queueMicrotask(() => caller.abort()); + }; + if (phase === "headers") + return new Promise((_, reject) => fail(reject)); + return new Response( + new ReadableStream({ + start(controller) { + fail((error) => controller.error(error)); + }, + }), + ); + }, + ); + try { + await assert.rejects( + client.exportReviews(parameters, { signal: caller.signal }), + { + type: timeoutFirst + ? "urn:proofline:sdk:transport" + : "urn:proofline:sdk:aborted", + }, + ); + } finally { + clearTimeout(keepAlive); + fetch.mock.restore(); + } + } + } +}); + +test("review export cancellation wins before yielding a page from an override", async (t) => { + const client = new ProoflineClient({ + baseUrl: "https://example.test", + token, + }); + const caller = new AbortController(); + t.mock.method(client, "exportReviews", async () => { + caller.abort(); + return { nextCursor: null }; + }); + const pages = client.iterExportPages( + { + path: { org_id: orgId, dataset: "reviews" }, + query: { from: "2026-10-01T00:00:00Z", to: "2026-10-25T00:00:00Z" }, + }, + { signal: caller.signal }, + ); + await assert.rejects(pages.next(), { type: "urn:proofline:sdk:aborted" }); +}); + test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and uploads", async (t) => { let mode = "running"; let onServerResponse; @@ -2822,7 +2896,7 @@ test("AbortSignal cancels waitForReview, Retry-After backoffs, pagination and up mode = "normal"; const reviewsAbort = new AbortController(); const reviewsBefore = fixture.calls.length; - const reviewOptions = { signal: reviewsAbort.signal }; + const reviewOptions = { maxItems: 1, signal: reviewsAbort.signal }; const reviewIter = client.iterReviews( { path: { org_id: orgId } }, reviewOptions, @@ -3012,10 +3086,14 @@ test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback const called = []; const observed = []; const seenBeforeSleep = []; + const callbackTimers = []; + let omitActions = false; const fixture = await server(t, (_, response) => { const status = states[Math.min(index, states.length - 1)]; index += 1; - json(response, 200, review(status)); + const current = review(status); + if (omitActions) delete current.actions; + json(response, 200, current); }); const original = globalThis.setTimeout; t.mock.method(globalThis, "setTimeout", (callback, delay, ...rest) => { @@ -3023,6 +3101,7 @@ test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback seenBeforeSleep.push([...observed]); return original(callback, 0, ...rest); } + callbackTimers.push(delay); return original(callback, delay, ...rest); }); const client = new ProoflineClient({ baseUrl: fixture.baseUrl, token }); @@ -3049,19 +3128,24 @@ test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback }, }); assert.equal(longTimeoutResult.status, "COMPLETED"); + assert(callbackTimers.includes(2_147_483_647)); + assert(callbackTimers.every((delay) => delay <= 2_147_483_647)); // Mutating nested fields on the review inside onPoll does not mutate the retained // timeout review, and a hanging onPoll still respects both timeoutMs and signal // (even with stopImmediatePropagation() on the caller's signal). index = 0; + let mutated = false; const timedOut = await client.waitForReview(orgId, reviewId, { - timeoutMs: 60, + timeoutMs: 250, onPoll: (current) => { + mutated = true; current.status = "MUTATED"; current.assessments[0].status = "MUTATED"; return new Promise(() => {}); }, }); + assert.equal(mutated, true); assert.equal(timedOut.status, "TIMED_OUT"); assert.equal(timedOut.review.status, "PENDING"); assert.equal(timedOut.review.assessments[0].status, "COMPLETED"); @@ -3145,10 +3229,43 @@ test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback ); assert.equal(index, 1); + index = 0; await assert.rejects( client.waitForReview(orgId, reviewId, { onPoll: "not-a-function" }), - TypeError, + { name: "TypeError", message: "onPoll must be a function" }, ); + assert.equal(index, 0); + + omitActions = true; + await assert.rejects( + client.waitForReview(orgId, reviewId, { + onPoll: () => assert.fail("invalid review reached onPoll"), + }), + { type: "urn:proofline:sdk:invalid-response" }, + ); + omitActions = false; + + index = 0; + const readClock = performance.now.bind(performance); + let advanced = false; + const clock = t.mock.method( + performance, + "now", + () => readClock() + (advanced ? 10_000 : 0), + ); + try { + const result = await client.waitForReview(orgId, reviewId, { + timeoutMs: 5_000, + onPoll: () => { + advanced = true; + throw new Error("callback rejected after deadline"); + }, + }); + assert.equal(advanced, true); + assert.equal(result.status, "TIMED_OUT"); + } finally { + clock.mock.restore(); + } // Verify consumer compilation with strict + exactOptionalPropertyTypes. const work = await mkdtemp(join(tmpdir(), "sdk-wait-types-")); @@ -3161,12 +3278,11 @@ test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback import type { ProoflineClient, RequestOptions, WaitOptions, Review } from ${JSON.stringify(entry)}; export async function wait(client: ProoflineClient, signal: AbortSignal): Promise { const req: RequestOptions = { signal }; + const syncPoll = (r: Review): void => { console.log(r.status); }; const opts: WaitOptions = { timeoutMs: 1000, signal, - onPoll: (r: Review) => { - console.log(r.status); - }, + onPoll: syncPoll, }; await client.waitForReview("org", "rev", opts); await client.waitForReview("org", "rev", { From 8a6a6305041dccd8476710d523451d651a0c8312 Mon Sep 17 00:00:00 2001 From: Nilanjan Saha Date: Thu, 3 Dec 2026 14:15:00 +0000 Subject: [PATCH 7/7] Validate review details before invoking onPoll --- src/index.ts | 50 +++++++++++++++++++++++++++++++++------------ tests/http.test.mjs | 48 +++++++++++++++++++++++++++++++++++-------- 2 files changed, 76 insertions(+), 22 deletions(-) diff --git a/src/index.ts b/src/index.ts index 1d510fd..2d0f75b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -366,12 +366,14 @@ export class ProoflineClient extends Operations { : null, ); if (onPoll) { + validatePollReview(review); const settled = await awaitPollCallback( onPoll, review, deadline, signal, ); + if (signal?.aborted) throw aborted(); if (!settled) return outcome( "TIMED_OUT", @@ -393,6 +395,37 @@ import { ProoflineError } from "./transport.js"; const MAX_TIMER_MS = 2_147_483_647; +// The polling loop validates review identity, state, and assessments separately. +function validatePollReview(review: Review): void { + const actions = review.actions; + if ( + !isObject(actions) || + typeof actions.promote_findings !== "boolean" || + typeof actions.publish !== "boolean" || + typeof actions.rerun !== "boolean" || + typeof actions.stop !== "boolean" || + typeof actions.validate_findings !== "boolean" + ) + throw protocol("the review response has no valid action permissions"); + if ( + typeof review.created_at !== "string" || + !Array.isArray(review.environment_display_names) || + !review.environment_display_names.every( + (name) => typeof name === "string", + ) || + !Number.isSafeInteger(review.finding_count) || + review.finding_count < 0 || + typeof review.kind !== "string" || + typeof review.public_key !== "string" || + typeof review.publication !== "string" || + !Array.isArray(review.related_reviews) || + typeof review.stoppable !== "boolean" || + !Array.isArray(review.subjects) || + typeof review.trigger_origin !== "string" + ) + throw protocol("the review response has no valid detail envelope"); +} + async function awaitPollCallback( callback: (review: Review) => void | Promise, review: Review, @@ -408,19 +441,10 @@ async function awaitPollCallback( .then(() => { if (settled || signal?.aborted || performance.now() >= deadline) return false; - const actions = review.actions; - if ( - !isObject(actions) || - typeof actions.promote_findings !== "boolean" || - typeof actions.publish !== "boolean" || - typeof actions.rerun !== "boolean" || - typeof actions.stop !== "boolean" || - typeof actions.validate_findings !== "boolean" - ) - throw protocol("the review response has no valid action permissions"); - return Promise.resolve(callback(structuredClone(review))).then( - () => true, - ); + const snapshot = structuredClone(review); + if (signal?.aborted) throw aborted(); + if (performance.now() >= deadline) return false; + return Promise.resolve(callback(snapshot)).then(() => true); }) .then( (completed) => { diff --git a/tests/http.test.mjs b/tests/http.test.mjs index 7d1927f..c66d9bd 100644 --- a/tests/http.test.mjs +++ b/tests/http.test.mjs @@ -3087,12 +3087,12 @@ test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback const observed = []; const seenBeforeSleep = []; const callbackTimers = []; - let omitActions = false; + let omittedField; const fixture = await server(t, (_, response) => { const status = states[Math.min(index, states.length - 1)]; index += 1; const current = review(status); - if (omitActions) delete current.actions; + if (omittedField) delete current[omittedField]; json(response, 200, current); }); const original = globalThis.setTimeout; @@ -3236,14 +3236,44 @@ test("waitForReview awaits non-terminal onPoll, clones payloads, bounds callback ); assert.equal(index, 0); - omitActions = true; - await assert.rejects( - client.waitForReview(orgId, reviewId, { - onPoll: () => assert.fail("invalid review reached onPoll"), - }), - { type: "urn:proofline:sdk:invalid-response" }, + for (const field of ["actions", "environment_display_names"]) { + index = 0; + omittedField = field; + await assert.rejects( + client.waitForReview(orgId, reviewId, { + onPoll: () => assert.fail("invalid review reached onPoll"), + }), + { type: "urn:proofline:sdk:invalid-response" }, + ); + } + omittedField = undefined; + + index = 0; + const clone = globalThis.structuredClone; + const monotonicNow = performance.now.bind(performance); + let cloned = false; + const cloneClock = t.mock.method( + performance, + "now", + () => monotonicNow() + (cloned ? 10_000 : 0), ); - omitActions = false; + const cloneMock = t.mock.method(globalThis, "structuredClone", (value) => { + if (value?.id === reviewId) cloned = true; + return clone(value); + }); + try { + const result = await client.waitForReview(orgId, reviewId, { + timeoutMs: 5_000, + onPoll: () => + assert.fail("onPoll ran after cloning crossed the deadline"), + }); + assert.equal(cloned, true); + assert.equal(result.status, "TIMED_OUT"); + assert.equal(index, 1); + } finally { + cloneMock.mock.restore(); + cloneClock.mock.restore(); + } index = 0; const readClock = performance.now.bind(performance);