fix(retry): Retry-After를 하한으로 지키고 그 위에 jitter를 더한다 #89
@@ -88,6 +88,14 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지
|
||||
- 옮기기 전: `src/platform/routing/`의 다른 파일이 features·contexts·apps·adapters·bootstrap·presentation·application을 import하거나, `context-route-module.ts`가 그 두 파일 밖의 제품 모듈을 import하면 FE-GATE-010(`check:architecture`)이 실패한다.
|
||||
- 옮기는 법: 그 파일을 제품 쪽(`src/apps`나 그 owner 곁)으로 옮긴다. routing에 descriptor가 정말 하나 더 필요하면 그 파일 이름을 새 규칙의 `to.pathNot`에 더한다. 폴더로 넓히지 않는다.
|
||||
- 옮긴 뒤 확인: `scripts/verify.sh script check:architecture`.
|
||||
- Browser RPC가 profile `maxRetryAfterMs`를 넘는 `Retry-After`에서 재시도하지 않는다. 전에는 그 값으로 잘라 더 일찍 다시 보냈다(REV-FE-0024).
|
||||
- 옮기기 전: `retryOwner: "FRONTEND_ADAPTER"`인 profile의 `maxRetryAfterMs`가 서버가 주는 힌트보다 작으면(0 포함) 재시도되던 호출이 그 힌트를 실은 실패에서 끝난다. 결과는 그 실패의 kind·code와 `retryAfterMs`다. 남은 deadline도 모자라 `RPC_RETRY_BUDGET_EXHAUSTED`로 끝나던 호출도 이제 그 실패의 code로 끝난다.
|
||||
- 옮기는 법: 자기 서버가 주는 힌트의 최댓값까지 `maxRetryAfterMs`를 올리고(하드 상한은 `BROWSER_RPC_HARD_LIMITS`), operation `totalDeadlineMs`를 「보낼 수 있는 시도(`maxAttempts`번) 시간의 합 + 재시도마다 max(그 차례 backoff, 힌트 + jitter 상한 2초)의 합」보다 길게 둔다. 기다리지 않을 것이면 그대로 둔다.
|
||||
- 옮긴 뒤 확인: 자기 profile과 deadline으로 상한과 같은 힌트는 재시도되고 넘는 힌트는 재시도되지 않는지 시험한다.
|
||||
- 재개형 업로드·realtime 재연결·bounded poll·Browser RPC가 서버 힌트 위에 jitter(2초 미만)를 더해 다시 보낸다(REV-FE-0024).
|
||||
- 옮기기 전: 대기가 힌트와 같거나, 힌트보다 늦은 로컬 지연과 같다고 단언한 시험이 실패할 수 있다. 실제 대기가 `maxDelayMs`·`maxIntervalMs`·`maxRetryAfterMs`보다 jitter만큼 길 수 있다. 상한 안의 힌트만 받던 설정도 다시 보낸 시도에 남는 시간이 줄어 timeout이 새로 날 수 있다.
|
||||
- 옮기는 법: 시간 예산(`totalDeadlineMs`, `maxElapsedMs`)을 재시도마다 더해지는 jitter 상한 2초만큼 여유 있게 둔다. 시험에 `random: () => 0`을 넣으면 jitter가 0이다. 그 밖에는 하한과 범위로 단언한다.
|
||||
- 옮긴 뒤 확인: `scripts/verify.sh script test:unit`.
|
||||
|
||||
### 보안·계약 변경
|
||||
|
||||
@@ -124,6 +132,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지
|
||||
| [계약] | FE-GATE-009의 `test:a11y`가 `playwright.a11y.config.ts`로 돌아 결과 폴더·HTML report·`results.xml`을 `artifacts/tests/a11y/`에 쓴다. 전에는 e2e 설정을 그대로 써서, merge browser job이 008 다음 009를 돌고 올린 e2e 증거가 009 실행의 것이었다. FE-GATE-009 증거에 a11y `results.xml`·`report/index.html`(producer `test-a11y`)이 들어간다. 게이트 밖 `test:e2e:dev`는 `artifacts/tests/e2e-dev/`에 쓴다. 새 시험이 package script가 부르는 Playwright 설정끼리·게이트 명령끼리 결과 경로가 겹치거나, 게이트 명령이 쓰는 JUnit·report가 그 게이트의 증거가 아니면 실패한다. 제거 fixture 사본은 두 새 결과 폴더를 복사하지 않고, 같은 시험이 각 Playwright 설정의 결과 폴더가 그 제외 목록에 드는지 본다. a11y 설정은 FE-GATE-029가 읽도록 `testDir`을 글자로 둔다. 위 "먼저 할 일" (1106 영역 11의 3.2 (3) 증거 읽기 주의) | `package.json`, `playwright.a11y.config.ts`, `playwright.dev.config.ts`, `config/ci/gates.json`, `config/repository-layout.json`, `scripts/lib/removal-fixture.ts`, `tests/unit/playwright-result-paths.test.ts`, `tests/unit/removal-fixture.test.ts`, `tests/unit/ungated-tests.test.ts`, `tests/helpers/playwright-run-isolation.ts`, `tests/unit/ci-workflow-generation.test.ts`, `docs/testing/taxonomy.md`, `docs/work/reference/decisions.md` | `ede99cb9` |
|
||||
| [계약] | `dependency-cache` 단계를 main job(`main_gate`)에도 둔다. 키·경로·main run만 저장·frozen install은 merge job과 같다. release·promotion·provider job은 그대로 거절한다. 위 `7ed0af3d` 행의 「merge job 셋에만」을 바꾼다(decisions.md FE-7) | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `.gitea/workflows/quality-gates.yml`, `tests/unit/ci-workflow-generation.test.ts`, `docs/operations/ci-quality-gates.md` | `d254d70a` |
|
||||
| [계약] | FE-GATE-005의 명령이 `test:coverage`·`check:scale:pr` 둘이 된다. `tests/unit`·`tests/contract`의 JUnit 증거(`unit.xml`·`contract.xml`, 이름·형식 그대로)는 coverage 실행 안의 reporter가 쓰고, 두 증거의 producer는 `test-coverage`다. 한 폴더에서 시험 파일이 하나도 돌지 않거나 보고서가 그 폴더에서 돈 파일과 다른 파일을 담으면 그 실행이 실패한다. unit·contract 시험은 이제 coverage 계측 아래에서만 돈다. FE-GATE-004·006·007은 자기 실행을 그대로 둔다(decisions.md FE-4) | `config/ci/gates.json`, `package.json`, `scripts/lib/coverage-bundle-junit-reporter.ts`, `scripts/lib/feature-scaffold-drill.ts`, `tests/unit/coverage-bundle-junit-reporter.test.ts`, `docs/operations/ci-quality-gates.md` | `6cba1f50` |
|
||||
| [계약] | 서버 힌트(`Retry-After`, SSE `retry`)를 반영하는 재시도 지연을 kernel `delayAfterRetryHint` 하나로 합친다. 힌트가 하한이고 그 위에 한도 있는 jitter를 더하며, 부르는 쪽 상한을 넘으면 다시 보내지 않는다. Browser RPC는 힌트를 잘라 먼저 보내던 동작이 없어지고 선택 칸 `random`(`BrowserRpcRuntimeDependencies`)을 받는다. 재개형 업로드·realtime 재연결·bounded poll은 힌트 시각에 몰리지 않는다. HTTP V3 동작은 같다. scale-architecture 13.3절·계약 16.1 표·VD-28 보완 절을 맞춘다. 위 "먼저 할 일" (REV-FE-0024) | `src/adapters/platform/retry-after.ts`, `src/adapters/browser-rpc/browser-rpc-runtime.ts`, `src/adapters/http/http-retry-lifecycle.ts`, `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts`, `src/adapters/realtime/`, `docs/architecture/scale-architecture.md`, `docs/architecture/backend-api-and-server-state-contract.md` | `4f6e7729`, `8d1c45c3`, `6e47167a`, `533b1779` |
|
||||
| [계약] | `check:ci:gating`(FE-GATE-029)이 Playwright 실행의 `--grep`·`--grep-invert`·파일 필터를 읽는다. testDir은 필터 없는 gated 실행이 있거나, `--grep-invert P` 실행마다 같은 testDir을 `--grep P`(같은 글자)로 도는 gated 실행이 있을 때만 게이트 안으로 센다. 파일 필터가 있는 실행, `--grep`·`--grep-invert`를 합쳐 둘 이상 쓴 실행, 설정(또는 그 설정이 import한 설정)에 `grep`·`grepInvert`가 있는 실행은 부분 실행으로 센다. 그 testDir의 게이트 밖 파일은 testDir·실행·빠진 짝을 대는 한 줄로 실패한다. 전에는 009의 Playwright 실행을 빼도 통과해, 시험이 모두 `@a11y`인 `tests/e2e/accessibility.spec.ts`가 어느 게이트에서도 돌지 않았다. `-c X`·`-cX`·`--config=X`로 고른 설정도 이제 읽는다(전에는 e2e 설정의 testDir로 셌다). 위 "먼저 할 일" | `scripts/lib/playwright-test-args.ts`, `scripts/lib/ungated-tests.ts`, `scripts/check-ci-gating.ts`, `playwright.a11y.config.ts`, `tests/unit/playwright-test-args.test.ts`, `tests/unit/ungated-tests.test.ts`, `tests/unit/playwright-result-paths.test.ts`, `docs/operations/ci-quality-gates.md` | `32982e55` |
|
||||
| [보안] | telemetry payload 정제가 복사하는 값의 총수를 `maxNodes`(기본 512)로 막는다. 같은 객체를 여러 key가 가리키는 payload(정규화된 엔티티 graph 등)를 경로마다 따로 복사해, `emit` 한 번이 호출 스택을 수 초 막거나 heap OOM으로 탭을 죽였다. 여러 경로가 가리키는 객체의 key는 한 번만 읽는다. 순회가 너비 우선이 되어 상한이 차면 얕은 필드가 남고 깊은 값이 `[truncated]`가 된다. 복사본 객체의 key 순서가 원본 순서가 된다(전에는 거꾸로, fingerprint는 그대로). 깊이 제한 시험이 잘린 모양과 순환 payload를 단언한다 | `src/platform/telemetry/redact-telemetry.ts`, `src/platform/telemetry/telemetry-pipeline.ts`, `tests/platform/telemetry/redact-telemetry.test.ts`, `config/scale/feature-shape-ceilings.json` | `d406c10b`, `0190b631` |
|
||||
| [계약] | `mapTransportFailure`가 `JsonBudgetExceededError`의 own data `violation`이 `"invalid-json"`이면 `response.invalid`로 분류한다. 전에는 `parseBoundedJson`이 JSON이 아닌 응답에 던진 오류가 `response.too-large`가 되어 날 `SyntaxError`(`response.invalid`)와 갈렸다. 두 kind의 category(`contract`)·retryability(`never`)는 같다. `violation`이 accessor면 부르지 않고 `response.too-large`로 둔다. 시험 표에 fan-out 초과·`TimeoutError`·invalid-json 줄을 더한다 | `src/platform/errors/platform-errors.ts`, `tests/platform/errors/platform-errors.test.ts` | `a934554d` |
|
||||
|
||||
@@ -676,3 +676,10 @@ common runtime status는 `AVAILABLE_NOT_COMPOSED`다. 위의 미완료 promotion
|
||||
- [RFC 8030](https://www.rfc-editor.org/rfc/rfc8030)
|
||||
- [RFC 8291](https://www.rfc-editor.org/rfc/rfc8291)
|
||||
- [RFC 8292](https://www.rfc-editor.org/rfc/rfc8292)
|
||||
|
||||
## 보완
|
||||
|
||||
> 위 본문은 고치지 않았다(`docs/README.md` 2절). 7절의 not-before 규칙은 아래처럼 바뀌었다.
|
||||
|
||||
- 2026-11-22: 7절의 「valid server hint는 local delay보다 이른 retry를 금지하는 not-before bound」를 `docs/architecture/scale-architecture.md` 13.3절 규칙으로 넓힌다. reconnect와 poll은 hint를 하한으로 두고 그 위에 한도 있는 jitter를 더한다. 전에는 local delay와 hint 중 큰 값을 그대로 써서, 같은 hint를 받은 client가 같은 순간에 다시 붙었다. 실제 대기는 「hint + jitter」와 local delay 중 늦은 쪽이다.
|
||||
- 2026-11-22: 같은 절의 「implementation max/remaining elapsed budget을 넘으면 낮춰 clamp하지 않고 종료」는 hint에 그대로 걸린다. max는 hint의 상한이라 실제 대기는 max보다 jitter만큼 길 수 있고, jitter는 hint 뒤에 남는 elapsed budget의 절반까지만 쓴다. 소유자가 직접 고른 것이 아니라 리뷰 담당이 자율 운영 규칙으로 정한 결정이다(카드 REV-FE-0024의 2026-11-22 정정, 안 A).
|
||||
|
||||
@@ -732,7 +732,7 @@ query invalidate hint로만 쓸지 operation별 reducer contract가 필요하다
|
||||
|---|---|---|
|
||||
| KEYED 명령 자동 재시도 | 전송 전 실패만 재시도한다. 전송 뒤 실패는 재시도하지 않고 `MAYBE_APPLIED`다. 응답으로는 재시도하지 않는다. 예외: Envelope operation이 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거절, 백엔드 §2가 같은 키 재전송을 요구)을 받으면 `retryBudget` 안에서 같은 키로 다시 보낸다 (`src/adapters/http/http-retry-lifecycle.ts` `canRetryTransport`, `isRetryableSemantics`, `backend-envelope.ts` `invitesKeyedResend`) | `KEYED_COMMAND`는 유효한 키가 있고 profile `retryOwner`가 `FRONTEND_ADAPTER`면 `retryableFailures`에서 같은 키로 다시 보낸다 (`src/adapters/browser-rpc/browser-rpc-runtime.ts` `shouldRetry`) |
|
||||
| 재시도 횟수 상한 | min(계약 `retryBudget`, `MAX_RETRY_ATTEMPTS`, 2) (`http-execution-v3.ts` `retryCeiling`) | profile `maxAttempts`(시도 횟수), 하드 상한 4 (`src/contracts/browser-rpc.ts` `BROWSER_RPC_HARD_LIMITS`) |
|
||||
| `Retry-After` | 5초를 넘으면 재시도하지 않는다. 이하면 hint에 jitter를 더해 기다린다 (`http-retry-lifecycle.ts` `retryDelayFor`) | profile `maxRetryAfterMs`로 잘라 max(backoff, hint)만큼 기다린다. 하드 상한 60초 (`browser-rpc-runtime.ts` `retryDelay`) |
|
||||
| `Retry-After` | 5초를 넘으면 재시도하지 않는다. 이하면 hint에 jitter를 더해 기다린다(`docs/architecture/scale-architecture.md` 13.3절) (`http-retry-lifecycle.ts` `retryDelayFor`) | profile `maxRetryAfterMs`를 넘으면 재시도하지 않는다. 이하면 「hint + jitter」와 backoff 중 늦은 쪽까지 기다린다(`docs/architecture/scale-architecture.md` 13.3절). 하드 상한 60초 (`browser-rpc-runtime.ts` `shouldRetry`, `retryDelay`) |
|
||||
| `REQUEST_TIMEOUT_MS` | 상한이다. 계약 `totalDeadlineMs`를 줄이기만 한다 (`runtime-adapters.ts` `requestDeadlineCeilingMs`) | 쓰지 않는다. operation `totalDeadlineMs`만 쓴다. 하드 상한 30분 |
|
||||
|
||||
결과 불명 뒤 사용자 재전송은 전송과 무관하게 같은 intent·같은 키를 쓴다
|
||||
|
||||
@@ -84,7 +84,7 @@ adapter가 presentation까지 들어온다.
|
||||
|
||||
- `src/adapters/platform/**` — 여러 adapter 그룹이 함께 쓰는 동작 장치:
|
||||
시스템 시계, 공용 abort 기본 요소, 용량 상한 가드, IndexedDB 연결·트랜잭션
|
||||
헬퍼, `Retry-After` 파싱, JSON 멤버 스캐너. bootstrap만 쓰는 platform
|
||||
헬퍼, `Retry-After` 파싱과 재시도 지연, JSON 멤버 스캐너. bootstrap만 쓰는 platform
|
||||
서비스 두 개도 여기 있다: 브라우저 lifecycle runtime과 mutation intent
|
||||
factory다(adapter는 이 둘을 import하지 않는다). kernel 파일은 동작 방식만
|
||||
소유한다. 이름, schema, 실패 코드, 관측 모양은 절대 소유하지 않는다.
|
||||
|
||||
@@ -566,6 +566,13 @@ C cannot retry after budget exhaustion
|
||||
|
||||
실제 재시도 시각은 서버가 알려 준 값에 한도가 있는 jitter(무작위 지연)를 합쳐 정한다.
|
||||
|
||||
HTTP V3, Browser RPC, 재개형 업로드, realtime 재연결, bounded poll이 같은 규칙(`src/adapters/platform/retry-after.ts`의 `delayAfterRetryHint`)을 쓴다.
|
||||
|
||||
- 서버 값이 하한이다. 「서버 값 + jitter」와 로컬 지연 중 늦은 쪽까지 기다린다.
|
||||
- jitter는 하한 위에 더한다. 창은 로컬 backoff 창과 서버 값의 4분의 1 중 큰 쪽이고, `RETRY_HINT_MAX_JITTER_MS`를 넘지 않는다. 남은 시간 예산을 건네는 호출처(Browser RPC, 재연결, poll)에서는 서버 값 뒤에 남는 예산의 절반까지만 쓴다. 나머지는 다시 보낸 시도가 답을 받을 시간이다.
|
||||
- 서버 값이 부르는 쪽 상한을 넘으면 다시 보내지 않는다. 잘라서 더 일찍 보내지 않는다. 상한은 서버 값에 걸리므로 실제 대기는 상한보다 jitter만큼 길 수 있다.
|
||||
- 상한 값과 실패 code는 각 adapter가 정한다.
|
||||
|
||||
## 14. 동시 실행 예산
|
||||
|
||||
interaction마다 동시에 보내는 물리 요청 수에 한도가 있다.
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
type FailureKind,
|
||||
} from "../../contracts/errors.ts";
|
||||
import type { RuntimeSchemaCodec } from "../../contracts/schema-registry.ts";
|
||||
import { delayAfterRetryHint } from "../platform/retry-after.ts";
|
||||
import { systemClock } from "../platform/system-clock.ts";
|
||||
import { decodeServerStreamLease } from "./transport.ts";
|
||||
import type {
|
||||
@@ -67,6 +68,8 @@ export type BrowserRpcRuntimeDependencies = Readonly<{
|
||||
transports: Readonly<Record<string, BrowserRpcTransport>>;
|
||||
generationFence?: BrowserRpcGenerationFence;
|
||||
clock?: ClockPort;
|
||||
/** Spreads the retry after a server hint. Defaults to `Math.random`. */
|
||||
random?: () => number;
|
||||
observations?: BrowserRpcObservationSink;
|
||||
}>;
|
||||
|
||||
@@ -112,6 +115,7 @@ export function createBrowserRpcRuntime(
|
||||
dependencies: BrowserRpcRuntimeDependencies,
|
||||
): BrowserRpcRuntime {
|
||||
const clock = dependencies.clock ?? systemClock;
|
||||
const random = dependencies.random ?? Math.random;
|
||||
const generationFence =
|
||||
dependencies.generationFence ?? stableGenerationFence;
|
||||
// RPC-RR-03 / RPC-03. Snapshot before validating — every registry, not just
|
||||
@@ -179,6 +183,7 @@ export function createBrowserRpcRuntime(
|
||||
isOutput,
|
||||
generationFence,
|
||||
clock,
|
||||
random,
|
||||
),
|
||||
});
|
||||
},
|
||||
@@ -289,6 +294,7 @@ async function executeUnary<Output>(
|
||||
isOutput: (value: unknown) => value is Output,
|
||||
generationFence: BrowserRpcGenerationFence,
|
||||
clock: ClockPort,
|
||||
random: () => number,
|
||||
): Promise<Result<Output, AppFailure>> {
|
||||
const { operation, profile, encoder, transport } = bound;
|
||||
const linked = linkedAbortController(context.signal);
|
||||
@@ -474,8 +480,29 @@ async function executeUnary<Output>(
|
||||
context.idempotencyKey,
|
||||
)
|
||||
) {
|
||||
const delay = retryDelay(profile, transportResult.failure, attempt);
|
||||
if (delay >= deadlineAt - safeNowOrDeadline(clock, deadlineAt)) {
|
||||
const sample = safeSample(random);
|
||||
if (sample === null) {
|
||||
return finish(
|
||||
failureResult(
|
||||
callFailure(
|
||||
operation,
|
||||
attempt,
|
||||
"SERVER_FAILURE",
|
||||
"RPC_RUNTIME_DEPENDENCY_FAILED",
|
||||
),
|
||||
),
|
||||
"FAILED",
|
||||
);
|
||||
}
|
||||
const retryBudgetMs = deadlineAt - safeNowOrDeadline(clock, deadlineAt);
|
||||
const delay = retryDelay(
|
||||
profile,
|
||||
transportResult.failure,
|
||||
attempt,
|
||||
sample,
|
||||
retryBudgetMs,
|
||||
);
|
||||
if (delay === null || delay >= retryBudgetMs) {
|
||||
linked.controller.abort("deadline");
|
||||
return finish(
|
||||
failureResult(
|
||||
@@ -1521,6 +1548,10 @@ function shouldRetry(
|
||||
profile.retryOwner === "FRONTEND_ADAPTER" &&
|
||||
attempt + 1 < profile.maxAttempts &&
|
||||
profile.retryableFailures.includes(failure.code) &&
|
||||
// A hint is a lower bound. Past the profile ceiling there is no retry,
|
||||
// never an earlier one.
|
||||
(failure.retryAfterMs === undefined ||
|
||||
failure.retryAfterMs <= profile.maxRetryAfterMs) &&
|
||||
(["SAFE", "IDEMPOTENT"].includes(operation.replayPolicy) ||
|
||||
(operation.replayPolicy === "KEYED_COMMAND" &&
|
||||
validIdempotencyKey(idempotencyKey)))
|
||||
@@ -1531,13 +1562,27 @@ function retryDelay(
|
||||
profile: BrowserRpcProviderProfile,
|
||||
failure: BrowserRpcTransportFailure,
|
||||
attempt: number,
|
||||
): number {
|
||||
sample: number,
|
||||
remainingMs: number,
|
||||
): number | null {
|
||||
const backoff = profile.backoffMs[attempt] ?? 0;
|
||||
const retryAfter = Math.min(
|
||||
failure.retryAfterMs ?? 0,
|
||||
profile.maxRetryAfterMs,
|
||||
);
|
||||
return Math.max(backoff, retryAfter);
|
||||
return delayAfterRetryHint({
|
||||
hintMs: failure.retryAfterMs ?? null,
|
||||
ceilingMs: profile.maxRetryAfterMs,
|
||||
localDelayMs: backoff,
|
||||
localWindowMs: backoff,
|
||||
sample,
|
||||
remainingMs,
|
||||
});
|
||||
}
|
||||
|
||||
function safeSample(random: () => number): number | null {
|
||||
try {
|
||||
const sample = random();
|
||||
return Number.isFinite(sample) && sample >= 0 && sample < 1 ? sample : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function mapTransportFailure(
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
combineAbortSignals,
|
||||
createAbortableOperation,
|
||||
} from "../../platform/abortable-operation.ts";
|
||||
import { delayAfterRetryHint } from "../../platform/retry-after.ts";
|
||||
import {
|
||||
observeTransferResult,
|
||||
transferAllowanceMs,
|
||||
@@ -1474,12 +1475,6 @@ async function waitForRetry<Capability>(
|
||||
signal: AbortSignal,
|
||||
operation: BrowserDataOperation,
|
||||
): Promise<BrowserDataResult<void>> {
|
||||
const retryAfter =
|
||||
Number.isSafeInteger(failure.retryAfterMs) &&
|
||||
(failure.retryAfterMs ?? -1) >= 0 &&
|
||||
(failure.retryAfterMs ?? 0) <= dependencies.policy.maxRetryAfterMs
|
||||
? (failure.retryAfterMs ?? 0)
|
||||
: null;
|
||||
const randomValue = safeRandom(dependencies);
|
||||
if (!randomValue.ok) return randomValue;
|
||||
const exponential = Math.min(
|
||||
@@ -1487,7 +1482,21 @@ async function waitForRetry<Capability>(
|
||||
dependencies.policy.retryBaseDelayMs * 2 ** retryIndex,
|
||||
);
|
||||
const jittered = Math.floor(exponential * (0.5 + randomValue.value / 2));
|
||||
const delayMs = Math.max(jittered, retryAfter ?? 0);
|
||||
const delayMs = delayAfterRetryHint({
|
||||
hintMs: failure.retryAfterMs ?? null,
|
||||
ceilingMs: dependencies.policy.maxRetryAfterMs,
|
||||
localDelayMs: jittered,
|
||||
localWindowMs: exponential,
|
||||
// `safeRandom` admits 1; the kernel's sample is below 1.
|
||||
sample: Math.min(randomValue.value, 1 - Number.EPSILON),
|
||||
});
|
||||
// `canRetry` admits no hint past the ceiling, so this does not wait less.
|
||||
if (delayMs === null) {
|
||||
return browserDataFailure("UNAVAILABLE", operation, {
|
||||
retryable: false,
|
||||
recovery: "RESUME",
|
||||
});
|
||||
}
|
||||
try {
|
||||
await dependencies.sleep(delayMs, signal);
|
||||
return signal.aborted
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { RetrySemantics } from "../../contracts/external-contract-runtime.ts";
|
||||
import { delayAfterRetryHint } from "../platform/retry-after.ts";
|
||||
import type { PhysicalAttemptState } from "./http-effect-certainty.ts";
|
||||
|
||||
const RETRYABLE_STATUSES: ReadonlySet<number> = new Set([
|
||||
@@ -45,22 +46,22 @@ export function jitteredDelay(
|
||||
return Math.floor(random() * localJitterCeiling(retryIndex));
|
||||
}
|
||||
|
||||
/**
|
||||
* scale-architecture.md §13.3. `Retry-After` is a floor, never an exact instant: every client
|
||||
* that received the same hint would otherwise retry in one synchronized second
|
||||
* spike. The cohort is spread over a bounded window that grows with the hint
|
||||
* (a quarter of it) but never beyond the local 2s jitter ceiling.
|
||||
*/
|
||||
/** scale-architecture.md §13.3, through the kernel `delayAfterRetryHint`. */
|
||||
export function retryDelayFor(
|
||||
retryAfterMs: number | null,
|
||||
retryIndex: number,
|
||||
random: () => number,
|
||||
): number | null {
|
||||
if (retryAfterMs === null) return jitteredDelay(retryIndex, random);
|
||||
if (retryAfterMs > RETRY_AFTER_CEILING_MS) return null;
|
||||
const window = Math.min(
|
||||
RETRY_MAX_LOCAL_DELAY_MS,
|
||||
Math.max(localJitterCeiling(retryIndex), Math.ceil(retryAfterMs / 4)),
|
||||
);
|
||||
return retryAfterMs + Math.floor(random() * window);
|
||||
// A refused hint needs no sample.
|
||||
if (retryAfterMs !== null && retryAfterMs > RETRY_AFTER_CEILING_MS) {
|
||||
return null;
|
||||
}
|
||||
const sample = random();
|
||||
return delayAfterRetryHint({
|
||||
hintMs: retryAfterMs,
|
||||
ceilingMs: RETRY_AFTER_CEILING_MS,
|
||||
localDelayMs: jitteredDelay(retryIndex, () => sample),
|
||||
localWindowMs: localJitterCeiling(retryIndex),
|
||||
sample,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -36,3 +36,42 @@ export function parseRetryAfterDelay(
|
||||
? Math.max(0, timestamp - nowEpochMs)
|
||||
: null;
|
||||
}
|
||||
|
||||
const RETRY_HINT_MAX_JITTER_MS = 2_000;
|
||||
|
||||
/**
|
||||
* scale-architecture.md §13.3. The one rule for waiting on a server retry hint.
|
||||
*
|
||||
* The hint is a floor, never an exact instant: every client that received the
|
||||
* same hint would otherwise retry in one synchronized spike. The jitter above
|
||||
* it spans the wider of the local window and a quarter of the hint, up to 2 s.
|
||||
* When the caller has a budget the jitter takes at most half of what the hint
|
||||
* leaves of it: the retried attempt needs the rest to answer. A hint past the
|
||||
* caller's ceiling is `null` (do not retry), never a shorter wait. The result
|
||||
* is the later of that instant and the local delay.
|
||||
*
|
||||
* Callers own the ceiling, the local backoff and the checked random sample.
|
||||
*/
|
||||
export function delayAfterRetryHint(input: Readonly<{
|
||||
hintMs: number | null;
|
||||
/** Bounds the hint, not the jitter added on top of it. */
|
||||
ceilingMs: number;
|
||||
localDelayMs: number;
|
||||
localWindowMs: number;
|
||||
/** A value in [0, 1). */
|
||||
sample: number;
|
||||
remainingMs?: number;
|
||||
}>): number | null {
|
||||
const { hintMs, localDelayMs } = input;
|
||||
if (hintMs === null) return localDelayMs;
|
||||
if (hintMs > input.ceilingMs) return null;
|
||||
const jitterWindowMs = Math.min(
|
||||
RETRY_HINT_MAX_JITTER_MS,
|
||||
Math.max(input.localWindowMs, Math.ceil(hintMs / 4)),
|
||||
((input.remainingMs ?? Number.POSITIVE_INFINITY) - hintMs) / 2,
|
||||
);
|
||||
return Math.max(
|
||||
localDelayMs,
|
||||
hintMs + Math.floor(input.sample * Math.max(0, jitterWindowMs)),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
type RealtimeFailureKind,
|
||||
type RealtimeResult,
|
||||
} from "../../../application/ports/realtime/shared.ts";
|
||||
import { delayAfterRetryHint } from "../../platform/retry-after.ts";
|
||||
import { systemClock } from "../../platform/system-clock.ts";
|
||||
import {
|
||||
captureRealtimeDataSnapshot,
|
||||
@@ -439,6 +440,7 @@ export function createBoundedPollCoordinator<
|
||||
? result.error.retryAfterMs
|
||||
: undefined,
|
||||
random,
|
||||
policy.maxElapsedMs - (attemptFinishedAt - startedAtMs),
|
||||
);
|
||||
if (failureDelay === null) {
|
||||
return pollFailure("POLL_BUDGET_EXHAUSTED");
|
||||
@@ -751,14 +753,13 @@ function retryDelay(
|
||||
consecutiveFailures: number,
|
||||
retryAfterMs: number | undefined,
|
||||
random: () => number,
|
||||
remainingMs: number,
|
||||
): number | null {
|
||||
const sample = safeRandom(random);
|
||||
if (sample === null) return null;
|
||||
if (
|
||||
retryAfterMs !== undefined &&
|
||||
(!Number.isSafeInteger(retryAfterMs) ||
|
||||
retryAfterMs < 0 ||
|
||||
retryAfterMs > policy.maxIntervalMs)
|
||||
(!Number.isSafeInteger(retryAfterMs) || retryAfterMs < 0)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
@@ -766,11 +767,17 @@ function retryDelay(
|
||||
policy.maxIntervalMs,
|
||||
policy.minimumIntervalMs * 2 ** Math.max(0, consecutiveFailures - 1),
|
||||
);
|
||||
return Math.max(
|
||||
policy.minimumIntervalMs,
|
||||
Math.floor(ceiling * sample),
|
||||
retryAfterMs ?? 0,
|
||||
);
|
||||
return delayAfterRetryHint({
|
||||
hintMs: retryAfterMs ?? null,
|
||||
ceilingMs: policy.maxIntervalMs,
|
||||
localDelayMs: Math.max(
|
||||
policy.minimumIntervalMs,
|
||||
Math.floor(ceiling * sample),
|
||||
),
|
||||
localWindowMs: ceiling,
|
||||
sample,
|
||||
remainingMs,
|
||||
});
|
||||
}
|
||||
|
||||
function isPollRetryableFailureKind(
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { delayAfterRetryHint } from "../platform/retry-after.ts";
|
||||
|
||||
export { parseRetryAfterDelay } from "../platform/retry-after.ts";
|
||||
|
||||
export const REALTIME_RECONNECT_CEILINGS = Object.freeze({
|
||||
@@ -35,7 +37,8 @@ export type ReconnectDelayInput = Readonly<{
|
||||
random: () => number;
|
||||
/**
|
||||
* Relative delay required by Retry-After, SSE retry or another validated
|
||||
* protocol hint. It is a lower bound, never a value to clamp downward.
|
||||
* protocol hint. It is a lower bound with bounded jitter above it, never a
|
||||
* value to clamp downward. `maxDelayMs` bounds the hint, not that jitter.
|
||||
*/
|
||||
serverNotBeforeMs?: number | null;
|
||||
}>;
|
||||
@@ -67,7 +70,8 @@ export function defineReconnectPolicy(
|
||||
}
|
||||
|
||||
/**
|
||||
* Full-jitter exponential backoff with a server-provided not-before floor.
|
||||
* Full-jitter exponential backoff. A server hint is a not-before floor with
|
||||
* bounded jitter above it (`delayAfterRetryHint`).
|
||||
* `null` means the attempt budget cannot safely admit another delay.
|
||||
*/
|
||||
export function calculateReconnectDelay(
|
||||
@@ -99,16 +103,22 @@ export function calculateReconnectDelay(
|
||||
policy.baseDelayMs * 2 ** input.attemptIndex,
|
||||
);
|
||||
const localDelay = Math.floor(exponentialCeiling * sample);
|
||||
const serverNotBeforeMs = input.serverNotBeforeMs ?? 0;
|
||||
const serverNotBeforeMs = input.serverNotBeforeMs ?? null;
|
||||
if (
|
||||
!Number.isSafeInteger(serverNotBeforeMs) ||
|
||||
serverNotBeforeMs < 0 ||
|
||||
serverNotBeforeMs > policy.maxDelayMs
|
||||
serverNotBeforeMs !== null &&
|
||||
(!Number.isSafeInteger(serverNotBeforeMs) || serverNotBeforeMs < 0)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const effectiveDelay = Math.max(localDelay, serverNotBeforeMs);
|
||||
return effectiveDelay >= input.remainingElapsedMs
|
||||
const effectiveDelay = delayAfterRetryHint({
|
||||
hintMs: serverNotBeforeMs,
|
||||
ceilingMs: policy.maxDelayMs,
|
||||
localDelayMs: localDelay,
|
||||
localWindowMs: exponentialCeiling,
|
||||
sample,
|
||||
remainingMs: input.remainingElapsedMs,
|
||||
});
|
||||
return effectiveDelay === null || effectiveDelay >= input.remainingElapsedMs
|
||||
? null
|
||||
: effectiveDelay;
|
||||
}
|
||||
|
||||
@@ -161,6 +161,97 @@ describe("Browser RPC provider-neutral runtime", () => {
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
|
||||
it("does not retry ahead of a server hint past the profile ceiling", async () => {
|
||||
const run = await retryAfterRun({ hintMs: 5_000, maxRetryAfterMs: 100 });
|
||||
|
||||
expect(run.calls).toBe(1);
|
||||
expect(run.delays).toEqual([]);
|
||||
expect(run.result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "SERVER_FAILURE",
|
||||
code: "RPC_UNAVAILABLE",
|
||||
retryAfterMs: 5_000,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("retries on a hint equal to the profile ceiling", async () => {
|
||||
const run = await retryAfterRun({ hintMs: 100, maxRetryAfterMs: 100 });
|
||||
|
||||
expect(run.calls).toBe(2);
|
||||
expect(run.delays).toEqual([100]);
|
||||
});
|
||||
|
||||
it("spreads a server hint above its floor", async () => {
|
||||
const early = await retryAfterRun({ hintMs: 1_000, random: () => 0 });
|
||||
const late = await retryAfterRun({ hintMs: 1_000, random: () => 0.999 });
|
||||
|
||||
expect(early.delays).toEqual([1_000]);
|
||||
expect(late.delays).toEqual([1_249]);
|
||||
});
|
||||
|
||||
it("keeps the jitter inside half of the deadline left after the hint", async () => {
|
||||
const run = await retryAfterRun({ hintMs: 4_900, random: () => 0.999 });
|
||||
|
||||
expect(run.delays).toEqual([4_949]);
|
||||
expect(run.calls).toBe(2);
|
||||
});
|
||||
|
||||
it("leaves the retried attempt time to answer", async () => {
|
||||
const run = await retryAfterRun({
|
||||
hintMs: 4_000,
|
||||
responseMs: [100, 200],
|
||||
random: () => 0.999,
|
||||
});
|
||||
|
||||
expect(run.delays).toEqual([4_449]);
|
||||
expect(run.result).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["no hint", undefined, 300, 300],
|
||||
["a hint before the backoff", 1_000, 3_000, 3_000],
|
||||
["a backoff wider than a quarter of the hint", 1_000, 400, 1_399],
|
||||
] as const)(
|
||||
"keeps the profile backoff with %s",
|
||||
async (_label, hintMs, backoffMs, expected) => {
|
||||
const run = await retryAfterRun({
|
||||
hintMs,
|
||||
backoffMs,
|
||||
random: () => 0.999,
|
||||
});
|
||||
|
||||
expect(run.delays).toEqual([expected]);
|
||||
},
|
||||
);
|
||||
|
||||
it("stops when the hint alone spends the total deadline", async () => {
|
||||
const run = await retryAfterRun({ hintMs: 5_000, random: () => 0.999 });
|
||||
|
||||
expect(run.calls).toBe(1);
|
||||
expect(run.result).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "RPC_RETRY_BUDGET_EXHAUSTED" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["throws", (): number => { throw new Error("no entropy"); }],
|
||||
["returns one", (): number => 1],
|
||||
["returns a negative number", (): number => -0.1],
|
||||
["returns NaN", (): number => Number.NaN],
|
||||
] as const)("fails closed when random %s", async (_label, random) => {
|
||||
const run = await retryAfterRun({ hintMs: 1_000, random });
|
||||
|
||||
expect(run.calls).toBe(1);
|
||||
expect(run.delays).toEqual([]);
|
||||
expect(run.result).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "RPC_RUNTIME_DEPENDENCY_FAILED" },
|
||||
});
|
||||
});
|
||||
|
||||
it("drops a late unary result after its scope generation changes", async () => {
|
||||
const transport = defineBrowserRpcTransport({
|
||||
runtimeProfileId: "CONNECT_REFERENCE_UNARY",
|
||||
@@ -398,6 +489,83 @@ function baseDependencies(transport: BrowserRpcTransport) {
|
||||
} as const;
|
||||
}
|
||||
|
||||
/** One failed attempt that carries a hint, then a success, on a fake clock. */
|
||||
async function retryAfterRun(input: Readonly<{
|
||||
hintMs: number | undefined;
|
||||
maxRetryAfterMs?: number;
|
||||
backoffMs?: number;
|
||||
/** How long the first and the retried attempt take to answer. */
|
||||
responseMs?: readonly [number, number];
|
||||
random?: () => number;
|
||||
}>) {
|
||||
let calls = 0;
|
||||
let now = 0;
|
||||
const delays: number[] = [];
|
||||
const profile = unaryProfile({
|
||||
retryProfileId: "RPC_RETRY_TWO",
|
||||
retryOwner: "FRONTEND_ADAPTER",
|
||||
maxAttempts: 2,
|
||||
backoffMs: [input.backoffMs ?? 0],
|
||||
retryableFailures: ["UNAVAILABLE"],
|
||||
maxRetryAfterMs: input.maxRetryAfterMs ?? 60_000,
|
||||
});
|
||||
const transport = defineBrowserRpcTransport({
|
||||
runtimeProfileId: profile.runtimeProfileId,
|
||||
providerId: profile.providerId,
|
||||
protocol: profile.protocol,
|
||||
rpcKind: profile.rpcKind,
|
||||
async invokeUnary() {
|
||||
calls += 1;
|
||||
now += input.responseMs?.[calls === 1 ? 0 : 1] ?? 0;
|
||||
return calls === 1
|
||||
? {
|
||||
ok: false,
|
||||
failure: {
|
||||
code: "UNAVAILABLE",
|
||||
...(input.hintMs === undefined
|
||||
? {}
|
||||
: { retryAfterMs: input.hintMs }),
|
||||
},
|
||||
}
|
||||
: {
|
||||
ok: true,
|
||||
message: { id: "resource-2", name: "Retried resource" },
|
||||
encodedBytes: 32,
|
||||
};
|
||||
},
|
||||
});
|
||||
const runtime = createBrowserRpcRuntime({
|
||||
...baseDependencies(transport),
|
||||
operations: {
|
||||
GET_RPC_RESOURCE: unaryOperation({ retryProfileId: "RPC_RETRY_TWO" }),
|
||||
},
|
||||
profiles: { CONNECT_REFERENCE_UNARY: profile },
|
||||
random: input.random ?? (() => 0),
|
||||
clock: {
|
||||
now: () => now,
|
||||
sleep(milliseconds, signal) {
|
||||
// raceWithin arms a deadline timer with its own signal; only the retry
|
||||
// wait resolves, and only it moves the clock.
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
delays.push(milliseconds);
|
||||
now += milliseconds;
|
||||
resolve();
|
||||
}, 0);
|
||||
signal?.addEventListener("abort", () => {
|
||||
clearTimeout(timer);
|
||||
reject(new DOMException("Aborted", "AbortError"));
|
||||
}, { once: true });
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
const result = await runtime
|
||||
.bindUnary("GET_RPC_RESOURCE", isResourceView)
|
||||
.execute({ resourceId: "resource-2" });
|
||||
return { calls, delays, result };
|
||||
}
|
||||
|
||||
function streamRuntime(
|
||||
transport: BrowserRpcTransport,
|
||||
observations?: Readonly<{
|
||||
|
||||
@@ -47,5 +47,12 @@ describe("HTTP retry lifecycle policy", () => {
|
||||
expect(retryDelayFor(400, 0, () => 0.5)).toBe(525);
|
||||
expect(retryDelayFor(400, 0, () => 0)).toBe(400);
|
||||
expect(retryDelayFor(5_001, 0, () => 0.5)).toBeNull();
|
||||
// A refused hint needs no sample, so a failing random cannot replace the
|
||||
// response's own failure.
|
||||
expect(
|
||||
retryDelayFor(5_001, 0, () => {
|
||||
throw new Error("random is unavailable");
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -633,6 +633,80 @@ describe("bounded poll coordinator", () => {
|
||||
expect(execute).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[0, 10_000, 60_000, 10_000],
|
||||
[0.999, 10_000, 60_000, 11_998],
|
||||
// The ceiling bounds the hint. The jitter goes above it, inside the lease.
|
||||
[0.999, 60_000, 120_000, 61_998],
|
||||
[0.999, 10_000, 15_100, 10_049],
|
||||
// The local window is wider than a quarter of the hint.
|
||||
[0.999, 5_000, 60_000, 6_998],
|
||||
] as const)(
|
||||
"spreads Retry-After (random %d, hint %d, lease %d)",
|
||||
async (sample, retryAfterMs, maxElapsedMs, expected) => {
|
||||
const clock = new ManualClock();
|
||||
const coordinator = createBoundedPollCoordinator<string>({
|
||||
policy: definePollLeasePolicy({ ...policy, maxElapsedMs }),
|
||||
operation,
|
||||
execute: async () => ({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "RATE_LIMITED",
|
||||
operation: "POLL",
|
||||
retryable: true,
|
||||
retryAfterMs,
|
||||
},
|
||||
}),
|
||||
environment: new MutableEnvironment(),
|
||||
clock,
|
||||
random: () => sample,
|
||||
});
|
||||
|
||||
const pending = coordinator.run();
|
||||
clock.advance(5_000);
|
||||
await flush();
|
||||
|
||||
expect(
|
||||
clock.sleepers.map((sleeper) => sleeper.dueAt - clock.current),
|
||||
).toEqual([expected]);
|
||||
coordinator.close();
|
||||
await expect(pending).resolves.toMatchObject({ ok: false });
|
||||
},
|
||||
);
|
||||
|
||||
it("does not poll again on a hint past the interval ceiling", async () => {
|
||||
const clock = new ManualClock();
|
||||
const execute = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "RATE_LIMITED",
|
||||
operation: "POLL",
|
||||
retryable: true,
|
||||
retryAfterMs: 60_001,
|
||||
},
|
||||
});
|
||||
const coordinator = createBoundedPollCoordinator<string>({
|
||||
policy: definePollLeasePolicy({ ...policy, maxElapsedMs: 120_000 }),
|
||||
operation,
|
||||
execute,
|
||||
environment: new MutableEnvironment(),
|
||||
clock,
|
||||
random: () => 0,
|
||||
});
|
||||
|
||||
const pending = coordinator.run();
|
||||
clock.advance(5_000);
|
||||
await flush();
|
||||
|
||||
// Nothing waits for another attempt.
|
||||
expect(clock.sleepers).toEqual([]);
|
||||
await expect(pending).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "POLL_BUDGET_EXHAUSTED" },
|
||||
});
|
||||
expect(execute).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each(["RATE_LIMITED", "PROVIDER_UNAVAILABLE"] as const)(
|
||||
"retries retryable %s without a server hint on policy backoff",
|
||||
async (kind) => {
|
||||
|
||||
@@ -2085,11 +2085,12 @@ describe("transport failures through the reconnect coordinator", () => {
|
||||
},
|
||||
});
|
||||
|
||||
// 10_000 is each read's connect timeout; 3_000 is the reconnect wait.
|
||||
// 10_000 is each read's connect timeout. The reconnect wait is the
|
||||
// 3_000 hint plus half of its jitter window (3_000 / 4).
|
||||
const running = coordinator.run();
|
||||
await flushUntil(() => clock.sleepCalls.length === 2);
|
||||
expect(clock.sleepCalls).toEqual([10_000, 3_000]);
|
||||
clock.advance(3_000);
|
||||
expect(clock.sleepCalls).toEqual([10_000, 3_375]);
|
||||
clock.advance(3_375);
|
||||
|
||||
// A hint above the policy's maxDelayMs still ends the run.
|
||||
await expect(running).resolves.toMatchObject({
|
||||
@@ -2097,7 +2098,7 @@ describe("transport failures through the reconnect coordinator", () => {
|
||||
error: { operation: "CONNECT", retryable: true },
|
||||
});
|
||||
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||
expect(clock.sleepCalls).toEqual([10_000, 3_000, 10_000]);
|
||||
expect(clock.sleepCalls).toEqual([10_000, 3_375, 10_000]);
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -36,7 +36,8 @@ describe("realtime reconnect policy", () => {
|
||||
random: () => 0.5,
|
||||
serverNotBeforeMs: 3_000,
|
||||
}),
|
||||
).toBe(3_000);
|
||||
// 3000 + floor(0.5 * min(2000, max(4000, 750)))
|
||||
).toBe(4_000);
|
||||
});
|
||||
|
||||
it("stops instead of clamping a hint past a hard or remaining budget", () => {
|
||||
@@ -68,6 +69,23 @@ describe("realtime reconnect policy", () => {
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("spreads a server hint that is later than the local delay", () => {
|
||||
const delay = (sample: number, hintMs: number, remainingElapsedMs: number) =>
|
||||
calculateReconnectDelay({
|
||||
policy,
|
||||
attemptIndex: 0,
|
||||
remainingElapsedMs,
|
||||
random: () => sample,
|
||||
serverNotBeforeMs: hintMs,
|
||||
});
|
||||
|
||||
expect(delay(0, 10_000, 100_000)).toBe(10_000);
|
||||
expect(delay(0.999, 10_000, 100_000)).toBe(11_998);
|
||||
// The ceiling bounds the hint. The jitter goes above it, inside the budget.
|
||||
expect(delay(0.999, 60_000, 100_000)).toBe(61_998);
|
||||
expect(delay(0.999, 10_000, 10_100)).toBe(10_049);
|
||||
});
|
||||
|
||||
it("parses only bounded-shape Retry-After syntax for caller validation", () => {
|
||||
expect(parseRetryAfterDelay("12", 0)).toBe(12_000);
|
||||
expect(
|
||||
|
||||
@@ -581,6 +581,69 @@ describe("production resumable upload runtime", () => {
|
||||
expect(delays).toEqual([7]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[0, 80, 1, 80],
|
||||
[0.999, 80, 1, 99],
|
||||
// This runtime's random may return 1; the jitter stays below its window.
|
||||
[1, 80, 1, 99],
|
||||
// The ceiling bounds the hint; the jitter goes above it.
|
||||
[0.999, 100, 1, 124],
|
||||
// The local window is wider than a quarter of the hint.
|
||||
[0.999, 80, 40, 119],
|
||||
// The local backoff (half of it with random 0) is later than the hint.
|
||||
[0, 7, 40, 20],
|
||||
] as const)(
|
||||
"spreads Retry-After (random %d, hint %d, backoff %d)",
|
||||
async (sample, retryAfterMs, backoffMs, expected) => {
|
||||
const harness = createControlHarness();
|
||||
const original = executorFor(harness);
|
||||
const delays: number[] = [];
|
||||
let uploadAttempts = 0;
|
||||
const runtime = createResumableUploadRuntime({
|
||||
controlPlane: harness.control,
|
||||
partExecutor: {
|
||||
async uploadPart(input) {
|
||||
uploadAttempts += 1;
|
||||
if (uploadAttempts > 1) return original.uploadPart(input);
|
||||
return Object.freeze({
|
||||
ok: false as const,
|
||||
error: Object.freeze({
|
||||
code: "UNAVAILABLE" as const,
|
||||
operation: "UPLOAD_PART" as const,
|
||||
retryable: true,
|
||||
recovery: "REISSUE_CAPABILITY" as const,
|
||||
retryAfterMs,
|
||||
}),
|
||||
});
|
||||
},
|
||||
},
|
||||
checkpoints: new MemoryCheckpointStore(),
|
||||
mutationLock: noContentionLock,
|
||||
crypto,
|
||||
policy: runtimePolicy({
|
||||
maxRetries: 1,
|
||||
retryBaseDelayMs: backoffMs,
|
||||
retryMaxDelayMs: Math.max(10, backoffMs),
|
||||
}),
|
||||
now: () => 1_000,
|
||||
random: () => sample,
|
||||
sleep: async (delay) => {
|
||||
delays.push(delay);
|
||||
},
|
||||
});
|
||||
const result = await runtime.upload({
|
||||
uploadKey: "upload_key_retry_jitter",
|
||||
purpose: "attachment",
|
||||
mediaType: "application/octet-stream",
|
||||
source: rangeSource(new Uint8Array([1, 2, 3, 4])),
|
||||
signal: activeSignal,
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(delays).toEqual([expected]);
|
||||
},
|
||||
);
|
||||
|
||||
it("detects source mutation between the fingerprint and transfer passes", async () => {
|
||||
let reads = 0;
|
||||
const source: ResumableUploadSource = {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { delayAfterRetryHint } from "../../src/adapters/platform/retry-after.ts";
|
||||
|
||||
const delay = (
|
||||
overrides: Partial<Parameters<typeof delayAfterRetryHint>[0]>,
|
||||
) =>
|
||||
delayAfterRetryHint({
|
||||
hintMs: 3_000,
|
||||
ceilingMs: 60_000,
|
||||
localDelayMs: 100,
|
||||
localWindowMs: 250,
|
||||
sample: 0,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("delay after a server retry hint", () => {
|
||||
it("spreads the same hint without retrying before it", () => {
|
||||
expect(delay({ sample: 0 })).toBe(3_000);
|
||||
// The window is max(250, 3000 / 4).
|
||||
expect(delay({ sample: 0.999 })).toBe(3_749);
|
||||
});
|
||||
|
||||
it("uses the local window when it is wider than a quarter of the hint", () => {
|
||||
expect(delay({ localWindowMs: 1_000, sample: 0.5 })).toBe(3_500);
|
||||
});
|
||||
|
||||
it("bounds the window whatever the hint and the local backoff are", () => {
|
||||
expect(
|
||||
delay({ hintMs: 60_000, localWindowMs: 60_000, sample: 0.999 }),
|
||||
).toBe(61_998);
|
||||
});
|
||||
|
||||
it("refuses a hint past the ceiling instead of cutting it", () => {
|
||||
expect(delay({ hintMs: 60_000 })).toBe(60_000);
|
||||
expect(delay({ hintMs: 60_001 })).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the local delay when there is no hint or it is later", () => {
|
||||
expect(delay({ hintMs: null, sample: 0.999 })).toBe(100);
|
||||
expect(delay({ hintMs: 0, localWindowMs: 100, sample: 0.5 })).toBe(100);
|
||||
expect(delay({ localDelayMs: 9_000, sample: 0.999 })).toBe(9_000);
|
||||
});
|
||||
|
||||
it("leaves at least half of the budget after the hint to the retry", () => {
|
||||
expect(delay({ remainingMs: 3_100, sample: 0.999 })).toBe(3_049);
|
||||
// A spent budget adds no negative jitter: the caller sees the hint and stops.
|
||||
expect(delay({ remainingMs: 2_000, sample: 0.999 })).toBe(3_000);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user