From a65df74046954061167b1761b8924d4b9b9ccf63 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:21:31 +0900 Subject: [PATCH 01/13] =?UTF-8?q?fix(realtime)!:=20bounded=20poll=EC=9D=84?= =?UTF-8?q?=20V3=20descriptor=EC=97=90=20=EB=AC=B6=EC=96=B4=20=EC=8B=A4?= =?UTF-8?q?=ED=96=89=EA=B8=B0=20=EC=9E=AC=EC=8B=9C=EB=8F=84=EB=A5=BC=20?= =?UTF-8?q?=EB=A7=89=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 BoundedPollOperationContract는 지운 V2 행의 어휘(contractVersion: 2, protocol, semantics, replayPolicy, retry, transportMaxAttempts, authRecoveryCount, maxCumulativeSleepMs, serverStream)로 된 자기 선언이다. assertBoundedPollOperation은 리터럴만 보고 실제로 실행할 descriptor와 대조하지 않는다. 조합 코드가 execute를 V3 실행기와 기본 GET descriptor(retryBudget 2)로 만들면 503마다 실행기가 두 번 더 보낸다. poll 3회가 요청 9회가 되고, poll 관측에는 1건씩만 보인다(리뷰 실험 P). 고른 방법 - coordinator의 operation을 V3 descriptor(InstalledHttpContract)로 바꾼다. 실행기는 재시도 상한을 그 descriptor의 frontend.retryBudget에서 읽는다 (http-execution-v3.ts retryCeiling). 그래서 생성 때 retryBudget === 0을 요구하면 실행기 옵션 없이 poll 한 attempt가 요청 한 번이 된다. 실행기(src/adapters/http)는 고치지 않았다. - 검사: operationId 일치, method GET·HEAD, retrySemantics SAFE·IDEMPOTENT, retryBudget 0, responseByteLimit 1..8 MiB. execute에 넘기는 maxResponseBytes는 min(policy.maxResponseBytes, responseByteLimit)이다. - V2 리터럴 필드는 모두 지운다. command descriptor·요청 본문은 조립 (composeContractContributions)이 GET·HEAD에서 이미 거절한다. - 버린 대안: (a) ApiOperationRow + HttpExecutionPolicy 두 인자. 행에는 retryBudget이 없고, 실행기가 실제로 받는 것은 descriptor 하나라 같은 객체를 넘기는 쪽이 어긋날 틈이 작다. (b) 실행기에 호출별 재시도 끄기 옵션 추가. 다른 에이전트가 고치는 http 영역을 건드리고, descriptor가 재시도를 허용한다는 사실은 그대로 남는다. (c) 문서에만 적기. 검출이 없다. 위험·한계 - 공개 타입이 바뀐다. repo 안 소비자는 테스트뿐이다. - 조합 코드가 coordinator에 넘긴 descriptor와 다른 객체를 실행기에 넘기면 막지 못한다. 타입 주석과 설계 9.2에 "같은 객체를 넘긴다"고 적었다. 조립된 행은 동결돼 있어 검사 뒤 값이 바뀌지 않는다. - 기능의 기본 GET(retryBudget 2)은 poll에 쓸 수 없다. poll 전용 operation을 따로 등록해야 한다. 검증 - 새 테스트를 옛 코드에 돌림: 21건 실패(RED). 새 코드: 32건 통과. - 실험 P를 테스트로 옮김: 기본 descriptor는 생성 때 TypeError, retryBudget 0 descriptor + maxRetryAttempts 2 실행기 + 503 서버에서 poll 3회 = 요청 3회. - 변이 5건(retryBudget·method·retrySemantics·operationId·응답 상한 검사 삭제) 모두 검출. - check:types 통과, 바꾼 파일 eslint 통과. BREAKING CHANGE: BoundedPollOperationContract를 지운다. createBoundedPollCoordinator의 operation과 assertBoundedPollOperation의 둘째 인자는 V3 descriptor(BoundedPollOperation = InstalledHttpContract)다. 조립된 행(composeContractContributions(...).httpByOperationId.get(id))을 넘기고, frontend.retryBudget을 0으로 둔 poll 전용 operation을 등록한다. execute 안에서는 같은 descriptor를 실행기에 넘긴다. Refs: docs/reviews/2026-11-03-maturity-review/04-adapters-realtime.md 04-01 --- ...ime-events-web-push-and-bounded-polling.md | 26 ++- .../polling/bounded-poll-coordinator.ts | 10 +- src/application/policies/bounded-polling.ts | 58 +++---- .../realtime/bounded-poll-coordinator.test.ts | 162 +++++++++++++++--- .../realtime/bounded-polling-policy.test.ts | 91 ++++++---- 5 files changed, 244 insertions(+), 103 deletions(-) diff --git a/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index 0f192bd5..b5071c30 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -1606,13 +1606,25 @@ type PollLeasePolicy = Readonly<{ implementation absolute ceiling보다 느슨한 값, zero interval, unlimited attempt, unknown terminal state와 arbitrary operation ID는 startup에서 거절한다. -`operationId`는 existing API registry의 terminal `QUERY`, `REST`, -`SAFE | IDEMPOTENT`, non-`SERVER_STREAM` operation이어야 한다. command/mutation, -GraphQL subscription, Connect/gRPC-Web server stream과 arbitrary status URL은 poll하지 -않는다. Poll-bound operation의 transport retry profile과 TanStack Query retry는 -`NONE`/`false`여야 한다. 구체적으로 VD-23 `LogicalExecutionBudget`은 -`maxAttempts=1`, `authRecoveryCount=0`, `maxCumulativeSleepMs=0`으로 고정해 -executor 내부 status retry나 401 replay가 일어나지 않게 한다. +poll coordinator는 실행할 V3 descriptor(`InstalledHttpContract`, 조립된 행 +`composeContractContributions(...).httpByOperationId.get(id)`)를 직접 받는다 +(1103/04-01). 생성 때 `assertBoundedPollOperation`이 그 descriptor를 본다. + +- `contract.operationId`가 lease의 `operationId`와 같다. +- `contract.method`가 `GET` 또는 `HEAD`다. +- `contract.retrySemantics`가 `SAFE` 또는 `IDEMPOTENT`다. +- `frontend.retryBudget`이 `0`이다. +- `frontend.responseByteLimit`이 poll 상한(8 MiB) 이하다. + +`retryBudget: 0`이 핵심이다. V3 실행기는 SAFE·IDEMPOTENT 읽기를 +`min(retryBudget, maxRetryAttempts, 2)`번 다시 보낸다 +(`http-execution-v3.ts` `retryCeiling`). 이 값을 descriptor에서 읽으므로, poll에 +묶은 descriptor가 0이면 실행기의 `maxRetryAttempts`(`MAX_RETRY_ATTEMPTS`)와 상관없이 +poll 한 attempt가 요청 한 번이다. 같은 descriptor를 `execute` 안에서 실행기에 +넘긴다. 기능의 기본 GET descriptor(`create:feature`는 `retryBudget: 2`)는 생성 때 +거절된다. poll 전용 operation을 따로 등록한다. V3에는 401 재전송이 없다. +command/mutation, GraphQL subscription, Connect/gRPC-Web server stream과 arbitrary +status URL은 poll하지 않는다. TanStack Query retry도 `false`여야 한다. 한 lease는 다음 조건 중 먼저 발생하는 시점에 종료한다. diff --git a/src/adapters/realtime/polling/bounded-poll-coordinator.ts b/src/adapters/realtime/polling/bounded-poll-coordinator.ts index dd463a8f..18804a90 100644 --- a/src/adapters/realtime/polling/bounded-poll-coordinator.ts +++ b/src/adapters/realtime/polling/bounded-poll-coordinator.ts @@ -1,7 +1,7 @@ import { assertBoundedPollOperation, definePollLeasePolicy, - type BoundedPollOperationContract, + type BoundedPollOperation, type PollLeasePolicy, } from "../../../application/policies/bounded-polling.ts"; import type { ClockPort } from "../../../application/ports/clock-port.ts"; @@ -96,7 +96,11 @@ export type BoundedPollObservation = Readonly<{ export type BoundedPollCoordinatorDependencies = Readonly<{ policy: PollLeasePolicy; - operation: BoundedPollOperationContract; + /** + * The V3 descriptor `execute` runs (`BoundedPollOperation`). Creation + * refuses one whose `frontend.retryBudget` is not 0. + */ + operation: BoundedPollOperation; execute(input: Readonly<{ operationId: string; attempt: number; @@ -131,7 +135,7 @@ export function createBoundedPollCoordinator( assertBoundedPollOperation(policy, dependencies.operation); const maxResponseBytes = Math.min( policy.maxResponseBytes, - dependencies.operation.maxResponseBytes, + dependencies.operation.frontend.responseByteLimit, ); const clock = dependencies.clock ?? systemClock; const random = dependencies.random ?? Math.random; diff --git a/src/application/policies/bounded-polling.ts b/src/application/policies/bounded-polling.ts index bea0609d..8d343df0 100644 --- a/src/application/policies/bounded-polling.ts +++ b/src/application/policies/bounded-polling.ts @@ -1,3 +1,5 @@ +import type { InstalledHttpContract } from "../../contracts/external-contract-runtime.ts"; + export const BOUNDED_POLLING_CEILINGS = Object.freeze({ minimumIntervalMs: 5_000, maxIntervalMs: 60_000, @@ -28,24 +30,18 @@ export type PollLeasePolicy = Readonly<{ }>; /** - * The HTTP executor used by a poll lease must represent exactly one physical - * request. Transport retry, credential replay and cumulative retry sleep stay - * disabled so a poll attempt cannot hide additional requests. + * 1103/04-01. A poll lease runs one installed V3 descriptor: the composed row + * (`composeContractContributions(...).httpByOperationId.get(id)`). Hand the + * same object 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. */ -export type BoundedPollOperationContract = Readonly<{ - operationId: string; - contractVersion: 2; - protocol: "REST"; - semantics: "QUERY"; - method: "GET" | "HEAD"; - replayPolicy: "SAFE" | "IDEMPOTENT"; - retry: "never"; - maxResponseBytes: number; - transportMaxAttempts: 1; - authRecoveryCount: 0; - maxCumulativeSleepMs: 0; - serverStream: false; -}>; +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; @@ -118,30 +114,26 @@ export function definePollLeasePolicy( export function assertBoundedPollOperation( policy: PollLeasePolicy, - operation: BoundedPollOperationContract, + operation: BoundedPollOperation, ): void { + const contract = operation?.contract; + const frontend = operation?.frontend; if ( - !operation || - typeof operation !== "object" || - operation.operationId !== policy.operationId || - operation.contractVersion !== 2 || - operation.protocol !== "REST" || - operation.semantics !== "QUERY" || - !["GET", "HEAD"].includes(operation.method) || - !["SAFE", "IDEMPOTENT"].includes(operation.replayPolicy) || - operation.retry !== "never" || - operation.serverStream !== false || - operation.transportMaxAttempts !== 1 || - operation.authRecoveryCount !== 0 || - operation.maxCumulativeSleepMs !== 0 || + !contract || + !frontend || + contract.operationId !== policy.operationId || + (contract.method !== "GET" && contract.method !== "HEAD") || + (contract.retrySemantics !== "SAFE" && + contract.retrySemantics !== "IDEMPOTENT") || + frontend.retryBudget !== 0 || !isIntegerWithin( - operation.maxResponseBytes, + frontend.responseByteLimit, 1, BOUNDED_POLLING_CEILINGS.maxResponseBytes, ) ) { throw new TypeError( - "Bounded polling operation must be one terminal replay-safe REST request.", + "Bounded polling operation must be a replay-safe read with retryBudget 0.", ); } } diff --git a/tests/unit/realtime/bounded-poll-coordinator.test.ts b/tests/unit/realtime/bounded-poll-coordinator.test.ts index acbddaa4..b5412809 100644 --- a/tests/unit/realtime/bounded-poll-coordinator.test.ts +++ b/tests/unit/realtime/bounded-poll-coordinator.test.ts @@ -1,12 +1,17 @@ import { describe, expect, it, vi } from "vitest"; import type { ClockPort } from "../../../src/application/ports/clock-port.ts"; -import { definePollLeasePolicy } from "../../../src/application/policies/bounded-polling.ts"; +import { + definePollLeasePolicy, + type BoundedPollOperation, +} from "../../../src/application/policies/bounded-polling.ts"; +import { createContractHttpExecutor } from "../../../src/adapters/http/index.ts"; import { createBoundedPollCoordinator, type BoundedPollAttemptResult, type BoundedPollEnvironment, } from "../../../src/adapters/realtime/polling/bounded-poll-coordinator.ts"; +import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts"; type Sleeper = { dueAt: number; @@ -117,20 +122,26 @@ const policy = definePollLeasePolicy({ fallbackReason: "CONVERGENCE", terminalStates: ["COMPLETED", "FAILED"], }); -const operation = { - operationId: "GET_JOB_STATUS", - contractVersion: 2, - protocol: "REST", - semantics: "QUERY", - method: "GET", - replayPolicy: "SAFE", - retry: "never", - maxResponseBytes: 1_024, - transportMaxAttempts: 1, - authRecoveryCount: 0, - maxCumulativeSleepMs: 0, - serverStream: false, -} as const; +const operation: BoundedPollOperation = Object.freeze({ + contract: Object.freeze({ + ...TEST_LIST_HTTP_CONTRACT.contract, + operationId: "GET_JOB_STATUS", + }), + frontend: Object.freeze({ + ...TEST_LIST_HTTP_CONTRACT.frontend, + responseByteLimit: 1_024, + retryBudget: 0 as const, + }), +}) as BoundedPollOperation; + +function withResponseByteLimit( + responseByteLimit: number, +): BoundedPollOperation { + return { + ...operation, + frontend: { ...operation.frontend, responseByteLimit }, + }; +} async function flush(): Promise { for (let turn = 0; turn < 12; turn += 1) { @@ -284,10 +295,7 @@ describe("bounded poll coordinator", () => { ); const coordinator = createBoundedPollCoordinator({ policy, - operation: { - ...operation, - maxResponseBytes: 4_096, - }, + operation: withResponseByteLimit(4_096), execute, environment: new MutableEnvironment(), clock, @@ -970,10 +978,7 @@ describe("bounded poll coordinator", () => { const clock = new ManualClock(); const coordinator = createBoundedPollCoordinator({ policy, - operation: { - ...operation, - maxResponseBytes: 512, - }, + operation: withResponseByteLimit(512), environment: new MutableEnvironment(), clock, execute: async () => ({ @@ -1019,3 +1024,114 @@ describe("bounded poll coordinator", () => { expect(coordinator.getState()).toBe("CLOSED"); }); }); + +// 1103/04-01. The natural composition: `execute` runs the poll's descriptor on +// the app's V3 executor. The executor's own retries would turn one poll attempt +// into up to three requests, hidden from the poll's budget and observations. +describe("a poll attempt on the V3 executor", () => { + const pollPolicy = definePollLeasePolicy({ + operationId: TEST_LIST_HTTP_CONTRACT.contract.operationId, + owner: "reference-job", + minimumIntervalMs: 5_000, + successIntervalMs: 5_000, + maxIntervalMs: 60_000, + maxAttempts: 3, + maxElapsedMs: 600_000, + maxResponseBytes: 32_768, + visibility: "VISIBLE_ONLY", + fallbackReason: "STREAM_UNAVAILABLE", + terminalStates: [], + }); + const scope = Object.freeze({ + generation: 1, + fingerprint: "scope-1", + identities: Object.freeze({}) as never, + signal: new AbortController().signal, + isCurrent: () => true, + }); + + function pollOn(descriptor: BoundedPollOperation, clock: ManualClock) { + const requests: string[] = []; + const executor = createContractHttpExecutor({ + baseUrl: "https://api.example/", + // The app default (`MAX_RETRY_ATTEMPTS`). + maxRetryAttempts: 2, + attachCredentials: () => ({ kind: "READY", headers: {} }), + fetcher: async (request) => { + requests.push(String(request)); + return new Response( + JSON.stringify({ type: "about:blank", title: "down", status: 503 }), + { + status: 503, + headers: { "content-type": "application/problem+json" }, + }, + ); + }, + sleep: async () => undefined, + random: () => 0.5, + createRequestId: () => "req-1", + }); + const coordinator = createBoundedPollCoordinator({ + policy: pollPolicy, + operation: descriptor, + environment: new MutableEnvironment(), + clock, + random: () => 0.5, + execute: async ({ signal }) => { + const outcome = await executor.execute( + descriptor, + { limit: 20 }, + { routeId: "TEST_ROUTE", scope, signal }, + ); + return outcome.kind === "SUCCESS" + ? { + ok: true, + value: { kind: "VALUE", value: outcome.value, responseBytes: 1 }, + } + : { + ok: false, + error: { + kind: "PROVIDER_UNAVAILABLE", + operation: "POLL", + retryable: true, + }, + }; + }, + }); + return { coordinator, requests }; + } + + it("refuses the default read descriptor, whose executor retries", () => { + expect(TEST_LIST_HTTP_CONTRACT.frontend.retryBudget).toBe(2); + expect(() => + pollOn(TEST_LIST_HTTP_CONTRACT as BoundedPollOperation, new ManualClock()), + ).toThrow(TypeError); + }); + + it("sends one request per poll attempt with a poll descriptor", async () => { + const clock = new ManualClock(); + const pollOnly = Object.freeze({ + ...TEST_LIST_HTTP_CONTRACT, + frontend: Object.freeze({ + ...TEST_LIST_HTTP_CONTRACT.frontend, + retryBudget: 0 as const, + }), + }) as BoundedPollOperation; + const { coordinator, requests } = pollOn(pollOnly, clock); + + let result: unknown = null; + void coordinator.run().then((value) => { + result = value; + }); + for (let turn = 0; turn < 400 && result === null; turn += 1) { + clock.advance(1_000); + await flush(); + } + + expect(result).toMatchObject({ + ok: false, + error: { kind: "POLL_BUDGET_EXHAUSTED" }, + }); + expect(requests).toHaveLength(pollPolicy.maxAttempts); + }); +}); diff --git a/tests/unit/realtime/bounded-polling-policy.test.ts b/tests/unit/realtime/bounded-polling-policy.test.ts index abcea2b9..07cc4b78 100644 --- a/tests/unit/realtime/bounded-polling-policy.test.ts +++ b/tests/unit/realtime/bounded-polling-policy.test.ts @@ -4,8 +4,9 @@ import { BOUNDED_POLLING_CEILINGS, assertBoundedPollOperation, definePollLeasePolicy, - type BoundedPollOperationContract, + type BoundedPollOperation, } from "../../../src/application/policies/bounded-polling.ts"; +import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts"; const input = { operationId: "GET_JOB_STATUS", @@ -56,50 +57,66 @@ describe("bounded polling policy", () => { ).toThrow(TypeError); }); - it("admits only a one-request terminal replay-safe REST query", () => { + // 1103/04-01. The V3 executor retries a SAFE or IDEMPOTENT read + // `min(retryBudget, maxRetryAttempts, 2)` times, reading the budget from the + // descriptor it executes. A poll binds that descriptor, not a declaration. + function pollOperation( + contract: Partial = {}, + frontend: Partial = {}, + ): BoundedPollOperation { + return { + contract: { + ...TEST_LIST_HTTP_CONTRACT.contract, + operationId: "GET_JOB_STATUS", + ...contract, + }, + frontend: { + ...TEST_LIST_HTTP_CONTRACT.frontend, + retryBudget: 0, + responseByteLimit: 16_384, + ...frontend, + }, + } as BoundedPollOperation; + } + + it("admits a replay-safe read whose descriptor turns transport retry off", () => { const policy = definePollLeasePolicy(input); - const operation: BoundedPollOperationContract = { - operationId: "GET_JOB_STATUS", - contractVersion: 2, - protocol: "REST", - semantics: "QUERY", - method: "GET", - replayPolicy: "SAFE", - retry: "never", - maxResponseBytes: 16_384, - transportMaxAttempts: 1, - authRecoveryCount: 0, - maxCumulativeSleepMs: 0, - serverStream: false, - }; expect(() => - assertBoundedPollOperation(policy, operation), + assertBoundedPollOperation(policy, pollOperation()), ).not.toThrow(); expect(() => - assertBoundedPollOperation(policy, { - ...operation, - transportMaxAttempts: 2 as 1, - }), - ).toThrow(TypeError); - expect(() => - assertBoundedPollOperation(policy, { - ...operation, - maxResponseBytes: 8_192, - }), + assertBoundedPollOperation( + policy, + pollOperation({ method: "HEAD", retrySemantics: "IDEMPOTENT" }), + ), ).not.toThrow(); expect(() => - assertBoundedPollOperation(policy, { - ...operation, - maxResponseBytes: 0, - }), - ).toThrow(TypeError); + assertBoundedPollOperation( + policy, + pollOperation({}, { responseByteLimit: 8_192 }), + ), + ).not.toThrow(); + }); + + it.each([ + ["another operation", { operationId: "GET_OTHER_STATUS" }, {}], + ["one transport retry", {}, { retryBudget: 1 as const }], + ["two transport retries", {}, { retryBudget: 2 as const }], + ["a write method", { method: "POST" as const }, {}], + ["keyed retry semantics", { retrySemantics: "KEYED" as const }, {}], + ["never retry semantics", { retrySemantics: "NEVER" as const }, {}], + ["an empty response limit", {}, { responseByteLimit: 0 }], + [ + "a response limit over the poll ceiling", + {}, + { responseByteLimit: BOUNDED_POLLING_CEILINGS.maxResponseBytes + 1 }, + ], + ])("refuses a descriptor with %s", (_case, contract, frontend) => { + const policy = definePollLeasePolicy(input); + expect(() => - assertBoundedPollOperation(policy, { - ...operation, - maxResponseBytes: - BOUNDED_POLLING_CEILINGS.maxResponseBytes + 1, - }), + assertBoundedPollOperation(policy, pollOperation(contract, frontend)), ).toThrow(TypeError); }); }); From af000673efc022d02a190c7f999954d8cddfbcbb Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:23:21 +0900 Subject: [PATCH 02/13] =?UTF-8?q?fix(realtime)!:=20=EC=84=9C=EB=B2=84?= =?UTF-8?q?=EC=97=90=20=EB=8B=BF=EC=A7=80=20=EC=95=8A=EC=9D=80=20SSE=C2=B7?= =?UTF-8?q?poll=20=EC=8B=A4=ED=8C=A8=EB=A5=BC=20PROVIDER=5FUNAVAILABLE?= =?UTF-8?q?=EB=A1=9C=20=EB=82=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 브라우저는 online인데 서버·프록시만 닿지 않을 때 실패 이름이 transport마다 다르다. SSE는 fetch·reader 거절을 OFFLINE, poll은 execute 거절을 OFFLINE, WebSocket은 error를 PROVIDER_UNAVAILABLE로 낸다. reconnect coordinator는 transport OFFLINE을 backoff로 재시도하고 예산을 다 쓰면 online인데도 OFFLINE으로 끝낸다. 설계 13.1의 OFFLINE 행은 "online hint 뒤 bounded check"라 5.3과 다른 말을 한다. kind로 화면 문구나 조합 판단을 고르면 같은 서버 장애가 SSE에서는 "오프라인", WS에서는 "서비스 이용 불가"가 되고, "OFFLINE이면 online 이벤트를 기다린다"는 조합 코드는 다시 멈춘다(0929/04-01의 모양). 고른 방법 - 리뷰 5.3절 판단대로 어휘를 맞춘다. SSE fetch 거절(CONNECT)과 reader 거절(RECEIVE), poll execute 거절을 PROVIDER_UNAVAILABLE(retryable)로 바꾼다. 이제 OFFLINE은 환경 신호에서만 나온다. - poll은 PROVIDER_UNAVAILABLE을 lease 안에서 재시도하므로, 던지는 execute는 바로 끝나지 않고 backoff로 maxAttempts까지 다시 시도한다. executor가 PROVIDER_UNAVAILABLE을 돌려준 경우와 같은 처리다. - 설계 13.1의 OFFLINE·PROVIDER_UNAVAILABLE 행과 5.3 문단을 고친다. - 버린 대안: 13.1에 OFFLINE의 두 뜻을 적기만 하기. 비용은 1행이지만 조합자가 navigator.onLine을 따로 봐야 원인을 안다. 운영 중인 제품이 없는 지금 어휘를 바꾸는 비용이 가장 작다(리뷰 5.3). 위험·한계 - 배럴로 공개된 SSE 연결·poll coordinator의 결과 kind가 바뀐다. repo 안 소비자는 테스트뿐이다. - 던지는 execute(조합 코드의 버그 포함)는 이제 lease 예산만큼 다시 불린다. 상한은 maxAttempts·maxElapsed 그대로다. - 환경 신호가 늦게 offline이 되는 경우 첫 실패는 PROVIDER_UNAVAILABLE로 보인다. offline 대기는 kind가 아니라 환경 신호로 걸리므로 멈춤은 없다 (before/after 테스트 그대로 통과). 검증 - 바꾼 기대값 3건을 옛 코드에 돌림: 3건 실패(RED). 새 코드: realtime 단위 241건 통과. - check:types 통과, 바꾼 파일 eslint 통과. BREAKING CHANGE: SSE 연결의 fetch·reader 거절과 bounded poll의 execute 거절이 OFFLINE 대신 PROVIDER_UNAVAILABLE(retryable)로 끝난다. poll은 던지는 execute를 lease 안에서 재시도한다. OFFLINE을 서버 장애로 읽던 조합 코드는 PROVIDER_UNAVAILABLE을 함께 본다. Refs: docs/reviews/2026-11-03-maturity-review/04-adapters-realtime.md 04-04 --- ...ime-events-web-push-and-bounded-polling.md | 12 +++--- .../polling/bounded-poll-coordinator.ts | 7 ++-- .../realtime/sse/fetch-sse-connection.ts | 6 ++- .../realtime/bounded-poll-coordinator.test.ts | 42 +++++++++++++++---- .../realtime-reconnect-coordinator.test.ts | 29 ++++++++----- 5 files changed, 68 insertions(+), 28 deletions(-) diff --git a/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index b5071c30..c7d70955 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -780,9 +780,11 @@ effectiveDelay = max(localDelay, validServerNotBefore) `navigator.onLine`은 실제 backend reachability authority가 아니다. offline 대기 시간은 elapsed budget에 넣지 않는다. online으로 돌아오면 elapsed budget을 다시 시작하고 attempt 상한은 유지한다 - (`reconnect-coordinator.ts:553-562`). 이 대기는 환경 신호가 offline일 때만 - 한다. transport가 보고한 `OFFLINE` 실패는 환경이 online이면 다른 retryable - 실패처럼 backoff로 재시도한다. 서버만 내려가면 online event가 오지 않는다. + (`reconnect-coordinator.ts:556-568`). 이 대기는 환경 신호가 offline일 때만 + 한다. 서버만 내려가면 online event가 오지 않는다. 그래서 템플릿 transport는 + 서버에 닿지 않은 실패를 `PROVIDER_UNAVAILABLE`로 보고하고, coordinator는 이를 + backoff로 재시도한다(1103/04-04). 조합 코드가 만든 transport가 `OFFLINE`을 + 보고해도 환경이 online이면 같은 backoff로 재시도한다. - auth expiry는 session owner의 single-flight recovery를 한 번 요청한다. 실패하면 `AUTH_REQUIRED`로 멈춘다. - protocol/schema/forbidden/policy failure는 retry하지 않는다. @@ -1905,13 +1907,13 @@ credential을 보호할 수 있다고 주장하지 않는다. | --- | --- | --- | | `ABORTED` | lifecycle/user cancellation | retry 없음 | | `UNSUPPORTED` | browser capability 없음 | declared fallback | -| `OFFLINE` | network hint/attempt failure | online hint 뒤 bounded check | +| `OFFLINE` | 환경 신호(`navigator.onLine` 등 조합 코드가 넘긴 `online()`)가 offline이다. 템플릿 transport는 이 kind를 내지 않는다(1103/04-04) | timer 없이 online hint를 기다린 뒤 bounded check. poll lease는 끝나고 `retryable: true`다 | | `CONNECT_TIMEOUT` | open deadline 초과 | bounded reconnect | | `IDLE_TIMEOUT` | transport: heartbeat/byte/unsubscribe deadline 초과(operation `RECEIVE`·`SUBSCRIBE`). 내부 task 마감에는 쓰지 않는다 | close + bounded reconnect | | `AUTH_REQUIRED` | session expired/recovery 실패 | sign-in UX | | `FORBIDDEN` | stream/resource 거절 | retry 없음 | | `RATE_LIMITED` | connection/request/provider limit | bounded server hint | -| `PROVIDER_UNAVAILABLE` | backend/push/hosting unavailable. stream coordinator의 recovery deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: false`). live↔Poll handoff coordinator의 checkpoint deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: true`) | bounded retry 또는 degraded. stream coordinator 마감은 재연결로 풀리지 않는다: task가 settle할 때까지 `DRAINING`을 유지한다. settle 뒤 recovery 마감은 다음 event가 recovery부터 하고, close 마감은 `CLOSED`가 된다. handoff checkpoint 마감은 그 전환을 fail-close하므로 새 handoff만 돌 수 있다. handoff close 마감 뒤에는 writer·checkpoint task가 settle하면 다시 부른 `close()`가 성공한다 | +| `PROVIDER_UNAVAILABLE` | backend/push/hosting unavailable. 환경은 online인데 서버·프록시에 닿지 않은 것(SSE fetch·reader 거절, WebSocket `error`, poll `execute` 거절)도 세 transport 모두 이 kind다(1103/04-04, `retryable: true`). stream coordinator의 recovery deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: false`). live↔Poll handoff coordinator의 checkpoint deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: true`) | bounded retry 또는 degraded. stream coordinator 마감은 재연결로 풀리지 않는다: task가 settle할 때까지 `DRAINING`을 유지한다. settle 뒤 recovery 마감은 다음 event가 recovery부터 하고, close 마감은 `CLOSED`가 된다. handoff checkpoint 마감은 그 전환을 fail-close하므로 새 handoff만 돌 수 있다. handoff close 마감 뒤에는 writer·checkpoint task가 settle하면 다시 부른 `close()`가 성공한다 | | `PROTOCOL_MISMATCH` | version/subprotocol/content type | terminal/rollout rollback | | `MALFORMED_EVENT` | state-bearing syntax/schema/exact-key 실패 | cursor 미진행, freshness `UNKNOWN`, close + registered recovery | | `MAPPING_CONTRACT_VIOLATION` | validated DTO의 registered mapper 실패 | effect/cache/cursor write 0, close + registered recovery | diff --git a/src/adapters/realtime/polling/bounded-poll-coordinator.ts b/src/adapters/realtime/polling/bounded-poll-coordinator.ts index 18804a90..c92908d3 100644 --- a/src/adapters/realtime/polling/bounded-poll-coordinator.ts +++ b/src/adapters/realtime/polling/bounded-poll-coordinator.ts @@ -320,8 +320,9 @@ export function createBoundedPollCoordinator( if (attemptOutcome.kind === "VALUE") { result = attemptOutcome.value; } else if (attemptOutcome.kind === "REJECTED") { + // 1103/04-04. No server answered; OFFLINE is the environment's. result = realtimeFailure( - controller.signal.aborted ? "ABORTED" : "OFFLINE", + controller.signal.aborted ? "ABORTED" : "PROVIDER_UNAVAILABLE", "POLL", !controller.signal.aborted, ); @@ -389,8 +390,8 @@ export function createBoundedPollCoordinator( !result.error.retryable || !isPollRetryableFailureKind(result.error.kind) ) { - // OFFLINE (a thrown executor included) ends this lease but stays - // retryable, like every other OFFLINE here. + // OFFLINE ends this lease but stays retryable, like every other + // OFFLINE here. return pollFailure( result.error.kind, result.error.kind === "OFFLINE" && result.error.retryable, diff --git a/src/adapters/realtime/sse/fetch-sse-connection.ts b/src/adapters/realtime/sse/fetch-sse-connection.ts index e7fcd788..bd920d5b 100644 --- a/src/adapters/realtime/sse/fetch-sse-connection.ts +++ b/src/adapters/realtime/sse/fetch-sse-connection.ts @@ -214,9 +214,11 @@ export function createFetchSseConnection( controller.abort(); return failed("CONNECT_TIMEOUT", "CONNECT", true); } + // 1103/04-04. A rejected fetch says no server answered, not that the + // device is offline: PROVIDER_UNAVAILABLE, as WebSocket reports it. if (responseResult.kind === "REJECTED") { return failed( - controller.signal.aborted ? "ABORTED" : "OFFLINE", + controller.signal.aborted ? "ABORTED" : "PROVIDER_UNAVAILABLE", "CONNECT", !controller.signal.aborted, ); @@ -399,7 +401,7 @@ export function createFetchSseConnection( } if (readResult.kind === "REJECTED") { return failed( - controller.signal.aborted ? "ABORTED" : "OFFLINE", + controller.signal.aborted ? "ABORTED" : "PROVIDER_UNAVAILABLE", "RECEIVE", !controller.signal.aborted, ); diff --git a/tests/unit/realtime/bounded-poll-coordinator.test.ts b/tests/unit/realtime/bounded-poll-coordinator.test.ts index b5412809..c2c9cfd3 100644 --- a/tests/unit/realtime/bounded-poll-coordinator.test.ts +++ b/tests/unit/realtime/bounded-poll-coordinator.test.ts @@ -10,6 +10,7 @@ import { createBoundedPollCoordinator, type BoundedPollAttemptResult, type BoundedPollEnvironment, + type BoundedPollObservation, } from "../../../src/adapters/realtime/polling/bounded-poll-coordinator.ts"; import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts"; @@ -902,22 +903,47 @@ describe("bounded poll coordinator", () => { }); }); - it("ends a run whose executor throws with a retryable OFFLINE", async () => { + // 1103/04-04. A rejected executor means the request did not reach a server + // that answered. It is PROVIDER_UNAVAILABLE, retried within the lease like + // one the executor reports; OFFLINE comes only from the environment. + it("retries a throwing executor as PROVIDER_UNAVAILABLE within the lease", async () => { const clock = new ManualClock(); + const observations: BoundedPollObservation[] = []; + const execute = vi.fn(async (): Promise> => { + throw new TypeError("Failed to fetch"); + }); const coordinator = createBoundedPollCoordinator({ policy, operation, environment: new MutableEnvironment(), clock, - execute: async () => { - throw new TypeError("Failed to fetch"); - }, + random: () => 0.5, + execute, + observe: (observation) => observations.push(observation), }); - const running = coordinator.run(); - clock.advance(5_000); - await expect(running).resolves.toEqual({ + + let result: unknown = null; + void coordinator.run().then((value) => { + result = value; + }); + for (let turn = 0; turn < 120 && result === null; turn += 1) { + clock.advance(1_000); + await flush(); + } + + expect(execute).toHaveBeenCalledTimes(policy.maxAttempts); + expect( + observations + .filter((observation) => observation.kind === "ATTEMPT_FINISHED") + .map((observation) => observation.outcome), + ).toEqual([ + "PROVIDER_UNAVAILABLE", + "PROVIDER_UNAVAILABLE", + "PROVIDER_UNAVAILABLE", + ]); + expect(result).toMatchObject({ ok: false, - error: { kind: "OFFLINE", operation: "POLL", retryable: true }, + error: { kind: "POLL_BUDGET_EXHAUSTED", operation: "POLL" }, }); }); diff --git a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts index 7a7b1b63..abf6b80e 100644 --- a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts +++ b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts @@ -2088,9 +2088,10 @@ describe("transport failures through the reconnect coordinator", () => { }, ); - // The SSE adapter reports a rejected fetch or read as OFFLINE, but // navigator.onLine stays true when only the server is down, so no online - // event ever arrives (0929/04-01). + // event ever arrives (0929/04-01). The SSE adapter reports a rejected fetch + // or read as PROVIDER_UNAVAILABLE, as WebSocket does; OFFLINE comes only + // from the environment signal (1103/04-04). it("retries an SSE fetch rejection with backoff while the browser stays online", async () => { const clock = new ManualClock(); const fetcher = vi @@ -2120,15 +2121,19 @@ describe("transport failures through the reconnect coordinator", () => { ]); expect(result).toEqual({ ok: false, - error: { kind: "OFFLINE", operation: "CONNECT", retryable: true }, + error: { + kind: "PROVIDER_UNAVAILABLE", + operation: "CONNECT", + retryable: true, + }, }); expect(observed).toEqual([ "ATTEMPT_STARTED", - "RETRY_SCHEDULED:OFFLINE", + "RETRY_SCHEDULED:PROVIDER_UNAVAILABLE", "ATTEMPT_STARTED", - "RETRY_SCHEDULED:OFFLINE", + "RETRY_SCHEDULED:PROVIDER_UNAVAILABLE", "ATTEMPT_STARTED", - "RUN_ENDED:OFFLINE:EXHAUSTED", + "RUN_ENDED:PROVIDER_UNAVAILABLE:EXHAUSTED", ]); }); @@ -2175,17 +2180,21 @@ describe("transport failures through the reconnect coordinator", () => { expect(fetcher).toHaveBeenCalledTimes(3); expect(result).toEqual({ ok: false, - error: { kind: "OFFLINE", operation: "CONNECT", retryable: true }, + error: { + kind: "PROVIDER_UNAVAILABLE", + operation: "CONNECT", + retryable: true, + }, }); expect(observed).toEqual([ "ATTEMPT_STARTED", "SESSION_OPENED", "SESSION_CLOSED", - "RETRY_SCHEDULED:OFFLINE", + "RETRY_SCHEDULED:PROVIDER_UNAVAILABLE", "ATTEMPT_STARTED", - "RETRY_SCHEDULED:OFFLINE", + "RETRY_SCHEDULED:PROVIDER_UNAVAILABLE", "ATTEMPT_STARTED", - "RUN_ENDED:OFFLINE:EXHAUSTED", + "RUN_ENDED:PROVIDER_UNAVAILABLE:EXHAUSTED", ]); }); From a145f30b48d77d30cf4ac56e5a98aee662499f84 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:24:14 +0900 Subject: [PATCH 03/13] =?UTF-8?q?fix(web-push):=20dot=20segment=EA=B0=80?= =?UTF-8?q?=20=EB=93=A0=20registry=20path=EB=A5=BC=20=EC=83=9D=EC=84=B1=20?= =?UTF-8?q?=EB=95=8C=20=EA=B1=B0=EC=A0=88=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 registry path는 router base path를 뺀 앱 경로이고, 정상 클릭은 `${appBasePath}${path}`를 URL로 풀어 연다. registry 검사는 `/` 시작, `//`·`\`·`#` 금지, 같은 origin만 본다. URL parser는 `..`와 `%2e%2e`를 dot segment로 풀기 때문에 scope `/app/`에서 `/../admin`과 `/%2e%2e/admin`이 모두 `https://app.example.test/admin`을 연다(리뷰 실험 ⑤). 검사를 통과한 경로가 앱 밖을 연다. 고른 방법 - safePath가 `new URL(path, base)`의 pathname + search가 입력과 같을 때만 받는다. `..`·`.`·`%2e%2e`(대소문자 무관)는 parser가 바꾸므로 거절된다. query는 그대로 남는다. - 버린 대안: 클릭 때 target.pathname이 앱 루트 아래인지 보기. 잘못된 registry가 클릭할 때에야 드러난다. registry는 제품 코드라 생성 시점에 throw하는 쪽이 이르고 작다(리뷰 5.3 (a)). 위험·한계 - 정규화되지 않은 경로(인코딩 안 된 비ASCII 문자, 빈 query `?`)도 거절된다. registry를 쓰는 제품 코드는 아직 없다. - registry가 서버가 내려주는 런타임 데이터가 되면 클릭 때 검사도 함께 둬야 한다(리뷰 재검토 조건). 검증 - 새 테스트를 옛 코드에 돌림: 5건 실패(RED). 새 코드: web-push 단위 6파일 76건 통과. - 바꾼 파일 eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/06-adapters-service-worker-push.md 06-02 --- ...ime-events-web-push-and-bounded-polling.md | 4 ++- .../web-push/notification-registry.ts | 8 ++++- tests/unit/web-push-worker-runtime.test.ts | 34 +++++++++++++++++++ 3 files changed, 44 insertions(+), 2 deletions(-) diff --git a/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index c7d70955..8b34816d 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -1552,7 +1552,9 @@ NotificationClickDataV1 registry `path`는 router base path를 뺀 앱 기준 경로다. 정상 click은 그 경로를 같은 앱 루트 아래에서 연다(`/app/` + `/inbox` → `/app/inbox`). 열린 창에 보내는 handoff `path`는 registry 값 그대로(`/inbox`)라서 router basename과 겹치지 -않는다(06-01). +않는다(06-01). registry는 URL parser가 바꾸지 않는 경로만 받는다. +`/../admin`, `/%2e%2e/admin`, `/./inbox`는 생성 때 거절한다. 이어 붙인 뒤 +parser가 dot segment를 풀면 base path 밖이 열리기 때문이다(1103/06-02). route intent가 stale/unknown이면 안전한 notification inbox/home으로 이동한다. notification action 자체에서 destructive 업무 mutation을 실행하려면 별도의 diff --git a/src/adapters/web-push/notification-registry.ts b/src/adapters/web-push/notification-registry.ts index 09eb0ed1..7d5ca99e 100644 --- a/src/adapters/web-push/notification-registry.ts +++ b/src/adapters/web-push/notification-registry.ts @@ -116,7 +116,13 @@ function safePath(path: string): boolean { } try { const parsed = new URL(path, "https://registry.invalid"); - return parsed.origin === "https://registry.invalid"; + // 1103/06-02. The click opens `${basePath}${path}`, and URL parsing would + // drop the base for `..` or `%2e%2e`. Only an already-normal path stays + // under the app root. + return ( + parsed.origin === "https://registry.invalid" && + parsed.pathname + parsed.search === path + ); } catch { return false; } diff --git a/tests/unit/web-push-worker-runtime.test.ts b/tests/unit/web-push-worker-runtime.test.ts index 093d6e25..75877c65 100644 --- a/tests/unit/web-push-worker-runtime.test.ts +++ b/tests/unit/web-push-worker-runtime.test.ts @@ -418,6 +418,40 @@ describe("Web Push worker runtime", () => { ]); }); + // 1103/06-02. The click joins the base path and the registry path, then + // the URL parser resolves dot segments, so `/app/` + `/../admin` opens + // `/admin`. The registry takes only a path that parsing leaves unchanged. + it.each(["/../admin", "/%2e%2e/admin", "/%2E%2E/admin", "/./inbox", "/inbox/.."])( + "refuses a registry path that parsing would rewrite: %s", + (path) => { + expect(() => + createWebPushNotificationRegistry([ + { + notificationType: "INBOX_ACTIVITY", + routeIntent: "OPEN_INBOX", + title: "새 알림이 있습니다", + body: "앱을 열어 최신 내용을 확인하세요.", + path, + }, + ]), + ).toThrow(TypeError); + }, + ); + + it("keeps a registry path with a query", () => { + expect( + createWebPushNotificationRegistry([ + { + notificationType: "INBOX_ACTIVITY", + routeIntent: "OPEN_INBOX", + title: "새 알림이 있습니다", + body: "앱을 열어 최신 내용을 확인하세요.", + path: "/inbox?filter=unread", + }, + ]).routePath("OPEN_INBOX"), + ).toBe("/inbox?filter=unread"); + }); + describe("a rejected click opens the app root (Q-6.6-11, D-14)", () => { async function rejectedClick( options: Readonly<{ at?: number; data?: unknown }>, From 0f58abbd328775e242c845af011576eb830e5f8d Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:26:24 +0900 Subject: [PATCH 04/13] =?UTF-8?q?fix(hosting):=20live=20probe=EA=B0=80=20?= =?UTF-8?q?=EC=82=AC=EC=A0=84=20=EC=BA=90=EC=8B=9C=20=ED=99=95=EC=9E=A5?= =?UTF-8?q?=EC=9E=90=EB=A7=88=EB=8B=A4=20Content-Type=EC=9D=84=20=ED=99=95?= =?UTF-8?q?=EC=9D=B8=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 워커 install은 사전 캐시 자산마다 응답 MIME이 manifest 값 (CACHEABLE_ASSET_CONTENT_TYPES: .css .js .mjs .png .svg .webp .woff2)과 정확히 같아야 하고, 하나라도 틀리면 release 전체를 거절한다. 호스팅 live probe는 index가 가리키는 entry script 하나만 요청하고 hashedAsset.contentTypes도 JavaScript뿐이다. 그래서 CSS를 text/plain, 글꼴을 octet-stream으로 보내는 호스트도 게이트는 PASS다. 페이지는 글꼴을 그대로 쓰므로 워커만 조용히 설치되지 않는다. 고른 방법 - probeAssetContentTypes를 더한다. 후보 dist의 assets/에서 확장자마다 첫 파일(이름순)을 요청하고, 그 확장자의 워커 표 MIME과 비교한다. 결과는 surface hashedAsset., header content-type이다. verify-hosting-headers live 모드에서만 부른다. - 기대 MIME은 워커 표에서 바로 읽는다. .js 계열은 hashedAsset surface와 같이 application/javascript도 받는다. 두 목록이 같다는 것을 테스트가 지킨다(acceptedAssetContentTypes(".js") = cache-policy hashedAsset). - 운영 문서(release-cache-rollback.md)에 새 검사를 적는다. - 버린 대안: (b) 워커가 비JS 자산 MIME을 느슨하게 받기 — 캐시에서 꺼낸 응답이 틀린 MIME을 그대로 갖고 설계 §18 확인 순서 4와 어긋난다. (c) 사전 캐시를 JS·CSS로 줄이기 — 글꼴 캐시 이득을 잃는다. (d) 문서만 — 검출이 없다(리뷰 5.2). 위험·한계 - live probe 요청이 확장자 수만큼 는다(지금 빌드는 .js·.css 2개). - 확장자마다 파일 하나만 본다. 같은 확장자 안에서 경로마다 MIME이 다른 호스트는 잡지 못한다. - cache-control은 이 자산들에서 다시 보지 않는다. entry script의 hashedAsset 검사가 그대로 본다. - 실제 호스트로 live 모드를 돌리지 않았다. fetcher 대역으로만 확인했다. - 하위 경로 base는 probe가 아직 거절한다(0929/13-06, 다른 영역). 새 함수는 base 기준 상대 경로로 요청하므로 그 수정 뒤에도 그대로 쓴다. 검증 - 새 테스트 4건을 옛 코드에 돌림: 4건 실패(RED). 새 코드: hosting-probe·service-worker-build-output 테스트 통과. - CSS를 text/plain으로 보내는 호스트 → hashedAsset.css FAIL. - check:types:node·check:types:test 통과, 바꾼 파일 eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/06-adapters-service-worker-push.md 06-03 --- docs/operations/release-cache-rollback.md | 7 +- scripts/lib/hosting-probe.ts | 65 ++++++++++++++++ scripts/verify-hosting-headers.ts | 3 + tests/unit/hosting-probe.test.ts | 91 +++++++++++++++++++++++ 4 files changed, 165 insertions(+), 1 deletion(-) diff --git a/docs/operations/release-cache-rollback.md b/docs/operations/release-cache-rollback.md index 2ec859a3..d3661342 100644 --- a/docs/operations/release-cache-rollback.md +++ b/docs/operations/release-cache-rollback.md @@ -72,7 +72,12 @@ for): the host must answer 200 with the same `index.html` (the same entry script) and the HTML headers, so a host without the SPA fallback fails (review 1101/13-04). When the build ships a worker it requests `/service-worker.js` and expects `no-cache`. The surfaces and their headers are -declared in `config/hosting/cache-policy.json`. +declared in `config/hosting/cache-policy.json`. For each cacheable extension the +release has under `assets/` (`.css`, `.js`, `.woff2` and the rest of +`CACHEABLE_ASSET_CONTENT_TYPES`) it requests the first such file and expects +exactly that type (`hashedAsset.css` and so on). The worker's install refuses +the whole release when one precached asset has another type, while a page +still uses a font served as `application/octet-stream` (review 1103/06-03). The served `release-manifest.json` must name the `buildId` and `releaseId` of the release being checked: correct headers on an earlier release are not diff --git a/scripts/lib/hosting-probe.ts b/scripts/lib/hosting-probe.ts index faf6473b..63cacf94 100644 --- a/scripts/lib/hosting-probe.ts +++ b/scripts/lib/hosting-probe.ts @@ -1,4 +1,7 @@ +import path from "node:path"; + import type { InstalledServiceWorkerSelection } from "../../src/contracts/service-worker.ts"; +import { CACHEABLE_ASSET_CONTENT_TYPES } from "../../src/contracts/service-worker-static-manifest.ts"; const LOOPBACK_IPV4 = /^127(?:\.\d{1,3}){3}$/; @@ -148,6 +151,68 @@ export async function probeLiveRelease( return { responses, results }; } +/** + * 1103/06-03. The types the probe accepts for a hashed asset: the worker's + * table (`CACHEABLE_ASSET_CONTENT_TYPES`), plus `application/javascript`, + * which servers still send for `.js` (R-6.5) and the `hashedAsset` surface in + * `config/hosting/cache-policy.json` also accepts. + */ +export function acceptedAssetContentTypes(extension: string): readonly string[] { + const type = Object.hasOwn(CACHEABLE_ASSET_CONTENT_TYPES, extension) + ? CACHEABLE_ASSET_CONTENT_TYPES[extension] + : undefined; + if (type === undefined) return []; + return type === "text/javascript" ? [type, "application/javascript"] : [type]; +} + +/** + * 1103/06-03. The worker's install compares every precached asset's + * Content-Type with the manifest's and refuses the whole release on one + * mismatch, while a page still uses, say, a font served as octet-stream. The + * entry script alone does not show that, so the live probe requests the first + * built `assets/` file of each cacheable extension. + */ +export async function probeAssetContentTypes( + base: URL, + distFiles: readonly string[], + fetcher: HostingFetcher = (url) => fetch(url, { redirect: "follow" }), +): Promise { + const samples = new Map(); + for (const file of distFiles.map((entry) => entry.split(path.sep).join("/")).sort()) { + const extension = path.posix.extname(file).toLowerCase(); + if ( + file.startsWith("assets/") && + acceptedAssetContentTypes(extension).length > 0 && + !samples.has(extension) + ) { + samples.set(extension, file); + } + } + const results: ProbeResult[] = []; + for (const [extension, file] of [...samples].sort(([left], [right]) => left.localeCompare(right))) { + const expected = acceptedAssetContentTypes(extension); + let observed: string; + try { + const response = await fetcher(new URL(file, base)); + await response.body?.cancel().catch(() => undefined); + observed = + response.status === 200 + ? (response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? "") + : `HTTP ${response.status}`; + } catch (error: unknown) { + observed = error instanceof Error ? error.name : "UnknownError"; + } + results.push({ + surface: `hashedAsset${extension}`, + header: "content-type", + expected, + observed, + passed: expected.includes(observed), + }); + } + return results; +} + /** A build ships a worker script for these selections (06-03: REMOVE_REGISTRATION ships the self-unregistering one). */ export function shipsServiceWorker(selection: InstalledServiceWorkerSelection | null): boolean { return selection?.mode === "ACTIVE" || selection?.mode === "REMOVE_REGISTRATION"; diff --git a/scripts/verify-hosting-headers.ts b/scripts/verify-hosting-headers.ts index 5d883661..5005c1c7 100644 --- a/scripts/verify-hosting-headers.ts +++ b/scripts/verify-hosting-headers.ts @@ -7,6 +7,7 @@ import { checkPublicServiceWorkers, classifyLiveHostingBaseUrl, hostingVerdict, + probeAssetContentTypes, probeLiveRelease, releaseIdentity, shipsServiceWorker, @@ -106,6 +107,8 @@ if (liveTarget?.passed && !slotEmpty) { const probed = await probeLiveRelease(liveTarget.url, paths, candidate); responses = probed.responses; probeResults.push(...probed.results); + // 1103/06-03. The worker needs every precached asset kind typed exactly. + probeResults.push(...(await probeAssetContentTypes(liveTarget.url, distFiles))); } else if (liveTarget && !liveTarget.passed) { mode = "invalid-live"; probeResults.push({ diff --git a/tests/unit/hosting-probe.test.ts b/tests/unit/hosting-probe.test.ts index 258e0825..ad0818e3 100644 --- a/tests/unit/hosting-probe.test.ts +++ b/tests/unit/hosting-probe.test.ts @@ -6,9 +6,11 @@ import path from "node:path"; import { describe, expect, it } from "vitest"; import { + acceptedAssetContentTypes, checkPublicServiceWorkers, classifyLiveHostingBaseUrl, hostingVerdict, + probeAssetContentTypes, probeLiveRelease, servedEntryScript, } from "../../scripts/lib/hosting-probe.ts"; @@ -207,6 +209,95 @@ describe("SPA fallback and worker script surfaces (1101/13-04)", () => { }); }); +// 1103/06-03. The worker's install requires each precached asset's exact +// Content-Type (CACHEABLE_ASSET_CONTENT_TYPES) and refuses the whole release on +// one mismatch. A page still uses a font served as octet-stream, so only the +// worker notices. The live probe requests one built asset per extension. +describe("hashed asset content types (1103/06-03)", () => { + const base = new URL("https://frontend.example.test/"); + const DIST_FILES = [ + "index.html", + "config.json", + "assets/index-A1.js", + "assets/chunk-B2.js", + "assets/index-C3.css", + "assets/inter-D4.woff2", + "assets/notes-E5.txt", + "robots.txt", + ]; + const host = + (types: Readonly>, requested: string[] = []) => + async (url: URL) => { + requested.push(url.pathname); + const extension = /\.[^./]+$/u.exec(url.pathname)?.[0] ?? ""; + const type = types[extension]; + const response = new Response("", { + status: type ? 200 : 404, + headers: type ? { "content-type": type } : {}, + }); + Object.defineProperty(response, "url", { value: url.href }); + return response; + }; + const CORRECT = { + ".js": "text/javascript; charset=utf-8", + ".css": "text/css", + ".woff2": "font/woff2", + }; + + it("requests one built asset per cacheable extension and passes correct types", async () => { + const requested: string[] = []; + const results = await probeAssetContentTypes(base, DIST_FILES, host(CORRECT, requested)); + expect(requested).toEqual([ + "/assets/index-C3.css", + "/assets/chunk-B2.js", + "/assets/inter-D4.woff2", + ]); + expect(results.map((result) => [result.surface, result.passed])).toEqual([ + ["hashedAsset.css", true], + ["hashedAsset.js", true], + ["hashedAsset.woff2", true], + ]); + }); + + it("fails a host that serves CSS as text/plain", async () => { + const results = await probeAssetContentTypes( + base, + DIST_FILES, + host({ ...CORRECT, ".css": "text/plain" }), + ); + expect(results.filter((result) => !result.passed)).toEqual([ + expect.objectContaining({ + surface: "hashedAsset.css", + header: "content-type", + expected: ["text/css"], + observed: "text/plain", + }), + ]); + }); + + it("fails a font served as octet-stream and an asset the host does not serve", async () => { + const results = await probeAssetContentTypes( + base, + DIST_FILES, + host({ ".js": "application/javascript", ".woff2": "application/octet-stream" }), + ); + expect( + results.filter((result) => !result.passed).map((result) => [result.surface, result.observed]), + ).toEqual([ + ["hashedAsset.css", "HTTP 404"], + ["hashedAsset.woff2", "application/octet-stream"], + ]); + }); + + it("accepts for JavaScript what the hashedAsset surface declares", async () => { + const policy = JSON.parse(await readFile("config/hosting/cache-policy.json", "utf8")) as { + surfaces: { hashedAsset: { contentTypes: string[] } }; + }; + expect(acceptedAssetContentTypes(".js")).toEqual(policy.surfaces.hashedAsset.contentTypes); + expect(acceptedAssetContentTypes(".woff2")).toEqual(["font/woff2"]); + }); +}); + // 1101/13-01. FE-GATE-019 checks the promoted candidate it downloaded, not a // local rebuild, and an empty deployment slot proves nothing about the host. describe("verify-hosting-headers on a promoted release root (1101/13-01)", () => { From 71446531096bd759a18b251409823957b92d5aa6 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:27:00 +0900 Subject: [PATCH 05/13] =?UTF-8?q?docs(operations):=20=EC=9B=8C=EC=BB=A4=20?= =?UTF-8?q?=EC=8A=A4=ED=81=AC=EB=A6=BD=ED=8A=B8=20=ED=97=A4=EB=8D=94=20?= =?UTF-8?q?=EA=B2=80=EC=82=AC=20=EB=B2=94=EC=9C=84=EB=A5=BC=20=EC=A7=80?= =?UTF-8?q?=EA=B8=88=20=EC=BD=94=EB=93=9C=EC=97=90=20=EB=A7=9E=EC=B6=98?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 SW runbook(browser-file-storage-recovery.md 8절)은 "verify:hosting-headers는 파일이 있는지만 보고 이 헤더는 보지 않는다"고 적는다. 지금은 워커를 싣는 빌드에서 serviceWorker surface가 필수이고 Cache-Control이 no-cache가 아니면 FAIL이다(cache-policy.json serviceWorker, verify-hosting-headers.ts). release-cache-rollback.md는 맞게 적어 두 운영 문서가 반대로 말한다. 고른 방법 - 그 문장을 live 모드가 /service-worker.js의 no-cache를 확인한다로 고친다. fixture 모드가 UNVERIFIED라는 것과, 하위 경로 base는 probe가 아직 받지 않아 손으로 확인해야 한다는 것을 함께 적는다. 위험·한계 - 하위 경로 문장은 0929/13-06이 고쳐지면 지워야 한다. 검증 - 문서와 코드(cache-policy.json, verify-hosting-headers.ts, hosting-probe.ts classifyLiveHostingBaseUrl)를 대조했다. Refs: docs/reviews/2026-11-03-maturity-review/06-adapters-service-worker-push.md 06-01 --- docs/operations/browser-file-storage-recovery.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/operations/browser-file-storage-recovery.md b/docs/operations/browser-file-storage-recovery.md index 66ae77e5..28243706 100644 --- a/docs/operations/browser-file-storage-recovery.md +++ b/docs/operations/browser-file-storage-recovery.md @@ -578,8 +578,13 @@ Service Worker를 별도 선택한 조합에서만 추가. 워커의 fetch 가 없어서 그동안의 요청은 모두 네트워크로 간다. 다음 load부터는 제어받지 않는다. 브라우저 확인: `tests/e2e/service-worker-recovery.spec.ts`. - 이 경로가 동작하려면 `service-worker.js`를 `Cache-Control: no-cache`로 서빙해야 - 한다. `verify:hosting-headers`는 파일이 있는지만 보고 이 헤더는 보지 않는다 - (`scripts/lib/hosting-probe.ts` `checkPublicServiceWorkers`). + 한다. 워커를 싣는 빌드(`ACTIVE`·`REMOVE_REGISTRATION`)에서는 + `verify:hosting-headers` live 모드가 `/service-worker.js`를 요청해 이 헤더를 + 확인하고, 다르면 FAIL이다(`config/hosting/cache-policy.json` `serviceWorker`, + `scripts/verify-hosting-headers.ts`). fixture 모드는 선언끼리만 대조하므로 + `UNVERIFIED`다. 하위 경로 base URL은 live probe가 아직 받지 않는다 + (`scripts/lib/hosting-probe.ts` `classifyLiveHostingBaseUrl`, 리뷰 0929/13-06). + 그때는 이 헤더를 손으로 확인한다. - 새 워커는 install에서 `skipWaiting()`하지 않고 waiting에 머문다 (`service-worker-entry.ts`). 활성화는 두 경로로 일어난다: 페이지의 `requestActivation()`이 성공하거나, 그 scope의 탭이 모두 닫힌다(브라우저 기본 From b4ae4c1ed3f618b67b5f660ccb1511dacc860f55 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:27:30 +0900 Subject: [PATCH 06/13] =?UTF-8?q?docs(operations):=20waiting=20=EA=B8=B0?= =?UTF-8?q?=EA=B0=84=EC=97=90=20=EC=86=8C=EC=9C=A0=20=EC=BA=90=EC=8B=9C?= =?UTF-8?q?=EA=B0=80=20=EC=8C=93=EC=9D=B4=EB=8A=94=20=EA=B2=83=EA=B3=BC=20?= =?UTF-8?q?=EC=A0=95=EB=A6=AC=20=EC=8B=9C=EC=A0=90=EC=9D=84=20=EC=A0=81?= =?UTF-8?q?=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 캐시를 지우는 곳은 activate 하나다(현재 + 마커가 가장 높은 직전 1개). 템플릿은 requestActivation()을 부르지 않으므로 활성화는 그 scope의 탭이 모두 닫혀야 일어난다. 그 사이 release마다 새 후보가 waiting 워커를 밀어내지만 밀려난 캐시는 남는다(리뷰 실험 L2: A 활성 + 탭 유지에서 B, C를 받으면 소유 캐시 3개, 활성화 뒤 2개). 운영 문서는 "현재 + 직전 1개"만 말해 waiting 기간의 캐시 수가 보이지 않는다. 고른 방법 - 리뷰 5.1 판단대로 (a) 문서만 고친다. SW runbook 8절에 쌓이는 규칙, 예, 크기 상한, 쿼터에 닿았을 때의 결과, 줄이는 방법 (requestActivation 화면)과 install이 지우지 않는 이유를 적는다. release-cache-rollback.md SW 1단계에 한 문장과 링크를 둔다. - 버린 대안: (b) install 성공 뒤 "무마커 + 이번 후보 아님 + 활성 캐시 아님"을 지우기. install하는 워커는 활성 캐시 이름을 모르고, 마커 쓰기에 실패한 활성 캐시는 후보와 구별되지 않는다. (c) 이번 후보를 뺀 무마커 캐시를 모두 지우기. 그 활성 캐시를 지워 직전 캐시 보존 성질을 깬다. 위험·한계 - 쌓이는 동작 자체는 그대로다. 사전 캐시가 1 MiB를 넘고 release가 잦아 지면 (b)를 다시 본다(리뷰 재검토 조건). - 브라우저 종료로 활성화되는지는 확인하지 않았다. 검증 - 문서와 코드(service-worker-lifecycle.ts onActivate, service-worker-static-assets.ts QUOTA_EXCEEDED, service-worker.ts assetSetBytes)를 대조했다. Refs: docs/reviews/2026-11-03-maturity-review/06-adapters-service-worker-push.md 06-04 --- docs/operations/browser-file-storage-recovery.md | 13 +++++++++++++ docs/operations/release-cache-rollback.md | 6 +++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/docs/operations/browser-file-storage-recovery.md b/docs/operations/browser-file-storage-recovery.md index 28243706..afe09ffb 100644 --- a/docs/operations/browser-file-storage-recovery.md +++ b/docs/operations/browser-file-storage-recovery.md @@ -592,6 +592,19 @@ Service Worker를 별도 선택한 조합에서만 추가. 워커의 fetch 가 부르는 화면이 없으므로 기본 경로는 뒤쪽이다. 따라서 결함 있는 워커가 waiting에 있으면 탭을 모두 닫았다 다시 연 사용자부터 그 워커를 쓴다. 기다리지 말고 다음 release로 교체하거나 `REMOVE_REGISTRATION` release를 배포한다. +- 활성화를 기다리는 동안 소유 캐시는 release 수만큼 쌓인다. 캐시를 지우는 곳은 + activate 하나이고, 현재 캐시와 마커가 가장 높은 직전 캐시 1개만 남긴다 + (`service-worker-lifecycle.ts` `onActivate`). 새 release가 waiting 워커를 + 밀어내도 밀려난 워커의 후보 캐시는 지우지 않는다. 예: 탭 하나를 연 채 A 활성 + 상태에서 B, C를 받으면 소유 캐시는 A·B·C 3개다. 탭을 모두 닫아 C가 활성화되면 + C·A 2개로 줄어든다(리뷰 1103/06-04 실험 L2, chromium·webkit). 캐시 하나는 + 사전 캐시 크기(상한 5 MiB, `src/contracts/service-worker.ts`)다. origin 쿼터에 + 닿으면 다음 install이 `QUOTA_EXCEEDED`로 실패하고, 저장소가 부족하면 브라우저가 + origin 저장소 전체(IndexedDB·OPFS 포함)를 지울 수 있다. 사용자가 탭을 오래 + 열어 두고 release가 잦은 제품은 `requestActivation()`을 부르는 화면을 붙여 + waiting 기간을 줄인다. install이 밀려난 캐시를 지우지 않는 이유: install하는 + 워커는 활성 워커의 캐시 이름을 모르고, 마커 쓰기에 실패한 활성 캐시는 마커가 + 없어 후보와 구별되지 않는다. - 제거는 `ACTIVE → REMOVE_REGISTRATION → PURGE_OWNED_RESOURCES → null` 순서로 release를 나눈다(`src/contracts/service-worker.ts` `InstalledServiceWorkerSelection`). 소유 캐시는 `PURGE_OWNED_RESOURCES` release의 diff --git a/docs/operations/release-cache-rollback.md b/docs/operations/release-cache-rollback.md index d3661342..1f374cd2 100644 --- a/docs/operations/release-cache-rollback.md +++ b/docs/operations/release-cache-rollback.md @@ -181,7 +181,11 @@ same build as the HTML and assets it caches. name is the asset-set digest, so if N's cache is still there as the retained previous cache, the install reuses it and never deletes it on failure (`service-worker-static-assets.ts` `installStaticAssets`). Tabs still on N+1 keep worker N+1, so N+1's assets - stay reachable for the rolling window above. + stay reachable for the rolling window above. Only activation deletes owned + caches (current plus the highest-marked previous one). While a worker + waits, every release that replaces the waiting worker leaves its cache + behind, so a scope holds one precache per release until its tabs close + (review 1103/06-04; `docs/operations/browser-file-storage-recovery.md` §8). 2. **Turn the worker off without a rebuild.** Set `CAPABILITY_OVERRIDES.SERVICE_WORKER: "DISABLED"` in the runtime config. The next boot unregisters the owned registration and registers nothing; owned From 615da352b9537416b52d9c38760540f1f2a77368 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:29:32 +0900 Subject: [PATCH 07/13] =?UTF-8?q?docs(realtime):=20=EC=A7=9D=20=EB=B0=B1?= =?UTF-8?q?=EC=97=94=EB=93=9C=20=EC=8B=A4=EC=8B=9C=EA=B0=84=20=EC=B6=9C?= =?UTF-8?q?=EA=B5=AC=EC=99=80=20=ED=94=84=EB=A1=A0=ED=8A=B8=20transport=20?= =?UTF-8?q?=EB=8C=80=EC=9D=91=ED=91=9C=EB=A5=BC=20=EC=A0=81=EB=8A=94?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 짝 백엔드의 실시간 출구는 STOMP-over-SockJS 채널(/ws, /topic 구독 1개, Map 투영, 재전송 없음)과 raw WebSocket 라이브러리 API, NDJSON·JSON text sequence writer다. 프론트 SSE 어댑터는 text/event-stream과 REALTIME_EVENT_V1 envelope을, WebSocket 어댑터는 subprotocol "realtime.v1"을 요구한다. 어느 repo에도 이 불일치와 지금 되는 경로가 적혀 있지 않아, 채택자가 두 repo를 다 읽어야 안다. 고른 방법 - 리뷰의 최소 방향을 프론트 repo 안에서 따른다. 설계 문서에 0.1절을 두고 transport별 대응표(지금 연결되나·이유), push가 필요할 때의 세 길, 재검토 조건을 적는다. 레시피 Realtime 절과 매뉴얼 03 C절에서 한 줄로 링크한다. - 다시 확인한 백엔드 사실(읽기만): 아키텍처 테스트가 MVC SseEmitter를 금지한다(ForbiddenApiArchitectureTest NO_SSE_EMITTER, 결정 D3). StreamMediaType.SSE는 OpenAPI 생성기만 쓴다. subprotocol 협상 코드는 없다. 그래서 첫째 길을 SSE가 아니라 realtime.v1 WebSocket handler로 적었다. - 지금 되는 경로(bounded polling)는 사실로 적고, push 경로는 고르지 않았다. 제품 결정이다. - 버린 대안: desktop-server-git/design-docs/에 쓰기. 이 브랜치 밖이라 함께 합쳐지지 않는다. 필요하면 그쪽에서 이 절을 링크한다. 위험·한계 - 백엔드 사실은 지금 백엔드 HEAD(70fb80bf)를 읽은 것이다. 백엔드가 바뀌면 표가 낡는다. 재검토 조건에 적었다. - 실제 연결은 실행하지 않았다(리뷰와 같음). 검증 - verify:documentation PASS_SCOPED. documentation-readiness· changelog-review-ids 테스트 15건 통과. Refs: docs/reviews/2026-11-03-maturity-review/04-adapters-realtime.md 04-02 --- docs/architecture/optional-adapter-recipes.md | 5 +++ ...ime-events-web-push-and-bounded-polling.md | 39 +++++++++++++++++++ docs/manual/03-outside-feature-folder.md | 1 + 3 files changed, 45 insertions(+) diff --git a/docs/architecture/optional-adapter-recipes.md b/docs/architecture/optional-adapter-recipes.md index 4281ddba..e85d9487 100644 --- a/docs/architecture/optional-adapter-recipes.md +++ b/docs/architecture/optional-adapter-recipes.md @@ -208,6 +208,11 @@ Web Push를 함께 설치하지 않는다. - detailed status, target contract와 구현 work package는 [Realtime events, Web Push, and bounded polling](./realtime-events-web-push-and-bounded-polling.md)을 따른다. 현재 concrete runtime과 product selection은 없다. +- 짝 백엔드 템플릿의 실시간 출구(STOMP-over-SockJS, NDJSON)와 이 repo의 SSE· + `realtime.v1` WebSocket 어댑터는 그대로 연결되지 않는다. 지금 두 템플릿만으로 + 되는 경로는 bounded polling이다. 대응표와 push를 고를 때의 세 길은 설계 문서 + [0.1절](./realtime-events-web-push-and-bounded-polling.md#01-짝-백엔드-템플릿과의-대응-110304-02)에 + 있다(1103/04-02). ### IndexedDB/OPFS diff --git a/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index 8b34816d..93317107 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -78,6 +78,45 @@ row의 `referenceRuntime.status=AVAILABLE_NOT_COMPOSED`가 reusable source의 | always-on background SSE/WebSocket/Polling | `PLATFORM_LIMITED` | 없음 | hidden/frozen/terminated browser 상태에서 공통 보장하지 않음 | | timely cross-browser Web Push | `PLATFORM_LIMITED` | 없음 | best-effort notification과 foreground authoritative refresh만 제공 | +### 0.1 짝 백엔드 템플릿과의 대응 (1103/04-02) + +결론: 짝 백엔드(`clean-architecture-backend-template`)의 실시간 출구와 이 +repo의 SSE·WebSocket 어댑터는 **지금 그대로 연결되는 조합이 없다.** 지금 두 +템플릿만으로 되는 경로는 bounded polling 하나다. push가 필요하면 한쪽에 새 코드를 +써야 하고, 어느 쪽을 쓸지는 제품이 정한다. + +```text +프론트 SSE 어댑터 → Accept: text/event-stream, REALTIME_EVENT_V1 envelope +프론트 WS 어댑터 → subprotocol 정확히 "realtime.v1", REALTIME_EVENT_V1 envelope +짝 백엔드 STOMP 채널 → SockJS /ws, /topic 구독 1개, Map 투영, 재전송 없음 +짝 백엔드 스트리밍 → NDJSON, JSON text sequence(RFC 7464). SSE writer는 없다 +``` + +| 프론트 transport | 짝 백엔드 출구 | 지금 연결되나 | 이유 | +| --- | --- | --- | --- | +| SSE (`fetch-sse-connection.ts`) | 없음 | 아니오 | 백엔드에 SSE writer가 없다(`StreamMediaType.SSE`는 OpenAPI 생성기만 쓴다). 아키텍처 테스트가 MVC `SseEmitter`를 금지한다(`ForbiddenApiArchitectureTest` `NO_SSE_EMITTER`, 백엔드 결정 D3). 스트리밍 writer는 NDJSON·JSON text sequence뿐이다(`src/adapter/inbound/web-advanced/README.md`) | +| WebSocket (`websocket-connection.ts`) | STOMP-over-SockJS 채널 | 아니오 | 프론트는 협상된 subprotocol이 정확히 `realtime.v1`이어야 연다(`websocket-protocol.ts`). 백엔드에는 subprotocol 협상 코드가 없다. STOMP frame은 `REALTIME_EVENT_V1` envelope(streamEpoch, sequence, eventId, scopeBinding)이 아니다 | +| WebSocket | raw WebSocket 라이브러리 API(`servlet/`) | 아니오(새 코드 필요) | 서비스 어댑터가 handler를 직접 조립한다. `realtime.v1` 협상과 envelope을 구현한 예시는 없다 | +| bounded polling (`bounded-poll-coordinator.ts`) | REST GET + Envelope | **예** | V3 실행기가 짝 백엔드 Envelope을 읽는다. poll 전용 operation의 `retryBudget`을 0으로 둔다(9.2절) | + +push가 필요할 때 고를 길(제품 결정, 리뷰 1103/04-02 결정의 근거): + +1. **백엔드에 `realtime.v1` WebSocket handler를 쓴다.** 프론트 어댑터를 그대로 + 쓰고 `CURSOR` 복구까지 갈 수 있다. 백엔드에 sequence·replay 저장소(outbox)가 + 필요하다. SSE는 백엔드 결정 D3을 먼저 바꿔야 하므로 이 표에서는 WebSocket을 + 먼저 적는다. +2. **프론트에 STOMP transport를 쓴다.** 백엔드는 그대로다. STOMP frame에는 + sequence·epoch가 없어 stream coordinator의 gap·cursor 기능을 못 쓴다. frame을 + query 무효화 hint로만 쓰고 데이터는 snapshot(REST GET)으로 다시 읽는다 + (`INVALIDATION_HINT` + `SNAPSHOT_ONLY`). simple broker는 재전송이 없으므로 + 연결이 끊긴 동안의 변경은 재연결 뒤 snapshot으로만 회복한다. +3. **push 없이 bounded polling만 쓴다.** 두 repo 모두 새 코드가 없다. freshness는 + poll 주기(최소 5초)로 정해진다. + +다시 볼 때: 백엔드에 `realtime.v1` handler나 SSE writer가 생기거나, 프론트에 STOMP +transport가 생기면 이 표를 고친다. 백엔드 쪽 정본은 백엔드 repo의 +`src/adapter/inbound/websocket/README.md`다. + 별도로 realtime catalog row 자체는 `RECIPE_AVAILABLE`이다. 이것은 primary runtime status가 아니다. 기존 copyable `RealtimePort`를 production wire authority나 generic mega port로 확장하지 않았고, reference runtime의 공개 계약은 diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index 1c13012f..4e36de80 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -104,6 +104,7 @@ release admission refused for staging: - `tests/e2e/accessibility.spec.ts`: 경로 파라미터가 `:resourceId`가 아닐 때, 또는 모든 API가 `[]`를 답하면 그려지지 않는 보호 페이지일 때. 치환 줄 고치는 법은 [01 문서 6단계](01-add-a-feature.md#6단계-라우트). - `src/bootstrap/product-composition.ts`: `needs`에 템플릿이 만들지 않는 capability를 적었을 때. 제품 인증 프로필의 자격 증명도 여기서 준다. - 템플릿 파일 `src/bootstrap/runtime-adapters.ts`는 고치지 않는다. + - 실시간 갱신: 짝 백엔드의 실시간 출구(STOMP·NDJSON)와 프론트 realtime 어댑터(SSE·`realtime.v1` WebSocket)는 그대로 연결되지 않는다. 지금 되는 경로는 bounded polling이다. 대응표: [realtime 설계 0.1절](../architecture/realtime-events-web-push-and-bounded-polling.md#01-짝-백엔드-템플릿과의-대응-110304-02). - `src/contracts/product-contracts.ts`: 제품 인증 프로필이나 제품 런타임 설정 키가 필요할 때. - 템플릿 파일 `src/contracts/rest-profiles.ts`는 고치지 않는다. - `config/runtime/.json`: 환경별로 기능을 끄고 싶을 때(`FEATURE_OVERRIDES`). From 5b2106df258852b2667a6e46b21bf967922f01b8 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:30:22 +0900 Subject: [PATCH 08/13] =?UTF-8?q?docs(realtime):=20realtime=20=EB=A0=88?= =?UTF-8?q?=EC=A7=80=EC=8A=A4=ED=8A=B8=EB=A6=AC=20=EC=84=B8=20=EB=B0=94?= =?UTF-8?q?=EC=9D=B8=EB=94=A9=EC=9D=98=20=EC=B6=9C=EC=B2=98=EB=A5=BC=20?= =?UTF-8?q?=EB=A0=88=EC=8B=9C=ED=94=BC=EC=97=90=20=EC=A0=81=EB=8A=94?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 realtime 레지스트리는 schemaCodecs·mappers·apiOperations 세 바인딩을 받아 event type과 checkpoint를 대조한다. V2 삭제(12f3bb7)로 기능의 runtimeSchemas·mappers 칸이 사라져 지금 출처가 있는 것은 apiOperations뿐이다. 레시피는 "제품 feature는 이 runtime에 schema/codec/query … 주입"이라고만 적어 조합자가 codec·mapper를 어디서 만드는지 알 수 없다. 고른 방법 - 리뷰의 최소 방향대로 레시피 Realtime 절에 세 바인딩의 출처를 적는다. apiOperations는 loadInstalledFeatureRuntimeRegistries().apiOperations, schemaCodecs는 V3 events[].payloadValidator·checkpoint outputValidator를 runtimeSchemaCodecFromValidator + composeRuntimeSchemaCodecs로, mappers는 조합 코드의 BoundaryMapper + composeBoundaryMapperRegistry다. 등록 때 맞아야 하는 id(payloadSchemaId = validator schemaId = mapper inputSchemaId)도 적었다(realtime-streams.ts 등록 검사). - 버린 대안: 지금 기능 모듈에 realtimeMappers 칸을 더하거나 V3 events에서 event type을 뽑기. 공개 계약이 바뀌고, 04-02의 push 경로(STOMP hint면 delta mapper가 필요 없을 수 있음)를 고른 뒤 정하는 것이 맞다. 위험·한계 - 코드 변경이 없다. 같은 이벤트를 V3 events와 realtime 등록 두 곳에 적는 중복은 문서 규칙으로만 막는다. 검증 - verify:documentation PASS_SCOPED. Refs: docs/reviews/2026-11-03-maturity-review/04-adapters-realtime.md 04-06 --- docs/architecture/optional-adapter-recipes.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/architecture/optional-adapter-recipes.md b/docs/architecture/optional-adapter-recipes.md index e85d9487..58740fb6 100644 --- a/docs/architecture/optional-adapter-recipes.md +++ b/docs/architecture/optional-adapter-recipes.md @@ -213,6 +213,22 @@ Web Push를 함께 설치하지 않는다. 되는 경로는 bounded polling이다. 대응표와 push를 고를 때의 세 길은 설계 문서 [0.1절](./realtime-events-web-push-and-bounded-polling.md#01-짝-백엔드-템플릿과의-대응-110304-02)에 있다(1103/04-02). +- realtime 레지스트리(`createRealtimePolicyRegistry`)가 받는 세 바인딩의 출처 + (1103/04-06). 기능 모듈에는 codec·mapper를 낼 칸이 없으므로 조합 코드가 모은다. + - `apiOperations`: `loadInstalledFeatureRuntimeRegistries().apiOperations` + (`projectApiOperationRows`). snapshot·checkpoint operation이 여기서 온다. + - `schemaCodecs`: 기능 contract contribution의 V3 `events[].payloadValidator` + (`composedContractContributions.eventByType`)와 checkpoint 응답의 + `outputValidator`를 `runtimeSchemaCodecFromValidator`로 바꿔 + `composeRuntimeSchemaCodecs`로 합친다. event type의 `payloadSchemaId`가 그 + validator의 `schemaId`와 같아야 등록된다. 같은 이벤트의 스키마를 V3 `events`와 + realtime 등록 두 곳에 따로 쓰지 않는다. + - `mappers`: 조합 코드가 `BoundaryMapper`(`src/contracts/boundary-mapper.ts`)를 + 쓰고 `composeBoundaryMapperRegistry`로 합친다. mapper의 `inputSchemaId`는 event + type의 `payloadSchemaId`와 같아야 한다. 템플릿이 만드는 출처는 없다. + - 기능 모듈에 칸을 더하는 것(V3 `events`에서 event type을 뽑거나 + `realtimeMappers` 칸)은 위 대응표에서 push 경로를 고른 뒤 정한다. STOMP hint + 경로면 delta mapper가 필요 없을 수 있다. ### IndexedDB/OPFS From 5d0f5ad7f837b6ef17796f507e77f5dbfff17b99 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:31:51 +0900 Subject: [PATCH 09/13] =?UTF-8?q?docs(realtime):=20heartbeat=EB=A5=BC=20?= =?UTF-8?q?=EB=A9=88=EC=B6=98=20WebSocket=EC=9D=B4=20=EC=98=88=EC=82=B0?= =?UTF-8?q?=EC=9D=84=20=EC=83=88=EB=A1=9C=20=EB=B0=9B=EC=A7=80=20=EB=AA=BB?= =?UTF-8?q?=ED=95=A8=EC=9D=84=20=EC=A0=81=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 heartbeatEligible()이 false면 WebSocket 연결은 HEARTBEAT를 보내지 않는다. 그러면 HEARTBEAT_ACK가 없고, 이벤트도 없는 조용한 stream은 유효 신호가 없어 reconnect 예산이 초기화되지 않는다(0929 실험 E7). 훅에 주석이 없어 채택자가 이 결과를 코드 두 곳(heartbeat 송신, isReconnectAttemptResetEligible)을 같이 읽어야 안다. 고른 방법 - 0929/04-04의 최소 방향대로 훅 옆에 주석을 달고 설계 5.3 예산 문단에 같은 문장을 더한다. hidden 연결은 닫거나 visible 복귀 때 새 run을 만들라고 적는다. 동작은 바꾸지 않는다. 위험·한계 - 동작 변경이 없다. 주석이 코드와 어긋나면 잡는 검사는 없다. 검증 - 바꾼 파일 eslint 통과. 주석만 바꿨다. Refs: docs/reviews/2026-11-03-maturity-review/04-adapters-realtime.md 2절 0929/04-04 --- .../realtime-events-web-push-and-bounded-polling.md | 5 ++++- src/adapters/realtime/websocket/websocket-connection.ts | 7 +++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index 93317107..4659ab70 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -810,7 +810,10 @@ effectiveDelay = max(localDelay, validServerNotBefore) `waitClosed` throw를 포함한 session의 모든 종료 경로에서 한다 (`reconnect-coordinator.ts:888-902`). valid heartbeat는 SSE `onComment`와 WebSocket `HEARTBEAT_ACK` 관측이다. 조합 코드가 이를 - `markValidHeartbeatOrEvent`로 넘긴다. + `markValidHeartbeatOrEvent`로 넘긴다. WebSocket `heartbeatEligible()`이 + false인 동안(hidden 탭)은 heartbeat를 보내지 않아 ACK가 없다. 조용한 + stream은 그동안 예산을 새로 받지 못한다. hidden 연결은 닫거나 visible + 복귀 때 새 run을 만든다(0929/04-04). - stream reconnect는 realtime recovery coordinator, credential recovery는 session owner, Poll attempt 사이 cadence는 poll coordinator가 각각 소유한다. Poll-bound REST transport retry와 Query retry는 끈다. 같은 logical recovery의 diff --git a/src/adapters/realtime/websocket/websocket-connection.ts b/src/adapters/realtime/websocket/websocket-connection.ts index 0417c313..db99cd95 100644 --- a/src/adapters/realtime/websocket/websocket-connection.ts +++ b/src/adapters/realtime/websocket/websocket-connection.ts @@ -179,6 +179,13 @@ export type WebSocketConnectionDependencies = Readonly<{ | RealtimeResult | Promise>; onRecoveryRequired(request: WebSocketRecoveryRequest): void; + /** + * False pauses sending HEARTBEAT (e.g. a hidden tab, design 6.4); absent or + * true sends it. While paused no HEARTBEAT_ACK arrives, so a quiet stream + * has no valid signal and the reconnect budget is never reset + * (`isReconnectAttemptResetEligible`). Close a hidden connection, or start a + * new run when the tab is visible again (0929/04-04). + */ heartbeatEligible?(): boolean; observe?(observation: WebSocketConnectionObservation): void; verifyCursorRotation?(input: Readonly<{ From 0cc2553381d7c15087b1c5c5f44d462368966ffc Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:32:32 +0900 Subject: [PATCH 10/13] =?UTF-8?q?docs(operations):=20=EC=9B=8C=EC=BB=A4=20?= =?UTF-8?q?=EC=A0=9C=EA=B1=B0=201=EB=8B=A8=EA=B3=84=EB=A5=BC=20=EC=B5=9C?= =?UTF-8?q?=EB=8C=80=20=EB=AF=B8=EB=B0=A9=EB=AC=B8=20=EA=B8=B0=EA=B0=84=20?= =?UTF-8?q?=EC=9D=B4=EC=83=81=20=EC=9C=A0=EC=A7=80=ED=95=98=EB=9D=BC?= =?UTF-8?q?=EA=B3=A0=20=EC=A0=81=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 자기 해제 service-worker.js는 REMOVE_REGISTRATION release만 낸다 (build-frontend.ts). 다음 단계 release에는 워커 파일이 없어 update 검사가 404로 실패한다. PURGE_OWNED_RESOURCES는 부팅한 페이지만 다시 unregister하고, null은 아무것도 하지 않는다. 1단계 기간에 오지 않은 사용자에게 부팅을 막는 워커나 옛 워커가 남는다(리뷰 1103 실험 L3). 운영 문서는 세 단계 순서만 적고 각 단계 유지 기간이 없다. 고른 방법 - 0929/06-06의 최소 방향 중 문서 한 줄을 고른다. SW runbook 8절과 release-cache-rollback.md 4단계에 "1단계를 최대 미방문 기간 이상 유지, 그 뒤 남은 사용자가 보이면 1단계를 다시 배포"를 적는다. - 버린 대안: 2단계도 자기 해제 워커를 내보내고 hosting 허용 목록을 맞추기. 빌드·hosting 검사·e2e를 함께 바꿔야 해서 이월 항목의 작은 수정 범위를 넘는다. 위험·한계 - 동작은 그대로다. 유지 기간을 지키는지는 운영자 몫이다. 검증 - 문서와 코드(build-frontend.ts, service-worker-page-controller.ts PURGE_OWNED_RESOURCES 분기, service-worker-removal.ts)를 대조했다. - verify:documentation PASS_SCOPED. Refs: docs/reviews/2026-11-03-maturity-review/06-adapters-service-worker-push.md 2절 0929/06-06 --- docs/operations/browser-file-storage-recovery.md | 8 ++++++++ docs/operations/release-cache-rollback.md | 5 +++++ 2 files changed, 13 insertions(+) diff --git a/docs/operations/browser-file-storage-recovery.md b/docs/operations/browser-file-storage-recovery.md index afe09ffb..5c4c8d9c 100644 --- a/docs/operations/browser-file-storage-recovery.md +++ b/docs/operations/browser-file-storage-recovery.md @@ -612,6 +612,14 @@ Service Worker를 별도 선택한 조합에서만 추가. 워커의 fetch 가 old controlled client가 drain되기 전에는 이 release를 배포하지 않는다. 캐시가 사라지면 그 탭의 워커는 요청을 네트워크로 넘기고(`service-worker-entry.ts` fetch 리스너의 `cached ?? fetch(request)`), 서버에 없는 옛 청크는 404가 된다. +- 자기 해제 `service-worker.js`를 내보내는 것은 `REMOVE_REGISTRATION` release뿐이다 + (`scripts/build-frontend.ts`). `PURGE_OWNED_RESOURCES` release에는 워커 파일이 + 없다. 페이지가 부팅하면 page controller가 unregister를 다시 하지만, 부팅을 막는 + 워커는 걷어내지 못한다. `null` release는 아무것도 하지 않아 옛 워커가 계속 + 등록·제어한다(리뷰 1103 실험 L3: `ACTIVE` 다음 바로 `null`, update 검사는 404로 + 실패). 그래서 `REMOVE_REGISTRATION` release는 제품이 지원하는 최대 미방문 기간 + 이상 유지한 뒤 다음 단계로 넘어간다. 그 뒤에 옛 워커가 남은 사용자가 보이면 + `REMOVE_REGISTRATION` release를 다시 배포한다(0929/06-06). hosting/CDN purge는 두 branch와 분리된 provider 절차로 실행한다. diff --git a/docs/operations/release-cache-rollback.md b/docs/operations/release-cache-rollback.md index 1f374cd2..7c2264da 100644 --- a/docs/operations/release-cache-rollback.md +++ b/docs/operations/release-cache-rollback.md @@ -205,3 +205,8 @@ same build as the HTML and assets it caches. 4. **Removing the worker** takes three releases: `REMOVE_REGISTRATION` → `PURGE_OWNED_RESOURCES` (deletes owned caches) → `null` (`src/contracts/service-worker.ts` `InstalledServiceWorkerSelection`). + Only the `REMOVE_REGISTRATION` release ships the self-unregistering + `service-worker.js`. Keep it deployed for at least the longest time a user + may stay away. A later release has no worker file, so the update check + fails with 404: on `PURGE_OWNED_RESOURCES` only a page that boots + unregisters the old worker, and on `null` nothing does (review 0929/06-06). From 3bc690d3fb1a465cac3807fce02505befe4e6eec Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:34:12 +0900 Subject: [PATCH 11/13] =?UTF-8?q?test(realtime):=20WebSocket=20=EA=B5=AC?= =?UTF-8?q?=EB=8F=85=EB=B3=84=20=EC=B4=88=EB=8B=B9=20event=20=EC=83=81?= =?UTF-8?q?=ED=95=9C=EC=9D=84=20=ED=85=8C=EC=8A=A4=ED=8A=B8=EB=A1=9C=20?= =?UTF-8?q?=EA=B3=A0=EC=A0=95=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 WebSocket 연결은 구독마다 1초 창에 maxEventsPerSecond(256, server가 알린 값과 작은 쪽)를 넘는 event가 오면 EVENT_RATE_EXCEEDED recovery를 요청하고 QUEUE_OVERFLOW로 닫는다. 이를 확인하는 테스트가 없어 검사를 꺼도 모든 테스트가 통과한다(리뷰 변이 R7, 두 라운드째). 설계 11절 상한표에도 행이 없다. 고른 방법 - 상한을 2로 낮춘 연결에서 2개 → 1초 뒤 2개(열림 유지) → 1개 더(닫힘, EVENT_RATE_EXCEEDED)를 보내는 테스트 1건을 더한다. 창 초기화와 상한 값 출처까지 한 테스트가 본다. - 설계 11절 상한표에 행 하나를 더한다. 위험·한계 - 동작은 바꾸지 않았다. 실제 서버 부하로는 확인하지 않았다. 검증 - 새 테스트 통과(websocket-connection 24건). - 변이 3건 모두 검출: 상한 검사 끄기(R7), 1초 창 초기화 삭제, 협상된 상한 대신 256 고정. - 바꾼 파일 eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/04-adapters-realtime.md 2절 1101/04-03 --- ...ime-events-web-push-and-bounded-polling.md | 1 + .../realtime/websocket-connection.test.ts | 57 +++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index 4659ab70..a0d3a2e7 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -1837,6 +1837,7 @@ authoritative query data를 덮지 않는다. | reorder buffer | 기본 0; 선택 시 64 event, 2초 | | WebSocket outbound queued bytes | 256 KiB | | WebSocket outbound queued messages | 128 | +| WebSocket 구독별 event rate | 1초 창마다 256 event. client 상한과 server가 알린 `maxEventsPerSecond` 중 작은 값. 넘으면 그 구독에 `EVENT_RATE_EXCEEDED` recovery를 요청하고 `QUEUE_OVERFLOW`로 연결을 닫는다(1101/04-03, `websocket-connection.ts` `processEvent`) | | reconnect attempts | 연속 10회 또는 5분 | | reconnect max delay | 60초 | | aborted reconnect task drain | 2초 고정; 구현 절대 최대 30초 | diff --git a/tests/unit/realtime/websocket-connection.test.ts b/tests/unit/realtime/websocket-connection.test.ts index e01ab249..aad6dc46 100644 --- a/tests/unit/realtime/websocket-connection.test.ts +++ b/tests/unit/realtime/websocket-connection.test.ts @@ -650,6 +650,63 @@ describe("WebSocket connection generation", () => { releaseFirst?.(); }); + // 1101/04-03. Each subscription may apply at most maxEventsPerSecond events + // in a one-second window (the lower of the client ceiling and the server's + // advertised limit). One more requests recovery and closes the generation. + it("closes a subscription that exceeds its per-second event ceiling", async () => { + const runtime = setup({ ceilings: { maxEventsPerSecond: 2 } }); + await openConnection(runtime); + runtime.connection.subscribe({ + subscriptionId: "subscription.0001", + streamId: "orders.v1", + scopeBinding: "scope.0001", + stateBearing: true, + checkpoint: { + streamEpoch: "stream-epoch.0001", + lastAppliedSequence: "10", + cursor: "cursor.0010", + }, + }); + runtime.socket.message( + serverFrame({ + type: "SUBSCRIBED", + subscriptionId: "subscription.0001", + streamEpoch: "stream-epoch.0001", + acceptedCursor: "cursor.0010", + nextExpectedSequence: "11", + }), + ); + await flush(); + const event = serverFrame({ + type: "EVENT", + subscriptionId: "subscription.0001", + envelope: { + protocol: "REALTIME_EVENT_V1", + streamId: "orders.v1", + }, + }); + const deliver = async (count: number) => { + for (let index = 0; index < count; index += 1) { + runtime.socket.message(event); + for (let turn = 0; turn < 5; turn += 1) await flush(); + } + }; + + await deliver(2); + runtime.clock.current += 1_000; + await deliver(2); + expect(runtime.onEvent).toHaveBeenCalledTimes(4); + expect(runtime.connection.inspect().status).toBe("OPEN"); + + await deliver(1); + expect(runtime.onEvent).toHaveBeenCalledTimes(4); + expect(runtime.connection.inspect().status).toBe("CLOSED"); + expect(runtime.recoveries).toContainEqual({ + subscriptionId: "subscription.0001", + reason: "EVENT_RATE_EXCEEDED", + }); + }); + it("rejects an event routed through the wrong logical subscription", async () => { const runtime = setup(); await openConnection(runtime); From c3aa5eba354494aa905fd4dd5304dc25269dd396 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:35:38 +0900 Subject: [PATCH 12/13] =?UTF-8?q?docs(recipes):=20Service=20Worker=20?= =?UTF-8?q?=EB=A0=88=EC=8B=9C=ED=94=BC=EA=B0=80=20=EC=98=A4=ED=94=84?= =?UTF-8?q?=EB=9D=BC=EC=9D=B8=20=EC=85=B8=EC=9D=84=20=EC=95=BD=EC=86=8D?= =?UTF-8?q?=ED=95=98=EC=A7=80=20=EC=95=8A=EA=B2=8C=20=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 catalog의 service-worker-pwa trigger는 "a measured offline-shell requirement"를 설치 조건으로 적고 failureKinds에 offline-fallback이 있다. 레시피 표도 "install/offline shell"이다. 그러나 reference 워커는 navigation을 NETWORK_ONLY로 두고, 사전 캐시에 index.html을 넣지 않으며, 설계는 cached index.html fallback을 금지한다(closed deep design 18.8). catalog를 보고 온 제품은 템플릿 파일을 고쳐야 한다는 것을 뒤늦게 알고, 이후 동기화마다 같은 파일에서 충돌한다(0929 리뷰의 memento 사례). 고른 방법 - 0929/06-03 최소 방향대로 주장을 설계에 맞춘다. trigger에서 오프라인 셸을 빼고 "navigation network-only, offline shell 없음, 별도 제품 capability"를 적는다. failureKinds의 offline-fallback을 offline-navigation-network-error로 바꾼다. - 레시피 3절 표를 고치고, 같은 절에 졸업 경로(넘겨받는 파일 넷, 다시 증명할 e2e 단언과 성질, 동기화 충돌)를 적는다. - 버린 대안: 선택 handler로 오프라인 셸 확장 지점을 만들기. 설계가 금지한 동작이고 재검토 조건(제품 요구)이 아직 없다. 위험·한계 - catalog 문구만 바뀐다. 오프라인 셸을 켜는 확장 지점은 여전히 없다. 검증 - json-schema 테스트 6건 통과, check:remediation-ledger· check:optional-recipe-fixtures PASS, verify:documentation PASS_SCOPED. Refs: docs/reviews/2026-11-03-maturity-review/06-adapters-service-worker-push.md 2절 0929/06-03 --- config/recipes/frontend-capability-recipes.json | 4 ++-- docs/architecture/optional-adapter-recipes.md | 13 ++++++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/config/recipes/frontend-capability-recipes.json b/config/recipes/frontend-capability-recipes.json index 51de02e7..0ba4f87e 100644 --- a/config/recipes/frontend-capability-recipes.json +++ b/config/recipes/frontend-capability-recipes.json @@ -137,12 +137,12 @@ ], "productionComposition": false }, - "trigger": "Installability, a measured offline-shell requirement, or an explicitly owned public HTTP representation cache is approved.", + "trigger": "Installability or an explicitly owned public HTTP representation cache is approved. The reference worker keeps navigation network-only and has no offline shell; an offline document is a separate product capability (closed deep design 18.8).", "forbiddenWhen": ["Hosting cache and worker cache ownership conflict.", "Update and rollback UX is undefined.", "Authenticated, private, opaque or personal responses would be cached.", "Cache freshness, byte and entry limits are undefined."], "boundary": "bootstrap update controller plus platform-local public Request/Response cache administration", "port": "ServiceWorkerUpdatePort / PublicResponseCacheAdmin recipe / PublicResponseCachePort / PublicResponseCacheAdminPort reference runtime", "fake": "FakeServiceWorkerUpdateAdapter / MemoryPublicResponseCache", - "failureKinds": ["stale-worker", "update-loop", "offline-fallback", "incomplete-candidate", "integrity-mismatch", "cache-policy-rejection", "quota"], + "failureKinds": ["stale-worker", "update-loop", "offline-navigation-network-error", "incomplete-candidate", "integrity-mismatch", "cache-policy-rejection", "quota"], "lifecycleMethods": ["unregister", "rollback", "delete-owned-caches"], "owner": "project-owner-required", "securityPrivacy": ["Cache only explicit same-origin public GET representations.", "Never cache authenticated, cookie-dependent, private, no-store, opaque or personal responses.", "Bind candidate cache names to release identity and a canonical manifest digest that includes normalized expectedContentType, exact request identity, expected byte length and integrity digest.", "Reject a response whose normalized Content-Type differs from manifest expectedContentType even when body integrity matches.", "Derive cleanup retention only from the verified active pointer and composition retainedPreviousReleaseCount; cleanup callers cannot submit cache names, release registry IDs or any retain set.", "Read active-pointer and release-marker control JSON through a strict UTF-8 stream capped at exactly 2 MiB (2097152 bytes), cancel on overflow and fail closed before parsing oversized metadata.", "Keep exact query and Vary semantics; ignoreSearch and ignoreVary are forbidden.", "Fail closed on malformed update metadata or integrity mismatch."], diff --git a/docs/architecture/optional-adapter-recipes.md b/docs/architecture/optional-adapter-recipes.md index 58740fb6..06edfc7e 100644 --- a/docs/architecture/optional-adapter-recipes.md +++ b/docs/architecture/optional-adapter-recipes.md @@ -108,7 +108,7 @@ type은 facade 밖으로 노출하지 않는다. | --- | --- | --- | --- | | realtime | foreground ordered event 또는 duplex protocol이 확정됨 | focus refetch/manual refresh가 충분하거나 ordering·replay owner 없음 | bounded polling 또는 stale UI | | offline/IndexedDB/OPFS | structured offline data/queue 또는 large local binary가 제품 요구 | credential, partition/retention/recovery 미정, HTTP cache로 충분 | read-only/online-only 또는 승인된 bounded Blob | -| Service Worker/Cache Storage | install/offline shell 또는 public HTTP representation cache owner 승인 | auth/private/opaque cache, update/rollback UX 없음 | hosting cache 기반 network app | +| Service Worker/Cache Storage | 설치형(installability) 또는 public HTTP representation cache owner 승인. 오프라인 셸은 지원하지 않는다(이 절 끝) | auth/private/opaque cache, update/rollback UX 없음 | hosting cache 기반 network app | | file/picker/download | selection/preview/upload/download와 bounded memory/integrity 요구 | backend 재검증 없음, whole-buffer large file, long-lived credential URL | native input + authorized direct download | | generated API | versioned source와 drift CI가 있음 | DTO가 domain/UI로 노출됨 | typed request builder + schema | | feature flag | rollout/kill switch owner와 default 있음 | authorization에 사용 | typed local default | @@ -152,6 +152,17 @@ Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7과 2의 시 비교한다. 준비 단계에서 실패하면 helper(`tests/e2e/support/service-worker-builds.ts`) 머리 주석의 전제 목록과 두 spec 머리 주석에서 바뀐 곳을 찾는다. +오프라인 셸(0929/06-03): reference 워커는 navigation을 가로채지 않는다 +(`service-worker-static-assets.ts` navigation `NETWORK_ONLY`, +`service-worker-lifecycle.ts` `intercepts`). 사전 캐시는 해시 이름의 +`assets/`뿐이고 `index.html`은 넣지 않는다(`scripts/generate-service-worker-assets.ts`). +설계가 cached `index.html` fallback을 금지한다(closed deep design 18.8). 오프라인 +셸이 필요한 제품은 템플릿 워커를 켜는 것으로 얻지 못한다. 별도 제품 capability로 +설계하고, 그때 넘겨받는 파일은 위 세 파일과 `vite.service-worker.config.ts`다. +`tests/e2e/service-worker-update.spec.ts`의 사전 캐시 단언과 "HTML과 자산은 같은 +release" 성질은 제품이 다시 증명한다. 넘겨받은 뒤에는 템플릿 동기화에서 이 파일들이 +충돌한다. + Web Push target은 현재 13번째 설치 recipe가 아니다. 기존 `realtime`, `service-worker-pwa`, `browser-permission`의 인접 경계를 조합해야 하는 별도 `NOT_SELECTED` capability다. 실제 선택 전 VD-10 amendment와 machine-readable From 4f19cd9e8b64434b50d4ad7dea846f1b2c6b8d3b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:40:11 +0900 Subject: [PATCH 13/13] =?UTF-8?q?test(service-worker):=20=EC=82=B4?= =?UTF-8?q?=EC=95=84=EB=82=A8=EB=8D=98=20=EC=9B=8C=EC=BB=A4=20=EB=B3=B4?= =?UTF-8?q?=ED=98=B8=20=EC=9E=A5=EC=B9=98=20=EB=B3=80=EC=9D=B4=204?= =?UTF-8?q?=EA=B1=B4=EC=9D=84=20=ED=85=8C=EC=8A=A4=ED=8A=B8=EB=A1=9C=20?= =?UTF-8?q?=EC=9E=A1=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 워커 보호 장치 넷은 지워도 테스트가 모두 통과한다(1101/06-04, 이번 리뷰에서 다시 생존). install fetch의 credentials: "omit"·redirect: "error"(M1), activate nonce 한 번만 쓰기(M3), 요청받지 않은 client의 CLIENT_DRAINED 거절(M9), 첫 설치를 "업데이트 대기"로 알리지 않기(N8). 고른 방법 - service-worker-runtime.test.ts에 테스트 3건을 더한다. - install이 자산마다 cache no-store, credentials omit, redirect error로 요청한다(M1). - 같은 nonce의 두 번째 ACTIVATE_REQUEST는 REJECTED, 요청받지 않은 client의 drain 응답은 세지 않는다(M3, M9). - active 워커가 없는 첫 설치는 onUpdateWaiting을 부르지 않는다(N8). - 동작은 바꾸지 않는다. 위험·한계 - N8 테스트는 시작 뒤 registration.active를 null로 바꿔 첫 설치를 흉내 낸다. 실제 브라우저 첫 설치 순서는 e2e가 본다. 검증 - service-worker-runtime 64건 통과. - 변이 4건(M1·M3·M9·N8)을 하나씩 넣어 각각 1건 실패를 확인하고 되돌렸다. - 바꾼 파일 eslint, check:types:test 통과. Refs: docs/reviews/2026-11-03-maturity-review/06-adapters-service-worker-push.md 2절 1101/06-04 --- tests/unit/service-worker-runtime.test.ts | 99 +++++++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/tests/unit/service-worker-runtime.test.ts b/tests/unit/service-worker-runtime.test.ts index 64cb3fd5..bd57ca01 100644 --- a/tests/unit/service-worker-runtime.test.ts +++ b/tests/unit/service-worker-runtime.test.ts @@ -768,6 +768,45 @@ describe("service worker worker-side protocol", () => { expect(fixture.scope.skipWaiting).toHaveBeenCalledTimes(1); }); + // 1101/06-04 (M3, M9). An activation nonce is single-use, and only a client + // the worker asked to drain can acknowledge it. + it("refuses a reused nonce and a drain reply from a client it did not ask", async () => { + const fixture = workerScope(); + const runtime = createServiceWorkerRuntime(fixture.scope as never, { + identity, + handlers: [], + manifest: null, + runtimeConfigUrl: "/runtime-config.json", + releaseManifestUrl: "/release-manifest.json", + }); + const message = (kind: "ACTIVATE_REQUEST" | "CLIENT_DRAINED") => + createServiceWorkerMessage({ + kind, + sourceBuildId: "page-build", + targetBuildId: "worker-build", + nonce: "activation-1", + }); + + const activation = runtime.onActivateRequest(message("ACTIVATE_REQUEST")); + let settled = false; + void activation.then(() => { + settled = true; + }); + await Promise.resolve(); + runtime.onClientMessage(message("CLIENT_DRAINED"), "client-a"); + runtime.onClientMessage(message("CLIENT_DRAINED"), "client-unasked"); + for (let turn = 0; turn < 10; turn += 1) await Promise.resolve(); + expect(settled).toBe(false); + expect(fixture.scope.skipWaiting).not.toHaveBeenCalled(); + + runtime.onClientMessage(message("CLIENT_DRAINED"), "client-b"); + await expect(activation).resolves.toBe("ACCEPTED"); + await expect( + runtime.onActivateRequest(message("ACTIVATE_REQUEST")), + ).resolves.toBe("REJECTED"); + expect(fixture.scope.skipWaiting).toHaveBeenCalledTimes(1); + }); + it("enumerates uncontrolled window clients before an activation drain", async () => { const fixture = workerScope(); const runtime = createServiceWorkerRuntime(fixture.scope as never, { @@ -1039,6 +1078,41 @@ describe("service worker static asset install", () => { return { result, put }; } + // 1101/06-04 (M1). The precache holds only public assets: no cookie or + // credential goes with the request, a redirect is refused rather than + // followed to another resource, and the HTTP cache is bypassed. + it("fetches each asset without credentials, redirects or the HTTP cache", async () => { + const fetcher = vi.fn( + async (_url: RequestInfo | URL, _init?: RequestInit) => + new Response(new Uint8Array([1]), { + status: 200, + headers: { "content-type": "text/javascript" }, + }), + ); + await expect( + installStaticAssets( + { + ...manifest, + assets: [{ ...manifest.assets[0]!, contentType: "text/javascript" }], + }, + { + caches: { + open: vi.fn(async () => ({ put: vi.fn(async () => {}) }) as unknown as Cache), + delete: vi.fn(async () => true), + }, + fetcher, + digest: vi.fn(async () => manifest.assets[0]!.sha256), + }, + ), + ).resolves.toMatchObject({ kind: "INSTALLED" }); + expect(fetcher).toHaveBeenCalledOnce(); + expect(fetcher.mock.calls[0]![1]).toMatchObject({ + cache: "no-store", + credentials: "omit", + redirect: "error", + }); + }); + it("installs JavaScript served under a JavaScript MIME synonym (R-6.5)", async () => { const { result, put } = installOne( new Response(new Uint8Array([1]), { @@ -1339,6 +1413,31 @@ describe("service worker static asset install", () => { await controller.stop(); }); + // 1101/06-04 (N8). A first install has no active worker to replace. It + // activates on its own, so it is never announced as an update waiting. + it("does not announce a first install as an update waiting", async () => { + const browser = pageContainer({ controlled: true }); + const controller = pageController(browser.container); + await expect(controller.start()).resolves.toMatchObject({ kind: "ACTIVE" }); + const updateWaiting = vi.fn(); + controller.onUpdateWaiting?.(updateWaiting); + const registration = browser.registration as unknown as EventTarget & { + installing: ServiceWorker | null; + waiting: ServiceWorker | null; + active: ServiceWorker | null; + }; + registration.active = null; + const first = fakeWorker([], "installing"); + registration.installing = first as unknown as ServiceWorker; + registration.dispatchEvent(new Event("updatefound")); + registration.installing = null; + registration.waiting = first as unknown as ServiceWorker; + setWorkerState(first, "installed"); + + expect(updateWaiting).not.toHaveBeenCalled(); + await controller.stop(); + }); + it("accepts a post-commit reply after the waiting worker was promoted (R-6.1)", async () => { const browser = pageContainer({ waiting: true }); const controller = pageController(browser.container);