Files
clean-architecture-frontend…/tests/unit/browser-rpc/browser-rpc-runtime.test.ts
DongHyeonka 6e47167abb fix(retry): Retry-After 하한 위에 jitter를 더해 재시도를 흩뜨린다
문제: resumable upload·realtime 재연결·bounded poll·browser-rpc가
max(로컬 지연, 힌트)만큼 기다린다. 힌트가 로컬 지연보다 크면 같은
힌트를 받은 클라이언트가 모두 힌트 시각에 다시 보낸다.
scale-architecture 13.3절은 jitter를 더하라고 적고 VD-28은 max를
적어 문서도 갈려 있다.

고른 방법: 넷이 kernel delayAfterRetryHint를 부른다. 상한 값과 실패
code는 그대로다. 시간 예산이 있는 셋은 jitter를 힌트 뒤 여유의
절반까지만 써서, 다시 보낸 시도가 답을 받을 시간을 남긴다.
browser-rpc는 주입할 수 있는 random(선택 칸)을 받는다. 13.3절·계약
16.1 표를 고치고 VD-28은 기록 규칙대로 보완 절로 고친다.
버린 대안: 재연결·poll은 max를 유지한다(카드 안 B). 문서 불일치와
몰림이 남는다. jitter까지 상한 안에 자르기는 힌트가 상한과 같을 때
모두 같은 순간에 다시 보내게 되어 버렸다.

위험·한계: 네 곳의 재시도가 최대 2초 미만 늦어진다. 실제 대기가
maxDelayMs·maxIntervalMs·maxRetryAfterMs보다 그만큼 길 수 있다.
다시 보낸 시도의 시간은 최악에 여유의 절반으로 준다. 로컬 지연에
난수가 없는 browser-rpc backoff 표와 poll 첫 실패의 최소 간격은
힌트보다 충분히 늦으면 여전히 같은 시각에 모인다.
안 A는 소유자가 아니라 review가 자율 운영 규칙으로 정했다.

검증: 새 시험이 고치기 전 desktop에서 실패했다(resumable 80≠99,
재연결·poll 10000≠11998, rpc 1000≠1249). 고친 뒤 check:types·lint·
architecture·unit·verify:documentation rc=0.

Refs: REV-FE-0024
2026-11-22 11:06:06 +09:00

