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