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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions docs/INTEGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,27 @@ Preflight results include:
Existing submit methods are unchanged; preflight is optional and does not
require live signing credentials beyond a source `publicKey` (or `secretKey`).

## External request timeouts

Every external request the SDK, keeper, appraisal client and Drand tooling
make is bounded by one shared default, `DEFAULT_REQUEST_TIMEOUT_MS`
(**10 000 ms**, exported from `@sub-rosa/time`), so a hung peer cannot stall a
component indefinitely. A per-call override must be an integer between
**100 and 300 000 ms**; `0`, `NaN` and out-of-range values are rejected
rather than silently disabling the bound.

| Client | Where the bound applies | Override |
| ------ | ----------------------- | -------- |
| `SubRosaClient` (Soroban RPC, also used by the keeper) | each RPC request | `rpcTimeoutMs` |
| `StatusClient` (keeper status API) | each status request | `timeoutMs` |
| `createPaidFetch` (appraisal API) | the probe and the paid retry | `requestTimeoutMs` |
| `drand-tools` quicknet helpers | each Drand HTTP request | none (default) |

`fetchWithTimeout` aborts the request and rejects with `RequestTimeoutError`
(never including the URL, which may carry credentials). The timer covers
connecting and receiving response headers; `confirmTimeout` is a separate,
longer bound on transaction finality polling.

## Auditor identity recovery CLI