654 lines
19 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
createBrowserRpcRuntime,
createUnavailableBrowserRpcTransport,
defineBrowserRpcTransport,
type BrowserRpcObservation,
type BrowserRpcServerStreamLease,
type BrowserRpcStreamFrame,
type BrowserRpcTransport,
} from "../../../src/adapters/browser-rpc/index.ts";
import type { Result } from "../../../src/contracts/result.ts";
import type { AppFailure } from "../../../src/contracts/errors.ts";
import {
MAPPERS,
SCHEMA_CODECS,
STREAM_ENCODER,
UNARY_ENCODER,
isResourceView,
streamOperation,
streamProfile,
unaryOperation,
unaryProfile,
} from "./fixture.ts";
describe("Browser RPC provider-neutral runtime", () => {
it("validates, encodes, maps and admits only the typed unary result", async () => {
const observations: BrowserRpcObservation[] = [];
const transport = defineBrowserRpcTransport({
runtimeProfileId: "CONNECT_REFERENCE_UNARY",
providerId: "REFERENCE_RPC",
protocol: "CONNECT_HTTP",
rpcKind: "UNARY",
async invokeUnary(call) {
expect(call.request).toEqual({ resourceId: "resource-1" });
expect(call.timeoutMs).toBeGreaterThan(0);
return Object.freeze({
ok: true,
message: Object.freeze({ id: "resource-1", name: "Resource one" }),
encodedBytes: 48,
});
},
});
const port = unaryRuntime(transport, {
observe(value) {
observations.push(value);
},
}).bindUnary("GET_RPC_RESOURCE", isResourceView);
await expect(port.execute({ resourceId: "resource-1" })).resolves.toEqual({
ok: true,
value: { id: "resource-1", label: "Resource one" },
});
expect(observations).toEqual([
{
operationId: "GET_RPC_RESOURCE",
protocol: "CONNECT_HTTP",
runtimeProfileId: "CONNECT_REFERENCE_UNARY",
rpcKind: "UNARY",
outcome: "SUCCESS",
attemptCount: 1,
messageCount: 1,
},
]);
});
it("fails before transport on invalid input or unexpected idempotency metadata", async () => {
let calls = 0;
const transport = defineBrowserRpcTransport({
runtimeProfileId: "CONNECT_REFERENCE_UNARY",
providerId: "REFERENCE_RPC",
protocol: "CONNECT_HTTP",
rpcKind: "UNARY",
async invokeUnary() {
calls += 1;
return {
ok: false,
failure: { code: "UNAVAILABLE" },
};
},
});
const port = unaryRuntime(transport).bindUnary(
"GET_RPC_RESOURCE",
isResourceView,
);
const invalid = await port.execute({ resourceId: 42 });
expect(invalid).toMatchObject({
ok: false,
error: {
kind: "VALIDATION_REJECTED",
code: "RPC_REQUEST_SCHEMA_INVALID",
},
});
const metadata = await port.execute(
{ resourceId: "resource-1" },
{ idempotencyKey: "caller-key-is-not-allowed" },
);
expect(metadata).toMatchObject({
ok: false,
error: {
kind: "VALIDATION_REJECTED",
code: "RPC_IDEMPOTENCY_KEY_INVALID",
},
});
expect(calls).toBe(0);
});
it("keeps the frontend retry owner bounded by replay policy and one total deadline", async () => {
let calls = 0;
const profile = unaryProfile({
retryProfileId: "RPC_RETRY_TWO",
retryOwner: "FRONTEND_ADAPTER",
maxAttempts: 2,
backoffMs: [0],
retryableFailures: ["UNAVAILABLE"],
maxRetryAfterMs: 100,
});
const operation = unaryOperation({
retryProfileId: "RPC_RETRY_TWO",
});
const transport = defineBrowserRpcTransport({
runtimeProfileId: profile.runtimeProfileId,
providerId: profile.providerId,
protocol: profile.protocol,
rpcKind: profile.rpcKind,
async invokeUnary() {
calls += 1;
if (calls === 1) {
return {
ok: false,
failure: { code: "UNAVAILABLE" },
};
}
return {
ok: true,
message: { id: "resource-2", name: "Retried resource" },
encodedBytes: 32,
};
},
});
const runtime = createBrowserRpcRuntime({
operations: { GET_RPC_RESOURCE: operation },
profiles: { CONNECT_REFERENCE_UNARY: profile },
schemaCodecs: SCHEMA_CODECS,
mappers: MAPPERS,
requestEncoders: {
RpcResourceRequestEncoder: UNARY_ENCODER,
},
transports: { CONNECT_REFERENCE_UNARY: transport },
});
await expect(
runtime
.bindUnary("GET_RPC_RESOURCE", isResourceView)
.execute({ resourceId: "resource-2" }),
).resolves.toMatchObject({
ok: true,
value: { id: "resource-2", label: "Retried resource" },
});
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",
providerId: "REFERENCE_RPC",
protocol: "CONNECT_HTTP",
rpcKind: "UNARY",
async invokeUnary() {
return {
ok: true,
message: { id: "late", name: "Late resource" },
encodedBytes: 24,
};
},
});
const runtime = createBrowserRpcRuntime({
...baseDependencies(transport),
generationFence: {
capture: () => 1,
isCurrent: () => false,
},
});
await expect(
runtime
.bindUnary("GET_RPC_RESOURCE", isResourceView)
.execute({ resourceId: "late" }),
).resolves.toMatchObject({
ok: false,
error: {
kind: "SCOPE_GENERATION_CHANGED",
code: "RPC_SCOPE_GENERATION_CHANGED",
},
});
});
it("uses an explicit unavailable adapter without network fallback", async () => {
const transport = createUnavailableBrowserRpcTransport({
runtimeProfileId: "CONNECT_REFERENCE_UNARY",
providerId: "REFERENCE_RPC",
protocol: "CONNECT_HTTP",
rpcKind: "UNARY",
});
const result = await unaryRuntime(transport)
.bindUnary("GET_RPC_RESOURCE", isResourceView)
.execute({ resourceId: "resource-1" });
expect(result).toMatchObject({
ok: false,
error: {
kind: "SERVER_FAILURE",
code: "RPC_UNAVAILABLE",
},
});
});
it("classifies valid oversized transport metadata as a response limit", async () => {
const transport = defineBrowserRpcTransport({
runtimeProfileId: "CONNECT_REFERENCE_UNARY",
providerId: "REFERENCE_RPC",
protocol: "CONNECT_HTTP",
rpcKind: "UNARY",
async invokeUnary() {
return {
ok: true,
message: { id: "large", name: "Large resource" },
encodedBytes: 4_097,
};
},
});
await expect(
unaryRuntime(transport)
.bindUnary("GET_RPC_RESOURCE", isResourceView)
.execute({ resourceId: "large" }),
).resolves.toMatchObject({
ok: false,
error: {
kind: "RESPONSE_BODY_LIMIT",
code: "RPC_RESPONSE_MESSAGE_LIMIT",
},
});
});
it("rejects transports that expose the wrong call shape", () => {
expect(() =>
defineBrowserRpcTransport({
runtimeProfileId: "CONNECT_REFERENCE_UNARY",
providerId: "REFERENCE_RPC",
protocol: "CONNECT_HTTP",
rpcKind: "UNARY",
async invokeUnary() {
return {
ok: false,
failure: { code: "UNAVAILABLE" },
};
},
openServerStream() {
return serverStreamLease(
(async function* () {
yield Object.freeze({ kind: "TERMINAL" as const, ok: true as const });
})(),
);
},
}),
).toThrow("transport is invalid");
});
it("commits mapped stream messages only before one valid terminal envelope", async () => {
const transport = streamTransport(async function* () {
yield message("resource-1", "One", 24);
yield message("resource-2", "Two", 24);
yield Object.freeze({ kind: "TERMINAL", ok: true });
});
const observations: BrowserRpcObservation[] = [];
const stream = streamRuntime(transport, {
observe(value) {
observations.push(value);
},
})
.bindServerStream("WATCH_RPC_RESOURCES", isResourceView)
.open({ resourceId: "scope-1" });
await expect(collect(stream)).resolves.toEqual([
{
ok: true,
value: { id: "resource-1", label: "One" },
},
{
ok: true,
value: { id: "resource-2", label: "Two" },
},
]);
expect(observations).toEqual([
{
operationId: "WATCH_RPC_RESOURCES",
protocol: "CONNECT_HTTP",
runtimeProfileId: "CONNECT_REFERENCE_STREAM",
rpcKind: "SERVER_STREAM",
outcome: "SUCCESS",
attemptCount: 1,
messageCount: 2,
},
]);
});
it("rejects EOF without terminal and data after terminal", async () => {
const missingTerminal = streamTransport(async function* () {
yield message("resource-1", "One", 24);
});
const missingResults = await collect(
streamRuntime(missingTerminal)
.bindServerStream("WATCH_RPC_RESOURCES", isResourceView)
.open({ resourceId: "scope-1" }),
);
expect(missingResults.at(-1)).toMatchObject({
ok: false,
error: {
kind: "API_CONTRACT_MISMATCH",
code: "RPC_PROTOCOL_MISMATCH",
},
});
const afterTerminal = streamTransport(async function* () {
yield Object.freeze({ kind: "TERMINAL", ok: true });
yield message("resource-2", "Two", 24);
});
await expect(
collect(
streamRuntime(afterTerminal)
.bindServerStream("WATCH_RPC_RESOURCES", isResourceView)
.open({ resourceId: "scope-1" }),
),
).resolves.toMatchObject([
{
ok: false,
error: {
kind: "API_CONTRACT_MISMATCH",
code: "RPC_PROTOCOL_MISMATCH",
},
},
]);
});
it("aborts the transport when stream message limits are exceeded", async () => {
let cleaned = false;
const transport = streamTransport(async function* (signal) {
try {
yield message("resource-1", "One", 24);
yield message("resource-2", "Two", 24);
yield Object.freeze({ kind: "TERMINAL", ok: true });
} finally {
cleaned = signal.aborted;
}
});
const operation = streamOperation({ maxResponseMessages: 1 });
const results = await collect(
streamRuntime(transport, undefined, operation)
.bindServerStream("WATCH_RPC_RESOURCES", isResourceView)
.open({ resourceId: "scope-1" }),
);
expect(results.at(-1)).toMatchObject({
ok: false,
error: {
kind: "RESPONSE_BODY_LIMIT",
code: "RPC_STREAM_MESSAGE_LIMIT",
},
});
expect(cleaned).toBe(true);
});
});
function unaryRuntime(
transport: BrowserRpcTransport,
observations?: Readonly<{
observe(value: BrowserRpcObservation): void;
}>,
) {
return createBrowserRpcRuntime({
...baseDependencies(transport),
observations,
});
}
function baseDependencies(transport: BrowserRpcTransport) {
return {
operations: { GET_RPC_RESOURCE: unaryOperation() },
profiles: { CONNECT_REFERENCE_UNARY: unaryProfile() },
schemaCodecs: SCHEMA_CODECS,
mappers: MAPPERS,
requestEncoders: {
RpcResourceRequestEncoder: UNARY_ENCODER,
},
transports: { CONNECT_REFERENCE_UNARY: transport },
} 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<{
observe(value: BrowserRpcObservation): void;
}>,
operation = streamOperation(),
) {
return createBrowserRpcRuntime({
operations: { WATCH_RPC_RESOURCES: operation },
profiles: { CONNECT_REFERENCE_STREAM: streamProfile() },
schemaCodecs: SCHEMA_CODECS,
mappers: MAPPERS,
requestEncoders: {
RpcResourceStreamRequestEncoder: STREAM_ENCODER,
},
transports: { CONNECT_REFERENCE_STREAM: transport },
observations,
});
}
function streamTransport(
source: (
signal: AbortSignal,
) => AsyncIterable<BrowserRpcStreamFrame>,
): BrowserRpcTransport {
return defineBrowserRpcTransport({
runtimeProfileId: "CONNECT_REFERENCE_STREAM",
providerId: "REFERENCE_RPC",
protocol: "CONNECT_HTTP",
rpcKind: "SERVER_STREAM",
openServerStream(call) {
return serverStreamLease(source(call.signal));
},
});
}
/**
* RPC-RR-01. Wraps a plain frame sequence in the lease the transport contract
* requires. `cancel` resolves `waitClosed`, which is what a cooperative
* transport does.
*/
let leaseSequence = 0;
function serverStreamLease(
frames: AsyncIterable<BrowserRpcStreamFrame>,
options: Readonly<{
onCancel?: (reason: string) => void;
closeOnCancel?: boolean;
}> = {},
): BrowserRpcServerStreamLease {
leaseSequence += 1;
let release: (() => void) | undefined;
const closed = new Promise<void>((resolve) => {
release = resolve;
});
return Object.freeze({
streamId: `test-stream-${leaseSequence}`,
frames,
cancel(reason: string) {
options.onCancel?.(reason);
if (options.closeOnCancel !== false) release?.();
},
waitClosed: () => closed,
});
}
function message(
id: string,
name: string,
encodedBytes: number,
): BrowserRpcStreamFrame {
return Object.freeze({
kind: "MESSAGE",
message: Object.freeze({ id, name }),
encodedBytes,
});
}
async function collect<Value>(
iterable: AsyncIterable<Result<Value, AppFailure>>,
): Promise<readonly Result<Value, AppFailure>[]> {
const values: Result<Value, AppFailure>[] = [];
for await (const value of iterable) values.push(value);
return values;
}