Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions packages/public-api-forwarding/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
111 changes: 104 additions & 7 deletions packages/public-api-forwarding/src/forward.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<PublicApiUnavailableReason> = 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<Value>(
promise: Promise<Value>,
signal: AbortSignal | undefined,
): Promise<Value> {
if (signal === undefined) {
return promise;
}
return new Promise<Value>((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(
Expand Down Expand Up @@ -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",
),
};
}

Expand All @@ -321,6 +398,7 @@ export function createPublicApiForwarder(
error: new PublicApiUnavailableError(
"The Public API is not configured on this deployment.",
503,
"not_configured",
),
};
}
Expand All @@ -340,6 +418,7 @@ export function createPublicApiForwarder(
error: new PublicApiUnavailableError(
"Could not obtain a credential for the Public API.",
502,
"credential_unavailable",
),
};
}
Expand Down Expand Up @@ -466,7 +545,15 @@ export function createPublicApiForwarder(
publicApiRequest: PublicApiRequest,
serverOptions: ServerRequestOptions = {},
): Promise<Response> {
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;
}
Expand All @@ -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",
};
Expand All @@ -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(
Expand All @@ -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);
Expand Down
Loading
Loading