From fdc1db94712416bd1cd97e9c6f642902783aaf25 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:19:06 +0900 Subject: [PATCH] =?UTF-8?q?feat(bootstrap):=20=EC=A0=9C=ED=92=88=EC=9D=B4?= =?UTF-8?q?=20SW=20blockers=C2=B7observe=EB=A5=BC=20composeProduct?= =?UTF-8?q?=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(); + } + }); +});