From bde7fa4609960d87fb07be7712b4c5b1fa08ff6e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:01:01 +0900 Subject: [PATCH 1/8] =?UTF-8?q?test(realtime):=20=EC=A1=B0=ED=95=A9=20tran?= =?UTF-8?q?sport=EC=9D=98=20OFFLINE=20=EC=9E=AC=EC=8B=9C=EB=8F=84=20?= =?UTF-8?q?=EA=B7=9C=EC=B9=99=EC=9D=84=20=ED=85=8C=EC=8A=A4=ED=8A=B8?= =?UTF-8?q?=EB=A1=9C=20=EB=8B=A4=EC=8B=9C=20=EB=A7=89=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 0929/04-01 규칙은 "환경이 online이면 transport가 낸 OFFLINE도 online 이벤트를 기다리지 않고 backoff로 재시도한다"이다 (reconnect-coordinator.ts의 RealtimeReconnectEnvironment 주석, 설계 5.3). 이 규칙을 막던 두 테스트는 SSE fetch·reader 거절이 OFFLINE이던 것을 이용했다. af00067(1103/04-04)이 SSE 거절을 PROVIDER_UNAVAILABLE로 바꾼 뒤 두 테스트는 그 kind의 재시도만 본다. 4d27b20이 지운 requireOnline() 두 줄을 되살리는 변이(MR1)에서 realtime 테스트가 모두 통과했다(리뷰 04-R4). 고른 방법: 조합 코드가 만든 transport로 그 경로를 직접 지나는 테스트 둘을 더한다. 환경은 계속 online이다. - attempt가 OFFLINE/CONNECT/retryable로 실패한다 → 3회 시도, backoff [50, 100], OFFLINE retryable로 끝난다. 관측 순서도 고정한다. - 세션이 열린 뒤 OFFLINE/RECEIVE/retryable로 닫힌다 → 3회 시도, OFFLINE retryable로 끝난다. 리뷰 대조 C1·C2와 같은 입력이고, `as never` 없이 파일의 도우미를 쓴다. 버린 대안: SSE 테스트 기대값을 OFFLINE으로 되돌리기. 템플릿 SSE는 이제 OFFLINE을 내지 않으므로 실제 동작과 다른 테스트가 된다. 위험·한계: 테스트만 더했다. 동작은 바뀌지 않는다. 그래서 RED(부모 코드)에서도 이 테스트는 통과한다. 결함을 보이는 방법은 변이 MR1이다. 검증: desktop batch에서 확인. - GREEN: node scripts/run-vitest.ts run tests/unit/realtime/ - 변이 MR1(reconnect-coordinator.ts의 두 retry 분기 뒤 OFFLINE이면 requireOnline()): 새 두 테스트가 attempts 1, result null로 실패해야 한다 Refs: 1105/04-01 --- .../realtime-reconnect-coordinator.test.ts | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts index abf6b80e..5ef1faf7 100644 --- a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts +++ b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts @@ -2198,6 +2198,93 @@ describe("transport failures through the reconnect coordinator", () => { ]); }); + // 1105/04-01. No template transport reports OFFLINE any more (1103/04-04), + // so the two SSE tests above no longer reach the 0929/04-01 rule. A + // composer's transport (a STOMP one, say) still may. While the environment + // stays online, its OFFLINE is retried with backoff; waiting for an online + // event that never comes would park the run with no retry and no result. + it("retries a composer transport's OFFLINE attempt failure while the browser stays online", async () => { + const clock = new ManualClock(); + const offline = realtimeFailure("OFFLINE", "CONNECT", true); + const observed: string[] = []; + let attempts = 0; + const coordinator = createRealtimeReconnectCoordinator({ + policy: policy(), + environment: new MutableOnlineEnvironment(true), + clock, + random: () => 0.5, + confirmTransportBarrier: confirmationSucceeded, + attempt: () => { + attempts += 1; + return failed(offline); + }, + observe: (observation) => observed.push(observationLabel(observation)), + }); + + let result: RealtimeResult | null = null; + void coordinator.run().then((value) => { + result = value; + }); + await advanceUntil(clock, () => result !== null); + + expect(attempts).toBe(3); + expect(clock.sleepCalls).toEqual([50, 100]); + expect(result).toEqual({ + ok: false, + error: { kind: "OFFLINE", operation: "CONNECT", retryable: true }, + }); + expect(observed).toEqual([ + "ATTEMPT_STARTED", + "RETRY_SCHEDULED:OFFLINE", + "ATTEMPT_STARTED", + "RETRY_SCHEDULED:OFFLINE", + "ATTEMPT_STARTED", + "RUN_ENDED:OFFLINE:EXHAUSTED", + ]); + }); + + it("reconnects after a composer session closes with OFFLINE while the browser stays online", async () => { + const clock = new ManualClock(); + const offline = realtimeFailure("OFFLINE", "RECEIVE", true); + const observed: string[] = []; + let attempts = 0; + const coordinator = createRealtimeReconnectCoordinator({ + policy: policy(), + environment: new MutableOnlineEnvironment(true), + clock, + random: () => 0.5, + confirmTransportBarrier: confirmationSucceeded, + attempt: () => { + attempts += 1; + return opened( + Object.freeze({ + classifyClosed: ( + receipt: RealtimeReconnectOutcome, + ) => receipt, + close: vi.fn(), + waitClosed: () => failed(offline), + }), + ); + }, + observe: (observation) => observed.push(observationLabel(observation)), + }); + + let result: RealtimeResult | null = null; + void coordinator.run().then((value) => { + result = value; + }); + await advanceUntil(clock, () => result !== null); + + expect(attempts).toBe(3); + expect(result).toEqual({ + ok: false, + error: { kind: "OFFLINE", operation: "RECEIVE", retryable: true }, + }); + expect( + observed.filter((label) => label === "RETRY_SCHEDULED:OFFLINE"), + ).toHaveLength(2); + }); + it.each(["before", "after"] as const)( "waits for the online event when the browser goes offline %s the SSE fetch rejects", async (order) => { From 05330e30a844d0dfd2cda8885df6667a4ae0f1ad Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:03:56 +0900 Subject: [PATCH 2/8] =?UTF-8?q?fix(realtime)!:=20=EB=8D=98=EC=A7=80?= =?UTF-8?q?=EB=8A=94=20poll=20execute=EB=A5=BC=20=EC=84=9C=EB=B2=84=20?= =?UTF-8?q?=EC=9E=A5=EC=95=A0=EA=B0=80=20=EC=95=84=EB=8B=88=EB=9D=BC=20PRO?= =?UTF-8?q?TOCOL=5FMISMATCH=EB=A1=9C=20=EB=81=9D=EB=82=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: bounded poll은 `execute`의 throw를 PROVIDER_UNAVAILABLE/retryable로 바꿔 lease 안에서 다시 부른다(af00067). 설계 9.2가 권하는 조합은 `execute` 안에서 V3 실행기를 부르는 것이고, 실행기는 fetch 거절을 던지지 않고 NETWORK_FAILURE 결과로 돌려준다. 그래서 그 조합에서 throw는 결과 매핑·디코딩 같은 조합 코드 결함이다. 지금은 그 결함이 maxAttempts번의 요청과 ATTEMPT_FINISHED: PROVIDER_UNAVAILABLE, 끝으로 POLL_BUDGET_EXHAUSTED가 되어 서버 장애로 보인다. 원인 예외는 남지 않는다. 고른 방법: 리뷰 04-02의 선택지 (b). throw를 모양이 틀린 결과와 같은 계약 위반으로 본다. coordinator는 이미 `parseAttemptResult`가 거절한 결과를 재시도 없이 PROTOCOL_MISMATCH로 끝낸다. throw도 그 길로 보낸다. lease 자신의 abort로 생긴 throw는 지금처럼 abort의 이유(ABORTED, OFFLINE, 예산 소진 등)로 끝난다. `execute` 타입 주석, 설계 9.2와 13.1의 PROVIDER_UNAVAILABLE·PROTOCOL_MISMATCH 행을 같이 고쳤다. 버린 대안: - (c) 주석과 13.1에만 "throw는 서버 장애로 재시도된다"를 적기. 완료 기준은 "결과를 보고 조합 결함과 서버 장애를 구분한다"인데, (c)는 읽는 사람만 알고 결과는 그대로라 구분할 수 없다. - 관측에 throw 표시 칸을 더하기. 닫힌 관측 어휘를 넓히고, 결과 kind는 여전히 서버 장애다. 위험·한계: - 배럴로 공개된 bounded poll의 결과가 바뀐다. repo 안 소비자는 테스트뿐이다. - `fetch`를 직접 부르는 조합은 네트워크 실패를 결과로 바꾸지 않으면 첫 거절에서 lease가 끝난다. 설계가 권하지 않는 조합이고, 타입 주석과 9.2가 "실패도 결과로 돌려준다"를 적는다. - reconnect coordinator는 던지는 `attempt`를 계속 PROVIDER_UNAVAILABLE로 재시도한다. 그쪽 attempt는 브라우저 연결 API를 감싸는 자리라 이번 범위 밖이다. - CHANGELOG.md 미출시 [계약] 행의 "poll은 던지는 execute도 lease 안에서 다시 시도한다"는 이 커밋과 맞지 않는다. CHANGELOG는 오케스트레이터가 고친다. 검증: desktop batch에서 확인. - node scripts/run-vitest.ts run tests/unit/realtime/ - RED: "ends the lease with PROTOCOL_MISMATCH for an async execute that rejects"·"... throws before returning"가 옛 코드에서 execute 3회, POLL_BUDGET_EXHAUSTED로 실패한다. "keeps ABORTED ..."는 양쪽에서 통과한다 (보존 조건). BREAKING CHANGE: createBoundedPollCoordinator의 `execute`가 던지면(abort로 생긴 것 제외) 재시도 없이 PROTOCOL_MISMATCH(retryable: false)로 lease가 끝난다. 전에는 PROVIDER_UNAVAILABLE로 maxAttempts까지 재시도했다. 네트워크 실패를 throw로 내던 `execute`는 그것을 retryable PROVIDER_UNAVAILABLE 결과로 바꿔 돌려준다. Refs: 1105/04-02 --- ...ime-events-web-push-and-bounded-polling.md | 7 +- .../polling/bounded-poll-coordinator.ts | 25 +++-- .../realtime/bounded-poll-coordinator.test.ts | 103 ++++++++++++------ 3 files changed, 92 insertions(+), 43 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 a0d3a2e7..428776d0 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -1667,7 +1667,8 @@ poll coordinator는 실행할 V3 descriptor(`InstalledHttpContract`, 조립된 (`http-execution-v3.ts` `retryCeiling`). 이 값을 descriptor에서 읽으므로, poll에 묶은 descriptor가 0이면 실행기의 `maxRetryAttempts`(`MAX_RETRY_ATTEMPTS`)와 상관없이 poll 한 attempt가 요청 한 번이다. 같은 descriptor를 `execute` 안에서 실행기에 -넘긴다. 기능의 기본 GET descriptor(`create:feature`는 `retryBudget: 2`)는 생성 때 +넘긴다. `execute`는 서버·네트워크 실패도 결과로 돌려준다. 던지면 조합 코드 +결함으로 보고 재시도 없이 `PROTOCOL_MISMATCH`로 lease를 끝낸다(1105/04-02). 기능의 기본 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`여야 한다. @@ -1958,8 +1959,8 @@ credential을 보호할 수 있다고 주장하지 않는다. | `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. 환경은 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 | +| `PROVIDER_UNAVAILABLE` | backend/push/hosting unavailable. 환경은 online인데 서버·프록시에 닿지 않은 것(SSE fetch·reader 거절, WebSocket `error`)도 이 kind다(1103/04-04, `retryable: true`). poll은 `execute`가 돌려준 결과의 kind를 쓴다. V3 실행기는 fetch 거절을 던지지 않고 `NETWORK_FAILURE` 결과로 돌려주므로, `execute`가 그 결과를 이 kind로 바꾼다. 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. poll `execute`가 던지거나 모양이 틀린 결과를 돌려준 것도 이 kind다. 조합 코드 결함이라 서버 장애로 재시도하지 않는다(1105/04-02, `retryable: false`) | 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 | | `EVENT_CONFLICT` | 같은 ID/sequence가 다른 event를 가리킴 | terminal protocol conflict + resync/rollback | diff --git a/src/adapters/realtime/polling/bounded-poll-coordinator.ts b/src/adapters/realtime/polling/bounded-poll-coordinator.ts index c92908d3..f2f73202 100644 --- a/src/adapters/realtime/polling/bounded-poll-coordinator.ts +++ b/src/adapters/realtime/polling/bounded-poll-coordinator.ts @@ -101,6 +101,12 @@ export type BoundedPollCoordinatorDependencies = Readonly<{ * refuses one whose `frontend.retryBudget` is not 0. */ operation: BoundedPollOperation; + /** + * Returns every outcome as a result, server and network failures included + * (the V3 executor returns a rejected fetch as NETWORK_FAILURE). A throw, + * like a result of the wrong shape, ends the lease with PROTOCOL_MISMATCH + * and is not retried: it is a composition defect, not a server outage. + */ execute(input: Readonly<{ operationId: string; attempt: number; @@ -300,7 +306,7 @@ export function createBoundedPollCoordinator( } attempts += 1; - let result: BoundedPollAttemptResult; + let result: BoundedPollAttemptResult | null; const attemptOutcome = await awaitWithinLease( () => trackWork( @@ -320,12 +326,14 @@ 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" : "PROVIDER_UNAVAILABLE", - "POLL", - !controller.signal.aborted, - ); + // 1105/04-02. `execute` returns every failure as a result; the V3 + // executor already returns a rejected fetch as NETWORK_FAILURE. A + // throw is a composition defect, read below like a malformed + // result, not retried as a server outage. One caused by this + // lease's abort ends with the abort's reason. + result = controller.signal.aborted + ? realtimeFailure("ABORTED", "POLL", false) + : null; } else { if (attemptOutcome.kind === "CLOCK_FAILED") { controller.abort(); @@ -374,7 +382,8 @@ export function createBoundedPollCoordinator( return pollFailure("POLL_BUDGET_EXHAUSTED"); } - const parsedResult = parseAttemptResult(result); + const parsedResult = + result === null ? null : parseAttemptResult(result); if (!parsedResult) { return pollFailure("PROTOCOL_MISMATCH"); } diff --git a/tests/unit/realtime/bounded-poll-coordinator.test.ts b/tests/unit/realtime/bounded-poll-coordinator.test.ts index c2c9cfd3..cbd8e735 100644 --- a/tests/unit/realtime/bounded-poll-coordinator.test.ts +++ b/tests/unit/realtime/bounded-poll-coordinator.test.ts @@ -903,47 +903,86 @@ describe("bounded poll coordinator", () => { }); }); - // 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 () => { + // 1105/04-02. `execute` returns server and network failures as results (the + // V3 executor returns a rejected fetch as NETWORK_FAILURE). A throw is a + // composition defect, like a malformed result: the lease ends at once with + // PROTOCOL_MISMATCH instead of retrying it as a server outage until the + // budget runs out. + it.each([ + ["an async execute that rejects", async () => { + throw new TypeError("Cannot read properties of undefined"); + }], + ["an execute that throws before returning", () => { + throw new TypeError("Cannot read properties of undefined"); + }], + ] as const)( + "ends the lease with PROTOCOL_MISMATCH for %s", + async (_label, body) => { + const clock = new ManualClock(); + const observations: BoundedPollObservation[] = []; + const execute = vi.fn( + body as () => Promise>, + ); + const coordinator = createBoundedPollCoordinator({ + policy, + operation, + environment: new MutableEnvironment(), + clock, + random: () => 0.5, + execute, + observe: (observation) => observations.push(observation), + }); + + 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(1); + expect(result).toEqual({ + ok: false, + error: { + kind: "PROTOCOL_MISMATCH", + operation: "POLL", + retryable: false, + }, + }); + expect(observations).toEqual([ + { kind: "LEASE_STARTED" }, + { kind: "LEASE_STOPPED", outcome: "PROTOCOL_MISMATCH" }, + ]); + expect(coordinator.getState()).toBe("IDLE"); + }, + ); + + it("keeps ABORTED when execute rejects because the caller aborted", async () => { const clock = new ManualClock(); - const observations: BoundedPollObservation[] = []; - const execute = vi.fn(async (): Promise> => { - throw new TypeError("Failed to fetch"); - }); + const caller = new AbortController(); const coordinator = createBoundedPollCoordinator({ policy, operation, environment: new MutableEnvironment(), clock, - random: () => 0.5, - execute, - observe: (observation) => observations.push(observation), + execute: ({ signal }) => + new Promise>((_resolve, reject) => { + signal.addEventListener( + "abort", + () => reject(new DOMException("Aborted", "AbortError")), + { once: true }, + ); + caller.abort(); + }), }); - 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({ + const running = coordinator.run({ signal: caller.signal }); + clock.advance(5_000); + await expect(running).resolves.toEqual({ ok: false, - error: { kind: "POLL_BUDGET_EXHAUSTED", operation: "POLL" }, + error: { kind: "ABORTED", operation: "POLL", retryable: false }, }); }); From 27e3dec5dd5848d8e4777a75577d67812b1f7e92 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:05:31 +0900 Subject: [PATCH 3/8] =?UTF-8?q?fix(realtime):=20poll=20execute=EC=97=90=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1=20=EB=95=8C=20=EA=B2=80=EC=82=AC=ED=95=9C=20?= =?UTF-8?q?descriptor=EB=A5=BC=20=EB=84=98=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: bounded poll은 생성 때 descriptor의 `retryBudget`이 0인지 본다 (1103/04-01). 그런데 `execute` 입력에는 descriptor가 없다. 조합 코드는 실행기에 넘길 descriptor를 스스로 골라야 하고, 같은 경로의 기본 GET (`retryBudget: 2`)을 넘겨도 막는 것이 없다. 리뷰 04-R1 P5에서 poll 3회가 요청 9회, 실행기 대기 6번이었다. 타입 주석과 설계 9.2가 "같은 객체를 넘긴다"고 적을 뿐이다. 고른 방법: coordinator가 생성 때 검사한 그 객체를 모든 `execute` 호출에 `input.operation`으로 넘긴다. 생성 때 한 번 잡아 두므로 나중에 dependencies 객체가 바뀌어도 검사한 객체가 간다. 조합 코드는 클로저의 descriptor 대신 이것을 실행기에 넘기면 된다. 테스트의 V3 조합도 그렇게 바꿨다. 타입 주석(`bounded-polling.ts`, `bounded-poll-coordinator.ts`)과 설계 9.2를 고쳤다. 버린 대안: coordinator가 실행기를 직접 받아 부르기. 실행기 타입은 `adapters/http`에 있어 realtime 어댑터가 import할 수 없다(adapter 사이 import 금지, kernel 예외 아님). 구조 타입을 새로 두면 결과 매핑까지 coordinator가 정해야 해서 공개 모양이 크게 바뀐다. 위험·한계: 일부만 닫는다. 조합 코드가 `input.operation`을 무시하고 다른 descriptor를 실행기에 넘기면 여전히 attempt마다 요청이 최대 3번이다. 설계 9.2가 이 남은 틈을 적는다. 입력 칸을 더한 것이라 기존 `execute`는 그대로 돈다. 검증: desktop batch에서 확인. - node scripts/run-vitest.ts run tests/unit/realtime/ - RED: "hands every execute call the descriptor it checked at creation" (받은 값이 undefined), "sends one request per poll attempt with a poll descriptor"(실행기에 undefined가 가서 요청 0개, PROTOCOL_MISMATCH)가 옛 코드에서 실패한다. Refs: 1103/04-01 --- ...ime-events-web-push-and-bounded-polling.md | 6 ++- .../polling/bounded-poll-coordinator.ts | 16 ++++-- src/application/policies/bounded-polling.ts | 5 +- .../realtime/bounded-poll-coordinator.test.ts | 51 ++++++++++++++++++- 4 files changed, 69 insertions(+), 9 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 428776d0..c2dd5e3f 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -1666,8 +1666,10 @@ poll coordinator는 실행할 V3 descriptor(`InstalledHttpContract`, 조립된 `min(retryBudget, maxRetryAttempts, 2)`번 다시 보낸다 (`http-execution-v3.ts` `retryCeiling`). 이 값을 descriptor에서 읽으므로, poll에 묶은 descriptor가 0이면 실행기의 `maxRetryAttempts`(`MAX_RETRY_ATTEMPTS`)와 상관없이 -poll 한 attempt가 요청 한 번이다. 같은 descriptor를 `execute` 안에서 실행기에 -넘긴다. `execute`는 서버·네트워크 실패도 결과로 돌려준다. 던지면 조합 코드 +poll 한 attempt가 요청 한 번이다. coordinator는 생성 때 검사한 그 descriptor를 +`execute` 입력의 `operation`으로 넘긴다. `execute`는 그것을 실행기에 넘긴다. +같은 경로의 다른 행(예: 기본 GET, `retryBudget: 2`)을 넘기면 막는 것이 없고 +attempt마다 요청이 최대 3번이다. `execute`는 서버·네트워크 실패도 결과로 돌려준다. 던지면 조합 코드 결함으로 보고 재시도 없이 `PROTOCOL_MISMATCH`로 lease를 끝낸다(1105/04-02). 기능의 기본 GET descriptor(`create:feature`는 `retryBudget: 2`)는 생성 때 거절된다. poll 전용 operation을 따로 등록한다. V3에는 401 재전송이 없다. command/mutation, GraphQL subscription, Connect/gRPC-Web server stream과 arbitrary diff --git a/src/adapters/realtime/polling/bounded-poll-coordinator.ts b/src/adapters/realtime/polling/bounded-poll-coordinator.ts index f2f73202..0e03c1fb 100644 --- a/src/adapters/realtime/polling/bounded-poll-coordinator.ts +++ b/src/adapters/realtime/polling/bounded-poll-coordinator.ts @@ -98,7 +98,8 @@ export type BoundedPollCoordinatorDependencies = Readonly<{ policy: PollLeasePolicy; /** * The V3 descriptor `execute` runs (`BoundedPollOperation`). Creation - * refuses one whose `frontend.retryBudget` is not 0. + * refuses one whose `frontend.retryBudget` is not 0, and every `execute` + * call receives this same object as `input.operation`. */ operation: BoundedPollOperation; /** @@ -109,6 +110,13 @@ export type BoundedPollCoordinatorDependencies = Readonly<{ */ execute(input: Readonly<{ operationId: string; + /** + * 1103/04-01. The `operation` this coordinator was created with, the + * object creation checked. Run this one on the executor, not another row + * for the same path: a descriptor with `retryBudget: 2` sends up to three + * requests per attempt. + */ + operation: BoundedPollOperation; attempt: number; /** * Hard response-body ceiling that must be enforced before decoding. @@ -138,10 +146,11 @@ export function createBoundedPollCoordinator( dependencies: BoundedPollCoordinatorDependencies, ): BoundedPollCoordinator { const policy = definePollLeasePolicy(dependencies.policy); - assertBoundedPollOperation(policy, dependencies.operation); + const operation = dependencies.operation; + assertBoundedPollOperation(policy, operation); const maxResponseBytes = Math.min( policy.maxResponseBytes, - dependencies.operation.frontend.responseByteLimit, + operation.frontend.responseByteLimit, ); const clock = dependencies.clock ?? systemClock; const random = dependencies.random ?? Math.random; @@ -312,6 +321,7 @@ export function createBoundedPollCoordinator( trackWork( dependencies.execute({ operationId: policy.operationId, + operation, attempt: attempts, maxResponseBytes, signal: controller.signal, diff --git a/src/application/policies/bounded-polling.ts b/src/application/policies/bounded-polling.ts index 8d343df0..25c31b7f 100644 --- a/src/application/policies/bounded-polling.ts +++ b/src/application/policies/bounded-polling.ts @@ -31,8 +31,9 @@ export type PollLeasePolicy = Readonly<{ /** * 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 + * (`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. diff --git a/tests/unit/realtime/bounded-poll-coordinator.test.ts b/tests/unit/realtime/bounded-poll-coordinator.test.ts index cbd8e735..db27657f 100644 --- a/tests/unit/realtime/bounded-poll-coordinator.test.ts +++ b/tests/unit/realtime/bounded-poll-coordinator.test.ts @@ -1142,9 +1142,11 @@ describe("a poll attempt on the V3 executor", () => { environment: new MutableEnvironment(), clock, random: () => 0.5, - execute: async ({ signal }) => { + // 1103/04-01. Runs the descriptor the coordinator hands back, never a + // closed-over one. + execute: async ({ operation: polled, signal }) => { const outcome = await executor.execute( - descriptor, + polled, { limit: 20 }, { routeId: "TEST_ROUTE", scope, signal }, ); @@ -1199,4 +1201,49 @@ describe("a poll attempt on the V3 executor", () => { }); expect(requests).toHaveLength(pollPolicy.maxAttempts); }); + + // 1103/04-01's remaining gap: `execute` had no descriptor, so composition + // code chose one itself and could run the default row (three requests per + // attempt, review 04-R1 P5). + it("hands every execute call the descriptor it checked at creation", 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 received: unknown[] = []; + const coordinator = createBoundedPollCoordinator({ + policy: pollPolicy, + operation: pollOnly, + environment: new MutableEnvironment(), + clock, + random: () => 0.5, + execute: async ({ operation: polled }) => { + received.push(polled); + return { + ok: false, + error: { + kind: "PROVIDER_UNAVAILABLE", + operation: "POLL", + retryable: true, + }, + }; + }, + }); + + 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(received).toHaveLength(pollPolicy.maxAttempts); + for (const polled of received) expect(polled).toBe(pollOnly); + }); }); From 05880d12faa726fdab5e582961d9acb4dffbc319 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:06:38 +0900 Subject: [PATCH 4/8] =?UTF-8?q?docs(realtime):=20VD-28=EA=B3=BC=20?= =?UTF-8?q?=EC=84=A4=EA=B3=84=203=EC=A0=88=EC=9D=98=20poll=20=EA=B7=9C?= =?UTF-8?q?=EC=B9=99=EC=9D=84=20V3=20descriptor=EB=A1=9C=20=EA=B3=A0?= =?UTF-8?q?=EC=B9=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: VD-28은 poll 규칙을 지운 V2 실행 예산으로 적는다. "operation은 registered terminal·replay-safe REST `QUERY`", "Poll-bound VD-23 budget은 `maxAttempts=1`, `authRecoveryCount=0`, `maxCumulativeSleepMs=0`"이다. 설계 3절도 "REST `QUERY` operation"과 "REST operation registry"라고 적는다. V2 실행 경로는 2026-11-03에 지웠고(VD-23 상태 줄), 지금 규칙은 V3 descriptor의 `frontend.retryBudget: 0`이다(설계 9.2, 1103/04-01). a65df74가 9.2만 고쳤다. 고른 방법: VD-28 1절 끝 문장과 11절 목록, 설계 3절 두 항목을 지금 규칙으로 바꾼다. GET·HEAD, SAFE·IDEMPOTENT인 V3 descriptor, `retryBudget` 0이 아니면 생성 때 거절, 실행기가 그 칸에서 재시도 상한을 읽어 한 attempt가 요청 하나라는 것이다. 상세는 9.2를 가리킨다. 설계 3절의 "REST operation registry의 credential, conditional request, ... 재사용"은 주어를 V3 실행기로 바꾸면서 conditional request를 뺐다. V3 실행기에는 ETag 처리가 없고(`http-execution-v3.ts`에 If-None-Match 없음), VD-23 상태 줄이 conditional execution을 `DESIGNED_NOT_IMPLEMENTED`로 적는다. 위험·한계: 문서만 바꿨다. VD-28 11절의 "ETag/`If-None-Match` 또는 server cursor 사용" 목표 줄은 결정 내용이라 그대로 두었다. 검증: 문서 전용이라 RED 없음. desktop batch에서 확인. - pnpm verify:documentation - `git grep -n "authRecoveryCount\|maxCumulativeSleepMs" -- docs/architecture/decisions/VD-28*` 0건(로컬 확인) Refs: 1105/04-03 --- ...altime-events-web-push-and-bounded-polling.md | 16 +++++++++------- ...altime-events-web-push-and-bounded-polling.md | 14 ++++++++------ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/docs/architecture/decisions/VD-28-realtime-events-web-push-and-bounded-polling.md b/docs/architecture/decisions/VD-28-realtime-events-web-push-and-bounded-polling.md index 402365a4..45414d1b 100644 --- a/docs/architecture/decisions/VD-28-realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/decisions/VD-28-realtime-events-web-push-and-bounded-polling.md @@ -114,9 +114,10 @@ protocol-specific terminal proof와 protobuf decode/schema/mapper를 끝낸 runtime-wide notification branch에서만 공통 scope/gap/resync coordinator를 재사용한다. frame/media/trailer, reconnect와 operation deadline owner를 SSE/WebSocket adapter로 합치거나 protobuf message를 -`REALTIME_EVENT_V1` JSON으로 다시 감싸지 않는다. Polling의 개별 attempt는 VD-23의 -terminal·replay-safe REST `QUERY` execution contract를 재사용하되 transport/Query -retry는 끄고, 이 결정은 attempt 사이 bounded lease만 소유한다. +`REALTIME_EVENT_V1` JSON으로 다시 감싸지 않는다. Polling의 개별 attempt는 V3 +contract executor가 실행하는 V3 REST descriptor 하나다(GET·HEAD, SAFE·IDEMPOTENT, +`frontend.retryBudget: 0`, 상세 설계 9.2). transport/Query retry는 끄고, 이 결정은 +attempt 사이 bounded lease만 소유한다. ### 2. source of truth는 서버다 @@ -438,10 +439,11 @@ Service Worker를 선택해도 offline fetch, PWA shell cache나 background sync 각 lease는 operation owner, minimum/success/max interval, max attempts, max elapsed, response byte cap, visible-only policy와 terminal states를 가진다. -- operation은 registered terminal·replay-safe REST `QUERY`여야 함 -- Poll `maxAttempts`는 physical request 하나인 logical completion을 셈 -- Poll-bound VD-23 budget은 `maxAttempts=1`, `authRecoveryCount=0`, - `maxCumulativeSleepMs=0`; TanStack Query retry도 끔 +- operation은 설치된 V3 REST descriptor(`InstalledHttpContract`)로, method가 + GET·HEAD이고 `retrySemantics`가 SAFE·IDEMPOTENT여야 함 +- descriptor의 `frontend.retryBudget`은 0이어야 함. 아니면 poll coordinator 생성이 + 거절한다(상세 설계 9.2, 1103/04-01). V3 실행기는 재시도 상한을 이 칸에서 읽으므로 + Poll `maxAttempts`의 한 attempt가 physical request 하나다. TanStack Query retry도 끔 - completion-chained timeout으로 single-flight - hidden/offline/pagehide/unmount/scope change/user cancel에서 stop - ETag/`If-None-Match` 또는 server cursor 사용 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 c2dd5e3f..dd8d6398 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -362,12 +362,14 @@ Connect/gRPC-Web server stream과 향후 GraphQL subscription은 이 문서의 S VD-29/VD-27 규칙을 우선한다. - API operation registry의 현재 `SERVER_STREAM`은 `CONNECT_HTTP | GRPC_WEB + rpcKind=SERVER_STREAM`만 허용한다. SSE, WebSocket과 Web Push는 - realtime registry가 소유하고, bounded polling은 terminal·replay-safe REST - `QUERY` operation에 적용하는 scheduling policy다. -- bounded polling의 한 logical attempt는 REST operation registry의 credential, - conditional request, schema/mapper와 deadline을 재사용한다. Poll 전용 - operation은 transport retry를 끄며 이 문서는 완료된 attempt 사이 cadence와 - failure backoff만 소유한다. + realtime registry가 소유하고, bounded polling은 V3 REST descriptor 중 + GET·HEAD이고 SAFE·IDEMPOTENT인 읽기 operation에 적용하는 scheduling policy다. +- bounded polling의 한 logical attempt는 V3 contract executor가 실행하고, 그 + 실행기의 credential, schema/mapper와 deadline을 재사용한다. conditional + request(ETag)는 V3 실행기에 아직 없다(VD-23 conditional execution + `DESIGNED_NOT_IMPLEMENTED`). Poll 전용 + operation은 `frontend.retryBudget: 0`으로 transport retry를 끈다(9.2). 이 문서는 + 완료된 attempt 사이 cadence와 failure backoff만 소유한다. 같은 stream을 Connect/gRPC-Web과 SSE로 자동 failover하지 않는다. wire와 resume 의미가 같다는 backend contract와 별도 rollout evidence가 있을 때만 명시된 fallback으로 From 1c7c614b47914f82284aaf0f99ef1ab6ba087cac Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:08:50 +0900 Subject: [PATCH 5/8] =?UTF-8?q?fix(service-worker):=20=EC=82=AC=EC=A0=84?= =?UTF-8?q?=20=EC=BA=90=EC=8B=9C=EB=A5=BC=20Vite=20assets=20=ED=8F=B4?= =?UTF-8?q?=EB=8D=94=EC=9D=98=20=ED=95=B4=EC=8B=9C=20=ED=8C=8C=EC=9D=BC?= =?UTF-8?q?=EB=A1=9C=20=EC=A0=9C=ED=95=9C=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 사전 캐시 수집기(`collectStaticAssets`)는 dist 전체를 돌고 파일 이름만 해시 정규식으로 본다. `public/` 파일은 이름 그대로 dist 루트에 복사되는데, `apple-touch-icon.png`, `android-chrome-192x192.png`, `safari-pinned-tab.svg`는 정규식에 걸려 immutable 자산으로 들어간다(리뷰 06-R1). 제품이 같은 이름으로 아이콘을 바꾸고 CDN이 옛 바이트를 주면 새 릴리스 install이 INTEGRITY_MISMATCH로 통째로 거절된다. 이전 릴리스 fallback, 호스팅 정책 `/assets/*`, MIME probe, 레시피 문서는 모두 `assets/`만 가정한다. 고른 방법: 리뷰 06-01의 (a). 계약 모듈에 `BUILD_ASSET_DIRECTORY = "assets/"` 하나를 두고, 수집기는 그 아래 파일만 받는다. 워커 fallback (`service-worker-static-assets.ts`)과 probe(`hosting-probe.ts`)도 같은 상수를 읽는다. `build.assetsDir`를 바꿀 때(0925/06-08) 이 상수 한 곳만 고치면 된다. 수집기의 `.vite/` 제외는 새 조건이 덮으므로 지웠다. 레시피 문서에 루트 파일이 빠진다는 문장을 더했다. 버린 대안: - 정규식을 Vite 해시 형식(8자 고정)으로 좁히기. 우연히 맞는 이름이 남는다. - 문서만 고치기. 아이콘 문제가 그대로다. 위험·한계: 루트에 해시 이름 파일을 일부러 두는 제품은 그 파일이 사전 캐시에서 빠진다. Vite는 그런 파일을 만들지 않는다. 상수는 vite 설정에서 읽지 않는다. `build.assetsDir`를 바꾸는 제품은 상수도 같이 바꿔야 한다 (0925/06-08은 그대로 남는다). 검증: desktop batch에서 확인. - node scripts/run-vitest.ts run tests/unit/service-worker-web-push-remediation.test.ts tests/unit/service-worker-runtime.test.ts tests/unit/hosting-probe.test.ts tests/unit/service-worker-build-output.test.ts - RED: "precaches only the assets directory, not public files at the dist root"가 옛 수집기에서 루트 아이콘 세 개를 받아 실패한다. Refs: 1105/06-01 --- docs/architecture/optional-adapter-recipes.md | 4 ++- scripts/generate-service-worker-assets.ts | 16 ++++++++-- scripts/lib/hosting-probe.ts | 7 +++-- .../service-worker-static-assets.ts | 9 +++--- src/contracts/service-worker.ts | 10 ++++++ ...ervice-worker-web-push-remediation.test.ts | 31 +++++++++++++++++++ 6 files changed, 66 insertions(+), 11 deletions(-) diff --git a/docs/architecture/optional-adapter-recipes.md b/docs/architecture/optional-adapter-recipes.md index 3027cdf7..16638e60 100644 --- a/docs/architecture/optional-adapter-recipes.md +++ b/docs/architecture/optional-adapter-recipes.md @@ -158,7 +158,9 @@ Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7과 2의 시 오프라인 셸(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`). +`assets/`(`src/contracts/service-worker.ts` `BUILD_ASSET_DIRECTORY`)뿐이고 `index.html`은 +넣지 않는다(`scripts/generate-service-worker-assets.ts`). `public/`에서 dist 루트로 복사된 +PWA 아이콘 같은 파일은 이름이 해시처럼 보여도 넣지 않는다(1105/06-01). 설계가 cached `index.html` fallback을 금지한다(closed deep design 18.8). 오프라인 셸이 필요한 제품은 템플릿 워커를 켜는 것으로 얻지 못한다. 별도 제품 capability로 설계하고, 그때 넘겨받는 파일은 위 세 파일과 `vite.service-worker.config.ts`다. diff --git a/scripts/generate-service-worker-assets.ts b/scripts/generate-service-worker-assets.ts index 282a3ec0..733fd405 100644 --- a/scripts/generate-service-worker-assets.ts +++ b/scripts/generate-service-worker-assets.ts @@ -11,6 +11,7 @@ import path from "node:path"; import { getBuildConfig } from "../src/contracts/env.ts"; import { + BUILD_ASSET_DIRECTORY, HASHED_STATIC_ASSET_NAME, SERVICE_WORKER_BOUNDS, SERVICE_WORKER_SCRIPT_PATH, @@ -19,7 +20,8 @@ import { /** * §17.2.2 step 4. Scans the completed app `dist` and emits the exact hashed - * asset list the Service Worker will verify at install time. + * asset list under `BUILD_ASSET_DIRECTORY` the Service Worker will verify at + * install time. * * `service-worker.js` itself and `index.html` are excluded (§17.2.2), as are * the runtime config and release manifest, which are network-only (§18.4). @@ -41,7 +43,12 @@ const EXCLUDED_FILES: ReadonlySet = new Set([ "runtime-config.schema.json", ]); -/** Vite emits content-hashed names; only those may be treated as immutable. */ +/** + * Vite emits content-hashed names under its assets directory; only those may + * be treated as immutable. A `public/` file copied to the dist root keeps its + * own name even when it looks hashed (`android-chrome-192x192.png`), and a + * product may change its bytes under that name (1105/06-01). + */ const HASHED_NAME = HASHED_STATIC_ASSET_NAME; /** @@ -59,7 +66,10 @@ export async function collectStaticAssets( for (const relative of files.sort()) { const base = path.basename(relative); - if (EXCLUDED_FILES.has(base) || relative.startsWith(".vite/")) continue; + if (!relative.split(path.sep).join("/").startsWith(BUILD_ASSET_DIRECTORY)) { + continue; + } + if (EXCLUDED_FILES.has(base)) continue; const contentType = CACHEABLE_EXTENSIONS[path.extname(base).toLowerCase()]; if (!contentType || !HASHED_NAME.test(base)) continue; diff --git a/scripts/lib/hosting-probe.ts b/scripts/lib/hosting-probe.ts index dc7bca24..310d2d3e 100644 --- a/scripts/lib/hosting-probe.ts +++ b/scripts/lib/hosting-probe.ts @@ -2,7 +2,10 @@ import { isIP } from "node:net"; import path from "node:path"; import { connect } from "node:tls"; -import type { InstalledServiceWorkerSelection } from "../../src/contracts/service-worker.ts"; +import { + BUILD_ASSET_DIRECTORY, + type InstalledServiceWorkerSelection, +} from "../../src/contracts/service-worker.ts"; import { CACHEABLE_ASSET_CONTENT_TYPES } from "../../src/contracts/service-worker-static-manifest.ts"; import { changedRuntimeConfigBuildFields } from "./runtime-config-switches.ts"; @@ -282,7 +285,7 @@ export async function probeAssetContentTypes( for (const file of distFiles.map((entry) => entry.split(path.sep).join("/")).sort()) { const extension = path.posix.extname(file).toLowerCase(); if ( - file.startsWith("assets/") && + file.startsWith(BUILD_ASSET_DIRECTORY) && acceptedAssetContentTypes(extension).length > 0 && !samples.has(extension) ) { diff --git a/src/adapters/service-worker/service-worker-static-assets.ts b/src/adapters/service-worker/service-worker-static-assets.ts index d96eb4e0..4affcdb0 100644 --- a/src/adapters/service-worker/service-worker-static-assets.ts +++ b/src/adapters/service-worker/service-worker-static-assets.ts @@ -1,4 +1,5 @@ import { + BUILD_ASSET_DIRECTORY, HASHED_STATIC_ASSET_NAME, isOwnedStaticCacheName, SERVICE_WORKER_BOUNDS, @@ -59,12 +60,10 @@ export function classifyFetch(input: ClassificationInput): FetchClassification { } /** - * 06-08. Vite's default `build.assetsDir`, under the app base that is also the - * registration scope. A hashed-looking API or download name elsewhere is not an - * old build chunk and is left to the browser. + * 06-08. `BUILD_ASSET_DIRECTORY` is resolved under the app base that is also + * the registration scope. A hashed-looking API or download name elsewhere is + * not an old build chunk and is left to the browser. */ -const BUILD_ASSET_DIRECTORY = "assets/"; - function isSameOriginHashedAsset(requestUrl: string, scopeUrl: string): boolean { try { const request = new URL(requestUrl); diff --git a/src/contracts/service-worker.ts b/src/contracts/service-worker.ts index b0f1f62a..85d4deeb 100644 --- a/src/contracts/service-worker.ts +++ b/src/contracts/service-worker.ts @@ -115,6 +115,16 @@ export interface StaticAssetManifestV1 { */ export const HASHED_STATIC_ASSET_NAME = /-[A-Za-z0-9_-]{8,}\.[a-z0-9]+$/; +/** + * 1105/06-01. Vite's default `build.assetsDir` (`vite.config.ts` leaves it + * unset), relative to the app base. Vite writes content-hashed files only + * here; `public/` files land at the dist root under their own names, so a + * name there that matches `HASHED_STATIC_ASSET_NAME` is not immutable. The + * precache generator, the worker's previous-release fallback and the hosting + * probe read this one value (0925/06-08: change it with `build.assetsDir`). + */ +export const BUILD_ASSET_DIRECTORY = "assets/" as const; + /** §18.2. `ca-static-v1-`. */ export const STATIC_CACHE_PREFIX = "ca-static-v1-" as const; diff --git a/tests/unit/service-worker-web-push-remediation.test.ts b/tests/unit/service-worker-web-push-remediation.test.ts index dfb9efc9..50b1e949 100644 --- a/tests/unit/service-worker-web-push-remediation.test.ts +++ b/tests/unit/service-worker-web-push-remediation.test.ts @@ -125,6 +125,37 @@ describe("SW-02 the generator and the decoder share one path grammar", () => { } }); + // 1105/06-01. `public/` files are copied to the dist root under their own + // names. A PWA icon such as `android-chrome-192x192.png` matches the hashed + // name pattern, but a product may change its bytes under the same name; a + // CDN that still serves the old bytes then fails every install with + // INTEGRITY_MISMATCH. Only Vite's assets directory holds hashed files. + it("precaches only the assets directory, not public files at the dist root", async () => { + const { collectStaticAssets } = await import( + "../../scripts/generate-service-worker-assets.ts" + ); + const root = await distWith({ + "index.html": "page", + "config.json": "{}", + "release-manifest.json": "{}", + "apple-touch-icon.png": "icon", + "android-chrome-192x192.png": "icon", + "safari-pinned-tab.svg": "icon", + "favicon.svg": "icon", + "robots.txt": "robots", + "icons/maskable-512x512.png": "icon", + "assets/index-AbCdEf12.js": "entry", + "assets/index-AbCdEf12.css": "style", + }); + + const manifest = await collectStaticAssets(root, "build-1", "release-1"); + + expect(manifest.assets.map((asset) => asset.url)).toEqual([ + "/assets/index-AbCdEf12.css", + "/assets/index-AbCdEf12.js", + ]); + }); + // 0929/06-02. dist is served under the router base path; a root URL made // the worker's install request /assets/... and fail under /app/. it("puts every asset URL under the router base path", async () => { From 4d6f25443873764080691327cc6fdda923f3ce20 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:11:49 +0900 Subject: [PATCH 6/8] =?UTF-8?q?fix(hosting):=20=EC=9E=90=EC=82=B0=20MIME?= =?UTF-8?q?=20probe=EA=B0=80=20redirect=EB=A5=BC=20=EA=B1=B0=EC=A0=88?= =?UTF-8?q?=ED=95=98=EA=B3=A0=20live=20=EB=B6=84=EA=B8=B0=EB=A5=BC=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 확장자별 MIME probe(1103/06-03)는 install 조건 일부만 옮겼다. 1. install fetch는 `redirect: "error"`라 redirect가 하나라도 있으면 실패한다. probe는 `redirect: "follow"`로 받고 최종 status와 MIME만 본다. 같은 origin 안 redirect 뒤 200을 주는 호스트가 PASS다(리뷰 06-R1). FE-GATE-019가 PASS인데 워커 install은 매번 실패한다. 2. 워커 없는 빌드에서도 돈다. 주석과 문서는 이유를 워커로만 적는다. 3. live 분기의 호출 줄(`verify-hosting-headers.ts`)을 지키는 테스트가 없다. live 모드는 루프백·http를 거절해 저장소 테스트가 들어갈 수 없다. 호출을 지우는 변이가 44건 통과로 살아남았다(06-R2). 고른 방법: 1. 자산 probe 기본 fetcher를 `redirect: "manual"`로 바꾸고, `response.redirected`이거나 `opaqueredirect`이면 관측 "redirected", 이유 "install fetch가 redirect를 거절"로 FAIL이다. 3xx는 지금처럼 `HTTP 3xx`로 FAIL이다. fetcher가 redirect를 따라가도 `redirected`로 잡으므로 fetcher 방식과 무관하다. 2. 동작은 그대로 두고 의도를 주석과 운영 문서에 적었다. 워커가 없어도 `nosniff` 아래 script·style은 MIME이 틀리면 페이지가 깨지고, 나중에 워커를 켜는 릴리스가 호스팅을 다시 확인하지 않아도 된다. 글꼴·이미지는 페이지에 피해가 없는데 FAIL한다는 것도 적었다. 워커 없는 빌드에서 script·style만 보도록 좁히는 것은 검사를 약하게 하는 정책 결정이라 하지 않았다(결정 대기, 템플릿 소유자). 3. live 분기 전체를 `probeLiveHosting`(release surface + 자산 MIME)으로 빼고 스크립트는 그것만 부른다. 테스트가 fetcher 대역으로 이 함수를 돌려 CSS `text/plain`이 FAIL인지 본다. 자산 probe 호출을 빼면 이 테스트가 실패한다. 스크립트에서 `probeLiveHosting` 호출을 빼면 live 결과가 비어 cache-control 행이 모두 FAIL이라 스스로 드러난다. 버린 대안: 문서에 한계만 적기(리뷰 (b)). 1·3이 그대로다. 위험·한계: 정규 경로 규칙으로 자산을 redirect하는 호스트는 이제 FE-GATE-019에서 FAIL이다. 워커가 없는 제품도 마찬가지다(2의 판단). 실제 호스트로 live 모드를 돌리지는 않았다. 검증: desktop batch에서 확인. - node scripts/run-vitest.ts run tests/unit/hosting-probe.test.ts - RED: "fails an asset the host answers only after a redirect"(옛 probe는 redirect 뒤 200을 PASS), "checks every built asset type besides the release surfaces"(옛 코드에 `probeLiveHosting`이 없음)가 실패한다. - 변이(06-R2 대응): `probeLiveHosting`에서 `probeAssetContentTypes` 결과를 빼면 "checks every built asset type ..."가 실패해야 한다. Refs: 1105/06-02 --- docs/operations/release-cache-rollback.md | 6 ++ scripts/lib/hosting-probe.ts | 47 ++++++++++++++-- scripts/verify-hosting-headers.ts | 8 +-- tests/unit/hosting-probe.test.ts | 67 +++++++++++++++++++++++ 4 files changed, 119 insertions(+), 9 deletions(-) diff --git a/docs/operations/release-cache-rollback.md b/docs/operations/release-cache-rollback.md index 9515ccb0..b6211a37 100644 --- a/docs/operations/release-cache-rollback.md +++ b/docs/operations/release-cache-rollback.md @@ -78,6 +78,12 @@ release has under `assets/` (`.css`, `.js`, `.woff2` and the rest of 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 install fetch also refuses any redirect, so an asset the host answers only +after a redirect fails even when the final answer is a correct 200 (review +1105/06-02). This asset check runs for a build without a worker too: under +`nosniff` a script or style of another type breaks the page anyway, and a later +release that turns the worker on then needs no new hosting check. A font or +image of another type fails it although a worker-free page still loads it. 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 310d2d3e..82e90fd5 100644 --- a/scripts/lib/hosting-probe.ts +++ b/scripts/lib/hosting-probe.ts @@ -275,11 +275,20 @@ export function acceptedAssetContentTypes(extension: string): readonly string[] * 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. + * + * 1105/06-02. The install fetch also refuses any redirect (`redirect: + * "error"`), so an asset answered only after one fails here too, whichever + * redirect mode the fetcher uses. + * + * It runs for a build without a worker as well, on purpose: under `nosniff` + * a script or style of another type breaks the page anyway, and a later + * release that turns the worker on needs no new hosting check. A font or + * image of another type fails this probe although such a page still loads it. */ export async function probeAssetContentTypes( base: URL, distFiles: readonly string[], - fetcher: HostingFetcher = (url) => fetch(url, { redirect: "follow" }), + fetcher: HostingFetcher = (url) => fetch(url, { redirect: "manual" }), ): Promise { const samples = new Map(); for (const file of distFiles.map((entry) => entry.split(path.sep).join("/")).sort()) { @@ -296,11 +305,14 @@ export async function probeAssetContentTypes( for (const [extension, file] of [...samples].sort(([left], [right]) => left.localeCompare(right))) { const expected = acceptedAssetContentTypes(extension); let observed: string; + let redirected = false; try { const response = await fetcher(new URL(file, base)); await response.body?.cancel().catch(() => undefined); - observed = - response.status === 200 + redirected = response.redirected || response.type === "opaqueredirect"; + observed = redirected + ? "redirected" + : response.status === 200 ? (response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? "") : `HTTP ${response.status}`; } catch (error: unknown) { @@ -311,12 +323,39 @@ export async function probeAssetContentTypes( header: "content-type", expected, observed, - passed: expected.includes(observed), + ...(redirected + ? { reason: "the worker's install fetch refuses a redirected asset" } + : {}), + passed: !redirected && expected.includes(observed), }); } return results; } +/** + * 1105/06-02. Everything live mode of `verify:hosting-headers` asks the + * deployed host: the release surfaces (`probeLiveRelease`) and one built asset + * per cacheable type (`probeAssetContentTypes`). Live mode refuses loopback + * and plain http, so tests reach it only through this function and a fetcher + * double; a check dropped from here fails a test. + */ +export async function probeLiveHosting( + base: URL, + paths: Readonly>, + candidate: CandidateRelease, + distFiles: readonly string[], + transport: ProbeTransport = {}, +): Promise<{ responses: ResponseHeaders; results: ProbeResult[] }> { + const probed = await probeLiveRelease(base, paths, candidate, transport); + return { + responses: probed.responses, + results: [ + ...probed.results, + ...(await probeAssetContentTypes(base, distFiles, transport.fetcher)), + ], + }; +} + /** 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 8829b375..f77db9f2 100644 --- a/scripts/verify-hosting-headers.ts +++ b/scripts/verify-hosting-headers.ts @@ -7,8 +7,7 @@ import { checkPublicServiceWorkers, classifyLiveHostingBaseUrl, hostingVerdict, - probeAssetContentTypes, - probeLiveRelease, + probeLiveHosting, releaseIdentity, shipsServiceWorker, type HostingMode, @@ -111,13 +110,12 @@ if (liveTarget?.passed && !slotEmpty) { runtimeConfig: await readFile(path.join(distRoot, "config.json"), "utf8"), indexHtml: await readFile(path.join(distRoot, "index.html"), "utf8"), }; - const probed = await probeLiveRelease(liveTarget.url, paths, candidate, { + // 1103/06-03, 1105/06-02. Release surfaces and every precached asset type. + const probed = await probeLiveHosting(liveTarget.url, paths, candidate, distFiles, { alpnProtocols: strings(recordValue(cachePolicy.transport).alpnProtocols), }); 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 9f109b45..0bae3ed7 100644 --- a/tests/unit/hosting-probe.test.ts +++ b/tests/unit/hosting-probe.test.ts @@ -11,6 +11,7 @@ import { classifyLiveHostingBaseUrl, hostingVerdict, probeAssetContentTypes, + probeLiveHosting, probeLiveRelease, servedEntryScript, } from "../../scripts/lib/hosting-probe.ts"; @@ -371,6 +372,30 @@ describe("hashed asset content types (1103/06-03)", () => { ]); }); + // 1105/06-02. The worker's install fetch uses `redirect: "error"`: a host + // that redirects a hashed asset, even to the same origin, fails every + // install although the final answer is a 200 with the right type. + it("fails an asset the host answers only after a redirect", async () => { + const results = await probeAssetContentTypes( + base, + ["assets/index-A1.js", "assets/index-C3.css"], + async (url) => { + const response = new Response("", { + status: url.pathname.endsWith(".js") ? 200 : 301, + headers: { "content-type": url.pathname.endsWith(".js") ? "text/javascript" : "text/html" }, + }); + Object.defineProperty(response, "url", { value: `${url.href}?moved=1` }); + Object.defineProperty(response, "redirected", { value: url.pathname.endsWith(".js") }); + return response; + }, + ); + expect(results.map((result) => [result.surface, result.observed, result.passed])).toEqual([ + ["hashedAsset.css", "HTTP 301", false], + ["hashedAsset.js", "redirected", false], + ]); + expect(results[1]).toMatchObject({ reason: expect.stringContaining("redirect") }); + }); + 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[] } }; @@ -380,6 +405,48 @@ describe("hashed asset content types (1103/06-03)", () => { }); }); +// 1105/06-02. Live mode of verify-hosting-headers refuses loopback and plain +// http, so no test can run the script against a host. Its whole live branch is +// probeLiveHosting; dropping the asset type probe from it fails here. +describe("live hosting probe (1105/06-02)", () => { + const base = new URL("https://frontend.example.test/"); + const INDEX = ''; + const IDENTITY = { buildId: "gitea-42-1", releaseId: "r-42" }; + const PATHS = { index: "/", releaseManifest: "/release-manifest.json" }; + const CANDIDATE = { ...IDENTITY, runtimeConfig: "{}", indexHtml: INDEX }; + const DIST_FILES = ["index.html", "release-manifest.json", "assets/index-A1.js", "assets/index-C3.css"]; + + it("checks every built asset type besides the release surfaces", async () => { + const served: Record = { + "/": [INDEX, "text/html"], + "/release-manifest.json": [JSON.stringify(IDENTITY), "application/json"], + "/assets/index-A1.js": ["", "text/javascript"], + "/assets/index-C3.css": ["", "text/plain"], + }; + const { results } = await probeLiveHosting(base, PATHS, CANDIDATE, DIST_FILES, { + fetcher: async (url) => { + const entry = served[url.pathname]; + const response = new Response(entry?.[0] ?? "Not Found", { + status: entry ? 200 : 404, + headers: entry ? { "content-type": entry[1] } : {}, + }); + Object.defineProperty(response, "url", { value: url.href }); + return response; + }, + }); + + expect( + results.filter((result) => !result.passed).map((result) => `${result.surface} ${result.header}`), + ).toEqual(["hashedAsset.css content-type"]); + expect(results).toContainEqual( + expect.objectContaining({ surface: "hashedAsset.js", header: "content-type", passed: true }), + ); + expect(results).toContainEqual( + expect.objectContaining({ surface: "releaseManifest", header: "build-id", passed: true }), + ); + }); +}); + // 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 aaa782bab4591cba820b4a277689ba550a23ea35 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:13:53 +0900 Subject: [PATCH 7/8] =?UTF-8?q?test(service-worker):=20=EC=98=9B=20?= =?UTF-8?q?=ED=83=AD=EC=9D=B4=20=EC=A7=80=EC=9B=8C=EC=A7=84=20route?= =?UTF-8?q?=EB=A5=BC=20reload=20=EC=97=86=EC=9D=B4=20=EC=97=AC=EB=8A=94?= =?UTF-8?q?=EC=A7=80=20=EB=B3=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: update spec은 옛 탭 회복을 페이지의 `fetch(removedChunk)`로만 본다. 바이트가 오는지는 알지만, B가 제어하는 A 탭에서 지워진 route를 여는 실제 경로는 아무 spec도 지나지 않는다. 워커 제어 아래 preload는 11-09 허용(`preloadunverifiable:service-worker:`) 때문에 fixture가 하나도 판정하지 못한다(리뷰 06-R9: 158줄 모두 ALLOWED). 워커가 직전 캐시로 답하지 않게 바꾼 변이(06-R10)에서 화면 단언은 통과했다. chunk 복구가 페이지를 B로 reload해 같은 not-found 화면을 그렸기 때문이다. 고른 방법: 리뷰 06-03의 (a). update spec에 test 하나를 더한다. B가 제어하는 A 탭에서 client navigation(pushState + popstate)으로 일치하지 않는 경로를 연다. `CHANGED_ROUTE_SOURCE`가 not-found 페이지라 그 경로가 지워진 chunk를 import한다. 단언: - not-found heading이 보인다. - 같은 문서다. navigation 전에 심은 전역 표시가 남아 있고 entry script가 그대로다(reload 없음). - 그 문서가 chunk를 요청했다(Resource Timing 항목, 단언이 빈 경로를 보지 않게). - navigation 뒤 서버 요청에 그 chunk가 없다(워커가 답했다). - strict fixture가 허용 밖 실패 줄을 보지 않는다(기존 teardown 검사). 지워진 chunk를 찾는 코드는 기존 test와 같이 쓰도록 `removedRouteChunk`로 뺐다. Firefox는 같은 파일의 기존 격리(quarantine, 2027-03-31)를 그대로 따른다. Playwright Firefox는 워커가 페이지를 제어하지 못한다(06-R11 확인). 버린 대안: fixture가 워커 쪽 응답을 추적. Playwright 워커 network 이벤트는 Chromium 전용이다. 위험·한계: 테스트만 더했다. 지금 코드는 맞으므로 RED(부모 코드)에서도 통과한다. 결함은 변이로 보인다. 엔진마다 약 7초가 늘어난다(06-R9 기준). WebKit에서는 chunk가 modulepreload link로 요청되어 워커 경로가 Chromium과 같은지 확인하지 않았다. 허용 패턴 자체는 그대로다. 검증: desktop batch에서 확인. - corepack pnpm exec playwright test tests/e2e/service-worker-update.spec.ts --project=chromium --project=webkit - 변이(06-R10과 같음, `service-worker-lifecycle.ts`의 PREVIOUS_RELEASE_FALLBACK 분기가 `return null`): 새 test가 chromium에서 sameDocument false(또는 fixture 실패 줄)로 실패해야 한다. Refs: 1105/06-03 --- tests/e2e/service-worker-update.spec.ts | 82 +++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 6 deletions(-) diff --git a/tests/e2e/service-worker-update.spec.ts b/tests/e2e/service-worker-update.spec.ts index 585df28c..3562825f 100644 --- a/tests/e2e/service-worker-update.spec.ts +++ b/tests/e2e/service-worker-update.spec.ts @@ -237,12 +237,10 @@ test("announces update-waiting and reload-required through the host when build B } }); -test("serves A's removed chunk from the previous cache once B controls the page", async ({ - page, - browserName, -}) => { - test.skip(browserName === "firefox", NO_CONTROLLED_PAGES); - const { dist } = requireBuilds(); +/** The route chunk of A that B no longer has: `CHANGED_ROUTE_SOURCE`'s. */ +async function removedRouteChunk( + dist: ServiceWorkerBuilds["dist"], +): Promise { const routeChunks = Object.values( ( JSON.parse( @@ -255,6 +253,16 @@ test("serves A's removed chunk from the previous cache once B controls the page" .map((chunk) => `/${chunk}`) .find((chunk) => !inB.has(chunk)); if (!removedChunk) throw new Error("Build B kept every route chunk of A."); + return removedChunk; +} + +test("serves A's removed chunk from the previous cache once B controls the page", async ({ + page, + browserName, +}) => { + test.skip(browserName === "firefox", NO_CONTROLLED_PAGES); + const { dist } = requireBuilds(); + const removedChunk = await removedRouteChunk(dist); const server = await startBuildServer(dist); try { @@ -279,6 +287,68 @@ test("serves A's removed chunk from the previous cache once B controls the page" } }); +type SameDocumentProbe = typeof globalThis & { __swE2eSameDocument?: boolean }; + +// 1105/06-03. The old tab's real path, not only `fetch()`: A's page, now +// controlled by B's worker, opens the route whose chunk B removed +// (`CHANGED_ROUTE_SOURCE` is the not-found page, so any unmatched path +// imports it). Under the worker the preload fixture cannot judge preloads +// (the 11-09 allowance above), so this test asserts the outcome: the route +// renders in the same document, the chunk never reaches the server, and the +// strict fixture sees no failure outside the allowance. A worker that cannot +// answer the chunk makes the app's chunk recovery reload into B, which also +// renders the not-found page; only the same-document check tells them apart +// (review 06-R10). +test("opens A's removed route in the old tab without a reload once B controls it", async ({ + page, + browserName, +}) => { + test.skip(browserName === "firefox", NO_CONTROLLED_PAGES); + const { dist } = requireBuilds(); + const removedChunk = await removedRouteChunk(dist); + + const server = await startBuildServer(dist); + try { + const { controlled } = await updateFromAToB(page, server); + expect(controlled).toBe(true); + const entryScript = () => + page.evaluate( + () => + document.querySelector('script[type="module"][src]') + ?.src ?? null, + ); + const entryBefore = await entryScript(); + await page.evaluate(() => { + (globalThis as SameDocumentProbe).__swE2eSameDocument = true; + }); + const servedBefore = server.served.length; + + // A client-side navigation, as a link inside the app makes. + await page.evaluate(() => { + history.pushState({}, "", "/sw-e2e-removed-route"); + dispatchEvent(new PopStateEvent("popstate")); + }); + + await expect( + page.getByRole("heading", { name: /페이지를 찾을 수 없습니다|Page not found/u }), + ).toBeVisible({ timeout: 30_000 }); + const after = await page.evaluate((chunk) => ({ + sameDocument: + (globalThis as SameDocumentProbe).__swE2eSameDocument === true, + chunkRequested: + performance.getEntriesByName(new URL(chunk, location.origin).href) + .length > 0, + }), removedChunk); + expect(after).toEqual({ sameDocument: true, chunkRequested: true }); + expect(await entryScript()).toBe(entryBefore); + expect( + server.served.slice(servedBefore).map((response) => response.path), + ).not.toContain(removedChunk); + } finally { + await server.close(); + } +}); + // `beforeAll` already ran `scripts/build-frontend.ts` unmodified (default // `bundle` config loader); this pins that both builds emitted the worker. test("builds the ACTIVE worker with the repo's unmodified build script", async () => { From fdc1db94712416bd1cd97e9c6f642902783aaf25 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:19:06 +0900 Subject: [PATCH 8/8] =?UTF-8?q?feat(bootstrap):=20=EC=A0=9C=ED=92=88?= =?UTF-8?q?=EC=9D=B4=20SW=20blockers=C2=B7observe=EB=A5=BC=20composeProduc?= =?UTF-8?q?t=EB=A1=9C=20=EB=84=98=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: SW를 켜는 선택은 제품 소유 `product-capabilities.ts`로 옮겼다 (1103/09-05 일부). 그런데 저장하지 않은 편집이 있는 탭의 활성화 거절 (`blockers`)과 page controller 관측(`observe`)은 템플릿 소유 `src/bootstrap/create-runtime-composition.ts`를 고쳐야 이어진다(매뉴얼 03 "SW 켜기", 레시피 "Service Worker를 켤 때 확인할 것" 2·3). 그 파일을 고친 제품은 템플릿 동기화마다 충돌한다. 고른 방법: 기존 제품 확장 지점에 선택 칸 하나를 더한다. `ProductComposition.serviceWorker?: { blockers?, observe? }` (`product-composition-contract.ts`). `createRuntimeAdapters`가 `composeProduct` 결과의 이 칸을 bundle에 `productServiceWorker`로 싣고, 템플릿 조립 (`create-runtime-composition.ts`)이 telemetry와 같은 방식으로 받아 `createOptionalRuntimeHost`에 넘긴다. blockers 목록은 한 번 복사한다. 던지는 blocker는 page controller가 이미 막는 쪽으로 본다. page controller는 `observe`의 throw를 잡지 않으므로, 제품 sink가 던져도 worker 흐름이 바뀌지 않게 조립에서 감쌌다. 매뉴얼 03과 레시피 2·3을 새 자리로 고쳤다. 버린 대안: - `product-composition.ts`에 새 export(`composeProductServiceWorker`)를 요구. 이미 그 파일을 가진 다운스트림이 동기화하면 import가 깨진다. 선택 칸은 기존 `composeProduct`를 그대로 둔다. - `composeProduct`를 조립에서 한 번 더 부르기. capability와 credential이 두 벌 생긴다. 위험·한계: 일부만 닫는다. 남은 것: - 활성화 화면(`onUpdateWaiting`·`requestActivation()`)과 reload 안내를 이을 제품 소유 자리가 없다(레시피 4·5, 0925/06-05). - realtime·Web Worker·오프라인 명령은 여전히 조립이 거절한다 (`optional-runtime-host.ts`, 그 런타임이 템플릿에 없다). `product-composition.ts`(제품 소유, 출하 상태 빈 값)는 고치지 않았다. 칸이 선택이라 기존 제품 파일과 1105/09-01의 타입 검사 탐침 내용이 그대로 통과한다. 검증: desktop batch에서 확인. - node scripts/run-vitest.ts run tests/component/runtime-composition-service-worker-product-wiring.test.ts tests/component/runtime-composition-service-worker-telemetry.test.ts - RED: "passes the product's blockers and observer to the page controller"가 옛 조립에서 observe 기록이 비어 실패한다. - 함께: check:types, lint, check:architecture, verify:documentation Refs: 1103/09-05 --- docs/architecture/optional-adapter-recipes.md | 22 ++- docs/manual/03-outside-feature-folder.md | 17 +- src/bootstrap/create-runtime-composition.ts | 35 ++++ src/bootstrap/product-composition-contract.ts | 20 +++ src/bootstrap/runtime-adapters.ts | 3 + ...tion-service-worker-product-wiring.test.ts | 162 ++++++++++++++++++ 6 files changed, 251 insertions(+), 8 deletions(-) create mode 100644 tests/component/runtime-composition-service-worker-product-wiring.test.ts diff --git a/docs/architecture/optional-adapter-recipes.md b/docs/architecture/optional-adapter-recipes.md index 16638e60..69a0483b 100644 --- a/docs/architecture/optional-adapter-recipes.md +++ b/docs/architecture/optional-adapter-recipes.md @@ -124,8 +124,9 @@ type은 facade 밖으로 노출하지 않는다. SSOT다. 문서와 catalog가 다르면 gate가 검사하는 catalog를 우선 고치고 이 표도 같이 갱신한다. -Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7과 2의 시작 실패 -이벤트만 갖고 있다. +Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7, 2의 시작 실패 +이벤트, 2의 `observe`와 3을 제품 소유 파일에서 잇는 자리를 갖고 있다. 4·5를 +잇는 제품 소유 자리는 아직 없다. 1. 제품 소유 파일 `src/features/product-capabilities.ts`의 `SERVICE_WORKER`를 `ACTIVE`로 바꾼다. `scripts/build-frontend.ts`가 worker 빌드를 추가로 돈다. @@ -139,11 +140,18 @@ Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7과 2의 시 `tests/component/runtime-composition-service-worker-telemetry.test.ts`가 확인한다. 템플릿이 연결하지 않은 것은 셋이다. 업데이트 설치 실패 (`watchForUpdates`, `src/adapters/service-worker/service-worker-page-controller.ts`)는 - 이벤트를 남기지 않는다. page controller의 `observe`는 composition이 넘기지 - 않는다. `OptionalRuntimeHost.health()`는 `src` 안에서 읽는 코드가 없다. - 필요하면 다운스트림이 `createRuntimeComposition`에서 연결한다. -3. blockers: 저장하지 않은 편집이 있는 탭이 활성화를 거절하게 - `createOptionalRuntimeHost`에 `blockers`를 넘긴다. 템플릿은 넘기지 않는다. + 이벤트를 남기지 않는다. page controller의 `observe`는 제품이 + `src/bootstrap/product-composition.ts`의 `composeProduct`에서 + `serviceWorker.observe`로 돌려준다(1103/09-05). 템플릿 조립이 그것을 optional + host에 넘기고, 던지면 무시한다. `OptionalRuntimeHost.health()`는 `src` 안에서 + 읽는 코드가 없다. +3. blockers: 저장하지 않은 편집이 있는 탭이 활성화를 거절하게 `composeProduct`가 + `serviceWorker.blockers`를 돌려준다. 하나가 true를 돌려주거나 던지면 + `requestActivation()`이 `BLOCKED_DIRTY_CLIENT`로 거절한다. 템플릿 파일 + `src/bootstrap/create-runtime-composition.ts`는 고치지 않는다. 실제 조립에서 두 + 값이 page controller에 닿는 것은 + `tests/component/runtime-composition-service-worker-product-wiring.test.ts`가 + 확인한다. 4. 활성화 UI: `ServiceWorkerRuntimeHost.onUpdateWaiting`을 구독하고, 사용자가 동의하면 `requestActivation()`을 부른다(`src/contracts/service-worker.ts`). 5. reload 처리: `onReloadRequired`를 구독해 reload를 안내한다. diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index ca3ce7c8..b1685824 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -151,7 +151,22 @@ src/features/product-capabilities.ts (SERVICE_WORKER = ACTIVE) 4. 지우려면 한 번에 `null`로 가지 않는다. `REMOVE_REGISTRATION` → `PURGE_OWNED_RESOURCES` → `null` 순서로 릴리스한다. 이미 설치된 브라우저의 worker를 먼저 내려야 한다. - 고치지 않는다: `src/features/installed-runtime-capabilities.ts`(템플릿 소유, D절). -- 템플릿이 아직 연결하지 않은 것: 저장하지 않은 편집이 있는 탭의 활성화 거절(`blockers`), page controller의 `observe`, 활성화 화면. 지금은 `src/bootstrap/create-runtime-composition.ts`(템플릿 소유)를 고쳐야 연결된다. 확인할 것 목록은 `docs/architecture/optional-adapter-recipes.md`의 "Service Worker를 켤 때 확인할 것"에 있다. +- 저장하지 않은 편집이 있는 탭의 활성화 거절(`blockers`)과 page controller의 `observe`는 제품 소유 `src/bootstrap/product-composition.ts`에서 잇는다. `composeProduct`가 `serviceWorker`를 돌려주면 템플릿 조립이 그대로 넘긴다(1103/09-05). `observe`가 던져도 worker 흐름은 바뀌지 않는다. + + ```ts + export function composeProduct(context: ProductCompositionContext) { + return { + capabilities: {}, + credentialProviders: {}, + serviceWorker: { + blockers: [() => hasUnsavedEdits()], + observe: (observation) => reportServiceWorker(observation), + }, + } satisfies ProductComposition; + } + ``` + +- 템플릿이 아직 연결하지 않은 것: 활성화 화면(`onUpdateWaiting`·`requestActivation()`). 확인할 것 목록은 `docs/architecture/optional-adapter-recipes.md`의 "Service Worker를 켤 때 확인할 것"에 있다. - realtime·Web Worker·오프라인 명령을 고르면 조립이 `Selected optional capabilities have no runtime to start them`로 거절한다. 템플릿 조립에 아직 그 런타임이 없다. --- diff --git a/src/bootstrap/create-runtime-composition.ts b/src/bootstrap/create-runtime-composition.ts index 9240c6b3..a6eea582 100644 --- a/src/bootstrap/create-runtime-composition.ts +++ b/src/bootstrap/create-runtime-composition.ts @@ -7,7 +7,9 @@ import { loadRuntimeConfig } from "./load-runtime-config.ts"; import { createOptionalRuntimeHost, type OptionalRuntimeHost, + type OptionalRuntimeHostInput, } from "./optional-runtime-host.ts"; +import type { ProductServiceWorkerWiring } from "./product-composition-contract.ts"; import { createRuntimeAdapters } from "./runtime-adapters.ts"; export type RuntimeCompositionDependencies = Readonly<{ @@ -27,6 +29,9 @@ export async function createRuntimeComposition( // 06-05. The optional host reports a Service Worker that did not start // through the same telemetry port as the application. let telemetry: TelemetryPort | undefined; + // 1103/09-05. `composeProduct` (product-owned) supplies the worker's + // blockers and observer; this template file only passes them on. + let productServiceWorker: ProductServiceWorkerWiring | null | undefined; const root = await createCompositionRoot({ loadConfig: () => loadRuntimeConfig({ fetcher: dependencies.fetcher }), loadRelease: (runtime) => @@ -39,6 +44,7 @@ export async function createRuntimeComposition( host: dependencies.host, }); telemetry = adapters.outputPorts.telemetry; + productServiceWorker = adapters.productServiceWorker; return adapters; }, }); @@ -52,6 +58,7 @@ export async function createRuntimeComposition( routerBasePath: root.config.build.routerBasePath, buildId: root.release.buildId, ...(telemetry ? { telemetry } : {}), + ...serviceWorkerWiring(productServiceWorker), ...(dependencies.host ? { host: dependencies.host as Parameters< @@ -78,3 +85,31 @@ export async function createRuntimeComposition( export type RuntimeComposition = Awaited< ReturnType >; + +/** + * 1103/09-05. The product's wiring in the optional host's terms. The blocker + * list is copied once; the page controller already treats a throwing blocker + * as blocking. A throwing observer is product code and must not break the + * worker flow, so its throw is dropped here. + */ +function serviceWorkerWiring( + wiring: ProductServiceWorkerWiring | null | undefined, +): Pick { + if (!wiring) return {}; + return { + ...(wiring.blockers + ? { blockers: Object.freeze([...wiring.blockers]) } + : {}), + ...(wiring.observe + ? { + observe: (observation: Readonly<{ event: string; outcome: string }>) => { + try { + wiring.observe?.(observation); + } catch { + // A failing product sink never changes the worker's outcome. + } + }, + } + : {}), + }; +} diff --git a/src/bootstrap/product-composition-contract.ts b/src/bootstrap/product-composition-contract.ts index 97705adf..4e253249 100644 --- a/src/bootstrap/product-composition-contract.ts +++ b/src/bootstrap/product-composition-contract.ts @@ -102,6 +102,24 @@ export type ProductScopeParticipant = Readonly<{ close(): void | Promise; }>; +/** + * 1103/09-05. The page side of the Service Worker the product selected in + * `src/features/product-capabilities.ts`. Unused when no worker is selected. + */ +export type ProductServiceWorkerWiring = Readonly<{ + /** + * §17.10. Asked each time this tab is about to let a waiting worker take + * over (`requestActivation()`). One that returns true, or throws, refuses + * with `BLOCKED_DIRTY_CLIENT`: say, while a form has unsaved edits. + */ + blockers?: readonly (() => boolean)[]; + /** + * The page controller's diagnostics (`register`, `activation`, `message`, + * `client_drain`, ...), each with its outcome. A throw is ignored. + */ + observe?(observation: Readonly<{ event: string; outcome: string }>): void; +}>; + export type ProductComposition = Readonly<{ capabilities: Readonly< Partial> @@ -125,4 +143,6 @@ export type ProductComposition = Readonly<{ * does. */ scopeParticipants?: readonly ProductScopeParticipant[]; + /** 1103/09-05. Optional. Read once, when the runtime is composed. */ + serviceWorker?: ProductServiceWorkerWiring; }>; diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 995c2e30..defcc2ba 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -733,5 +733,8 @@ export async function createRuntimeAdapters( }, }), featureLoaders, + // 1103/09-05. The optional host is built after this bundle, by + // create-runtime-composition.ts, and reads the product's wiring here. + productServiceWorker: productContract.serviceWorker ?? null, }); } diff --git a/tests/component/runtime-composition-service-worker-product-wiring.test.ts b/tests/component/runtime-composition-service-worker-product-wiring.test.ts new file mode 100644 index 00000000..440de1f3 --- /dev/null +++ b/tests/component/runtime-composition-service-worker-product-wiring.test.ts @@ -0,0 +1,162 @@ +// @vitest-environment jsdom + +import { describe, expect, it, vi } from "vitest"; + +import { createRuntimeComposition } from "../../src/bootstrap/create-runtime-composition.ts"; +import type { ProductComposition } from "../../src/bootstrap/product-composition-contract.ts"; + +/** + * 1103/09-05. A product that turns the worker on wires its activation blockers + * (a tab with unsaved edits) and the page controller's observer in its own + * `product-composition.ts`, not in the template's composition file. This runs + * the real composition with an ACTIVE selection, a product composition that + * returns `serviceWorker`, and a registration whose update is waiting. + */ + +const product = vi.hoisted(() => ({ + observed: [] as Array>, + dirty: true, +})); + +vi.mock("../../src/features/installed-runtime-capabilities.ts", async (importOriginal) => { + const original = + await importOriginal(); + return { + INSTALLED_RUNTIME_CAPABILITIES: Object.freeze({ + ...original.INSTALLED_RUNTIME_CAPABILITIES, + serviceWorker: Object.freeze({ + mode: "ACTIVE", + scriptPath: "service-worker.js", + handlers: Object.freeze(["PWA_STATIC_ASSETS"]), + }), + }), + }; +}); + +/** The product's `src/bootstrap/product-composition.ts`. */ +vi.mock("../../src/bootstrap/product-composition.ts", () => ({ + composeProductSessionOwner: () => null, + composeProduct: (): ProductComposition => ({ + capabilities: {}, + credentialProviders: {}, + serviceWorker: { + blockers: [() => product.dirty], + observe(observation) { + product.observed.push(observation); + // The composition drops a throwing product sink. + throw new Error("product sink failure"); + }, + }, + }), +})); + +const origin = "http://localhost"; + +const runtimeConfig = { + APP_ENV: "local", + API_BASE_URL: "http://localhost:8080", + REQUEST_TIMEOUT_MS: 10_000, + MAX_RETRY_ATTEMPTS: 2, + TELEMETRY_ENABLED: false, + AUTH_MODE: "demo", + CONFIG_SCHEMA_VERSION: "1", + API_CONTRACT_VERSION: "1", + RELEASE_MANIFEST_URL: "/release-manifest.json", + BUILD_ID: "local-build", + RELEASE_ID: "local-release", +}; + +const releaseManifest = { + schemaVersion: 1, + appVersion: "0.2.0", + buildId: "local-build", + commitSha: "local", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "test-hash", + releaseId: "local-release", + builtAt: "2026-07-26T00:00:00.000Z", + routeChunks: { + "route-home": "assets/home.js", + "route-examples-ui": "assets/ui.js", + "route-examples-states": "assets/states.js", + "route-examples-auth": "assets/auth.js", + "route-not-found": "assets/not-found.js", + }, +}; + +async function fetcher(input: RequestInfo | URL): Promise { + const url = + typeof input === "string" + ? input + : input instanceof URL + ? input.href + : input.url; + return Response.json( + url.includes("release-manifest") ? releaseManifest : runtimeConfig, + ); +} + +/** This page's worker is active and the next build's is waiting. */ +function updateWaitingContainer(): ServiceWorkerContainer { + const worker = (scriptURL: string, state: string) => ({ + scriptURL, + state, + postMessage: vi.fn(), + addEventListener() {}, + removeEventListener() {}, + }); + const register = vi.fn( + async (scriptURL: string | URL, options?: RegistrationOptions) => { + const script = new URL(scriptURL, origin).href; + return { + scope: new URL(options?.scope ?? "/", origin).href, + installing: null, + waiting: worker(script, "installed"), + active: worker(script, "activated"), + addEventListener() {}, + removeEventListener() {}, + update: vi.fn(async () => {}), + } as unknown as ServiceWorkerRegistration; + }, + ); + return { + controller: null, + register, + getRegistration: vi.fn(async () => undefined), + getRegistrations: vi.fn(async () => []), + addEventListener() {}, + removeEventListener() {}, + } as unknown as ServiceWorkerContainer; +} + +describe("1103/09-05 the product wires the worker in product-composition.ts", () => { + it("passes the product's blockers and observer to the page controller", async () => { + const container = updateWaitingContainer(); + const composition = await createRuntimeComposition({ + fetcher, + host: { + location: { origin }, + navigator: { serviceWorker: container }, + }, + }); + + try { + await composition.optional.startAfterMount(); + expect(container.register).toHaveBeenCalledTimes(1); + expect(product.observed).toEqual([ + { event: "register", outcome: "UPDATE_WAITING" }, + ]); + + await expect( + composition.optional.serviceWorker!.requestActivation(), + ).resolves.toEqual({ kind: "BLOCKED_DIRTY_CLIENT" }); + expect(product.observed.at(-1)).toEqual({ + event: "activation", + outcome: "BLOCKED_DIRTY_CLIENT", + }); + } finally { + await composition.dispose(); + } + }); +});