For pilots that need machine-readable selective-disclosure evidence, recover
Expand Down
24 changes: 22 additions & 2 deletions packages/sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ import {
type PasskeySessionBinding,
} from "./network.js";
import {
resolveRequestTimeoutMs,
resolveTimeContext,
systemTime,
type Clock,
Expand Down Expand Up @@ -106,6 +107,11 @@ export interface SubRosaClientConfig {
* using an external submitter. Must be at least 100. Default: 1_500.
*/
pollInterval?: number;
/**
* Timeout (ms) for each Soroban RPC request. Integer between 100 and 300_000.
* Default: the shared `DEFAULT_REQUEST_TIMEOUT_MS` (10_000).
*/
rpcTimeoutMs?: number;
/** Injectable wall clock and scheduler. Default: systemTime. */
time?: PartialTimeContext;
/**
Expand Down Expand Up @@ -204,6 +210,7 @@ export class SubRosaClient {
readonly #submitter?: TransactionSubmitter;
readonly #confirmTimeout: number;
readonly #pollInterval: number;
readonly #rpcTimeoutMs: number;
readonly #assetConfig?: import("./asset-config.js").AssetConfig;
readonly #clock: Clock;
readonly #scheduler: Scheduler;
Expand Down Expand Up @@ -235,6 +242,15 @@ export class SubRosaClient {
);
}

let rpcTimeoutMs: number;
try {
rpcTimeoutMs = resolveRequestTimeoutMs(config.rpcTimeoutMs);
} catch (error) {
throw new SubRosaClientConfigError(
`rpcTimeoutMs: ${error instanceof Error ? error.message : String(error)}`,
);
}

const keypair = config.secretKey
? Keypair.fromSecret(config.secretKey)
: undefined;
Expand All @@ -251,13 +267,14 @@ export class SubRosaClient {
this.#submitter = config.submitter;
this.#confirmTimeout = confirmTimeout;
this.#pollInterval = pollInterval;
this.#rpcTimeoutMs = rpcTimeoutMs;
this.#assetConfig = config.assetConfig;

const time = resolveTimeContext(systemTime, config.time);
this.#clock = time.clock;
this.#scheduler = time.scheduler;
this.#session = config.session;
this.#server = config._server ?? new rpc.Server(config.rpcUrl, { allowHttp });
this.#server = config._server ?? new rpc.Server(config.rpcUrl, { allowHttp, timeout: rpcTimeoutMs });

if (config._sleep) this.#sleep = config._sleep;
else this.#sleep = (ms) => this.#scheduler.sleep(ms);
Expand Down Expand Up @@ -393,7 +410,10 @@ export class SubRosaClient {
{ cause: e },
);
}
const server = new rpc.Server(this.#rpcUrl, { allowHttp: this.#allowHttp });
const server = new rpc.Server(this.#rpcUrl, {
allowHttp: this.#allowHttp,
timeout: this.#rpcTimeoutMs,
});
const deadline = this.#clock.nowMs() + this.#confirmTimeout;
let lastStatus = "NOT_FOUND";
while (this.#clock.nowMs() < deadline) {
Expand Down
15 changes: 15 additions & 0 deletions packages/sdk/src/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,21 @@ describe("SubRosaClientConfig validation", () => {
}
});

it("rejects an rpcTimeoutMs outside the shared 100-300000 ms range", () => {
for (const rpcTimeoutMs of [0, 99, 1.5, Number.NaN, 300_001]) {
assert.throws(
() => new SubRosaClient({ ...BASE_CONFIG, rpcTimeoutMs }),
(e) => e instanceof SubRosaClientConfigError && /rpcTimeoutMs/.test(e.message),
String(rpcTimeoutMs),
);
}
});

it("accepts the default and an explicit rpcTimeoutMs", () => {
assert.doesNotThrow(() => new SubRosaClient(BASE_CONFIG));
assert.doesNotThrow(() => new SubRosaClient({ ...BASE_CONFIG, rpcTimeoutMs: 2_500 }));
});

it("accepts confirmTimeout = 1000", () => {
assert.doesNotThrow(
() => new SubRosaClient({ ...BASE_CONFIG, confirmTimeout: 1000 }),
Expand Down
5 changes: 3 additions & 2 deletions packages/sdk/src/mainnet-readiness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
TransactionBuilder,
} from "@stellar/stellar-sdk";
import type { BidState, GlobalConfig, Round, Status } from "@sub-rosa/round-bindings";
import { DEFAULT_REQUEST_TIMEOUT_MS } from "@sub-rosa/time";

import type { SubRosaClient } from "./client.js";
import {
Expand Down Expand Up @@ -465,7 +466,7 @@ export function createSacBalanceReader(
tokenSacId: string,
sourcePublicKey: string,
): (address: string) => Promise<bigint> {
const server = new rpc.Server(rpcUrl);
const server = new rpc.Server(rpcUrl, { timeout: DEFAULT_REQUEST_TIMEOUT_MS });
const sac = new Contract(tokenSacId);
return async (address: string): Promise<bigint> => {
const source = new Account(sourcePublicKey, "0");
Expand Down Expand Up @@ -967,7 +968,7 @@ export async function runMainnetReadiness(
}

// ── Live: read the deployment through the read-only client ───────────────
const rpcServer = deps.rpc ?? new rpc.Server(input.rpcUrl);
const rpcServer = deps.rpc ?? new rpc.Server(input.rpcUrl, { timeout: DEFAULT_REQUEST_TIMEOUT_MS });

try {
await rpcServer.getHealth();
Expand Down
4 changes: 2 additions & 2 deletions packages/sdk/src/status-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
// and return stable typed JSON (see ../status.ts).

import { normalizeError } from "@sub-rosa/logging/errors";
import { systemScheduler, type Scheduler } from "@sub-rosa/time";
import { DEFAULT_REQUEST_TIMEOUT_MS, systemScheduler, type Scheduler } from "@sub-rosa/time";
import { assertNoUrlCredentials } from "./network.js";
import type {
KeeperHealthResponse,
Expand Down Expand Up @@ -120,7 +120,7 @@ export class KeeperStatusClient {
this.baseURL = opts.baseURL;
this.fetchImpl = opts.fetchImpl ?? globalThis.fetch;
this.headers = opts.headers ?? {};
this.timeoutMs = opts.timeoutMs ?? 10_000;
this.timeoutMs = opts.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
this.scheduler = opts.scheduler ?? systemScheduler;
this.contractId = opts.contractId;
this.roundId = opts.roundId === undefined ? undefined : String(opts.roundId);
Expand Down
2 changes: 1 addition & 1 deletion packages/time/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
".": "./src/index.ts"
},
"scripts": {
"test": "node --import tsx --test src/clock.test.ts src/scheduler.test.ts src/fake.test.ts src/boundary.test.ts",
"test": "node --import tsx --test src/clock.test.ts src/scheduler.test.ts src/fake.test.ts src/boundary.test.ts src/request-timeout.test.ts",
"typecheck": "tsc --noEmit -p tsconfig.json"
},
"devDependencies": {
Expand Down
9 changes: 9 additions & 0 deletions packages/time/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,12 @@ export {
} from "./system.js";
export { FakeClock } from "./fake-clock.js";
export { FakeScheduler, createFakeTime } from "./fake-scheduler.js";
export {
DEFAULT_REQUEST_TIMEOUT_MS,
MAX_REQUEST_TIMEOUT_MS,
MIN_REQUEST_TIMEOUT_MS,
RequestTimeoutError,
fetchWithTimeout,
resolveRequestTimeoutMs,
} from "./request-timeout.js";
export type { FetchWithTimeoutOptions } from "./request-timeout.js";
103 changes: 103 additions & 0 deletions packages/time/src/request-timeout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { describe, it } from "node:test";
import assert from "node:assert/strict";

import {
DEFAULT_REQUEST_TIMEOUT_MS,
RequestTimeoutError,
createFakeTime,
fetchWithTimeout,
resolveRequestTimeoutMs,
} from "./index.js";

/** A fetch that never answers and rejects when its signal aborts. */
const hangingFetch: typeof fetch = (_input, init) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true });
});

