diff --git a/packages/public-api-forwarding/README.md b/packages/public-api-forwarding/README.md index e54cac2ce5..eff17ca716 100644 --- a/packages/public-api-forwarding/README.md +++ b/packages/public-api-forwarding/README.md @@ -44,6 +44,60 @@ The Auth0 token request never follows a redirect, which would re-send the client `isJsonMediaType()` is the JSON content-type check the package and its routes share: `application/json` or any `application/...+json` type. +The sections below call the Public API "API v1", its name in PolicyEngine's other repositories. + +`fetchFromServer()` also takes a `signal`. When it aborts, the request stops and `fetchFromServer()` rejects with the signal's reason at once, also while the server credential is being fetched; that token request goes on, since other requests may be waiting on it. + +Its `PublicApiUnavailableError` names why API v1 cannot be called in `reason`: `unknown_route`, `not_configured` or `credential_unavailable`, found before anything is sent; or `unreachable`, `timed_out` or `answer_lost` (API v1 answered, but the answer was lost while it arrived). `requestMayHaveArrived` is `false` for the first three and `true` for the others: API v1 may have received the request. Fetch doesn't say whether anything was sent, so it is `true` even for a connection refused before sending. + +## Household calculations + +`createHouseholdCalculator({ forwarder })` returns `calculateHousehold(request, options)`, which calculates a household on API v1 without storing it. It is for server code that used to send API v1's synchronous `POST /{country}/calculate`, and takes the same household and policy: + +```ts +import { createHouseholdCalculator } from "@policyengine/public-api-forwarding"; + +const calculator = createHouseholdCalculator({ forwarder: websitePublicApi }); +const calculated = await calculator.calculateHousehold( + { + country: "us", + household: situation, // /calculate's situation; its axes are sent separately + policy: { + "gov.irs.credits.ctc.amount.base[0].amount": { + "2026-01-01.2100-12-31": 3000, + }, + }, + }, + { signal: request.signal }, +); +calculated.household; // what /calculate answered as `result` +``` + +What it does, through `fetchFromServer()`: + +1. Submits `{country_id, household, policy?, axes?, add_missing_variables?, spm?}` to `POST /v2/household-calculations`. `household` is the situation without its `axes`, which go in the request's own `axes` field; the caller's object is not changed. API v1 keeps the calculation as a household job only: no stored household, policy or user association. +2. Reads `GET /v2/household-calculations/{calculation_id}` every 2 seconds until the calculation succeeds or fails. When the submission's answer already says `succeeded` or `failed`, which the simulation service answers for a job that finished before it could confirm the call, it reads the calculation at once. +3. Gives up 10 minutes after the call starts, or after `timeLimitMilliseconds`: a number, 0 or more, or `Infinity`; anything else rejects with `RangeError` before submitting. No wait runs past that deadline; the last read happens at it, and an accepted calculation is read at least once, even with a limit of 0. + +The submission's timeout is the time left before the deadline, and at least 30 seconds: it may wait for an API v1 instance to start, which takes minutes after the service has scaled to zero, and timing it out sooner would leave a job that may exist. In practice it can't take longer than 300 seconds, after which Node's `fetch` stops waiting for the answer's headers and API v1's Cloud Run service ends the request; either way the submission is not sent again. Each read takes at most 30 seconds. A request's timeout starts once the server credential is in hand, which takes up to 10 seconds when a new token is needed. So a call can end up to about 80 seconds after the deadline (a submission started just before it, then the read it is owed); with the 10-minute default, a call ends within about 11.5 minutes, inside the website route's 800-second limit. + +It resolves with the calculated household, `warnings`, `spmConfig`, `spmProvenance`, the calculation ID and the versions it ran with. It throws: + +- `HouseholdCalculationFailedError` when the calculation fails, with the household function's `code` (such as `invalid_inputs`), `inputErrors` and `spmError`. A null `code` means the function raised or was cancelled, and submitting again may succeed. +- `HouseholdCalculationTimeoutError` when the time limit passes, with the calculation ID and the last status read (the submission's status if no read succeeded). +- `RangeError` for a time limit that is not a number, 0 or more, or `Infinity`. A limit that isn't a whole number is fine: timeouts are rounded up to whole milliseconds. +- `HouseholdCalculationRefusedError` when API v1 refuses a request or its answer cannot be read, with the HTTP status, API v1's message and `code` (such as `missing_parameters`), the parsed body, `Retry-After` and the observability and request IDs. +- `PublicApiUnavailableError` when API v1 cannot be called. +- The signal's reason when the signal aborts. + +Brief outages are retried until 90 seconds pass without a good answer: + +- **Reads** are retried on 429, 502, 503 and 504, and on a `PublicApiUnavailableError` whose `reason` is `credential_unavailable`, `unreachable`, `timed_out` or `answer_lost`. A 429 or 503 with `Retry-After` waits that many seconds, or 2 seconds if that is longer; anything else waits 2 seconds. +- **The submission** is retried only when no job can exist: on API v1's own 503 (with its `{status: "error", message}` body), which it answers when no job of the submission will run, and when the credential cannot be obtained (`reason: "credential_unavailable"`), so the request was never sent. It is not retried on any other 503, such as Cloud Run's plain-text one when its connection to an instance fails; on a 502; or when fetch rejects or times out after the request was handed to it: in each case API v1 may have created the job, and submitting again would create a second one. Nor is it retried when the wait before it would reach the deadline, since the calculation could then not be read. +- Nothing else is retried, including 400, 401, 403, 404, 409, 413, 422 and 500. + +How `calculated` differs from `/calculate`'s answer: there is no `{status, message, result}` envelope; `warnings` and `spm_provenance` are fields of the result, as `warnings` and `spmProvenance`; and inputs the model does not recognise come back as a failed calculation (`code: "invalid_inputs"`, `inputErrors`), thrown as `HouseholdCalculationFailedError`, not as a 400 with `errors`. + ## Configuration | Variable | Meaning | diff --git a/packages/public-api-forwarding/src/forward.ts b/packages/public-api-forwarding/src/forward.ts index beac2b35f7..b448ca1218 100644 --- a/packages/public-api-forwarding/src/forward.ts +++ b/packages/public-api-forwarding/src/forward.ts @@ -57,25 +57,98 @@ export interface ServerRequestOptions { }; /** How long to wait for the whole request. */ readonly timeoutMilliseconds?: number; + /** + * The caller's signal. When it aborts, the request stops and + * fetchFromServer rejects with the signal's reason. + */ + readonly signal?: AbortSignal; } +/** + * Why API v1 cannot be called: + * - "unknown_route": the path is not one a route may name; + * - "not_configured": the deployment has no API v1 URL, or a partial + * credential; + * - "credential_unavailable": the server credential could not be obtained; + * - "unreachable": fetch rejected, so API v1 could not be reached; + * - "timed_out": API v1 did not answer in time; + * - "answer_lost": API v1 answered, but the answer was lost while it arrived. + * The first three are found before anything is sent. + */ +export type PublicApiUnavailableReason = + | "unknown_route" + | "not_configured" + | "credential_unavailable" + | "unreachable" + | "timed_out" + | "answer_lost"; + +const REASONS_AFTER_SENDING: ReadonlySet = new Set([ + "unreachable", + "timed_out", + "answer_lost", +]); + /** * The Public API cannot be called: it is not configured, the server * credential cannot be obtained, or the path is not one a route may name. - * The message is safe to show; details go to the server's log. + * Or, from fetchFromServer, API v1 could not be reached or did not answer in + * time. The message is safe to show; details go to the server's log. */ export class PublicApiUnavailableError extends Error { override name = "PublicApiUnavailableError"; + /** + * False when the request was never sent (an unknown route, no + * configuration, or no credential), so sending it again cannot repeat + * it. True otherwise: API v1 may have received the request and acted on + * it. Fetch doesn't say whether anything was sent, so this is true even + * for a connection refused before sending. + */ + readonly requestMayHaveArrived: boolean; constructor( message: string, /** The status a route would answer with for this failure. */ readonly statusCode: number, + readonly reason: PublicApiUnavailableReason, ) { super(message); + this.requestMayHaveArrived = REASONS_AFTER_SENDING.has(reason); } } +/** + * Resolves or rejects as `promise` does, but rejects with the signal's + * reason as soon as the signal aborts. `promise` keeps running: a token + * request it waits on may be serving other requests too. + */ +function untilAborted( + promise: Promise, + signal: AbortSignal | undefined, +): Promise { + if (signal === undefined) { + return promise; + } + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(signal.reason); + return; + } + const onAbort = () => reject(signal.reason); + signal.addEventListener("abort", onAbort, { once: true }); + promise.then( + (value) => { + signal.removeEventListener("abort", onAbort); + resolve(value); + }, + (error: unknown) => { + signal.removeEventListener("abort", onAbort); + reject(error); + }, + ); + }); +} + export interface PublicApiForwarder { /** Sends a browser's request on to the Public API and streams the answer. */ forward( @@ -307,7 +380,11 @@ export function createPublicApiForwarder( if (!isForwardablePath(publicApiRequest.path)) { return { ok: false, - error: new PublicApiUnavailableError("Unknown route.", 404), + error: new PublicApiUnavailableError( + "Unknown route.", + 404, + "unknown_route", + ), }; } @@ -321,6 +398,7 @@ export function createPublicApiForwarder( error: new PublicApiUnavailableError( "The Public API is not configured on this deployment.", 503, + "not_configured", ), }; } @@ -340,6 +418,7 @@ export function createPublicApiForwarder( error: new PublicApiUnavailableError( "Could not obtain a credential for the Public API.", 502, + "credential_unavailable", ), }; } @@ -466,7 +545,15 @@ export function createPublicApiForwarder( publicApiRequest: PublicApiRequest, serverOptions: ServerRequestOptions = {}, ): Promise { - const connection = await connect(publicApiRequest); + const callerSignal = serverOptions.signal; + callerSignal?.throwIfAborted(); + // Getting the token can take a while; when the caller leaves meanwhile, + // the abort is the answer at once, not whatever the token request + // ends with. + const connection = await untilAborted( + connect(publicApiRequest), + callerSignal, + ); if (!connection.ok) { throw connection.error; } @@ -483,14 +570,18 @@ export function createPublicApiForwarder( headers.set("Authorization", `Bearer ${serverToken}`); } + const timeoutSignal = AbortSignal.timeout( + serverOptions.timeoutMilliseconds ?? + DEFAULT_SERVER_REQUEST_TIMEOUT_MILLISECONDS, + ); const init: RequestInit & { next?: ServerRequestOptions["next"] } = { method: publicApiRequest.method, headers, body: publicApiRequest.body, - signal: AbortSignal.timeout( - serverOptions.timeoutMilliseconds ?? - DEFAULT_SERVER_REQUEST_TIMEOUT_MILLISECONDS, - ), + signal: + callerSignal === undefined + ? timeoutSignal + : AbortSignal.any([timeoutSignal, callerSignal]), // Never followed: a redirect would carry the server credential. redirect: "manual", }; @@ -501,6 +592,9 @@ export function createPublicApiForwarder( try { upstream = await fetchImplementation(upstreamUrl, init); } catch (error) { + if (callerSignal?.aborted) { + throw callerSignal.reason; + } const timedOut = error instanceof DOMException && error.name === "TimeoutError"; logger.error( @@ -509,14 +603,17 @@ export function createPublicApiForwarder( : `Could not reach the Public API for ${publicApiRequest.method} ${publicApiRequest.path}:`, error instanceof Error ? error.message : error, ); + // The request was sent, so API v1 may have received it. throw timedOut ? new PublicApiUnavailableError( "The Public API did not answer in time.", 504, + "timed_out", ) : new PublicApiUnavailableError( "The Public API could not be reached.", 502, + "unreachable", ); } warnIfCredentialRefused(publicApiRequest, serverToken, upstream); diff --git a/packages/public-api-forwarding/src/householdCalculation.ts b/packages/public-api-forwarding/src/householdCalculation.ts new file mode 100644 index 0000000000..4163fa20f1 --- /dev/null +++ b/packages/public-api-forwarding/src/householdCalculation.ts @@ -0,0 +1,768 @@ +// Calculates a household on API v1 without storing it. The household, in +// the situation shape POST /{country}/calculate takes, goes to +// POST /v2/household-calculations; the helper then reads +// GET /v2/household-calculations/{calculation_id} until the calculation +// succeeds or fails. API v1 keeps the calculation as a household job only, +// with no stored household, policy or user association. +// +// For server code: every request goes through the forwarder's +// fetchFromServer, which adds the server credential. + +import { + DEFAULT_SERVER_REQUEST_TIMEOUT_MILLISECONDS, + PublicApiUnavailableError, + type PublicApiForwarder, + type PublicApiRequest, + type PublicApiUnavailableReason, +} from "./forward"; + +/** How long the helper waits between reads of a calculation. */ +export const HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS = 2_000; +/** How long after it starts the helper gives up on a calculation. */ +export const HOUSEHOLD_CALCULATION_TIME_LIMIT_MILLISECONDS = 10 * 60_000; +/** + * How long brief outages are retried without a good answer from API v1 + * before the helper gives up and throws the last failure. + */ +export const HOUSEHOLD_CALCULATION_OUTAGE_LIMIT_MILLISECONDS = 90_000; + +const SUBMISSION_PATH = "/v2/household-calculations"; +/** Read answers that a brief outage or a rate limit explains. */ +const RETRIED_READ_STATUSES = new Set([429, 502, 503, 504]); +/** + * The submission answer after which API v1 says no job will run, so + * submitting again cannot create a second one. It counts only with API v1's + * own error body: Cloud Run, in front of API v1, also answers 503 when its + * connection to an instance fails mid-request, after which the job may + * exist. A 502 is never retried: API v1 answers it when the job may exist. + */ +const RETRIED_SUBMISSION_STATUSES = new Set([503]); +/** Answers whose Retry-After the helper waits out. */ +const RETRY_AFTER_STATUSES = new Set([429, 503]); +const OBSERVABILITY_ID_HEADER = "x-policyengine-observability-id"; +const REQUEST_ID_HEADER = "x-policyengine-request-id"; +/** setTimeout runs any longer delay at once, so no wait is longer. */ +const LONGEST_TIMER_MILLISECONDS = 2 ** 31 - 1; +/** A calculation ID is a UUID; this also keeps it one path segment. */ +const CALCULATION_ID_PATTERN = /^[0-9A-Fa-f-]{1,64}$/; + +export type HouseholdCalculationCountry = "us" | "uk"; +export type HouseholdCalculationStatus = + | "pending" + | "running" + | "succeeded" + | "failed"; +/** The statuses of a calculation that has not finished yet. */ +export type HouseholdCalculationUnfinishedStatus = "pending" | "running"; + +type JsonObject = Record; + +/** A household to calculate, as POST /{country}/calculate takes it. */ +export interface InlineHouseholdCalculationRequest { + readonly country: HouseholdCalculationCountry; + /** + * The household in the situation shape. Its `axes`, if any, are sent as + * the request's own `axes` field, which is where API v1 takes them. + */ + readonly household: Readonly>; + /** + * Parameter changes keyed by parameter path, each mapping a period such as + * "2026-01-01.2100-12-31" to a value. Current law when omitted. + */ + readonly policy?: Readonly>; + /** Adds every variable the household lacks, as /calculate-full does. */ + readonly addMissingVariables?: boolean; + /** SPM settings for a US household. */ + readonly spm?: Readonly>; +} + +export interface HouseholdCalculationOptions { + /** Stops the requests in flight and any wait, rejecting with its reason. */ + readonly signal?: AbortSignal; + /** + * How long after the call starts to give up, 10 minutes by default. The + * last read happens at the deadline, and an accepted calculation is read + * at least once. So a call can end up to about 80 seconds after the + * deadline: a submission started just before it takes at least 30 + * seconds, the read after it up to 30, and each may first wait up to 10 + * seconds for a new server token. + */ + readonly timeLimitMilliseconds?: number; +} + +/** A calculation that succeeded. */ +export interface CalculatedHousehold { + readonly calculationId: string; + /** + * The household with each calculated value filled in by period, in the + * shape /calculate answered as `result`. + */ + readonly household: Record; + /** Inputs the country model ignored. */ + readonly warnings: readonly string[]; + /** For a US household, the SPM selection the calculation applied. */ + readonly spmConfig: Record | null; + /** For a US household, the receipt of the SPM forecast it used. */ + readonly spmProvenance: Record | null; + readonly countryPackageVersion: string; + readonly policyengineVersion: string; +} + +export interface HouseholdCalculatorDependencies { + readonly forwarder: Pick; + /** The current time in milliseconds; Date.now by default. */ + readonly now?: () => number; + /** Waits, rejecting with the signal's reason when it aborts; a timer by default. */ + readonly wait?: (milliseconds: number, signal?: AbortSignal) => Promise; +} + +export interface HouseholdCalculator { + /** + * Submits the household and reads the calculation until it finishes. + * Resolves with the calculated household. Throws + * HouseholdCalculationFailedError when the calculation fails, + * HouseholdCalculationTimeoutError when the time limit passes, + * HouseholdCalculationRefusedError when API v1 refuses a request or its + * answer cannot be read, and PublicApiUnavailableError when API v1 cannot + * be called. + */ + calculateHousehold( + request: InlineHouseholdCalculationRequest, + options?: HouseholdCalculationOptions, + ): Promise; +} + +/** The calculation ran and failed. */ +export class HouseholdCalculationFailedError extends Error { + override name = "HouseholdCalculationFailedError"; + + constructor( + message: string, + readonly calculationId: string, + /** + * The household function's error code, such as "invalid_inputs". Null + * when the function raised or was cancelled; submitting again may then + * succeed. + */ + readonly code: string | null, + /** For "invalid_inputs", each input the country model does not recognise. */ + readonly inputErrors: readonly Record[], + /** For "invalid_spm_selection", what is wrong with the SPM settings. */ + readonly spmError: Record | null, + ) { + super(message); + } +} + +/** + * The time limit passed before the calculation finished. API v1 may still + * finish it; GET /v2/household-calculations/{calculationId} reads it. + */ +export class HouseholdCalculationTimeoutError extends Error { + override name = "HouseholdCalculationTimeoutError"; + + constructor( + message: string, + readonly calculationId: string, + /** + * The status the last successful read gave, or the submission's when no + * read succeeded. It is "succeeded" or "failed" only when the + * submission's answer said so and no read could get the outcome before + * the deadline. + */ + readonly lastStatus: HouseholdCalculationStatus, + ) { + super(message); + } +} + +export interface HouseholdCalculationRefusal { + /** The HTTP status of API v1's answer. */ + readonly statusCode: number; + /** The answer's parsed body, or null when it was empty or not JSON. */ + readonly body: unknown; + /** API v1's error code, such as "missing_parameters", when it gave one. */ + readonly code: string | null; + /** Seconds from the answer's Retry-After, when it had one. */ + readonly retryAfterSeconds: number | null; + readonly observabilityId: string | null; + readonly requestId: string | null; + /** The calculation the answer concerns, or null before one was accepted. */ + readonly calculationId: string | null; +} + +/** + * API v1 refused a request, failed with an error status, or answered in a + * shape the helper cannot read. The message is API v1's, when it gave one. + */ +export class HouseholdCalculationRefusedError + extends Error + implements HouseholdCalculationRefusal +{ + override name = "HouseholdCalculationRefusedError"; + readonly statusCode: number; + readonly body: unknown; + readonly code: string | null; + readonly retryAfterSeconds: number | null; + readonly observabilityId: string | null; + readonly requestId: string | null; + readonly calculationId: string | null; + + constructor(message: string, refusal: HouseholdCalculationRefusal) { + super(message); + this.statusCode = refusal.statusCode; + this.body = refusal.body; + this.code = refusal.code; + this.retryAfterSeconds = refusal.retryAfterSeconds; + this.observabilityId = refusal.observabilityId; + this.requestId = refusal.requestId; + this.calculationId = refusal.calculationId; + } +} + +interface ApiV1Answer { + readonly response: Response; + readonly body: unknown; +} + +interface SubmittedCalculation { + readonly calculationId: string; + /** + * Usually "pending". The simulation service answers with the job's + * current status, so a fast job can already have finished. + */ + readonly status: HouseholdCalculationStatus; +} + +const CALCULATION_STATUSES: ReadonlySet = new Set([ + "pending", + "running", + "succeeded", + "failed", +]); + +function isCalculationStatus( + value: unknown, +): value is HouseholdCalculationStatus { + return CALCULATION_STATUSES.has(value); +} + +function isString(value: unknown): value is string { + return typeof value === "string"; +} + +/** A list of strings; an absent list is empty; anything else is undefined. */ +function stringsOrUndefined(value: unknown): string[] | undefined { + if (value === undefined || value === null) { + return []; + } + return Array.isArray(value) && value.every(isString) ? value : undefined; +} + +function isJsonObject(value: unknown): value is JsonObject { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function objectOrNull(value: unknown): JsonObject | null | undefined { + if (value === undefined || value === null) { + return null; + } + return isJsonObject(value) ? value : undefined; +} + +function retryAfterSeconds(response: Response): number | null { + const value = response.headers.get("retry-after"); + if (value === null) { + return null; + } + // A delay is decimal digits only; a date, or anything else, is ignored. + const digits = value.trim(); + return /^[0-9]+$/.test(digits) ? Number(digits) : null; +} + +function waitWithTimer( + milliseconds: number, + signal?: AbortSignal, +): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason); + return; + } + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason); + }; + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, milliseconds); + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +/** + * API v1's inline request: the situation without its axes, which go in the + * request's own `axes` field. + */ +function submissionBody( + request: InlineHouseholdCalculationRequest, +): JsonObject { + const { axes, ...householdWithoutAxes } = request.household; + return { + country_id: request.country, + household: householdWithoutAxes, + ...(request.policy === undefined ? {} : { policy: request.policy }), + ...(axes === undefined ? {} : { axes }), + ...(request.addMissingVariables === undefined + ? {} + : { add_missing_variables: request.addMissingVariables }), + ...(request.spm === undefined ? {} : { spm: request.spm }), + }; +} + +function refusal( + answer: ApiV1Answer, + calculationId: string | null, + fallbackMessage = `API v1 answered HTTP ${answer.response.status}.`, +): HouseholdCalculationRefusedError { + const fields = isJsonObject(answer.body) ? answer.body : {}; + const message = + typeof fields.message === "string" && fields.message.length > 0 + ? fields.message + : fallbackMessage; + return new HouseholdCalculationRefusedError(message, { + statusCode: answer.response.status, + body: answer.body, + code: typeof fields.code === "string" ? fields.code : null, + retryAfterSeconds: retryAfterSeconds(answer.response), + observabilityId: answer.response.headers.get(OBSERVABILITY_ID_HEADER), + requestId: answer.response.headers.get(REQUEST_ID_HEADER), + calculationId, + }); +} + +/** + * An answer that came with a success status but cannot be read. Its own + * message, if any, is not the reason, so `message` replaces it. + */ +function unreadable( + answer: ApiV1Answer, + calculationId: string | null, + message: string, +): HouseholdCalculationRefusedError { + return new HouseholdCalculationRefusedError( + message, + refusal(answer, calculationId), + ); +} + +/** `result.item` of a success answer, when the answer has one. */ +function resultItem(body: unknown): JsonObject | undefined { + const result = isJsonObject(body) ? body.result : undefined; + const item = isJsonObject(result) ? result.item : undefined; + return isJsonObject(item) ? item : undefined; +} + +/** Whether a body is API v1's own error answer: `{status: "error", message}`. */ +function isApiV1ErrorBody(body: unknown): boolean { + return ( + isJsonObject(body) && + body.status === "error" && + typeof body.message === "string" + ); +} + +/** The accepted calculation in a submission's answer. */ +function readSubmitted(answer: ApiV1Answer): SubmittedCalculation { + const item = resultItem(answer.body); + const calculationId = item?.calculation_id; + const status = item?.status; + if ( + typeof calculationId !== "string" || + !CALCULATION_ID_PATTERN.test(calculationId) || + !isCalculationStatus(status) + ) { + throw unreadable( + answer, + null, + "API v1 accepted the household calculation, but its answer has no calculation ID the helper can read, so the calculation, if one started, cannot be read.", + ); + } + return { calculationId, status }; +} + +type CalculationRead = + | { readonly status: HouseholdCalculationUnfinishedStatus } + | { readonly status: "succeeded"; readonly calculated: CalculatedHousehold } + | { + readonly status: "failed"; + readonly failure: HouseholdCalculationFailedError; + }; + +/** The calculation in a read's answer, or a refusal when it cannot be read. */ +function readCalculation( + answer: ApiV1Answer, + calculationId: string, +): CalculationRead { + const cannotRead = () => + unreadable( + answer, + calculationId, + `API v1's answer for household calculation ${calculationId} cannot be read.`, + ); + const item = resultItem(answer.body); + if (item === undefined || item.calculation_id !== calculationId) { + throw cannotRead(); + } + + if (item.status === "pending" || item.status === "running") { + return { status: item.status }; + } + + if (item.status === "succeeded") { + const result = item.result; + if (!isJsonObject(result) || !isJsonObject(result.household)) { + throw cannotRead(); + } + const warnings = stringsOrUndefined(result.warnings); + const spmConfig = objectOrNull(result.spm_config); + const spmProvenance = objectOrNull(result.spm_provenance); + if ( + warnings === undefined || + spmConfig === undefined || + spmProvenance === undefined || + typeof item.country_package_version !== "string" || + typeof item.policyengine_version !== "string" + ) { + throw cannotRead(); + } + return { + status: "succeeded", + calculated: { + calculationId, + household: result.household, + warnings, + spmConfig, + spmProvenance, + countryPackageVersion: item.country_package_version, + policyengineVersion: item.policyengine_version, + }, + }; + } + + if (item.status === "failed") { + const error = item.error; + if (!isJsonObject(error) || typeof error.message !== "string") { + throw cannotRead(); + } + const code = error.code ?? null; + const inputErrors = error.input_errors ?? []; + const spmError = objectOrNull(error.spm_error); + if ( + (code !== null && typeof code !== "string") || + !Array.isArray(inputErrors) || + !inputErrors.every(isJsonObject) || + spmError === undefined + ) { + throw cannotRead(); + } + return { + status: "failed", + failure: new HouseholdCalculationFailedError( + error.message, + calculationId, + code, + inputErrors, + spmError, + ), + }; + } + + throw cannotRead(); +} + +/** + * A failure of fetchFromServer that sending again cannot repeat: the server + * credential could not be obtained, so the request was never sent. + */ +function isUnsentCredentialFailure(error: unknown): boolean { + return ( + error instanceof PublicApiUnavailableError && + error.reason === "credential_unavailable" + ); +} + +/** Failures of fetchFromServer that a brief outage explains. */ +const BRIEF_OUTAGE_REASONS: ReadonlySet = new Set([ + "credential_unavailable", + "unreachable", + "timed_out", + "answer_lost", +]); + +/** + * A failure of fetchFromServer that a brief outage explains: the credential + * could not be obtained, or API v1 could not be reached, did not answer in + * time, or its answer was lost. An unknown route or a deployment with no + * API v1 configured is not one. + */ +function isBriefOutage(error: unknown): boolean { + return ( + error instanceof PublicApiUnavailableError && + BRIEF_OUTAGE_REASONS.has(error.reason) + ); +} + +export function createHouseholdCalculator( + dependencies: HouseholdCalculatorDependencies, +): HouseholdCalculator { + const { forwarder } = dependencies; + const now = dependencies.now ?? Date.now; + const wait = dependencies.wait ?? waitWithTimer; + + async function send( + request: PublicApiRequest, + signal: AbortSignal | undefined, + timeoutMilliseconds: number, + ): Promise { + const response = await forwarder.fetchFromServer(request, { + signal, + timeoutMilliseconds, + }); + let text: string; + try { + text = await response.text(); + } catch { + if (signal?.aborted) { + throw signal.reason; + } + // The answer was lost after the request arrived. + throw new PublicApiUnavailableError( + "API v1's answer was lost before it could be read.", + 502, + "answer_lost", + ); + } + let body: unknown = null; + try { + body = text === "" ? null : JSON.parse(text); + } catch { + // Not JSON, such as a load balancer's error page; the status still tells. + } + return { response, body }; + } + + /** + * How long to wait before trying again after a retried answer: its + * Retry-After for a 429 or 503, but never less than one interval, so + * that a Retry-After of 0 cannot make the helper send requests back to + * back. + */ + function retryWaitMilliseconds(response: Response): number { + const seconds = RETRY_AFTER_STATUSES.has(response.status) + ? retryAfterSeconds(response) + : null; + return seconds === null + ? HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS + : Math.max( + seconds * 1_000, + HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS, + ); + } + + /** + * Waits before submitting again, and true; or false, without waiting, + * when the wait would reach the deadline, since a calculation submitted + * then could not be read. + */ + async function waitToResubmit( + milliseconds: number, + deadline: number, + signal: AbortSignal | undefined, + ): Promise { + if (now() + milliseconds >= deadline) { + return false; + } + await wait(Math.min(milliseconds, LONGEST_TIMER_MILLISECONDS), signal); + return true; + } + + async function submit( + request: InlineHouseholdCalculationRequest, + deadline: number, + signal: AbortSignal | undefined, + ): Promise { + const body = JSON.stringify(submissionBody(request)); + const startedAt = now(); + const canRetry = () => + now() - startedAt < HOUSEHOLD_CALCULATION_OUTAGE_LIMIT_MILLISECONDS; + + for (;;) { + signal?.throwIfAborted(); + // A submission may wait for an API v1 instance to start, which can + // take minutes, so its timeout is the time left before the deadline + // (at least the forwarder's usual 30 seconds). Timing it out sooner + // would leave a job that may exist, which the helper must not submit + // again. Node's fetch and API v1's Cloud Run service each end a + // request after 300 seconds anyway. + // AbortSignal.timeout takes whole milliseconds only. + const timeoutMilliseconds = Math.ceil( + Math.min( + Math.max( + DEFAULT_SERVER_REQUEST_TIMEOUT_MILLISECONDS, + deadline - now(), + ), + LONGEST_TIMER_MILLISECONDS, + ), + ); + let answer: ApiV1Answer; + try { + answer = await send( + { method: "POST", path: SUBMISSION_PATH, body }, + signal, + timeoutMilliseconds, + ); + } catch (error) { + if ( + !isUnsentCredentialFailure(error) || + !canRetry() || + !(await waitToResubmit( + HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS, + deadline, + signal, + )) + ) { + throw error; + } + continue; + } + + if (answer.response.ok) { + return readSubmitted(answer); + } + const failure = refusal(answer, null); + if ( + !RETRIED_SUBMISSION_STATUSES.has(answer.response.status) || + !isApiV1ErrorBody(answer.body) || + !canRetry() || + !(await waitToResubmit( + retryWaitMilliseconds(answer.response), + deadline, + signal, + )) + ) { + throw failure; + } + } + } + + async function readUntilFinished( + submitted: SubmittedCalculation, + deadline: number, + signal: AbortSignal | undefined, + ): Promise { + const { calculationId } = submitted; + const path = `${SUBMISSION_PATH}/${calculationId}`; + let lastStatus: HouseholdCalculationStatus = submitted.status; + let lastGoodAnswerAt = now(); + // A calculation the submission's answer says has finished is read at + // once, for its result or error. + let nextWaitMilliseconds = + submitted.status === "succeeded" || submitted.status === "failed" + ? 0 + : HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS; + const outageLimitReached = () => + now() - lastGoodAnswerAt >= + HOUSEHOLD_CALCULATION_OUTAGE_LIMIT_MILLISECONDS; + const timedOut = () => + new HouseholdCalculationTimeoutError( + `Household calculation ${calculationId} did not finish in time.`, + calculationId, + lastStatus, + ); + + // Wait, read, then stop if the deadline has come: so the accepted + // calculation is read at least once, and the last read happens at the + // deadline. + for (;;) { + const waitMilliseconds = Math.min( + nextWaitMilliseconds, + Math.max(deadline - now(), 0), + LONGEST_TIMER_MILLISECONDS, + ); + if (waitMilliseconds > 0) { + await wait(waitMilliseconds, signal); + } + signal?.throwIfAborted(); + nextWaitMilliseconds = HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS; + + let answer: ApiV1Answer; + try { + answer = await send( + { method: "GET", path }, + signal, + DEFAULT_SERVER_REQUEST_TIMEOUT_MILLISECONDS, + ); + } catch (error) { + if (!isBriefOutage(error) || outageLimitReached()) { + throw error; + } + if (now() >= deadline) { + throw timedOut(); + } + continue; + } + + if (!answer.response.ok) { + if ( + !RETRIED_READ_STATUSES.has(answer.response.status) || + outageLimitReached() + ) { + throw refusal(answer, calculationId); + } + if (now() >= deadline) { + throw timedOut(); + } + nextWaitMilliseconds = retryWaitMilliseconds(answer.response); + continue; + } + + const calculation = readCalculation(answer, calculationId); + lastGoodAnswerAt = now(); + if (calculation.status === "succeeded") { + return calculation.calculated; + } + if (calculation.status === "failed") { + throw calculation.failure; + } + lastStatus = calculation.status; + if (now() >= deadline) { + throw timedOut(); + } + } + } + + return { + async calculateHousehold(request, options = {}) { + const { signal } = options; + const timeLimitMilliseconds = + options.timeLimitMilliseconds ?? + HOUSEHOLD_CALCULATION_TIME_LIMIT_MILLISECONDS; + // Anything else would make a deadline that never comes, or waits that + // setTimeout runs at once. + if ( + typeof timeLimitMilliseconds !== "number" || + Number.isNaN(timeLimitMilliseconds) || + timeLimitMilliseconds < 0 + ) { + throw new RangeError( + `timeLimitMilliseconds must be a number, 0 or more, or Infinity; got ${String(timeLimitMilliseconds)}.`, + ); + } + const deadline = now() + timeLimitMilliseconds; + const submitted = await submit(request, deadline, signal); + return readUntilFinished(submitted, deadline, signal); + }, + }; +} diff --git a/packages/public-api-forwarding/src/index.ts b/packages/public-api-forwarding/src/index.ts index a11ce037b2..adc635c464 100644 --- a/packages/public-api-forwarding/src/index.ts +++ b/packages/public-api-forwarding/src/index.ts @@ -29,8 +29,27 @@ export { type PublicApiForwarderOptions, type PublicApiMethod, type PublicApiRequest, + type PublicApiUnavailableReason, type ServerRequestOptions, } from "./forward"; +export { + HOUSEHOLD_CALCULATION_OUTAGE_LIMIT_MILLISECONDS, + HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS, + HOUSEHOLD_CALCULATION_TIME_LIMIT_MILLISECONDS, + HouseholdCalculationFailedError, + HouseholdCalculationRefusedError, + HouseholdCalculationTimeoutError, + createHouseholdCalculator, + type CalculatedHousehold, + type HouseholdCalculationCountry, + type HouseholdCalculationOptions, + type HouseholdCalculationRefusal, + type HouseholdCalculationStatus, + type HouseholdCalculationUnfinishedStatus, + type HouseholdCalculator, + type HouseholdCalculatorDependencies, + type InlineHouseholdCalculationRequest, +} from "./householdCalculation"; export { isJsonMediaType } from "./mediaType"; export { ROUTE_ERROR_HEADER, errorResponse } from "./responses"; export { diff --git a/packages/public-api-forwarding/tests/forward.test.ts b/packages/public-api-forwarding/tests/forward.test.ts index 9fb47f837a..648d6d4567 100644 --- a/packages/public-api-forwarding/tests/forward.test.ts +++ b/packages/public-api-forwarding/tests/forward.test.ts @@ -775,4 +775,187 @@ describe("fetchFromServer", () => { expect(failure).toMatchObject({ statusCode: 404 }); expect(fetchImplementation).not.toHaveBeenCalled(); }); + + test("given the caller's signal aborts then it rejects with the signal's reason", async () => { + // Given an API v1 that answers only when the request is aborted, and + // says when the request has started + let requestStarted: () => void = () => {}; + const started = new Promise((resolve) => { + requestStarted = resolve; + }); + const fetchImplementation = vi.fn( + (_input: RequestInfo | URL, init?: RequestInit) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener("abort", () => + reject(init.signal?.reason), + ); + requestStarted(); + }), + ); + const forwarder = createPublicApiForwarder({ + environment: PREVIEW_ENVIRONMENT_WITHOUT_CREDENTIAL, + callerName: "policyengine-test-caller", + sharedTokenStore: null, + clientAddress: () => undefined, + fetchImplementation, + logger: silentLogger, + }); + const controller = new AbortController(); + const callerLeft = new Error("The caller went away."); + + // When the caller aborts while the request is in flight, long before + // the request's own timeout would end it + const pendingRequest = forwarder + .fetchFromServer(DEPLOYMENT_REPORT_REQUEST, { + signal: controller.signal, + timeoutMilliseconds: 60_000, + }) + .catch((error: unknown) => error); + await started; + controller.abort(callerLeft); + const failure = await pendingRequest; + + // Then + expect(fetchImplementation).toHaveBeenCalledTimes(1); + expect(failure).toBe(callerLeft); + }); + + test("given the caller aborts while the token is fetched then it rejects with the signal's reason without waiting for the token request", async () => { + // Given a token request that fails only when the test says so + let tokenRequested: () => void = () => {}; + const requested = new Promise((resolve) => { + tokenRequested = resolve; + }); + let failTokenRequest: () => void = () => {}; + const tokenFailure = new Promise((resolve) => { + failTokenRequest = () => + resolve(jsonResponse({ error: "access_denied" }, 403)); + }); + const { forwarder, publicApiCalls } = forwarderWith({ + tokenAnswer: () => { + tokenRequested(); + return tokenFailure; + }, + }); + const controller = new AbortController(); + const callerLeft = new Error("The caller went away."); + + // When the caller aborts while the token request is still running + const pendingRequest = forwarder + .fetchFromServer(DEPLOYMENT_REPORT_REQUEST, { signal: controller.signal }) + .catch((error: unknown) => error); + await requested; + controller.abort(callerLeft); + const failure = await pendingRequest; + failTokenRequest(); + + // Then + expect(failure).toBe(callerLeft); + expect(publicApiCalls()).toHaveLength(0); + }); + + test("given the token request fails then the error says the request never reached API v1", async () => { + // Given + const { forwarder } = forwarderWith({ + tokenAnswer: () => jsonResponse({ error: "access_denied" }, 403), + }); + + // When + const failure = await forwarder + .fetchFromServer(DEPLOYMENT_REPORT_REQUEST) + .catch((error: unknown) => error); + + // Then + expect(failure).toBeInstanceOf(PublicApiUnavailableError); + expect(failure).toMatchObject({ + statusCode: 502, + reason: "credential_unavailable", + requestMayHaveArrived: false, + }); + }); + + test("given API v1 cannot be reached then the error says the request may have arrived", async () => { + // Given + const { forwarder } = forwarderWith({ + publicApiAnswer: () => { + throw new TypeError("fetch failed"); + }, + }); + + // When + const failure = await forwarder + .fetchFromServer(DEPLOYMENT_REPORT_REQUEST) + .catch((error: unknown) => error); + + // Then + expect(failure).toBeInstanceOf(PublicApiUnavailableError); + expect(failure).toMatchObject({ + statusCode: 502, + reason: "unreachable", + requestMayHaveArrived: true, + }); + }); + + test("given a path that could leave API v1 then the error names an unknown route that was never sent", async () => { + // Given + const { forwarder } = forwarderWith(); + + // When + const failure = await forwarder + .fetchFromServer({ method: "GET", path: "/../deployment" }) + .catch((error: unknown) => error); + + // Then + expect(failure).toMatchObject({ + reason: "unknown_route", + requestMayHaveArrived: false, + }); + }); + + test("given no API v1 URL on a preview deployment then the error names a missing configuration that was never sent", async () => { + // Given + const { forwarder } = forwarderWith({ + environment: { VERCEL_ENV: "preview" }, + }); + + // When + const failure = await forwarder + .fetchFromServer(DEPLOYMENT_REPORT_REQUEST) + .catch((error: unknown) => error); + + // Then + expect(failure).toMatchObject({ + reason: "not_configured", + requestMayHaveArrived: false, + }); + }); + + test("given API v1 does not answer in time then the error names a timeout that may have arrived", async () => { + // Given an API v1 that answers only when the request is aborted + const forwarder = createPublicApiForwarder({ + environment: PREVIEW_ENVIRONMENT_WITHOUT_CREDENTIAL, + callerName: "policyengine-test-caller", + sharedTokenStore: null, + clientAddress: () => undefined, + fetchImplementation: (_input, init) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener("abort", () => + reject(new DOMException("timed out", "TimeoutError")), + ); + }), + logger: silentLogger, + }); + + // When + const failure = await forwarder + .fetchFromServer(DEPLOYMENT_REPORT_REQUEST, { timeoutMilliseconds: 10 }) + .catch((error: unknown) => error); + + // Then + expect(failure).toMatchObject({ + statusCode: 504, + reason: "timed_out", + requestMayHaveArrived: true, + }); + }); }); diff --git a/packages/public-api-forwarding/tests/householdCalculation.test.ts b/packages/public-api-forwarding/tests/householdCalculation.test.ts new file mode 100644 index 0000000000..ea6dcb83db --- /dev/null +++ b/packages/public-api-forwarding/tests/householdCalculation.test.ts @@ -0,0 +1,1345 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { + PublicApiUnavailableError, + type PublicApiRequest, + type ServerRequestOptions, +} from "../src/forward"; +import { + HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS, + HOUSEHOLD_CALCULATION_TIME_LIMIT_MILLISECONDS, + HouseholdCalculationFailedError, + HouseholdCalculationRefusedError, + HouseholdCalculationTimeoutError, + createHouseholdCalculator, + type HouseholdCalculatorDependencies, + type InlineHouseholdCalculationRequest, +} from "../src/householdCalculation"; +import { jsonResponse } from "./fixtures"; + +const CALCULATION_ID = "8a1f6b0e-3c2d-4e5f-9a7b-1c2d3e4f5a6b"; +const CALCULATION_PATH = `/v2/household-calculations/${CALCULATION_ID}`; +const OBSERVABILITY_ID = "obs-4d2c1b0a"; +const COUNTRY_PACKAGE_VERSION = "1.500.0"; +const POLICYENGINE_VERSION = "3.4.0"; + +const US_SITUATION = { + people: { you: { age: { 2026: 40 }, employment_income: { 2026: 50_000 } } }, + households: { + your_household: { + members: ["you"], + household_net_income: { 2026: null }, + }, + }, +}; + +const CALCULATED_US_SITUATION = { + people: { you: { age: { 2026: 40 }, employment_income: { 2026: 50_000 } } }, + households: { + your_household: { + members: ["you"], + household_net_income: { 2026: 44_210.5 }, + }, + }, +}; + +const CHILD_TAX_CREDIT_REFORM = { + "gov.irs.credits.ctc.amount.base[0].amount": { + "2026-01-01.2100-12-31": 3000, + }, +}; + +const US_REFORM_REQUEST: InlineHouseholdCalculationRequest = { + country: "us", + household: US_SITUATION, + policy: CHILD_TAX_CREDIT_REFORM, +}; + +const INVALID_INPUT_ERROR = { + type: "unknown_variable", + name: "employment_incme", + path: "people.you.employment_incme", + message: "employment_incme is not a variable of the US model.", +}; + +type CalculationStatus = "pending" | "running" | "succeeded" | "failed"; + +const EMPLOYMENT_INCOME_AXES = [ + [ + { + name: "employment_income", + count: 401, + min: 0, + max: 200_000, + period: 2026, + }, + ], +]; + +function submittedAnswer(status: CalculationStatus = "pending"): Response { + return jsonResponse( + { + status: "ok", + message: null, + result: { + item: { + calculation_id: CALCULATION_ID, + status, + country_id: "us", + household_id: null, + policy_id: null, + dynamic_id: null, + year: 2026, + }, + }, + }, + 202, + ); +} + +function calculationAnswer( + status: CalculationStatus | "queued", + outcome: { result?: unknown; error?: unknown } = {}, + calculationId = CALCULATION_ID, +): Response { + return jsonResponse({ + status: "ok", + message: null, + result: { + item: { + calculation_id: calculationId, + country_id: "us", + household_id: null, + policy_id: null, + dynamic_id: null, + year: 2026, + catalog_version_id: "0b9d7c55-6e1f-4a2b-8c3d-4e5f6a7b8c9d", + country_package_version: COUNTRY_PACKAGE_VERSION, + policyengine_version: POLICYENGINE_VERSION, + status, + created_at: "2026-11-28T12:00:00Z", + started_at: status === "pending" ? null : "2026-11-28T12:00:01Z", + completed_at: + status === "succeeded" || status === "failed" + ? "2026-11-28T12:00:05Z" + : null, + result: outcome.result ?? null, + error: outcome.error ?? null, + }, + }, + }); +} + +function succeededAnswer(): Response { + return calculationAnswer("succeeded", { + result: { + household: CALCULATED_US_SITUATION, + warnings: ["Ignored input: rent"], + spm_config: { geography_kind: "national" }, + spm_provenance: { forecast_content_sha256: "ab12" }, + }, + }); +} + +function errorAnswer( + statusCode: number, + message: string, + extraFields: Record = {}, + headers: Record = {}, +): Response { + return jsonResponse( + { status: "error", message, ...extraFields }, + statusCode, + headers, + ); +} + +/** An answer whose body is lost while it arrives: reading it rejects. */ +function lostBodyAnswer(statusCode: number): Response { + return new Response( + new ReadableStream({ + start(controller) { + controller.error(new TypeError("terminated")); + }, + }), + { status: statusCode, headers: { "Content-Type": "application/json" } }, + ); +} + +/** A 503 from Cloud Run in front of API v1: plain text, not API v1's envelope. */ +function cloudRunUnavailableAnswer(): Response { + return new Response("Service Unavailable", { + status: 503, + headers: { "Content-Type": "text/html" }, + }); +} + +type ScriptedAnswer = Response | Error; + +interface RecordedRequest { + readonly request: PublicApiRequest; + readonly options: ServerRequestOptions | undefined; + readonly atMilliseconds: number; +} + +/** + * A fake API v1 on a fake clock: each request gets the next answer that + * `answerFor` gives, and each wait moves the clock on instead of sleeping. + */ +function fakeApiV1( + answerFor: (request: PublicApiRequest) => ScriptedAnswer, + overrides: Partial = {}, +) { + const clock = { milliseconds: 0 }; + const requests: RecordedRequest[] = []; + const waits: number[] = []; + const fetchFromServer = vi.fn( + async (request: PublicApiRequest, options?: ServerRequestOptions) => { + // fetchFromServer hands the timeout to AbortSignal.timeout, which + // throws for a value it cannot take; so does the fake. + if (options?.timeoutMilliseconds !== undefined) { + AbortSignal.timeout(options.timeoutMilliseconds); + } + requests.push({ request, options, atMilliseconds: clock.milliseconds }); + const answer = answerFor(request); + if (answer instanceof Error) { + throw answer; + } + return answer; + }, + ); + const calculator = createHouseholdCalculator({ + forwarder: { fetchFromServer }, + now: () => clock.milliseconds, + wait: async (milliseconds, signal) => { + signal?.throwIfAborted(); + waits.push(milliseconds); + clock.milliseconds += milliseconds; + }, + ...overrides, + }); + const submissions = () => + requests.filter(({ request }) => request.method === "POST"); + const reads = () => + requests.filter(({ request }) => request.method === "GET"); + return { calculator, requests, submissions, reads, waits, clock }; +} + +/** Answers the requests in order from a list, failing on any request past its end. */ +function inOrder(answers: ScriptedAnswer[]) { + const remaining = [...answers]; + return (request: PublicApiRequest): ScriptedAnswer => { + const answer = remaining.shift(); + if (answer === undefined) { + throw new Error( + `The test expected no request ${request.method} ${request.path}`, + ); + } + return answer; + }; +} + +/** Answers the submission with `submission`, and every read with `readAnswer()`. */ +function submissionThenEveryRead( + submission: () => ScriptedAnswer, + readAnswer: () => ScriptedAnswer, +) { + return (request: PublicApiRequest): ScriptedAnswer => + request.method === "POST" ? submission() : readAnswer(); +} + +async function failureOf(promise: Promise): Promise { + return promise.then( + () => { + throw new Error("Expected the calculation to fail, but it resolved."); + }, + (error: unknown) => error, + ); +} + +function submittedBody(recorded: RecordedRequest): unknown { + return JSON.parse(recorded.request.body ?? "null"); +} + +describe("calculateHousehold", () => { + test("given a calculation that finishes after several reads then it resolves with the calculated household", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + calculationAnswer("pending"), + calculationAnswer("running"), + succeededAnswer(), + ]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated).toEqual({ + calculationId: CALCULATION_ID, + household: CALCULATED_US_SITUATION, + warnings: ["Ignored input: rent"], + spmConfig: { geography_kind: "national" }, + spmProvenance: { forecast_content_sha256: "ab12" }, + countryPackageVersion: COUNTRY_PACKAGE_VERSION, + policyengineVersion: POLICYENGINE_VERSION, + }); + expect(api.requests.map(({ request }) => request.method)).toEqual([ + "POST", + "GET", + "GET", + "GET", + ]); + expect(api.submissions()[0].request.path).toBe( + "/v2/household-calculations", + ); + expect(submittedBody(api.submissions()[0])).toEqual({ + country_id: "us", + household: US_SITUATION, + policy: CHILD_TAX_CREDIT_REFORM, + }); + expect(api.reads().map(({ request }) => request.path)).toEqual([ + CALCULATION_PATH, + CALCULATION_PATH, + CALCULATION_PATH, + ]); + expect(api.waits).toEqual([2_000, 2_000, 2_000]); + }); + + test("given no policy and the missing-variable and SPM options then the submission sends the options and leaves policy out", async () => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), succeededAnswer()])); + + // When + await api.calculator.calculateHousehold({ + country: "us", + household: US_SITUATION, + addMissingVariables: true, + spm: { geography_kind: "national" }, + }); + + // Then + expect(submittedBody(api.submissions()[0])).toEqual({ + country_id: "us", + household: US_SITUATION, + add_missing_variables: true, + spm: { geography_kind: "national" }, + }); + }); + + test("given a calculation that fails then it throws HouseholdCalculationFailedError with the job's error", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + calculationAnswer("running"), + calculationAnswer("failed", { + error: { + code: "invalid_inputs", + message: "The household names inputs the US model does not have.", + input_errors: [INVALID_INPUT_ERROR], + spm_error: null, + }, + }), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationFailedError); + expect(failure).toMatchObject({ + calculationId: CALCULATION_ID, + code: "invalid_inputs", + message: "The household names inputs the US model does not have.", + inputErrors: [INVALID_INPUT_ERROR], + spmError: null, + }); + expect(api.reads()).toHaveLength(2); + }); + + test("given a calculation still running at its time limit then it reads once more at the deadline and throws HouseholdCalculationTimeoutError", async () => { + // Given + const api = fakeApiV1( + submissionThenEveryRead(submittedAnswer, () => + calculationAnswer("running"), + ), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds: 5_000, + }), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationTimeoutError); + expect(failure).toMatchObject({ + calculationId: CALCULATION_ID, + lastStatus: "running", + }); + expect(api.waits).toEqual([2_000, 2_000, 1_000]); + expect(api.reads().map(({ atMilliseconds }) => atMilliseconds)).toEqual([ + 2_000, 4_000, 5_000, + ]); + }); + + test("given the default settings then it reads every 2 seconds and gives up 10 minutes after it starts", async () => { + // Given + const api = fakeApiV1( + submissionThenEveryRead(submittedAnswer, () => + calculationAnswer("pending"), + ), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS).toBe(2_000); + expect(HOUSEHOLD_CALCULATION_TIME_LIMIT_MILLISECONDS).toBe(600_000); + expect(failure).toBeInstanceOf(HouseholdCalculationTimeoutError); + expect(new Set(api.waits)).toEqual(new Set([2_000])); + expect(api.reads()).toHaveLength(300); + expect(api.reads().at(-1)?.atMilliseconds).toBe(600_000); + }); + + test.each([429, 502, 503, 504])( + "given a read answers %i then it waits one interval and reads again", + async (statusCode) => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + errorAnswer(statusCode, "Try again shortly"), + succeededAnswer(), + ]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated.household).toEqual(CALCULATED_US_SITUATION); + expect(api.reads()).toHaveLength(2); + expect(api.waits).toEqual([2_000, 2_000]); + }, + ); + + test("given a read answers 503 with Retry-After then it waits that many seconds before reading again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + errorAnswer(503, "Storage is unavailable", {}, { "Retry-After": "7" }), + succeededAnswer(), + ]), + ); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(api.waits).toEqual([2_000, 7_000]); + }); + + test("given a read cannot reach API v1 then it reads again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + new PublicApiUnavailableError( + "Could not be reached.", + 502, + "unreachable", + ), + succeededAnswer(), + ]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.reads()).toHaveLength(2); + }); + + test("given reads fail for 90 seconds without a good answer then it throws the last failure", async () => { + // Given + const api = fakeApiV1( + submissionThenEveryRead(submittedAnswer, () => + errorAnswer(502, "Bad gateway"), + ), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ + statusCode: 502, + calculationId: CALCULATION_ID, + }); + expect(api.reads().at(-1)?.atMilliseconds).toBe(90_000); + expect(api.reads()).toHaveLength(45); + }); + + test("given a read answers 404 then it throws HouseholdCalculationRefusedError without reading again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + errorAnswer(404, `Household calculation ${CALCULATION_ID} not found.`), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ + statusCode: 404, + message: `Household calculation ${CALCULATION_ID} not found.`, + calculationId: CALCULATION_ID, + }); + expect(api.reads()).toHaveLength(1); + }); + + test("given the submission answers 503 then it submits again after Retry-After", async () => { + // Given + const api = fakeApiV1( + inOrder([ + errorAnswer( + 503, + "The simulation service cannot be reached", + {}, + { "Retry-After": "3" }, + ), + submittedAnswer(), + succeededAnswer(), + ]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.submissions()).toHaveLength(2); + expect(api.waits).toEqual([3_000, 2_000]); + }); + + test("given the submission answers 502 then it throws without submitting again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + errorAnswer( + 502, + "The simulation service's answer cannot be read; submitting again creates a second job if the first went through.", + ), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ statusCode: 502, calculationId: null }); + expect(api.submissions()).toHaveLength(1); + }); + + test("given the submission may have reached API v1 before its connection failed then it throws without submitting again", async () => { + // Given + const timedOut = new PublicApiUnavailableError( + "The Public API did not answer in time.", + 504, + "timed_out", + ); + const api = fakeApiV1(inOrder([timedOut])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBe(timedOut); + expect(api.submissions()).toHaveLength(1); + }); + + test("given the credential cannot be obtained before submitting then it submits again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + new PublicApiUnavailableError( + "Could not obtain a credential for the Public API.", + 502, + "credential_unavailable", + ), + submittedAnswer(), + succeededAnswer(), + ]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.submissions()).toHaveLength(2); + }); + + test("given API v1 is not configured on the deployment then it throws without trying again", async () => { + // Given + const notConfigured = new PublicApiUnavailableError( + "The Public API is not configured on this deployment.", + 503, + "not_configured", + ); + const api = fakeApiV1(inOrder([notConfigured])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBe(notConfigured); + expect(api.requests).toHaveLength(1); + }); + + test("given API v1 refuses a policy with missing parameters then it throws HouseholdCalculationRefusedError with the code and body", async () => { + // Given + const refusalBody = { + status: "error", + message: "The policy sets parameters the running catalog does not have.", + code: "missing_parameters", + missing_parameters: ["gov.irs.credits.ctc.amount.base[0].amount"], + }; + const api = fakeApiV1( + inOrder([ + jsonResponse(refusalBody, 422, { + "X-PolicyEngine-Observability-Id": OBSERVABILITY_ID, + }), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ + statusCode: 422, + code: "missing_parameters", + message: refusalBody.message, + body: refusalBody, + observabilityId: OBSERVABILITY_ID, + calculationId: null, + }); + expect(api.requests).toHaveLength(1); + }); + + test("given an accepted submission without a calculation ID then it throws HouseholdCalculationRefusedError", async () => { + // Given + const api = fakeApiV1( + inOrder([ + jsonResponse( + { status: "ok", message: null, result: { item: {} } }, + 202, + ), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ statusCode: 202, calculationId: null }); + }); + + test("given a signal then every request carries it", async () => { + // Given + const controller = new AbortController(); + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + calculationAnswer("running"), + succeededAnswer(), + ]), + ); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST, { + signal: controller.signal, + }); + + // Then + expect(api.requests).toHaveLength(3); + for (const { options } of api.requests) { + expect(options?.signal).toBe(controller.signal); + } + }); + + test("given the signal aborts during a wait then it rejects with the abort reason and reads no more", async () => { + // Given + const controller = new AbortController(); + const callerLeft = new Error("The caller went away."); + const api = fakeApiV1( + submissionThenEveryRead(submittedAnswer, () => + calculationAnswer("running"), + ), + { + // A wait that ends only through the signal it is given: without + // it, the call would never finish. + wait: (_milliseconds, signal) => + new Promise((_resolve, reject) => { + signal?.addEventListener("abort", () => reject(signal.reason), { + once: true, + }); + controller.abort(callerLeft); + }), + }, + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + signal: controller.signal, + }), + ); + + // Then + expect(failure).toBe(callerLeft); + expect(api.reads()).toHaveLength(0); + }); + + test.each([ + ["not a number", Number.NaN], + ["negative", -1], + ["a string", "600000" as unknown as number], + ])( + "given a time limit that is %s then it rejects with RangeError before submitting", + async (_description, timeLimitMilliseconds) => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), succeededAnswer()])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds, + }), + ); + + // Then + expect(failure).toBeInstanceOf(RangeError); + expect(api.requests).toHaveLength(0); + }, + ); + + test("given an infinite time limit then it keeps reading until the calculation finishes", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + ...Array.from({ length: 400 }, () => calculationAnswer("running")), + succeededAnswer(), + ]), + ); + + // When + const calculated = await api.calculator.calculateHousehold( + US_REFORM_REQUEST, + { timeLimitMilliseconds: Number.POSITIVE_INFINITY }, + ); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.reads()).toHaveLength(401); + }); + test("given a household with axes then the submission sends them as a separate axes field", async () => { + // Given + const householdWithAxes = { ...US_SITUATION, axes: EMPLOYMENT_INCOME_AXES }; + const api = fakeApiV1(inOrder([submittedAnswer(), succeededAnswer()])); + + // When + await api.calculator.calculateHousehold({ + country: "us", + household: householdWithAxes, + policy: CHILD_TAX_CREDIT_REFORM, + }); + + // Then + expect(submittedBody(api.submissions()[0])).toEqual({ + country_id: "us", + household: US_SITUATION, + policy: CHILD_TAX_CREDIT_REFORM, + axes: EMPLOYMENT_INCOME_AXES, + }); + expect(householdWithAxes.axes).toBe(EMPLOYMENT_INCOME_AXES); + }); + + test("given the default time limit then the submission may take until the deadline and each read 30 seconds", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + calculationAnswer("running"), + succeededAnswer(), + ]), + ); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(api.submissions()[0].options?.timeoutMilliseconds).toBe(600_000); + expect( + api.reads().map(({ options }) => options?.timeoutMilliseconds), + ).toEqual([30_000, 30_000]); + }); + + test("given a short time limit then the submission still gets 30 seconds", async () => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), succeededAnswer()])); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds: 5_000, + }); + + // Then + expect(api.submissions()[0].options?.timeoutMilliseconds).toBe(30_000); + }); + + test("given the submission gets a 503 that is not API v1's own then it throws without submitting again", async () => { + // Given + const api = fakeApiV1(inOrder([cloudRunUnavailableAnswer()])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ statusCode: 503, body: null }); + expect(api.submissions()).toHaveLength(1); + }); + + test("given a submission retry would wait until the deadline then it throws the last failure without submitting again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + errorAnswer(503, "No job will run", {}, { "Retry-After": "10" }), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds: 5_000, + }), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ statusCode: 503 }); + expect(api.submissions()).toHaveLength(1); + expect(api.waits).toEqual([]); + }); + + test("given a time limit of 0 then it submits, reads once and throws HouseholdCalculationTimeoutError", async () => { + // Given + const api = fakeApiV1( + inOrder([submittedAnswer(), calculationAnswer("running")]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds: 0, + }), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationTimeoutError); + expect(failure).toMatchObject({ lastStatus: "running" }); + expect(api.reads()).toHaveLength(1); + }); + + test("given the submission's connection fails after sending then it throws without submitting again", async () => { + // Given + const connectionLost = new PublicApiUnavailableError( + "The Public API could not be reached.", + 502, + "unreachable", + ); + const api = fakeApiV1(inOrder([connectionLost])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBe(connectionLost); + expect(api.submissions()).toHaveLength(1); + }); + + test("given the submission's answer is lost while it arrives then it throws without submitting again", async () => { + // Given + const api = fakeApiV1(inOrder([lostBodyAnswer(202)])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(PublicApiUnavailableError); + expect(failure).toMatchObject({ requestMayHaveArrived: true }); + expect(api.submissions()).toHaveLength(1); + }); + + test("given the submission answers 429 then it throws without submitting again", async () => { + // Given + const api = fakeApiV1(inOrder([errorAnswer(429, "Too many requests")])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toMatchObject({ statusCode: 429 }); + expect(api.submissions()).toHaveLength(1); + }); + + test("given the submission answers 503 for 90 seconds then it throws the last answer", async () => { + // Given + const api = fakeApiV1(() => errorAnswer(503, "No job will run")); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ statusCode: 503 }); + expect(api.submissions().at(-1)?.atMilliseconds).toBe(90_000); + expect(api.submissions()).toHaveLength(46); + }); + + test("given a read's answer is lost while it arrives then it reads again", async () => { + // Given + const api = fakeApiV1( + inOrder([submittedAnswer(), lostBodyAnswer(200), succeededAnswer()]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.reads()).toHaveLength(2); + }); + + test("given the credential cannot be obtained for a read then it reads again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + new PublicApiUnavailableError( + "Could not obtain a credential for the Public API.", + 502, + "credential_unavailable", + ), + succeededAnswer(), + ]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.reads()).toHaveLength(2); + }); + + test("given API v1 is no longer configured when it reads then it throws without reading again", async () => { + // Given + const notConfigured = new PublicApiUnavailableError( + "The Public API is not configured on this deployment.", + 503, + "not_configured", + ); + const api = fakeApiV1(inOrder([submittedAnswer(), notConfigured])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBe(notConfigured); + expect(api.reads()).toHaveLength(1); + }); + + test("given a read answers 429 with Retry-After then it waits that many seconds", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + errorAnswer(429, "Too many requests", {}, { "Retry-After": "5" }), + succeededAnswer(), + ]), + ); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(api.waits).toEqual([2_000, 5_000]); + }); + + test("given a Retry-After that is a date then it waits one interval", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + errorAnswer( + 503, + "Storage is unavailable", + {}, + { "Retry-After": "Sat, 28 Nov 2026 12:00:00 GMT" }, + ), + succeededAnswer(), + ]), + ); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(api.waits).toEqual([2_000, 2_000]); + }); + + test.each([ + [ + "another calculation's ID", + () => + calculationAnswer( + "running", + {}, + "00000000-0000-4000-8000-000000000000", + ), + ], + ["an unknown status", () => calculationAnswer("queued")], + ["a failure without its error", () => calculationAnswer("failed")], + ["a success without its result", () => calculationAnswer("succeeded")], + ])( + "given a read answer with %s then it throws HouseholdCalculationRefusedError", + async (_description, unreadableAnswer) => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), unreadableAnswer()])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ + statusCode: 200, + calculationId: CALCULATION_ID, + }); + expect(api.reads()).toHaveLength(1); + }, + ); + + test("given a failure without a code then HouseholdCalculationFailedError has a null code", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + calculationAnswer("failed", { + error: { + code: null, + message: "household_function_error: worker ran out of memory", + input_errors: [], + spm_error: null, + }, + }), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationFailedError); + expect(failure).toMatchObject({ + code: null, + message: "household_function_error: worker ran out of memory", + inputErrors: [], + }); + }); + + test("given the signal aborts while an answer arrives then it rejects with the abort reason", async () => { + // Given + const controller = new AbortController(); + const callerLeft = new Error("The caller went away."); + // Built when the submission is sent; the caller aborts only when the + // helper starts reading the answer's body. + const abortingAnswer = () => + new Response( + new ReadableStream( + { + pull(streamController) { + controller.abort(callerLeft); + streamController.error(new DOMException("aborted", "AbortError")); + }, + }, + { highWaterMark: 0 }, + ), + { status: 202 }, + ); + const api = fakeApiV1(() => abortingAnswer()); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + signal: controller.signal, + }), + ); + + // Then + expect(failure).toBe(callerLeft); + expect(api.submissions()).toHaveLength(1); + }); + test.each([ + [ + "succeeded", + () => succeededAnswer(), + async (outcome: Promise) => { + await expect(outcome).resolves.toMatchObject({ + household: CALCULATED_US_SITUATION, + }); + }, + ], + [ + "failed", + () => + calculationAnswer("failed", { + error: { + code: "invalid_household", + message: "The household has no people.", + input_errors: [], + spm_error: null, + }, + }), + async (outcome: Promise) => { + await expect(outcome).rejects.toBeInstanceOf( + HouseholdCalculationFailedError, + ); + }, + ], + ] as const)( + "given the submission answers that the calculation already %s then it reads it at once", + async (status, readAnswer, checkOutcome) => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(status), readAnswer()])); + + // When + const outcome = api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + await checkOutcome(outcome); + expect(api.reads()).toHaveLength(1); + expect(api.waits).toEqual([]); + }, + ); + + test("given a time limit that is not a whole number then the submission's timeout is whole milliseconds", async () => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), succeededAnswer()])); + + // When + const calculated = await api.calculator.calculateHousehold( + US_REFORM_REQUEST, + { timeLimitMilliseconds: 45_000.5 }, + ); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.submissions()[0].options?.timeoutMilliseconds).toBe(45_001); + }); + + test("given an infinite time limit then the submission's timeout is the longest a timer can wait", async () => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), succeededAnswer()])); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds: Number.POSITIVE_INFINITY, + }); + + // Then + expect(api.submissions()[0].options?.timeoutMilliseconds).toBe(2 ** 31 - 1); + }); + test.each([ + ["answers 503", () => errorAnswer(503, "Storage is unavailable")], + [ + "cannot reach API v1", + () => + new PublicApiUnavailableError( + "The Public API could not be reached.", + 502, + "unreachable", + ), + ], + ])( + "given a read at the deadline %s then it throws HouseholdCalculationTimeoutError without reading again", + async (_description, failedRead) => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), failedRead()])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds: 2_000, + }), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationTimeoutError); + expect(failure).toMatchObject({ lastStatus: "pending" }); + expect(api.reads()).toHaveLength(1); + }, + ); + + test("given reads cannot reach API v1 for 90 seconds then it throws the last failure", async () => { + // Given + const unreachable = new PublicApiUnavailableError( + "The Public API could not be reached.", + 502, + "unreachable", + ); + const api = fakeApiV1( + submissionThenEveryRead(submittedAnswer, () => unreachable), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBe(unreachable); + expect(api.reads().at(-1)?.atMilliseconds).toBe(90_000); + expect(api.reads()).toHaveLength(45); + }); +}); + +describe("calculateHousehold with its own timer", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + function calculatorWithTimer(answers: ScriptedAnswer[]) { + const answerFor = inOrder(answers); + const fetchFromServer = vi.fn(async (request: PublicApiRequest) => { + const answer = answerFor(request); + if (answer instanceof Error) { + throw answer; + } + return answer; + }); + const calculator = createHouseholdCalculator({ + forwarder: { fetchFromServer }, + now: () => Date.now(), + }); + return { calculator, fetchFromServer }; + } + + test("given no wait of its own then it reads after 2 seconds", async () => { + // Given + vi.useFakeTimers(); + const { calculator, fetchFromServer } = calculatorWithTimer([ + submittedAnswer(), + succeededAnswer(), + ]); + + // When + const calculation = calculator.calculateHousehold(US_REFORM_REQUEST); + await vi.advanceTimersByTimeAsync(1_999); + const requestsBeforeTheInterval = fetchFromServer.mock.calls.length; + await vi.advanceTimersByTimeAsync(1); + const calculated = await calculation; + + // Then + expect(requestsBeforeTheInterval).toBe(1); + expect(fetchFromServer).toHaveBeenCalledTimes(2); + expect(calculated.calculationId).toBe(CALCULATION_ID); + }); + + test("given the signal aborts during its own wait then it rejects at once and leaves no timer", async () => { + // Given + vi.useFakeTimers(); + const controller = new AbortController(); + const callerLeft = new Error("The caller went away."); + const { calculator, fetchFromServer } = calculatorWithTimer([ + submittedAnswer(), + ]); + + // When + const calculation = failureOf( + calculator.calculateHousehold(US_REFORM_REQUEST, { + signal: controller.signal, + }), + ); + await vi.advanceTimersByTimeAsync(500); + controller.abort(callerLeft); + const failure = await calculation; + + // Then + expect(failure).toBe(callerLeft); + expect(vi.getTimerCount()).toBe(0); + expect(fetchFromServer).toHaveBeenCalledTimes(1); + }); +});