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/optional-adapter-recipes.md b/docs/architecture/optional-adapter-recipes.md index 3027cdf7..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를 안내한다. @@ -158,7 +166,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/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index a0d3a2e7..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으로 @@ -1666,8 +1668,11 @@ 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` 안에서 실행기에 -넘긴다. 기능의 기본 GET descriptor(`create:feature`는 `retryBudget: 2`)는 생성 때 +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 status URL은 poll하지 않는다. TanStack Query retry도 `false`여야 한다. @@ -1958,8 +1963,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/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index 87c18924..01b8847f 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -153,7 +153,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/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/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..82e90fd5 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"; @@ -272,17 +275,26 @@ 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()) { const extension = path.posix.extname(file).toLowerCase(); if ( - file.startsWith("assets/") && + file.startsWith(BUILD_ASSET_DIRECTORY) && acceptedAssetContentTypes(extension).length > 0 && !samples.has(extension) ) { @@ -293,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) { @@ -308,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/src/adapters/realtime/polling/bounded-poll-coordinator.ts b/src/adapters/realtime/polling/bounded-poll-coordinator.ts index c92908d3..0e03c1fb 100644 --- a/src/adapters/realtime/polling/bounded-poll-coordinator.ts +++ b/src/adapters/realtime/polling/bounded-poll-coordinator.ts @@ -98,11 +98,25 @@ 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; + /** + * 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; + /** + * 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. @@ -132,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; @@ -300,12 +315,13 @@ export function createBoundedPollCoordinator( } attempts += 1; - let result: BoundedPollAttemptResult; + let result: BoundedPollAttemptResult | null; const attemptOutcome = await awaitWithinLease( () => trackWork( dependencies.execute({ operationId: policy.operationId, + operation, attempt: attempts, maxResponseBytes, signal: controller.signal, @@ -320,12 +336,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 +392,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/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/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/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 574b3776..5f570a7f 100644 --- a/src/bootstrap/product-composition-contract.ts +++ b/src/bootstrap/product-composition-contract.ts @@ -110,6 +110,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> @@ -133,4 +151,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 ac560b84..9a0bab6a 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -740,5 +740,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/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/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(); + } + }); +}); 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 () => { 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)", () => { diff --git a/tests/unit/realtime/bounded-poll-coordinator.test.ts b/tests/unit/realtime/bounded-poll-coordinator.test.ts index c2c9cfd3..db27657f 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 }, }); }); @@ -1103,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 }, ); @@ -1160,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); + }); }); 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) => { 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 () => {