describe("shared request timeout", () => {
it("defaults to a single 10s bound", () => {
assert.equal(DEFAULT_REQUEST_TIMEOUT_MS, 10_000);
assert.equal(resolveRequestTimeoutMs(), 10_000);
assert.equal(resolveRequestTimeoutMs(2_500), 2_500);
});

it("rejects values that would disable or distort the bound", () => {
for (const bad of [0, -1, 99, 1.5, Number.NaN, Number.POSITIVE_INFINITY, 300_001]) {
assert.throws(() => resolveRequestTimeoutMs(bad), RangeError, String(bad));
}
});

it("aborts a hung request with RequestTimeoutError after the default timeout", async () => {
const { scheduler } = createFakeTime();
const pending = fetchWithTimeout("https://example.invalid/x", {}, { fetchImpl: hangingFetch, scheduler });
const outcome = pending.then(
() => "resolved",
(e: unknown) => e,
);

scheduler.advance(DEFAULT_REQUEST_TIMEOUT_MS - 1);
await Promise.resolve();
assert.equal(scheduler.pendingCount(), 1, "still waiting just before the deadline");

scheduler.advance(1);
const error = await outcome;
assert.ok(error instanceof RequestTimeoutError);
assert.equal(error.timeoutMs, DEFAULT_REQUEST_TIMEOUT_MS);
assert.match(error.message, /timed out after 10000ms/);
assert.doesNotMatch(error.message, /example\.invalid/, "must not leak the URL");
});

it("honours a per-call timeout override", async () => {
const { scheduler } = createFakeTime();
const outcome = fetchWithTimeout("https://x.invalid", {}, { fetchImpl: hangingFetch, scheduler, timeoutMs: 250 }).then(
() => "resolved",
(e: unknown) => e,
);
scheduler.advance(250);
const error = await outcome;
assert.ok(error instanceof RequestTimeoutError);
assert.equal(error.timeoutMs, 250);
});

it("clears the timer when the request succeeds", async () => {
const { scheduler } = createFakeTime();
const ok: typeof fetch = async () => new Response("{}", { status: 200 });
const res = await fetchWithTimeout("https://x.invalid", {}, { fetchImpl: ok, scheduler });
assert.equal(res.status, 200);
assert.equal(scheduler.pendingCount(), 0);
});

it("clears the timer and rethrows a non-timeout failure unchanged", async () => {
const { scheduler } = createFakeTime();
const boom = new Error("connect refused");
const failing: typeof fetch = async () => {
throw boom;
};
await assert.rejects(fetchWithTimeout("https://x.invalid", {}, { fetchImpl: failing, scheduler }), (e) => e === boom);
assert.equal(scheduler.pendingCount(), 0);
});

it("preserves a caller abort instead of reporting a timeout", async () => {
const { scheduler } = createFakeTime();
const caller = new AbortController();
const reason = new Error("caller cancelled");
const outcome = fetchWithTimeout("https://x.invalid", { signal: caller.signal }, { fetchImpl: hangingFetch, scheduler }).then(
() => "resolved",
(e: unknown) => e,
);
caller.abort(reason);
assert.equal(await outcome, reason);
assert.equal(scheduler.pendingCount(), 0);
});

it("rejects immediately when the caller signal is already aborted", async () => {
const { scheduler } = createFakeTime();
const caller = new AbortController();
caller.abort();
await assert.rejects(
fetchWithTimeout("https://x.invalid", { signal: caller.signal }, { fetchImpl: hangingFetch, scheduler }),
);
assert.equal(scheduler.pendingCount(), 0);
});
});
92 changes: 92 additions & 0 deletions packages/time/src/request-timeout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { systemScheduler } from "./system.js";
import type { Scheduler } from "./types.js";

