문제: poll `execute`가 받는 `input.operation`은 `BoundedPollOperation`
(`InstalledHttpContract<unknown, unknown, unknown>`)이다. 권하는 대로
`executor.execute(input.operation, x, …)`를 부르면 `Input`이 `unknown`이
되어 `x`는 아무 값이나 통과하고 `outcome.value`도 `unknown`이다. 입력이
틀리면 런타임 `CONTRACT_VIOLATION`(INPUT_INVALID)으로만 드러난다. 타입을
지키려면 클로저 descriptor를 써야 해서 1103/04-01의 잔여 위험(다른 행을
실행) 쪽이 유리해진다. 또 V3 결과 9종을 poll 결과로 바꾸는 대응표가 없다.
repo의 유일한 V3 조합 예(테스트)는 SUCCESS 외 전부를 retryable
PROVIDER_UNAVAILABLE로 바꿔, 옮기면 401·403·입력 거절도 maxAttempts번
다시 요청된다.
고른 방법: 리뷰 선택지 (b) + (c).
- `createBoundedPollCoordinator`와 `BoundedPollCoordinatorDependencies`에
`Operation extends BoundedPollOperation = BoundedPollOperation`을 더하고
`operation`·`input.operation`을 `Operation`으로 둔다. `operation`에서
추론되므로 실행기 호출이 기능 descriptor의 입력·출력 타입으로 검사된다.
런타임 코드는 바뀌지 않는다.
- 설계 9.2에 V3 결과 kind마다 poll 결과(kind, retryable, retryAfterMs)를
적은 표를 두고, 13.1 PROVIDER_UNAVAILABLE 행에서 그 표를 가리킨다.
9.2 "auth에서 lease 종료", 9.3 "401은 attempt를 끝낸다", 9.4, 13.1과
맞췄다. `retryAfterMs`는 값이 있을 때만 둔다(빈 칸은 모양 오류).
- 테스트 조합 예를 표대로 바꿨다(`pollAttemptResult`). 503 재시도
테스트는 같은 결과다(503 PROBLEM → retryable PROVIDER_UNAVAILABLE).
- 테스트: 틀린 입력에 `@ts-expect-error`, 출력을 기능 타입으로 받는 타입
테스트 1건. 401·403이 요청 1번으로 lease를 끝내는 테스트 2건.
버린 대안:
- (d) 대응 함수를 bootstrap이나 recipe에 두기. realtime 어댑터는
adapters/http 타입을 import할 수 없고, 레시피 번들과 제거 드릴 범위가
바뀐다.
- `BoundedPollOperation` 자체를 제네릭으로 바꾸기. application 정책의
공개 이름이 바뀐다. 제약으로만 두면 기존 이름이 그대로다.
위험·한계:
- 기존 호출은 그대로 컴파일된다. `Value`를 직접 적은 호출은 `Operation`이
기본값이라 예전처럼 `unknown`이다. 타입을 원하면 둘 다 적거나 추론에
맡긴다(타입 주석과 9.2에 적음). 그래서 `!`를 붙이지 않았다. 단, 추론에
맡긴 호출이 descriptor 타입과 다른 입력을 실행기에 넘기고 있었다면 이제
check:types가 실패한다. 이 커밋이 잡으려는 결함이다.
- 표는 조합 코드가 따를 규칙이고 강제 수단은 없다. 템플릿은 poll
`execute` 기본 구현을 주지 않는다(리뷰 재검토 조건).
- 409·410의 `CURSOR_EXPIRED` 행은 reset 계약이 있는 기능만 해당한다.
테스트 계약에는 없어 테스트 예는 그 갈래가 없다.
- CHANGELOG 행은 이 커밋에 없다. CHANGELOG 담당이 더한다.
검증: desktop batch에서 확인.
- corepack pnpm check:types:test
- node scripts/run-vitest.ts run tests/unit/realtime/bounded-poll-coordinator.test.ts
- RED: 부모 커밋의 src에서 check:types:test가 실패한다.
bounded-poll-coordinator.test.ts의 `@ts-expect-error` 줄이 TS2578(쓰이지
않은 지시문, 입력이 `unknown`이라 `{ size: 20 }`이 통과), 그 아래
`pollAttemptResult<…>(outcome)`이 TS2345(`outcome.value`가 `unknown`).
vitest 테스트는 양쪽에서 통과한다.
- lint, check:architecture, verify:documentation
Refs: 1106/04-02
154 lines
4.3 KiB
TypeScript
154 lines
4.3 KiB
TypeScript
import type { InstalledHttpContract } from "../../contracts/external-contract-runtime.ts";
|
|
|
|
export const BOUNDED_POLLING_CEILINGS = Object.freeze({
|
|
minimumIntervalMs: 5_000,
|
|
maxIntervalMs: 60_000,
|
|
maxAttempts: 120,
|
|
maxElapsedMs: 30 * 60 * 1_000,
|
|
maxResponseBytes: 8 * 1_024 * 1_024,
|
|
maxTerminalStates: 32,
|
|
});
|
|
|
|
export type PollFallbackReason =
|
|
| "CONVERGENCE"
|
|
| "RELAXED_FRESHNESS"
|
|
| "STREAM_DEGRADED"
|
|
| "STREAM_UNAVAILABLE";
|
|
|
|
export type PollLeasePolicy = Readonly<{
|
|
operationId: string;
|
|
owner: string;
|
|
minimumIntervalMs: number;
|
|
successIntervalMs: number;
|
|
maxIntervalMs: number;
|
|
maxAttempts: number;
|
|
maxElapsedMs: number;
|
|
maxResponseBytes: number;
|
|
visibility: "VISIBLE_ONLY";
|
|
fallbackReason: PollFallbackReason;
|
|
terminalStates: readonly string[];
|
|
}>;
|
|
|
|
/**
|
|
* 1103/04-01. A poll lease runs one installed V3 descriptor: the composed row
|
|
* (`composeContractContributions(...).httpByOperationId.get(id)`). The poll
|
|
* coordinator hands that same object back to `execute` as `input.operation`;
|
|
* pass it to the executor (`createContractHttpExecutor().execute`). The
|
|
* executor reads its retry ceiling from `frontend.retryBudget`, so a budget of
|
|
* 0 is what makes one poll attempt one physical request; the poll coordinator
|
|
* owns every retry between attempts. This type is the bound: the coordinator
|
|
* keeps the descriptor's own input and output types (1106/04-02).
|
|
*/
|
|
export type BoundedPollOperation = InstalledHttpContract<
|
|
unknown,
|
|
unknown,
|
|
unknown
|
|
>;
|
|
|
|
const OPERATION_ID = /^[A-Z][A-Z0-9_]{2,79}$/u;
|
|
const OWNER_ID = /^[A-Za-z][A-Za-z0-9._:-]{0,127}$/u;
|
|
const TERMINAL_STATE = /^[A-Z][A-Z0-9_]{0,63}$/u;
|
|
|
|
export function definePollLeasePolicy(
|
|
input: PollLeasePolicy,
|
|
): PollLeasePolicy {
|
|
if (
|
|
!input ||
|
|
typeof input !== "object" ||
|
|
!OPERATION_ID.test(input.operationId) ||
|
|
!OWNER_ID.test(input.owner) ||
|
|
input.visibility !== "VISIBLE_ONLY" ||
|
|
![
|
|
"CONVERGENCE",
|
|
"RELAXED_FRESHNESS",
|
|
"STREAM_DEGRADED",
|
|
"STREAM_UNAVAILABLE",
|
|
].includes(input.fallbackReason) ||
|
|
!isIntegerWithin(
|
|
input.minimumIntervalMs,
|
|
BOUNDED_POLLING_CEILINGS.minimumIntervalMs,
|
|
BOUNDED_POLLING_CEILINGS.maxIntervalMs,
|
|
) ||
|
|
!isIntegerWithin(
|
|
input.successIntervalMs,
|
|
input.minimumIntervalMs,
|
|
BOUNDED_POLLING_CEILINGS.maxIntervalMs,
|
|
) ||
|
|
!isIntegerWithin(
|
|
input.maxIntervalMs,
|
|
input.successIntervalMs,
|
|
BOUNDED_POLLING_CEILINGS.maxIntervalMs,
|
|
) ||
|
|
!isIntegerWithin(
|
|
input.maxAttempts,
|
|
1,
|
|
BOUNDED_POLLING_CEILINGS.maxAttempts,
|
|
) ||
|
|
!isIntegerWithin(
|
|
input.maxElapsedMs,
|
|
input.minimumIntervalMs,
|
|
BOUNDED_POLLING_CEILINGS.maxElapsedMs,
|
|
) ||
|
|
!isIntegerWithin(
|
|
input.maxResponseBytes,
|
|
1,
|
|
BOUNDED_POLLING_CEILINGS.maxResponseBytes,
|
|
) ||
|
|
!Array.isArray(input.terminalStates) ||
|
|
input.terminalStates.length >
|
|
BOUNDED_POLLING_CEILINGS.maxTerminalStates ||
|
|
input.terminalStates.some(
|
|
(state) =>
|
|
typeof state !== "string" || !TERMINAL_STATE.test(state),
|
|
) ||
|
|
new Set(input.terminalStates).size !== input.terminalStates.length ||
|
|
(input.fallbackReason === "CONVERGENCE" &&
|
|
input.terminalStates.length === 0)
|
|
) {
|
|
throw new TypeError("Invalid bounded polling lease policy.");
|
|
}
|
|
|
|
return Object.freeze({
|
|
...input,
|
|
terminalStates: Object.freeze([...input.terminalStates]),
|
|
});
|
|
}
|
|
|
|
export function assertBoundedPollOperation(
|
|
policy: PollLeasePolicy,
|
|
operation: BoundedPollOperation,
|
|
): void {
|
|
const contract = operation?.contract;
|
|
const frontend = operation?.frontend;
|
|
if (
|
|
!contract ||
|
|
!frontend ||
|
|
contract.operationId !== policy.operationId ||
|
|
(contract.method !== "GET" && contract.method !== "HEAD") ||
|
|
(contract.retrySemantics !== "SAFE" &&
|
|
contract.retrySemantics !== "IDEMPOTENT") ||
|
|
frontend.retryBudget !== 0 ||
|
|
!isIntegerWithin(
|
|
frontend.responseByteLimit,
|
|
1,
|
|
BOUNDED_POLLING_CEILINGS.maxResponseBytes,
|
|
)
|
|
) {
|
|
throw new TypeError(
|
|
"Bounded polling operation must be a replay-safe read with retryBudget 0.",
|
|
);
|
|
}
|
|
}
|
|
|
|
function isIntegerWithin(
|
|
value: number,
|
|
minimum: number,
|
|
maximum: number,
|
|
): boolean {
|
|
return (
|
|
Number.isSafeInteger(value) &&
|
|
value >= minimum &&
|
|
value <= maximum
|
|
);
|
|
}
|