/**
* Shared default timeout (ms) for every external request the SDK, keeper,
* appraisal client and Drand tooling make. One value, so a hung peer cannot
* stall one component indefinitely while another gives up.
*/
export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;

/** Smallest accepted per-request timeout override (ms). */
export const MIN_REQUEST_TIMEOUT_MS = 100;

/** Largest accepted per-request timeout override (ms). */
export const MAX_REQUEST_TIMEOUT_MS = 300_000;

/** Raised when an external request does not answer within its timeout. */
export class RequestTimeoutError extends Error {
readonly name = "RequestTimeoutError";
readonly timeoutMs: number;

constructor(timeoutMs: number) {
super(`request timed out after ${timeoutMs}ms`);
this.timeoutMs = timeoutMs;
}
}

/**
* Resolve a timeout override. `undefined` yields the shared default; anything
* that is not a finite integer within [MIN, MAX] throws a `RangeError` so a
* typo (`0`, `NaN`, `1e9`) can never silently disable the bound.
*/
export function resolveRequestTimeoutMs(value?: number): number {
if (value === undefined) return DEFAULT_REQUEST_TIMEOUT_MS;
if (
!Number.isInteger(value) ||
value < MIN_REQUEST_TIMEOUT_MS ||
value > MAX_REQUEST_TIMEOUT_MS
) {
throw new RangeError(
`request timeout must be an integer between ${MIN_REQUEST_TIMEOUT_MS} and ${MAX_REQUEST_TIMEOUT_MS} ms, got ${value}`,
);
}
return value;
}

export interface FetchWithTimeoutOptions {
/** Timeout in ms. Default: {@link DEFAULT_REQUEST_TIMEOUT_MS}. */
timeoutMs?: number;
/** Fetch implementation. Default: `globalThis.fetch`. */
fetchImpl?: typeof fetch;
/** Scheduler used for the timer. Default: the system scheduler. */
scheduler?: Scheduler;
}

/**
* `fetch` bounded by a timeout. The timer covers connecting and receiving the
* response headers; it aborts the request and rejects with
* {@link RequestTimeoutError}. A caller `init.signal` still cancels the request
* and its own abort reason is preserved. The error never includes the URL,
* which may carry credentials.
*/
export async function fetchWithTimeout(
input: Parameters<typeof fetch>[0],
init: RequestInit = {},
options: FetchWithTimeoutOptions = {},
): Promise<Response> {
const timeoutMs = resolveRequestTimeoutMs(options.timeoutMs);
const scheduler = options.scheduler ?? systemScheduler;
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
const callerSignal = init.signal ?? undefined;

if (callerSignal?.aborted) {
throw callerSignal.reason ?? new DOMException("Aborted", "AbortError");
}

const controller = new AbortController();
const timeoutError = new RequestTimeoutError(timeoutMs);
const onCallerAbort = () => controller.abort(callerSignal?.reason);
callerSignal?.addEventListener("abort", onCallerAbort, { once: true });
const timer = scheduler.setTimeout(() => controller.abort(timeoutError), timeoutMs);

try {
return await fetchImpl(input, { ...init, signal: controller.signal });
} catch (error) {
if (controller.signal.reason === timeoutError) throw timeoutError;
throw error;
} finally {
scheduler.clear(timer);
callerSignal?.removeEventListener("abort", onCallerAbort);
}
}
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading