fix(r9): 업로드 401을 주인에게 보내고 짝 계약 pin과 SW 제품 칸을 고친다 #53

Merged
donghyeon.kang merged 3 commits from donghyeon.kang/r9-credential-contract-sw AGit into main 2026-11-13 18:03:45 +00:00
35 changed files with 1276 additions and 271 deletions
+1 -1
View File
@@ -300,7 +300,7 @@
},
{
"name": "feature-and-app-roots-do-not-reach-adapters",
"comment": "12-03. The graph checks one edge at a time, so a module that presentation may import must not re-export a concrete adapter: presentation would then reach it with every direct rule passing. That covers every file under src/features outside a feature's adapters/ folder (the root files, and any folder that is not a layer, such as support/: 0929/12-03), src/contexts and src/apps. Inside a feature, only its adapters/ folder reaches src/adapters; the product composes adapters in bootstrap. Exception: src/features/feature-adapter-contribution.ts imports the InstalledHttpOperationExecutor type that bootstrap hands to feature adapters (type only). Owner: frontend-platform. Revisit when that type moves to an application port.",
"comment": "12-03. The graph checks one edge at a time, so a module that presentation may import must not re-export a concrete adapter: presentation would then reach it with every direct rule passing. That covers every file under src/features outside a feature's adapters/ folder (the root files, and any folder that is not a layer, such as support/: 0929/12-03), src/contexts and src/apps. Inside a feature, only its adapters/ folder reaches src/adapters; the product composes adapters in bootstrap. Exception: src/features/feature-adapter-contribution.ts imports the adapter types of the capabilities it declares, InstalledHttpOperationExecutor and the opt-in FileserverUploadClientDependencies (type only, 1112/09-01). Owner: frontend-platform. Revisit when that type moves to an application port.",
"severity": "error",
"from": {
"path": "^src/(features/|contexts/|apps/)",
+36 -7
View File
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"backend": {
"repository": "clean-architecture-backend-template",
"commit": "45d2a478b800586f1d84151723629a560265d58e",
"commit": "d32b4b53de734aca7d76dc08acf6e97bea899672",
"document": "docs/web/http-contract.md",
"sectionsCompared": ["1", "2", "4"],
"scaffoldSources": [
@@ -12,12 +12,12 @@
"copiedTo": { "file": "scripts/create-feature.ts", "symbol": "backendPathSegment" }
},
{
"path": "scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__.java.tmpl",
"path": "scripts/feature-scaffold/templates/src/domain/core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__.java.tmpl",
"fact": "NAME_MAX_LENGTH 100",
"copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "BACKEND_NAME_MAX_LENGTH" }
},
{
"path": "scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__ErrorCode.java.tmpl",
"path": "scripts/feature-scaffold/templates/src/application/core/src/main/java/dev/caskeleton/application/__feature__/__Feature__ErrorCode.java.tmpl",
"fact": "오류 코드 <FEATURE>_INVALID와 <FEATURE>_NOT_FOUND",
"copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "invalidCode" }
},
@@ -32,22 +32,51 @@
"copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "renderWriteDescriptors" }
},
{
"path": "scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Create__Feature__UseCase.java.tmpl",
"path": "scripts/feature-scaffold/templates/src/application/core/src/main/java/dev/caskeleton/application/__feature__/Create__Feature__UseCase.java.tmpl",
"fact": "권한, 이름 검사, 쓰기 순서다. 거절은 쓰기 전에 일어난다",
"copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "refusedBeforeWrite" }
}
],
"codeSources": [
{
"path": "src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java",
"fact": "작업이 파일을 게시하기 전에 내는 5xx: PARTIAL_WRITE, ATOMIC_PUBLISH_UNSUPPORTED, STORAGE_UNAVAILABLE, SERVER_BUSY, STORAGE_FULL",
"copiedTo": { "file": "src/adapters/http/fileserver-upload.ts", "symbol": "NOT_APPLIED_5XX_CODES" },
"codes": ["PARTIAL_WRITE", "ATOMIC_PUBLISH_UNSUPPORTED", "STORAGE_UNAVAILABLE", "SERVER_BUSY", "STORAGE_FULL"]
},
{
"path": "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutor.java",
"fact": "전송 pool 포화는 작업 전 503 SERVER_BUSY, 대기 시간 초과는 작업 단계와 상관없는 504 TRANSFER_TIMEOUT",
"copiedTo": { "file": "src/adapters/http/fileserver-upload.ts", "symbol": "NOT_APPLIED_5XX_CODES" }
},
{
"path": "src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionController.java",
"fact": "instance 전송 permit 포화는 use case 시작 때의 503 SERVER_BUSY",
"copiedTo": { "file": "src/adapters/http/fileserver-upload.ts", "symbol": "NOT_APPLIED_5XX_CODES" }
},
{
"path": "src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadFileApplicationUseCase.java",
"fact": "모호하지 않은 실패는 업로드를 취소한다. 4xx는 READY 파일을 남기지 않는다",
"copiedTo": { "file": "src/adapters/http/fileserver-upload.ts", "symbol": "fileserverFailureEffect" }
}
]
},
"frontend": {
"contractDocument": "docs/architecture/backend-api-and-server-state-contract.md",
"contractSections": ["4.1", "6", "6.1"],
"readers": ["src/adapters/http/backend-envelope.ts"]
"readers": ["src/adapters/http/backend-envelope.ts", "src/adapters/http/fileserver-upload.ts"]
},
"tables": {
"idempotencyAnswers": "config/contracts/backend-idempotency-answers.json",
"backendExcerpt": "config/contracts/backend-http-contract-excerpt.json"
},
"notCopied": [],
"notCopied": [
{
"section": "4",
"code": "OPERATION_NOT_FOUND",
"reason": "durable operation 조회(`DurableOperationController`)의 404다. 쓰기의 적용 여부 답이 아니고, 프론트는 그 조회를 부르지 않는다"
}
],
"owner": "frontend-platform",
"comparedOn": "2026-11-05"
"comparedOn": "2026-11-13"
}
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"source": {
"repository": "clean-architecture-backend-template",
"commit": "45d2a478b800586f1d84151723629a560265d58e",
"commit": "d32b4b53de734aca7d76dc08acf6e97bea899672",
"document": "docs/web/http-contract.md"
},
"sections": {
@@ -27,10 +27,11 @@
[
"| 코드 | status | category | `retryable` | `Retry-After` | 언제 |",
"| --- | --- | --- | --- | --- | --- |",
"| `REQUEST_TIMEOUT` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 없음 | 비동기 요청(`Callable`·`DeferredResult`·스트리밍)이 시간 안에 끝나지 않았다. GraphQL도 같은 이름을 쓰지만 그쪽 `category`는 GraphQL 전용 어휘 `TIMEOUT`이다(`src/adapter/inbound/graphql/README.md`) |",
"| `REQUEST_TIMEOUT` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 없음 | 비동기 요청(`Callable`·`DeferredResult`·스트리밍)이 시간 안에 끝나지 않았다. 그 밖의 503(필터의 `sendError(503)` 등)은 공용 `SERVER_BUSY`다. GraphQL도 같은 이름을 쓰지만 그쪽 `category`는 GraphQL 전용 어휘 `TIMEOUT`이다(`src/adapter/inbound/graphql/README.md`) |",
"| `IDEMPOTENCY_KEY_INVALID` | 400 | `VALIDATION` | `false` | 없음 | 2절 |",
"| `RATE_LIMIT_UNAVAILABLE` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 있음 | rate-limit 저장소 응답 없음(`docs/web/runbook.md`) |",
"| `RATE_LIMIT_INCOMPATIBLE` | 503 | `INTERNAL` | `false` | 없음 | rate-limit 제공자가 계약과 맞지 않음 |"
"| `RATE_LIMIT_INCOMPATIBLE` | 503 | `INTERNAL` | `false` | 없음 | rate-limit 제공자가 계약과 맞지 않음 |",
"| `OPERATION_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | durable operation 조회(`DurableOperationController`)에서 그 operation이 없거나 다른 호출자의 것이다. 둘을 가르지 않는다 |"
]
]
}
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"source": {
"repository": "clean-architecture-backend-template",
"commit": "45d2a478b800586f1d84151723629a560265d58e",
"commit": "d32b4b53de734aca7d76dc08acf6e97bea899672",
"document": "docs/web/http-contract.md"
},
"answers": [
@@ -151,7 +151,7 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정
- 정본: [`clean-architecture-backend-template/docs/web/http-contract.md`](../../../clean-architecture-backend-template/docs/web/http-contract.md)
1절 "Envelope 키 존재 규칙"
- 기준 커밋: 백엔드 `45d2a478`. 기계가 읽는 정본은
- 기준 커밋: 백엔드 `d32b4b53`. 기계가 읽는 정본은
`config/contracts/backend-contract-pin.json`(repo, 전체 SHA, 대조한 절 §1·§2·§4,
담당)이다. 백엔드 §2 표와 §4의 503 셋(`REQUEST_TIMEOUT`, `RATE_LIMIT_UNAVAILABLE`,
`RATE_LIMIT_INCOMPATIBLE`)은
@@ -163,7 +163,8 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정
- 백엔드 §2·§4 표의 행은 pin 커밋 그대로
`config/contracts/backend-http-contract-excerpt.json`에 옮겨 두었다. 같은 테스트가
답 표의 code·status를 이 사본과 대조한다. 사본에만 있는 행은 답 표에 옮기거나 pin의
`notCopied`에 이유와 함께 적는다(지금은 없다). pin의
`notCopied`에 이유와 함께 적는다. 지금은 §4의 404 `OPERATION_NOT_FOUND` 하나다(durable
operation 조회의 답이라 쓰기의 적용 여부와 무관하고, 프론트는 그 조회를 부르지 않는다). pin의
`sectionsCompared`의 §4에서 답 표가 옮긴 행은 503 셋(`REQUEST_TIMEOUT`,
`RATE_LIMIT_UNAVAILABLE`, `RATE_LIMIT_INCOMPATIBLE`)이다.
`IDEMPOTENCY_KEY_INVALID`는 §2 행으로 옮겼다.
@@ -177,6 +178,11 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정
pin의 `backend.scaffoldSources`에 있고, 각 항목이 옮긴 곳(프론트 파일과
이름)을 적는다. drift 검사는 pin 뒤 HEAD에서 이 파일들이 바뀌었는지도 보고,
바뀐 파일마다 다시 볼 프론트 위치를 말하며 1로 끝난다(1105/16-02).
- Fileserver 업로드 client가 읽는 백엔드 code 파일(`FileserverErrorCode` 등)은 pin의
`backend.codeSources`에 있다. 게시 전 5xx 표는 그 행의 `codes`에 옮겨 두었고,
`tests/unit/backend-contract-pin.test.ts`가 `fileserver-upload.ts`의 표와 대조한다. drift 검사는
이 파일들도 pin 뒤 HEAD에서 바뀌었는지 본다(1105/01-02). pin이 적은 경로가 pin 커밋에 없으면
(백엔드가 폴더를 옮겼다) 그것도 1이다.
- 프론트에서 Envelope를 읽는 곳: `src/adapters/http/backend-envelope.ts`(스키마와
해석). V3 실행기는 descriptor가 `responseEnvelope: "ENVELOPE_V1"`일 때 쓴다.
`create:feature`가 만든 기능은 이 값을 선언한다. Envelope가 없는 백엔드의
@@ -267,7 +273,7 @@ backend idempotency를 대체하지 않는다.
- 정본: [`clean-architecture-backend-template/docs/web/http-contract.md`](../../../clean-architecture-backend-template/docs/web/http-contract.md)
2절 "멱등성 응답", 4절 "web 전용 오류 코드"
- 기준 커밋: 4.1절과 같다(백엔드 `45d2a478`, `config/contracts/backend-contract-pin.json`).
- 기준 커밋: 4.1절과 같다(백엔드 `d32b4b53`, `config/contracts/backend-contract-pin.json`).
- 프론트가 그 응답을 읽는 곳:
- 키 생성·검사: `src/contracts/mutation-intent.ts` `isValidIdempotencyKey`
- 결과 불명 재전송이 같은 키를 쓰고 `Retry-After`까지 기다리는 곳:
@@ -293,24 +299,29 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐
읽었다. 처리 중·불일치 판정은 그대로 action 전이고 줄 번호만 옮겼다. `45d2a478`에서는
바뀐 `GlobalExceptionHandler`(로그 줄 정리)와 `IdempotencyExecutor`를 다시 읽었다. 인용한
블록의 내용은 그대로이고 줄 번호만 옮겼다. §2는 처리 중(PostgreSQL 저장소는 409 대신
기다림)과 `IDEMPOTENCY_UNAVAILABLE`(lease 만료로 시작 거절) 설명만 늘었고 code·status·재시도는 같다. 같은 code가 쓰기 전과
기다림)과 `IDEMPOTENCY_UNAVAILABLE`(lease 만료로 시작 거절) 설명만 늘었고 code·status·재시도는 같다.
`d32b4b53`에서는 계층 폴더 재배치(`application-core` 모듈이
`clean-architecture-backend-template/src/application/core/`로 가는 식, 내용 같음)와 샘플 모듈
`sample-portfolio` 삭제를 따라 근거를 다시 찾았다. 판정은 바뀌지 않았다. 샘플과 함께
사라진 근거(참조 도메인 code, `WorkLogWebMapper`·`RepoStatsAclMapper`, `PosterImagePublicationController`)는
표에서 뺐다. 400·409·422 code 집합(`clean-architecture-backend-template/docs/registries/error-codes.yaml`)은 같다. 같은 code가 쓰기 전과
뒤에서 모두 나오면 "쓰기 뒤 가능"으로 둔다. 프론트는 code만 보고 둘을 가를 수
없다.
| code (status) | 나오는 곳 | 단계 | 프론트 결과 | 백엔드 파일:줄 |
| --- | --- | --- | --- | --- |
| `VALIDATION_FAILED` (400), details = 필드 목록 | 요청 본문 `@Valid` 실패, 컨트롤러 파라미터 제약 실패. 컨트롤러 메서드가 불리기 전 | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:205-218`, `:333-355` |
| `VALIDATION_FAILED` (400), details = 필드 목록 | `ConstraintViolationException`. 어느 층에서 던져도 이 handler가 받는다. 요청 경로에서 던지는 코드는 없다(application bean에 `@Validated` 없음, JPA entity에 Bean Validation 제약 없음, 직접 throw 없음) | 쓰기 전(현재 출처 없음) | `NOT_APPLIED` | `GlobalExceptionHandler.java:101-106` |
| `VALIDATION_FAILED` (400), details = `{cause}` 또는 없음 | 본문을 읽지 못함(`HttpMessageNotReadableException`) | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:220-238` |
| `VALIDATION_FAILED` (400), details = `{field, code}` | 페이지·정렬 파라미터. 목록 GET 컨트롤러가 use case 전에 검사한다 | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:149-153`, `PageParams.java:27-33`, `SortParam.java:16-43` |
| `IDEMPOTENCY_KEY_INVALID` (400) | KEYED 컨트롤러 첫 줄의 키 파싱 | 쓰기 전 | `NOT_APPLIED` | `IdempotencyKeyHeader.java:32-38`, `PosterImagePublicationController.java:64` |
| `IDEMPOTENT_REQUEST_MISMATCH` (422) | 멱등성 executor가 action 전에 판정 | 쓰기 전 | `NOT_APPLIED` | `IdempotencyExecutor.java:127-128`, `:166-167` |
| `IDEMPOTENT_IN_FLIGHT` (409) | 멱등성 executor가 action 전에 판정. 같은 키의 앞선 요청이 실행 중이다 | 이번 요청은 쓰기 전. 앞선 요청은 적용될 수 있다 | `MAYBE_APPLIED` | `IdempotencyExecutor.java:129-130`, `:168-169` |
| `BAD_PARAMETER` (400) | 타입 변환 실패, 필수 파라미터·헤더 없음(쓰기 전). **어느 층이든 `IllegalArgumentException`**(use case·domain 포함) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `GlobalExceptionHandler.java:92-99`, `:108-116`, `:384-404`, `HttpStatusErrorCodes.java:33-34` |
| `MAPPING_FAILED` (400) | web 매퍼(쓰기 전), outbound ACL 매퍼(use case 안), 멱등성 응답 직렬화(action이 끝난 뒤) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `WorkLogWebMapper.java:36`, `RepoStatsAclMapper.java:14`, `JsonIdempotentResponseCodec.java:32`, `IdempotencyExecutor.java:276` |
| `VALIDATION_FAILED` (400), details = 필드 목록 | 요청 본문 `@Valid` 실패, 컨트롤러 파라미터 제약 실패. 컨트롤러 메서드가 불리기 전 | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:228-241`, `:361-383` |
| `VALIDATION_FAILED` (400), details = 필드 목록 | `ConstraintViolationException`. 어느 층에서 던져도 이 handler가 받는다. application bean에 `@Validated`가 없고 JPA entity에 Bean Validation 제약이 없다. 직접 던지는 곳은 web-advanced patch 적용 하나다(`PatchBodies.java:49-51`, 컨트롤러가 patch 결과를 use case에 넘기기 전) | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:105-110` |
| `VALIDATION_FAILED` (400), details = 필드 목록 | 알림 제출·템플릿 컨트롤러가 본문에서 use case 전에 던지는 필드 거절(`NotificationFieldRejectedException`) | 쓰기 전 | `NOT_APPLIED` | `NotificationSubmissionController.java:72`, `:95`, `NotificationTemplateController.java:76-81` |
| `VALIDATION_FAILED` (400), details = `{cause}` 또는 없음 | 본문을 읽지 못함(`HttpMessageNotReadableException`) | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:248-266` |
| `VALIDATION_FAILED` (400), details = `{field, code}` | 페이지·정렬 파라미터. 목록 GET 컨트롤러가 use case 전에 검사한다 | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:161-165`, `PageParams.java:27-33`, `SortParam.java:16-43` |
| `IDEMPOTENCY_KEY_INVALID` (400) | KEYED 컨트롤러 첫 줄의 키 파싱. main에는 이 헤더를 읽는 운영 컨트롤러가 없고, 시험 fixture가 그 모양을 보인다 | 쓰기 전 | `NOT_APPLIED` | `IdempotencyKeyHeader.java:32-38`, `FaultFixtureController.java:58` |
| `IDEMPOTENT_REQUEST_MISMATCH` (422) | 멱등성 executor가 action 전에 판정 | 쓰기 전 | `NOT_APPLIED` | `IdempotencyExecutor.java:129-130`, `:168-169` |
| `IDEMPOTENT_IN_FLIGHT` (409) | 멱등성 executor가 action 전에 판정. 같은 키의 앞선 요청이 실행 중이다 | 이번 요청은 쓰기 전. 앞선 요청은 적용될 수 있다 | `MAYBE_APPLIED` | `IdempotencyExecutor.java:131-132`, `:170-171` |
| `BAD_PARAMETER` (400) | 타입 변환 실패, 필수 파라미터·헤더 없음(쓰기 전). **어느 층이든 `IllegalArgumentException`**(use case·domain 포함) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `GlobalExceptionHandler.java:94-103`, `:118-126`, `:412-445`, `HttpStatusErrorCodes.java:47-48` |
| `MAPPING_FAILED` (400) | 멱등성 응답 직렬화(action이 끝난 뒤)와 재생할 응답의 역직렬화(action 전) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `JsonIdempotentResponseCodec.java:32`, `:41`, `IdempotencyExecutor.java:279` |
| `DB_SERIALIZATION_FAILURE`, `DB_DEADLOCK`, `DB_LOCK_TIMEOUT`, `DB_NULL_VIOLATION`, `DB_FK_VIOLATION`, `DB_UNIQUE_VIOLATION`, `DB_CHECK_VIOLATION`, `DB_OPTIMISTIC_CONFLICT` (409) | persistence 어댑터가 SQL·JPA 실패를 바꾼 것. 트랜잭션 안이나 commit에서 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `FailureCategory.java:86-102`, `StandardSqlStateErrorMapping.java:46-52`, `PersistenceExceptionTranslator.java:133` |
| `LOCK_ACQUISITION_TIMEOUT` (409) | 분산 락 대기 초과. use case 안 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `LockRegistryDistributedLock.java:50`, `:53` |
| 참조 도메인 `WORKLOG_INVALID`, `POSTER_INVALID_STATE`, `POSTER_IMAGE_REQUIRED` (400), `WORKLOG_CONFLICT`, `POSTER_ALREADY_EXISTS`, `POSTER_IMAGE_ALREADY_PUBLISHED` (409) | application·domain 예외 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `DomainExceptionHandler.java:52-90` |
| 선택 모듈 web-advanced `PATCH_REJECTED` (400), `PATCH_TEST_FAILED` (409) | patch 라이브러리. 부르는 코드가 단계를 정한다 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `clean-architecture-backend-template/src/adapter/inbound/web-advanced/README.md` 「오류 응답」 |
| 선택 모듈 fileserver `BAD_REQUEST` (400), `FILE_ALREADY_EXISTS`, `FILE_NOT_READY`, `UPLOAD_OFFSET_MISMATCH`, `CONCURRENT_MODIFICATION` (409), `INTEGRITY_MISMATCH`, `MALWARE_DETECTED`, `INVALID_PATH`, `PATH_OUTSIDE_NAMESPACE` (422) | application·outbound 층. `INTEGRITY_MISMATCH`·`MALWARE_DETECTED`는 레코드를 `REJECTED`로 쓴 뒤 던진다 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `FileserverErrorCode.java:26-44`, `FinalizeUploadApplicationUseCase.java:211-224`, `:336-341` |
@@ -336,28 +347,34 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐
503 `RATE_LIMIT_INCOMPATIBLE`(rate-limit 제공자가 계약과 맞지 않음)은 status와 code가
함께 맞으면 기능 분류기와 상관없이 `NOT_APPLIED`다(1105/03-02, `backend-envelope.ts`
`REFUSED_BEFORE_WRITE`). 백엔드 `RateLimitInterceptor.java`의 `preHandle`이 컨트롤러 전에
`false`를 돌려주며 낸다. `45d2a478`의 main 소스에서 이 두 code를 내는 곳은 그 두
줄뿐이다. KEYED·NEVER는 자동 재전송이 없다. IDEMPOTENT 쓰기는 `retryBudget` 안에서
`false`를 돌려주며 낸다. `d32b4b53`의 main 소스에서 이 두 code를 내는 곳은 그 두
줄뿐이다(`:58`, `:63`). KEYED·NEVER는 자동 재전송이 없다. IDEMPOTENT 쓰기는 `retryBudget` 안에서
`Retry-After`(5초 이하) 뒤 다시 보낸다. 실행기는 status로 판단하므로 백엔드가
`retryable: false`로 보내는 `RATE_LIMIT_INCOMPATIBLE`도 다시 보낸다
(`tests/integration/http-execution-v3-envelope.test.ts`, 1106/03-02).
남은 위험(추론, 실행 확인 안 함): Spring MVC는 비동기 처리(`Callable`·`DeferredResult`)가 끝난 뒤의 ASYNC 재디스패치에서도 interceptor의
`preHandle`을 다시 부른다. 그 interceptor는 dispatcher 종류를 보지 않으므로 비동기 쓰기
컨트롤러라면 이 503(그리고 429)이 쓰기 뒤에도 나올 수 있다. `45d2a478`에는 Envelope을
컨트롤러라면 이 503(그리고 429)이 쓰기 뒤에도 나올 수 있다. `d32b4b53`에도 Envelope을
돌려주는 비동기 쓰기 컨트롤러가 없다(web-advanced 스트리밍과 fileserver 전송뿐).
- 서버 포화의 503 `SERVER_BUSY`(백엔드 `697e62e8c`부터, §4 아래 목록)는 V3 표에 없다. 그래서
기능 분류기의 판정을 따르고, 분류기가 없으면 결과 불명이다. 대부분 컨트롤러 전에 나오지만
(`VirtualThreadAdmissionFilter`), 상태만 정해진 모든 503도 이 code가 되어(`HttpStatusErrorCodes.java:45`)
단계를 code로 가를 수 없다. Fileserver 업로드 client는 따로 읽는다(아래).
- 파일 위치(백엔드 repo `clean-architecture-backend-template` 기준):
- `GlobalExceptionHandler.java`, `HttpStatusErrorCodes.java`: `clean-architecture-backend-template/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/`
- `PageParams.java`, `SortParam.java`: 같은 모듈 `.../web/pagination/`
- `IdempotencyKeyHeader.java`: 같은 모듈 `.../web/http/`
- `IdempotencyExecutor.java`: `clean-architecture-backend-template/src/application-core/src/main/java/dev/caskeleton/application/idempotency/`
- `IdempotencyExecutor.java`: `clean-architecture-backend-template/src/application/core/src/main/java/dev/caskeleton/application/idempotency/`
- `JsonIdempotentResponseCodec.java`: `clean-architecture-backend-template/src/adapter/inbound/web-advanced/.../advanced/idempotency/`
- `FailureCategory.java`, `StandardSqlStateErrorMapping.java`,
- `FailureCategory.java`(같은 이름이 여럿이다. persistence의 것), `StandardSqlStateErrorMapping.java`,
`PersistenceExceptionTranslator.java`, `LockRegistryDistributedLock.java`:
`clean-architecture-backend-template/src/adapter/outbound/persistence-jpa/`
- `PosterImagePublicationController.java`, `WorkLogWebMapper.java`,
`RepoStatsAclMapper.java`, `DomainExceptionHandler.java`: `clean-architecture-backend-template/src/sample-portfolio/`
- `FileserverErrorCode.java`, `FinalizeUploadApplicationUseCase.java`:
`clean-architecture-backend-template/src/application-fileserver/`
- `PatchBodies.java`: `clean-architecture-backend-template/src/adapter/inbound/web-advanced/.../advanced/patch/`
- `NotificationSubmissionController.java`, `NotificationTemplateController.java`:
`clean-architecture-backend-template/src/adapter/inbound/web-notification/`
- `FaultFixtureController.java`: `clean-architecture-backend-template/src/adapter/inbound/web/src/testFixtures/` (시험 fixture)
- `FileserverErrorCode.java`, `FinalizeUploadApplicationUseCase.java`, `UploadFileApplicationUseCase.java`,
`TransferAdmissionController.java`: `clean-architecture-backend-template/src/application/fileserver/`
- Fileserver 한 번 업로드(`POST /v1/files`)는 V3 실행기가 아니라
`src/adapters/http/fileserver-upload.ts`의 client가 부른다(1105/01-02). 이 client는
위 표의 fileserver 행과 달리 4xx를 `NOT_APPLIED`로 본다. 업로드 use case
@@ -368,9 +385,12 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐
- 멱등성 code와 V3 표(`REFUSED_BEFORE_WRITE`, `MAYBE_APPLIED_ANSWERS`)에 있는 답은
client도 V3 표로 판정한다. 그래서 503 `IDEMPOTENCY_UNAVAILABLE`은 `MAYBE_APPLIED`다.
`tests/integration/fileserver-upload.test.ts`가 복사한 답 표의 행마다 둘이 같은지 본다.
- 5xx는 작업 스레드가 게시 전에 내는 code 넷(`PARTIAL_WRITE`,
`ATOMIC_PUBLISH_UNSUPPORTED`, `STORAGE_UNAVAILABLE`, `STORAGE_FULL`)만
`NOT_APPLIED`다. 504 `TRANSFER_TIMEOUT`은 `MAYBE_APPLIED`다. 대기 스레드가
- 5xx는 파일을 게시하기 전에 나는 code 다섯(`PARTIAL_WRITE`,
`ATOMIC_PUBLISH_UNSUPPORTED`, `STORAGE_UNAVAILABLE`, `SERVER_BUSY`, `STORAGE_FULL`)만
`NOT_APPLIED`다. `SERVER_BUSY`는 instance 전송 permit과 전송 pool이 찼을 때 작업 전에
낸다(`TransferAdmissionController.java:79`, `BlockingTransferExecutor.java:61`. 백엔드
`697e62e8c` 전에는 429 `TRANSFER_ADMISSION_REJECTED`였다). 이 표는 pin의 `backend.codeSources`에
옮겨 두었다. 504 `TRANSFER_TIMEOUT`은 `MAYBE_APPLIED`다. 대기 스레드가
작업 단계와 상관없이 내고, 게시 rename과 `READY` 커밋은 interrupt로 멈추지 않는다
(`BlockingTransferExecutor.java`, `FinalizeUploadApplicationUseCase.java`). 백엔드는
이 code를 `retryable: true`, `ambiguous` 없이 보낸다. 이 차이는 백엔드 결정으로 남는다.
@@ -391,7 +411,7 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐
`LOCK_ACQUISITION_TIMEOUT`, fileserver code)도 적을 수 없다(1105/03-01). 계약 조립이
거절하고 실행기도 무시한다. 목록은 `src/contracts/external-contract-runtime.ts`의
`PLATFORM_CODES_POSSIBLY_AFTER_WRITE`이고, `tests/unit/backend-contract-pin-document.test.ts`가
이 표의 "쓰기 뒤 가능" 행과 대조한다. 참조 도메인 code와 web-advanced patch code는
이 표의 "쓰기 뒤 가능" 행과 대조한다. web-advanced patch code는
엔드포인트가 단계를 정하므로 그 엔드포인트를 확인한 기능 작성자가 적을 수 있다. 이 표에
"쓰기 뒤 가능" 플랫폼 code를 더하면 그 목록도 같은 변경에서 고친다.
- `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에는 적을 수 없다. 실행기가
@@ -406,7 +426,7 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐
백엔드에 붙이는 Envelope operation은 `src/adapters/http/backend-envelope.ts`의
표가 400·409·422를 정한다(`3261208`).
남은 위험: "쓰기 전"은 현재 코드에서 그 handler에 닿는 출처를 센 결과다. 백엔드가
남은 위험: "쓰기 전"은 현재 코드(`d32b4b53`)에서 그 handler에 닿는 출처를 센 결과다. 백엔드가
application bean에 `@Validated`를 달거나 JPA entity에 Bean Validation 제약을
넣으면, 필드 목록이 있는 400 `VALIDATION_FAILED`가 use case 안에서도 나온다.
백엔드에는 이것을 막는 검사가 없다.
+13 -11
View File
@@ -124,9 +124,8 @@ type은 facade 밖으로 노출하지 않는다.
SSOT다. 문서와 catalog가 다르면 gate가 검사하는 catalog를 우선 고치고 이 표도
같이 갱신한다.
Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7, 2의 시작 실패
이벤트, 2의 `observe`와 3을 제품 소유 파일에서 잇는 자리를 갖고 있다. 4·5를
잇는 제품 소유 자리는 아직 없다.
Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7·8, 2의 시작 실패
이벤트를 갖고 있다. 2의 `observe`와 3·4·5는 제품 소유 파일에서 잇는 자리가 있다.
1. 제품 소유 파일 `src/features/product-capabilities.ts`의 `SERVICE_WORKER`를
`ACTIVE`로 바꾼다. `scripts/build-frontend.ts`가 worker 빌드를 추가로 돈다.
@@ -138,9 +137,7 @@ Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7, 2의 시
(`src/bootstrap/optional-runtime-host.ts`). 실제 composition에서 첫 설치가
실패하면 이벤트가 1건 나가는 것은
`tests/component/runtime-composition-service-worker-telemetry.test.ts`가
확인한다. 템플릿이 연결하지 않은 것은 셋이다. 업데이트 설치 실패
(`watchForUpdates`, `src/adapters/service-worker/service-worker-page-controller.ts`)는
이벤트를 남기지 않는다. page controller의 `observe`는 제품이
확인한다. 템플릿이 연결하지 않은 것은 둘이다. page controller의 `observe`는 제품이
`src/bootstrap/product-composition.ts`의 `composeProduct`에서
`serviceWorker.observe`로 돌려준다(1103/09-05). 템플릿 조립이 그것을 optional
host에 넘기고, 던지면 무시한다. `OptionalRuntimeHost.health()`는 `src` 안에서
@@ -152,12 +149,17 @@ Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7, 2의 시
값이 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를 안내한다.
6. 끄기·롤백·제거: `docs/operations/release-cache-rollback.md`의 Service Worker
4. 활성화 UI: `composeProduct`가 `serviceWorker.onUpdateWaiting`을 돌려준다. 템플릿
조립이 `ServiceWorkerRuntimeHost.onUpdateWaiting`을 worker 시작 전에 구독해 그것을
부르고, 받은 `activate()`는 `requestActivation()`이다. 사용자가 동의하면 부른다
(1103/09-05).
5. reload 처리: `serviceWorker.onReloadRequired`로 reload를 안내한다. 템플릿 조립이
`onReloadRequired`를 구독해 부른다.
6. 갱신 실패: 설치에 실패한 갱신(`update_install` `REDUNDANT`)과 실패한 주기 검사
(`update_check` `FAILED`)도 `observe`로 온다(0925/06-05).
7. 끄기·롤백·제거: `docs/operations/release-cache-rollback.md`의 Service Worker
절차. `service-worker.js`는 `Cache-Control: no-cache`로 서빙한다.
7. 실제 브라우저 검사: `tests/e2e/service-worker-update.spec.ts`와
8. 실제 브라우저 검사: `tests/e2e/service-worker-update.spec.ts`와
`service-worker-recovery.spec.ts`를 제품 구성으로 돌린다. helper는 이미
`ACTIVE`인 선택을 그대로 쓰고, 캐시 단언은 빌드가 만든 사전 캐시 목록과
비교한다. 준비 단계에서 실패하면 helper(`tests/e2e/support/service-worker-builds.ts`)
+41 -44
View File
@@ -436,7 +436,7 @@ export function mapInvoiceCreateProblem(
- 빈 파일은 보내지 않는다. 짝 백엔드 기본 검증기가 빈 파일을 거절하기 때문이다. `VALIDATION_REJECTED`, code `FILE_EMPTY`, `NOT_STARTED`다.
- 실패 `effect`:
- `NOT_STARTED`: 보내지 않았다. 입력, 크기, 자격 증명에서 거절했다.
- `NOT_APPLIED`: 서버가 거절했고 파일은 없다. Fileserver는 모호하지 않은 실패에서 업로드를 취소한다. 아래 `MAYBE_APPLIED` 경우를 뺀 4xx와, 5xx 중 작업 스레드가 게시 전에 내는 code 넷(`PARTIAL_WRITE`, `ATOMIC_PUBLISH_UNSUPPORTED`, `STORAGE_UNAVAILABLE`, `STORAGE_FULL`)이다.
- `NOT_APPLIED`: 서버가 거절했고 파일은 없다. Fileserver는 모호하지 않은 실패에서 업로드를 취소한다. 아래 `MAYBE_APPLIED` 경우를 뺀 4xx와, 5xx 중 파일을 게시하기 전에 나는 code 다섯(`PARTIAL_WRITE`, `ATOMIC_PUBLISH_UNSUPPORTED`, `STORAGE_UNAVAILABLE`, `SERVER_BUSY`, `STORAGE_FULL`)이다. `SERVER_BUSY`(503)는 서버의 전송 permit이나 작업 pool이 찬 거절이고 `retryable: true`다.
- `MAYBE_APPLIED`: 올라갔을 수도 있다. 응답을 잃음, 시간 초과, `details.ambiguous: true`, 그 밖의 5xx다. 504 `TRANSFER_TIMEOUT`도 여기 든다. 백엔드는 대기 시간이 지나면 작업이 어느 단계에 있든 이 code를 내고, 작업은 그 뒤에 끝나 `READY`가 될 수 있다. 다시 보낼 때는 같은 `idempotencyKey`를 쓴다.
- 멱등성 응답(`IDEMPOTENT_*`, `IDEMPOTENCY_*`)과 V3 표에 있는 web 공통 응답은 V3 실행기와 같은 표(`backend-envelope.ts`, 4절)로 판정한다. 400 `IDEMPOTENCY_KEY_INVALID`·422 `IDEMPOTENT_REQUEST_MISMATCH`는 `NOT_APPLIED`, 409 `IDEMPOTENT_IN_FLIGHT`·503 `IDEMPOTENCY_UNAVAILABLE`·503 `IDEMPOTENCY_COMPLETION_UNKNOWN`·500 `IDEMPOTENCY_RECOVERY_REQUIRED`는 `MAYBE_APPLIED`다.
- `APPLIED_CONFIRMED`: 서버는 만들었다고 답했지만 응답을 읽지 못했다. 다시 올리지 않는다.
@@ -445,77 +445,74 @@ export function mapInvoiceCreateProblem(
- client는 스스로 다시 보내지 않는다. `retryable: true`이고 `retryAfterMs`가 있으면 그만큼 기다린 뒤 기능이 다시 부른다. 서버가 상한(`maxRetryAfterMs`, 기본 30초)보다 길게 기다리라고 하면 `retryable: false`다.
- `MAYBE_APPLIED`는 언제나 `retryable: false`다. 백엔드가 Envelope에 `retryable: true`와 `Retry-After`를 붙여도(504 `TRANSFER_TIMEOUT`) 기능이 자동으로 다시 부르지 않는다. 아래 주의대로 먼저 확인한다.
**주의 — 멱등 키**: 짝 백엔드(`45d2a478`)의 `POST /v1/files`는 멱등 키를 읽지 않는다(업로드 use case가 `NOT_IDEMPOTENT`).
**주의 — 멱등 키**: 짝 백엔드(pin `d32b4b53`)의 `POST /v1/files`는 멱등 키를 읽지 않는다(업로드 use case가 `NOT_IDEMPOTENT`).
- 그래서 `MAYBE_APPLIED` 뒤 다시 보내면 같은 파일이 두 개 생길 수 있다.
- 같은 키 재전송이 중복을 막는 것은 배포가 업로드를 백엔드 멱등성 executor 뒤에 둘 때뿐이다.
- 그 전에는 다시 보내기 전에 업무 데이터(파일 목록 등)로 먼저 확인한다.
**어디에 적나**: 두 곳이다.
**어디에 적나**: 두 곳이다. 템플릿 파일은 고치지 않는다.
1. `src/bootstrap/product-composition.ts`: client를 만들 재료(주소, 인증 프로필, 자격 증명, 크기 상한)를 capability로 넘긴다. client 코드는 넘기지 않는다. 기능 adapter는 기능 runtime과 함께 늦게 적재되므로, 업로드 코드가 boot 번들이 아니라 기능 chunk에 든다.
2. 기능 `adapters/create-<base>-feature-input.ts`: `needs`에 그 capability를 적고, 거기서 `createFileserverUploadClient`를 부른다.
1. `src/bootstrap/product-composition.ts`: client를 만들 재료(주소, 인증 프로필, 자격 증명, 크기 상한)를 capability `fileserverUpload`로 넘긴다. client 코드는 넘기지 않는다. 기능 adapter는 기능 runtime과 함께 늦게 적재되므로, 업로드 코드가 boot 번들이 아니라 기능 chunk에 든다.
- 그 타입은 템플릿이 `FeaturePlatformCapabilities`에 opt-in 키로 선언해 두었다(`src/features/feature-adapter-contribution.ts`, `indexedDb`와 같다). `declare module`로 보강하지 않는다. `check:types:node`가 그 보강을 보지 못한다(매뉴얼 03).
- 자격 증명은 `context.credentials`를 펼친다. V3 요청과 같은 주인(scope fence → ANONYMOUS 프로필 → `credentialProviders` → 템플릿 세션)이 헤더를 붙이고, 업로드의 401도 V3 401과 같은 곳(제품 provider의 자격 증명이면 `onCredentialRejected`, 템플릿 세션의 것이면 세션)으로 간다.
2. 기능 `adapters/`: `create-<base>-feature-input.ts`의 `needs`에 `fileserverUpload`를 더하고, 받은 값으로 `createFileserverUploadClient`를 부른다.
<!-- manual-code-block: src/bootstrap/product-composition.ts -->
```ts
// src/bootstrap/product-composition.ts (제품 소유). BACKEND_SESSION은
// src/contracts/product-contracts.ts에 더한 쿠키 세션 프로필이다.
import type { FileserverUploadClientDependencies } from "../adapters/http/index.ts";
import { PRODUCT_REST_AUTH_PROFILES } from "../contracts/product-contracts.ts";
// 파일에 이미 있는 import에 ProductCredentialProvider를 더한다.
import type { ProductCredentialProvider } from "./product-composition-contract.ts";
// JWT·Keycloak 모드(템플릿 세션의 bearer, EXTERNAL_BEARER)의 예다.
import { REST_AUTH_PROFILES } from "../contracts/rest-profiles.ts";
import type {
ProductComposition,
ProductCompositionContext,
ProductSessionOwner,
ProductSessionOwnerContext,
} from "./product-composition-contract.ts";
declare module "../features/feature-adapter-contribution.ts" {
interface FeaturePlatformCapabilities {
readonly fileserverUpload: FileserverUploadClientDependencies;
}
export function composeProductSessionOwner(
context: ProductSessionOwnerContext,
): ProductSessionOwner {
return null;
}
export function composeProduct(context: ProductCompositionContext) {
const sessionCredentials: ProductCredentialProvider = () => {
if (!context.isScopeReady()) return { kind: "SCOPE_FENCED" };
const csrf = context.readCookie("XSRF-TOKEN");
return csrf === undefined
? { kind: "UNAUTHENTICATED" }
: { kind: "READY", headers: { "x-xsrf-token": csrf } };
};
return {
capabilities: {
fileserverUpload: {
...context.credentials,
baseUrl: context.config.API_BASE_URL,
authProfile: PRODUCT_REST_AUTH_PROFILES.BACKEND_SESSION,
attachCredentials: sessionCredentials,
authProfile: REST_AUTH_PROFILES.EXTERNAL_BEARER,
maxFileBytes: 20 * 1024 * 1024,
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
},
},
credentialProviders: { BACKEND_SESSION: sessionCredentials },
// BACKEND_SESSION은 세션 쿠키 그 자체다. 그 401은 세션을 로그아웃시킨다(5절).
onCredentialRejected: () => context.notifySessionUnauthenticated(),
credentialProviders: {},
} satisfies ProductComposition;
}
```
<!-- manual-code-block: src/features/invoice-feature/adapters/invoice-attachment-uploads.ts -->
```ts
// src/features/<id>/adapters/create-<base>-feature-input.ts
import { createFileserverUploadClient } from "../../../adapters/http/index.ts";
import { defineFeatureAdapterContribution } from "../../feature-adapter-contribution.ts";
import {
createFileserverUploadClient,
type FileserverUploadClient,
} from "../../../adapters/http/index.ts";
import type { FeatureCapabilitySelection } from "../../feature-adapter-contribution.ts";
export const createAttachmentFeatureInput = defineFeatureAdapterContribution({
featureId: "attachment",
needs: ["http", "fileserverUpload"],
createInput: ({ http, fileserverUpload }) => {
const uploads = createFileserverUploadClient(fileserverUpload);
return {
featureId: "attachment",
// 기능 port 구현이 uploads.upload({ source, filename, mediaType, idempotencyKey, signal })를 부른다.
input: { /* … */ },
};
},
});
// create-invoice-feature-input.ts가 needs: ["http", "fileserverUpload"]로 받은 값을 넘긴다.
// 기능 port 구현이 uploads.upload({ source, filename, mediaType, idempotencyKey, signal })를 부른다.
export function createInvoiceAttachmentUploads({
fileserverUpload,
}: FeatureCapabilitySelection<["fileserverUpload"]>): FileserverUploadClient {
return createFileserverUploadClient(fileserverUpload);
}
```
- 이 두 조각도 `tests/unit/manual-code-blocks.test.ts`가 저장소 사본에 넣어 타입 검사한다. `product-composition.ts`는 제품 소유 파일이라 조각이 파일 전체를 바꾼다.
- 쿠키 세션 모드(Redis session, BFF)는 `authProfile`을 `src/contracts/product-contracts.ts`에 더한 쿠키 프로필(예: `BACKEND_SESSION`)로 바꾸고, `credentialProviders`에 그 프로필의 provider(XSRF 쿠키를 헤더로 붙이는 함수)를 둔다. `context.credentials`가 그 provider를 부른다. 그 provider는 세션 쿠키 자체를 보내므로 `onCredentialRejected: () => context.notifySessionUnauthenticated()`로 401을 세션에 알린다(5절).
- `context.credentials`를 펼치지 않고 `attachCredentials`만 직접 주면 업로드의 401이 아무에게도 가지 않는다. 화면은 로그인 상태로 남고 업로드만 `AUTH_REQUIRED`로 실패한다(매뉴얼 04).
- `baseUrl`은 끝이 `/`여야 한다. `v1/files`를 그 아래에 붙인다. 경로가 base 밖으로 나가면 조립할 때 `TypeError`다.
- 자격 증명 함수는 V3 실행기의 `attachCredentials`와 계약이 같다. 같은 프로필의 `credentialProviders`를 그대로 쓴다. 프로필이 허락하지 않은 헤더를 주면 보내지 않고 `AUTH_INTEGRATION_FAILURE`다.
- 자격 증명 함수는 V3 실행기의 `attachCredentials`와 계약이 같다. 프로필이 허락하지 않은 헤더를 주면 보내지 않고 `AUTH_INTEGRATION_FAILURE`다.
**틀리면**
@@ -523,5 +520,5 @@ export const createAttachmentFeatureInput = defineFeatureAdapterContribution({
- 파일이 `maxFileBytes`보다 크면 읽기 전에 `FILE_TOO_LARGE`(`NOT_STARTED`)다. 비어 있으면 `FILE_EMPTY`(`NOT_STARTED`)다.
- 202 응답을 모두 "검사 중"으로 보이면 `QUARANTINED` 파일의 화면이 끝나지 않는다. state마다 따로 보인다.
- 멱등성·web 공통 응답의 판정은 V3 표를 그대로 쓴다. `tests/integration/fileserver-upload.test.ts`가 pin 옆에 복사한 백엔드 답 표(`config/contracts/backend-idempotency-answers.json`)의 행마다 client와 V3 표가 같은지 본다. pin을 옮기면 같이 다시 돈다.
- 백엔드가 Fileserver 응답 모양이나 Fileserver 자신의 code를 바꾸면 검사가 잡지 못한다. 그 표(`fileserver-upload.ts`의 `NOT_APPLIED_5XX_CODES`)는 백엔드 `45d2a478`(pin) 코드를 읽은 것이다. 백엔드 SHA가 바뀌면 `FileserverErrorCode`, `BlockingTransferExecutor`, 게시 경로를 같이 다시 본다. 4xx를 `NOT_APPLIED`로 보는 이유는 [계약 문서](../architecture/backend-api-and-server-state-contract.md) 6.1절에 있다.
- 백엔드가 Fileserver 응답 모양을 바꾸면 검사가 잡지 못한다. Fileserver 자신의 code 표(`fileserver-upload.ts`의 `NOT_APPLIED_5XX_CODES`)는 백엔드 pin 코드를 읽은 것이고, 읽은 파일과 표를 pin의 `backend.codeSources`에 적어 두었다. `tests/unit/backend-contract-pin.test.ts`가 둘을 대조하고, `check:backend-contract-drift`가 pin 뒤 백엔드에서 그 파일이 바뀌면 알린다. 4xx를 `NOT_APPLIED`로 보는 이유는 [계약 문서](../architecture/backend-api-and-server-state-contract.md) 6.1절에 있다.
- 테스트 예: `tests/integration/fileserver-upload.test.ts`(백엔드 코드가 답하는 대로 답하는 MSW. 백엔드 문서는 202 `VERIFYING`만 적는다).
+4 -1
View File
@@ -117,6 +117,7 @@ release admission refused for staging:
- `tests/e2e/accessibility.spec.ts`: 기능마다 고치지 않는다. 경로 파라미터와 API 응답을 설치된 라우트·descriptor에서 만든다. 보호 페이지가 설치된 GET이 아닌 요청을 그리기 전에 보낼 때만 손본다. 자세한 동작은 [01 문서 6단계](01-add-a-feature.md#6단계-라우트).
- `src/features/product-capabilities.ts`: `needs`에 템플릿이 만들지 않는 capability를 적었을 때. 그 capability의 타입을 `ProductFeaturePlatformCapabilities`에 적는다.
- `product-composition.ts` 안에서 `FeaturePlatformCapabilities`를 보강(`declare module`)하면 `check:types:node`가 그 키를 보지 못한다.
- 템플릿이 타입만 선언한 opt-in 키(`indexedDb`, 짝 백엔드 업로드 `fileserverUpload`)는 여기 다시 적지 않는다. `product-composition.ts`에서 값만 돌려준다([02 결정표 7절](02-decision-tables.md#7-파일-업로드)).
- `src/bootstrap/product-composition.ts`: 위 capability의 값을 돌려줄 때. 제품 인증 프로필의 자격 증명도 여기서 준다.
- 로그아웃·계정 전환 때 닫아야 하는 것(파일 runtime 등)은 `scopeParticipants`로 돌려준다. 예제: `recipes/frontend-capabilities/browser-file-session-capability.ts`.
- `label`은 `browser-files` 같은 소문자 kebab-case 토큰으로 쓴다. 다른 형식이면 조립이 `TypeError`로 멈춘다.
@@ -176,12 +177,14 @@ src/features/product-capabilities.ts (SERVICE_WORKER = ACTIVE)
serviceWorker: {
blockers: [() => hasUnsavedEdits()],
observe: (observation) => reportServiceWorker(observation),
onUpdateWaiting: (activate) => showUpdateNotice({ onAccept: activate }),
onReloadRequired: () => showReloadNotice(),
},
} satisfies ProductComposition;
}
```
- 템플릿이 아직 연결하지 않은 것: 활성화 화면(`onUpdateWaiting`·`requestActivation()`). 확인할 것 목록은 `docs/architecture/optional-adapter-recipes.md`의 "Service Worker를 켤 때 확인할 것"에 있다.
- 활성화 화면도 같은 자리다(1103/09-05). `onUpdateWaiting`은 새 버전이 설치되어 기다릴 때(worker가 시작할 때 이미 기다리고 있던 것도) 불리고, 받은 `activate()`가 `requestActivation()`이다. 그래서 `blockers`가 그대로 걸린다. `onReloadRequired`는 다른 빌드의 worker가 넘겨받았을 때 불린다. 둘 다 던져도 worker 흐름은 바뀌지 않는다. 화면(`showUpdateNotice` 등)은 제품 것이다. 확인할 것 목록은 `docs/architecture/optional-adapter-recipes.md`의 "Service Worker를 켤 때 확인할 것"에 있다.
- realtime·Web Worker·오프라인 명령을 고르면 조립이 `Selected optional capabilities have no runtime to start them`로 거절한다. 템플릿 조립에 아직 그 런타임이 없다.
### Web Worker를 들일 때 tsconfig 더하기
+6 -5
View File
@@ -7,7 +7,7 @@
- 템플릿에는 demo owner만 있다. demo는 `APP_ENV=local`에서만 켜지고, 그 표식 토큰은 백엔드 JWT 검증을 통과하지 못한다.
- `AUTH_MODE: "external"`인데 owner가 없으면 세션은 `integration-failed`로 닫히고, 인증이 필요한 화면은 "로그인 연동이 필요합니다"를 보인다.
이 문서의 백엔드 사실은 백엔드 `bbe944bd` 기준이다. 백엔드가 인증 설정을 바꾸면 이 문서와 recipe를 함께 맞춘다.
이 문서의 백엔드 사실은 짝 계약 pin(`config/contracts/backend-contract-pin.json`, 지금 백엔드 `d32b4b53`) 기준이다. pin을 옮기거나 백엔드가 인증 설정을 바꾸면 이 문서와 recipe를 함께 맞춘다.
---
@@ -26,9 +26,9 @@
백엔드 근거 위치:
- 두 모드의 보안 체인: `clean-architecture-backend-template/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java`
- 쿠키·CSRF 이름과 모드 기본값: `clean-architecture-backend-template/src/app-bootstrap/src/main/resources/config/security.yml`
- local issuer·audience·CORS: `clean-architecture-backend-template/src/app-bootstrap/src/main/resources/application-local.yml`
- realm: `clean-architecture-backend-template/infra/keycloak/realms/ca-skeleton-realm.json`
- 쿠키·CSRF 이름과 모드 기본값: `clean-architecture-backend-template/src/bootstrap/app/src/main/resources/config/security.yml`
- local issuer·audience·CORS: `clean-architecture-backend-template/src/bootstrap/app/src/main/resources/application-local.yml`
- realm: `clean-architecture-backend-template/compose/keycloak/realms/ca-skeleton-realm.json`
---
@@ -108,7 +108,7 @@ realm JSON의 `clients`에 넣거나 Keycloak 관리 화면에서 같은 값으
}
```
- audience mapper가 꼭 있어야 한다. 백엔드는 access token의 `aud`에 `APP_SECURITY_JWT_AUDIENCE`(local 기본 `ca-skeleton-api`)가 없으면 401 `AUTH_AUDIENCE_MISMATCH`로 거부한다.
- audience mapper가 꼭 있어야 한다. 백엔드는 access token의 `aud`에 `APP_SECURITY_JWT_AUDIENCE`(local 기본 `ca-skeleton-api`, 쉼표로 여럿을 적으면 하나만 맞아도 된다)가 없으면 401 `AUTH_AUDIENCE_MISMATCH`로 거부한다.
- `webOrigins`는 브라우저가 토큰 엔드포인트를 부를 때의 CORS 허용이다.
- realm에는 사람 사용자가 없다. local에서는 관리 화면에서 사용자를 하나 만들고 realm role `user`를 준다.
- 백엔드 권한은 `realm_access.roles`와 `resource_access.ca-skeleton-api.roles`에서 온다. 쓰기 권한이 필요하면 그 사용자에게 `ca-skeleton-api`의 client role을 준다(`clean-architecture-backend-template/docs/manual/07-authorization.md`).
@@ -189,6 +189,7 @@ export function composeProductSessionOwner(
```
- 서버 401이 세션에 닿는 길은 4.3의 `onCredentialRejected` 한 줄뿐이다. 템플릿은 제품 provider가 낸 자격 증명의 401을 제품에만 알린다([02 결정표](02-decision-tables.md) 5절). 이 줄을 빼면 서버 세션이 끝나도(Redis TTL 만료, 다른 탭·서버에서 로그아웃) 화면은 로그인 상태로 남고, 요청마다 `AUTH_REQUIRED` 실패 화면만 보인다.
- Fileserver 업로드처럼 제품이 직접 보내는 요청도 같은 길을 쓴다. 업로드 capability에 `context.credentials`를 펼치면 그 401도 `onCredentialRejected`로 간다([02 결정표](02-decision-tables.md) 7절).
- CSRF: 다른 사이트가 사용자의 쿠키로 쓰기를 보내는 공격이다. 백엔드는 스크립트가 읽을 수 있는 `XSRF-TOKEN` 쿠키를 주고, 쓰기 요청의 `X-XSRF-TOKEN` 헤더가 그 값과 같은지 본다. 다른 사이트의 스크립트는 이 쿠키를 읽지 못한다.
- 백엔드는 plain 방식이다(`CsrfTokenRequestAttributeHandler`). 쿠키 값을 그대로 헤더에 넣는다.
@@ -34,7 +34,7 @@ import { STORAGE_REGISTRY } from "../../src/contracts/storage-keys.ts";
* State transitions follow `SessionState` in
* `src/application/ports/auth-session-port.ts`.
*
* The backend's realm (`infra/keycloak/realms/ca-skeleton-realm.json` there)
* The backend's realm (`compose/keycloak/realms/ca-skeleton-realm.json` there)
* has only a confidential service client; a product registers the public
* client this owner signs in with. Copy this file into `src/bootstrap/` and
* return it from `composeProductSessionOwner`; `docs/manual/04-paired-backend-session.md`
+27 -8
View File
@@ -23,13 +23,16 @@ import {
* (`backend.scaffoldSources`) that `create:feature --with-create` copies
* four facts from (path plural rule, name limit, error codes, check
* order). Each changed file names the frontend copy to recheck.
* 5. 1105/01-02: nor have the backend code files (`backend.codeSources`)
* the frontend reads a code table from, such as the Fileserver codes the
* upload client reads as refused before publishing.
*
* corepack pnpm check:backend-contract-drift [--backend <dir>] [--write-excerpt]
*
* `--write-excerpt` copies the excerpt from the pinned commit first: run it
* after moving the pin, then fix the answer table until this passes.
*
* Exit 0: all four hold. Exit 1: one does not; the output names the rows or
* Exit 0: all five hold. Exit 1: one does not; the output names the rows or
* files. Recheck the frontend contract 6.1 table, the answer table, the
* excerpt, the generator copies and the pin in one change. Exit 2: nothing
* was compared (no checkout, or the pinned commit or document is missing),
@@ -46,12 +49,15 @@ type ScaffoldSource = Readonly<{
copiedTo: Readonly<{ file: string; symbol: string }>;
}>;
type CodeSource = ScaffoldSource & Readonly<{ codes?: readonly string[] }>;
type Pin = Readonly<{
backend: Readonly<{
repository: string;
commit: string;
document: string;
scaffoldSources?: readonly ScaffoldSource[];
codeSources?: readonly CodeSource[];
}>;
tables: Readonly<{ idempotencyAnswers: string; backendExcerpt: string }>;
notCopied: readonly NotCopiedRow[];
@@ -103,6 +109,7 @@ function main(): void {
const directory = backendDirectory(pin);
const { commit, document } = pin.backend;
const scaffoldSources = pin.backend.scaffoldSources ?? [];
const codeSources = pin.backend.codeSources ?? [];
if (!existsSync(path.join(directory, ".git"))) {
cannotCompare(
`No ${pin.backend.repository} checkout at ${directory}; pass --backend <dir>. test:unit holds the answer table to ${pin.tables.backendExcerpt}, and only this script holds that copy to the backend.`,
@@ -136,6 +143,13 @@ function main(): void {
}
const excerpt = readJson<Excerpt>(pin.tables.backendExcerpt);
const failures: string[] = [];
// A copied source the pinned commit does not have is a path the pin got
// wrong (a moved file), and a diff against HEAD would read it as deleted.
for (const source of [...scaffoldSources, ...codeSources]) {
if (git(directory, "cat-file", "-e", `${commit}:${source.path}`).status !== 0) {
failures.push(`${source.path} is not in the pinned ${commit.slice(0, 12)}: fix its path in ${PIN_PATH}`);
}
}
const source = excerpt.source;
if (source.repository !== pin.backend.repository || source.commit !== commit || source.document !== document) {
@@ -167,14 +181,19 @@ function main(): void {
}
}
// 1105/16-02. The generator's copies of backend scaffold facts.
for (const scaffold of scaffoldSources) {
const scaffoldDiff = git(directory, "diff", "--unified=0", `${commit}..HEAD`, "--", scaffold.path);
if (scaffoldDiff.stdout.trim() === "") continue;
// 1105/01-02. The frontend's copies of backend code tables.
const sources = [
...scaffoldSources.map((source) => ({ source, kind: "scaffold", reader: "the generator" })),
...codeSources.map((source) => ({ source, kind: "code", reader: "the frontend" })),
];
for (const { source, kind, reader } of sources) {
const sourceDiff = git(directory, "diff", "--unified=0", `${commit}..HEAD`, "--", source.path);
if (sourceDiff.stdout.trim() === "") continue;
failures.push(
`scaffold source ${scaffold.path} changed between the pin ${commit.slice(0, 12)} and HEAD ${headCommit.slice(0, 12)}`,
`${kind} source ${source.path} changed between the pin ${commit.slice(0, 12)} and HEAD ${headCommit.slice(0, 12)}`,
);
failures.push(
` the generator copies "${scaffold.fact}" from it: recheck ${scaffold.copiedTo.symbol} in ${scaffold.copiedTo.file}`,
` ${reader} copies "${source.fact}" from it: recheck ${source.copiedTo.symbol} in ${source.copiedTo.file}`,
);
}
}
@@ -183,14 +202,14 @@ function main(): void {
console.log(
headCommit === commit
? `Backend contract drift: ${directory} is at the pinned ${commit.slice(0, 12)}; the excerpt and the answer table match it`
: `Backend contract drift: HEAD ${headCommit.slice(0, 12)} is past the pin ${commit.slice(0, 12)}, ${document} and ${scaffoldSources.length} scaffold sources unchanged; the excerpt and the answer table match it`,
: `Backend contract drift: HEAD ${headCommit.slice(0, 12)} is past the pin ${commit.slice(0, 12)}, ${document}, ${scaffoldSources.length} scaffold sources and ${codeSources.length} code sources unchanged; the excerpt and the answer table match it`,
);
return;
}
console.error("Backend contract drift:");
for (const failure of failures) console.error(` ${failure}`);
console.error(
`Recheck docs/architecture/backend-api-and-server-state-contract.md 6.1, ${pin.tables.idempotencyAnswers}, ${pin.tables.backendExcerpt}, the generator copies of changed scaffold sources and ${PIN_PATH} together.`,
`Recheck docs/architecture/backend-api-and-server-state-contract.md 6.1, ${pin.tables.idempotencyAnswers}, ${pin.tables.backendExcerpt}, the copies of changed scaffold and code sources and ${PIN_PATH} together.`,
);
process.exitCode = 1;
}
@@ -94,6 +94,13 @@ export async function collectStaticAssets(
});
}
// 0925/06-08. Nothing under the directory means vite.config.ts moved the
// hashed files (`build.assetsDir`) away from the one the worker reads.
if (assets.length === 0) {
throw new Error(
`No hashed static asset under ${BUILD_ASSET_DIRECTORY} in the build: vite.config.ts build.assetsDir must name the directory BUILD_ASSET_DIRECTORY (src/contracts/service-worker.ts) names.`,
);
}
// 1112/06-02. The count and the bound, so the failure says how far over
// it is. Each generated feature adds its lazy chunks here: with the Service
// Worker on, the asset bound can come before the initial JavaScript budget.
+55 -6
View File
@@ -37,8 +37,8 @@ import type { AuthOperationContext } from "./http-execution-v3.ts";
/**
* 2026-11-03 01-01. A client for the paired backend Fileserver's multipart
* single upload, `POST /v1/files` (clean-architecture-backend-template
* `45d2a478`, the commit config/contracts/backend-contract-pin.json pins;
* single upload, `POST /v1/files` (clean-architecture-backend-template at
* the commit config/contracts/backend-contract-pin.json pins;
* docs/fileserver/http-contract.md and its code; Envelope and idempotency in
* docs/web/http-contract.md §1–§2).
*
@@ -115,7 +115,7 @@ export type FileserverUploadRequest = Readonly<{
mediaType?: string;
/**
* Sent as `Idempotency-Key`. After a `MAYBE_APPLIED` failure, resend with
* the same key and never a new one. At `45d2a478` the backend runs
* the same key and never a new one. At the pinned backend commit it runs
* `POST /v1/files` without its idempotency executor, so the key protects
* only a deployment that routes the upload through it.
*/
@@ -143,6 +143,16 @@ export type FileserverUploadClientDependencies = Readonly<{
}>,
context: AuthOperationContext,
): Promise<CredentialPatchOutcome> | CredentialPatchOutcome;
/**
* 1112/07-01. Called once when the server answers an upload 401, with the
* operation and the profile, before the `AUTH_REQUIRED` failure returns.
* The V3 executor's 401 goes to whoever supplied the credential; pass the
* composition's `credentials` (both fields) so the upload's goes the same
* way. A throw is ignored.
*/
onUnauthenticated?(
binding: Readonly<{ operationId: string; authProfileId: string }>,
): void;
/** A larger file is refused before it is read. */
maxFileBytes: number;
fetcher?: typeof fetch;
@@ -179,10 +189,11 @@ const MAX_FILENAME_LENGTH = 255;
* its worker raises except an ambiguous completion, and the Fileserver
* contract marks a failure that may already have taken effect with
* `details.ambiguous`. So a 4xx Envelope is NOT_APPLIED unless it says
* otherwise. A 5xx stays MAYBE_APPLIED except these codes, which the worker
* otherwise. A 5xx stays MAYBE_APPLIED except these codes, which the backend
* raises before the file is published (`FileserverErrorCode`,
* `AtomicMoveContentPublisher`). Recheck the list when the pinned backend
* commit moves; contract §6.1 says why the 4xx reading differs from its
* `AtomicMoveContentPublisher`). The pin names those backend files
* (`backend.codeSources`), so check:backend-contract-drift says when one
* changes; contract §6.1 says why the 4xx reading differs from its
* fileserver row.
*
* 1105/01-02. 504 TRANSFER_TIMEOUT is not here. The waiting servlet thread
@@ -195,9 +206,23 @@ const NOT_APPLIED_5XX_CODES: ReadonlySet<string> = new Set([
"PARTIAL_WRITE",
"ATOMIC_PUBLISH_UNSUPPORTED",
"STORAGE_UNAVAILABLE",
// 1112/02-05. From backend `697e62e8c` the instance permit and the transfer
// pool answer a full server with 503 SERVER_BUSY where they answered 429
// TRANSFER_ADMISSION_REJECTED, still before the work runs
// (`TransferAdmissionController`, `BlockingTransferExecutor`).
"SERVER_BUSY",
"STORAGE_FULL",
]);
/**
* 1105/01-02. The codes above, for the test that holds them to the copy the
* pin keeps beside the backend files they were read from
* (config/contracts/backend-contract-pin.json `backend.codeSources`).
*/
export function notAppliedFileserver5xxCodes(): readonly string[] {
return Object.freeze([...NOT_APPLIED_5XX_CODES]);
}
/**
* 1105/01-02. The web contract's own answers (idempotency §2, and the other
* codes the V3 table lists) read as the V3 executor reads them, so the same
@@ -320,6 +345,7 @@ type Settings = Readonly<{
url: string;
authProfile: RestAuthProfile;
attachCredentials: FileserverUploadClientDependencies["attachCredentials"];
onUnauthenticated: FileserverUploadClientDependencies["onUnauthenticated"];
maxFileBytes: number;
timeoutMs: number;
minTransferBytesPerSecond: number;
@@ -363,6 +389,12 @@ function snapshotDependencies(
if (typeof dependencies.attachCredentials !== "function") {
invalid("attachCredentials");
}
if (
dependencies.onUnauthenticated !== undefined &&
typeof dependencies.onUnauthenticated !== "function"
) {
invalid("onUnauthenticated");
}
const positive = (value: number | undefined, fallback: number, field: string) => {
const resolved = value ?? fallback;
return Number.isSafeInteger(resolved) && resolved > 0
@@ -377,6 +409,7 @@ function snapshotDependencies(
requiredCredentialHeaders: Object.freeze([...profile.requiredCredentialHeaders]),
}),
attachCredentials: dependencies.attachCredentials,
onUnauthenticated: dependencies.onUnauthenticated,
maxFileBytes: positive(dependencies.maxFileBytes, 0, "maxFileBytes"),
timeoutMs: positive(dependencies.timeoutMs, DEFAULTS.timeoutMs, "timeoutMs"),
minTransferBytesPerSecond: positive(
@@ -608,6 +641,19 @@ async function credentialHeaders(
}
}
function reportUnauthenticated(settings: Settings): void {
try {
settings.onUnauthenticated?.(
Object.freeze({
operationId: FILESERVER_UPLOAD_OPERATION_ID,
authProfileId: settings.authProfile.authProfileId,
}),
);
} catch {
// A hook defect cannot change the upload's own outcome.
}
}
async function readAnswer(
response: Response,
attempt: AbortableOperation,
@@ -616,6 +662,9 @@ async function readAnswer(
sentBytes: number,
): Promise<Result<FileserverUploadedFile, AppFailure>> {
const status = response.status;
// 1112/07-01. The server's verdict on the credential this upload carried,
// whatever the body says, as a V3 401 is.
if (status === 401) reportUnauthenticated(settings);
const created = status === 201 || status === 202;
// A 2xx the contract does not list says something happened; what is unknown.
const effect: FailureEffectCertainty = created
@@ -9,7 +9,10 @@ import {
createServiceWorkerRuntime,
type WorkerScopeLike,
} from "./service-worker-lifecycle.ts";
import { parseServiceWorkerMessage } from "./service-worker-protocol.ts";
import {
createServiceWorkerMessage,
parseServiceWorkerMessage,
} from "./service-worker-protocol.ts";
/**
* §17.1. The one physical worker entry for this scope.
@@ -166,12 +169,14 @@ if (handlers.includes("OFFLINE_SYNC_WAKEUP")) {
event.waitUntil(
self.clients.matchAll({ type: "window" }).then((clients) => {
for (const client of clients) {
client.postMessage({
protocolVersion: 1,
kind: "SYNC_WAKE_OBSERVED",
messageId: crypto.randomUUID(),
sourceBuildId: identity.buildId,
});
// 1101 R3. Built like every other message, so a protocol version
// change reaches this one too.
client.postMessage(
createServiceWorkerMessage({
kind: "SYNC_WAKE_OBSERVED",
sourceBuildId: identity.buildId,
}),
);
}
}),
);
@@ -161,12 +161,12 @@ export function createServiceWorkerRuntime(
const previous = highestOld?.cacheName ?? oldCaches.at(-1) ?? null;
// Q-6.6-9. Stale caches go first: when storage is full the marker write
// below is what fails, and deleting is the only way space comes back.
// The current cache and one previous one (the rollback target) stay.
const stale = selectCachesToDelete(names, current, previous);
let deleted = 0;
for (const name of stale) {
if (await scope.caches.delete(name).catch(() => false)) deleted += 1;
}
void SERVICE_WORKER_BOUNDS.retainedPreviousCaches;
if (
!currentMarker ||
currentMarker.activationSequence < (highestOld?.activationSequence ?? 0)
@@ -188,6 +188,9 @@ export function createServiceWorkerPageController(
if (registration.waiting) {
observe("register", "UPDATE_WAITING");
// 1103/09-05. The waiting update was installed before this page looked;
// its listeners hear it as they hear one found later.
notify(updateWaitingListeners);
return Object.freeze({ kind: "UPDATE_WAITING" as const });
}
// R-6.4. On a first visit `register()` resolves while the only worker is
@@ -339,6 +342,10 @@ export function createServiceWorkerPageController(
watched.active
) {
notify(updateWaitingListeners);
} else if (worker.state === "redundant" && watched.active) {
// 0925/06-05. An update that failed to install leaves this page on
// its build with nothing waiting; only this record says why.
observe("update_install", "REDUNDANT");
}
});
};
@@ -357,7 +364,9 @@ export function createServiceWorkerPageController(
updateTimer = setInterval(() => {
if (page?.visibilityState === "hidden") return;
void registration?.update().catch(() => {
// A failed update check never fails a product flow.
// A failed update check never fails a product flow. 0925/06-05: it is
// recorded, so a deployment that never updates says so.
observe("update_check", "FAILED");
});
}, SERVICE_WORKER_BOUNDS.updateCheckIntervalMs);
}
@@ -13,9 +13,6 @@ import {
*/
const MESSAGE_KINDS: ReadonlySet<string> = new Set<ServiceWorkerMessageKind>([
"PAGE_HELLO",
"WORKER_HELLO_ACK",
"UPDATE_READY",
"ACTIVATE_REQUEST",
"ACTIVATE_ACCEPTED",
"ACTIVATE_REJECTED",
@@ -125,6 +125,9 @@ export function validateStaticAssetManifest(
) {
return rejected("MANIFEST_INVALID");
}
// 0925/06-08. A build whose `build.assetsDir` left `BUILD_ASSET_DIRECTORY`
// generates no assets; installing that would serve nothing, silently.
if (manifest.assets.length === 0) return rejected("MANIFEST_INVALID");
if (manifest.assets.length > bounds.assets) {
return rejected("ASSET_COUNT_EXCEEDED");
}
@@ -233,6 +236,7 @@ async function installCandidate(
const queue = [...manifest.assets];
let failure: InstallOutcome | null = null;
const previous = await previousStaticCaches(dependencies.caches, cacheName);
const worker = async (): Promise<void> => {
for (;;) {
@@ -244,7 +248,9 @@ async function installCandidate(
}
const asset = queue.shift();
if (!asset) return;
const outcome = await storeAsset(asset, cache, dependencies, signal);
const outcome = (await reuseVerifiedAsset(asset, cache, previous, dependencies, signal))
? null
: await storeAsset(asset, cache, dependencies, signal);
if (outcome) {
failure ??= outcome;
abortController.abort();
@@ -265,6 +271,67 @@ async function installCandidate(
});
}
/**
* 1101/06-05. The verified caches of earlier releases still in this origin,
* newest last. Each asset URL is content-hashed, so an unchanged file keeps
* its URL from release to release.
*/
async function previousStaticCaches(
caches: InstallDependencies["caches"],
cacheName: string,
): Promise<readonly Cache[]> {
try {
const names = ((await caches.keys?.()) ?? []).filter(
(name) => isOwnedStaticCacheName(name) && name !== cacheName,
);
return Object.freeze(await Promise.all(names.map((name) => caches.open(name))));
} catch {
return Object.freeze([]);
}
}
/**
* 1101/06-05. Copies an asset an earlier release already cached instead of
* downloading it again, after checking its bytes against this manifest's
* digest exactly as a download is checked. Anything else (no copy, another
* size or digest, a cache that throws) is a miss and the asset is fetched.
*/
async function reuseVerifiedAsset(
asset: StaticAssetManifestV1["assets"][number],
cache: Cache,
previous: readonly Cache[],
dependencies: InstallDependencies,
signal: AbortSignal,
): Promise<boolean> {
for (const candidate of [...previous].reverse()) {
if (signal.aborted) return false;
try {
const found = await abortable(Promise.resolve(candidate.match(asset.url)), signal);
if (found === ABORTED) return false;
if (!found || found.status !== 200) continue;
// The copy keeps its stored headers, so they pass the download's check.
if (!contentTypeMatches(found, asset.contentType)) continue;
const body = await readBoundedBody(found, asset.bytes, signal);
if (!body.ok) continue;
const digest = await abortable(Promise.resolve(dependencies.digest(body.bytes)), signal);
if (digest === ABORTED) return false;
if (digest !== asset.sha256) continue;
await cache.put(
asset.url,
new Response(body.bytes.slice(), {
status: found.status,
statusText: found.statusText,
headers: found.headers,
}),
);
return true;
} catch {
// A broken earlier cache is a miss, never an install failure.
}
}
return false;
}
async function storeAsset(
asset: StaticAssetManifestV1["assets"][number],
cache: Cache,
@@ -298,18 +365,7 @@ async function storeAsset(
if (response.status !== 200 || response.type === "opaque") {
return rejected("STATUS_INVALID");
}
const contentType =
response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ??
"";
const expectedType = asset.contentType.toLowerCase();
if (
contentType !== expectedType &&
// R-6.5. Servers still send `application/javascript` for `.js`.
!(
JAVASCRIPT_MIME_TYPES.has(contentType) &&
JAVASCRIPT_MIME_TYPES.has(expectedType)
)
) {
if (!contentTypeMatches(response, asset.contentType)) {
return rejected("CONTENT_TYPE_INVALID");
}
@@ -347,6 +403,18 @@ async function storeAsset(
return null;
}
function contentTypeMatches(response: Response, expected: string): boolean {
const contentType =
response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ??
"";
const expectedType = expected.toLowerCase();
return (
contentType === expectedType ||
// R-6.5. Servers still send `application/javascript` for `.js`.
(JAVASCRIPT_MIME_TYPES.has(contentType) && JAVASCRIPT_MIME_TYPES.has(expectedType))
);
}
/** WHATWG MIME Sniffing: every essence that denotes a JavaScript MIME type. */
const JAVASCRIPT_MIME_TYPES: ReadonlySet<string> = new Set([
"application/ecmascript",
@@ -7,7 +7,10 @@ import {
type WebPushObserver,
type WebPushResult,
} from "../../../contracts/web-push.ts";
import type { PushAssociationFenceStore } from "../push-association-fence-store.ts";
import {
type PushAssociationFenceStore,
validateActivePushFence,
} from "../push-association-fence-store.ts";
import { decodeNotificationClickData } from "../push-codec.ts";
import type { WebPushNotificationRegistry } from "../notification-registry.ts";
import {
@@ -353,30 +356,17 @@ export function createNotificationClickAdapter(dependencies: Readonly<{
);
}
async function validateActiveFence(
function validateActiveFence(
associationEpoch: string,
releaseEpoch: string,
signal: AbortSignal,
): Promise<WebPushResult<void>> {
const control = await dependencies.fenceStore.read({ signal });
if (!control.ok) return control;
if (
!control.value ||
control.value.control.association.state !== "ACTIVE" ||
control.value.control.association.associationEpoch !==
associationEpoch
) {
return webPushFailure(
"ASSOCIATION_MISMATCH",
"NOTIFICATION_CLICK",
);
}
return control.value.control.releaseEpoch === releaseEpoch
? webPushSuccess(undefined)
: webPushFailure(
"RELEASE_MISMATCH",
"NOTIFICATION_CLICK",
);
return validateActivePushFence(
dependencies.fenceStore,
{ associationEpoch, releaseEpoch },
"NOTIFICATION_CLICK",
signal,
);
}
}
@@ -6,7 +6,10 @@ import {
type WebPushObserver,
type WebPushResult,
} from "../../../contracts/web-push.ts";
import type { PushAssociationFenceStore } from "../push-association-fence-store.ts";
import {
type PushAssociationFenceStore,
validateActivePushFence,
} from "../push-association-fence-store.ts";
import {
clickDataFromHint,
decodeWebPushHint,
@@ -193,23 +196,16 @@ export function createPushEventAdapter(dependencies: Readonly<{
return webPushSuccess(undefined);
}
async function validateActiveFence(
function validateActiveFence(
associationEpoch: string,
releaseEpoch: string,
signal: AbortSignal,
): Promise<WebPushResult<void>> {
const control = await dependencies.fenceStore.read({ signal });
if (!control.ok) return control;
if (
!control.value ||
control.value.control.association.state !== "ACTIVE" ||
control.value.control.association.associationEpoch !==
associationEpoch
) {
return webPushFailure("ASSOCIATION_MISMATCH", "PUSH_HANDLE");
}
return control.value.control.releaseEpoch === releaseEpoch
? webPushSuccess(undefined)
: webPushFailure("RELEASE_MISMATCH", "PUSH_HANDLE");
return validateActivePushFence(
dependencies.fenceStore,
{ associationEpoch, releaseEpoch },
"PUSH_HANDLE",
signal,
);
}
}
@@ -144,6 +144,32 @@ export interface PushAssociationFenceStore {
close(): void;
}
/**
* 1101 R2. The fence a push and a notification click both pass before they
* act: an ACTIVE association with the same epoch, then the same release.
* One copy, so the two inbound adapters cannot drift apart.
*/
export async function validateActivePushFence(
fenceStore: Pick<PushAssociationFenceStore, "read">,
expected: Readonly<{ associationEpoch: string; releaseEpoch: string }>,
operation: WebPushOperation,
signal: AbortSignal,
): Promise<WebPushResult<void>> {
const control = await fenceStore.read({ signal });
if (!control.ok) return control;
if (
!control.value ||
control.value.control.association.state !== "ACTIVE" ||
control.value.control.association.associationEpoch !==
expected.associationEpoch
) {
return webPushFailure("ASSOCIATION_MISMATCH", operation);
}
return control.value.control.releaseEpoch === expected.releaseEpoch
? webPushSuccess(undefined)
: webPushFailure("RELEASE_MISMATCH", operation);
}
export type PushAssociationFenceStoreDependencies = Readonly<{
repository: PushControlRepository;
idempotencyKeyFactory?: () => string;
@@ -68,11 +68,17 @@ export async function createRuntimeComposition(
: {}),
});
const disconnectProductServiceWorker = connectProductServiceWorker(
optional.serviceWorker,
productServiceWorker,
);
return Object.freeze({
...root,
capabilities,
optional,
async dispose(): Promise<void> {
disconnectProductServiceWorker();
// §20.3. Optional runtime first, then the base infrastructure: the query
// cache is cleared only after realtime and worker admission has closed,
// so a late effect cannot repopulate a cleared cache.
@@ -113,3 +119,42 @@ function serviceWorkerWiring(
: {}),
};
}
/**
* 1103/09-05. The product's update notice and reload prompt, subscribed
* before the worker starts so a waiting update found at start reaches them.
* Their throws are product code and are dropped. Returns the unsubscribe.
*/
function connectProductServiceWorker(
host: OptionalRuntimeHost["serviceWorker"],
wiring: ProductServiceWorkerWiring | null | undefined,
): () => void {
if (!host || !wiring) return () => {};
const unsubscribes: (() => void)[] = [];
const { onUpdateWaiting, onReloadRequired } = wiring;
if (onUpdateWaiting && host.onUpdateWaiting) {
unsubscribes.push(
host.onUpdateWaiting(() => {
try {
onUpdateWaiting(() => host.requestActivation());
} catch {
// A failing product notice never changes the worker's outcome.
}
}),
);
}
if (onReloadRequired && host.onReloadRequired) {
unsubscribes.push(
host.onReloadRequired(() => {
try {
onReloadRequired();
} catch {
// As above.
}
}),
);
}
return () => {
for (const unsubscribe of unsubscribes.splice(0)) unsubscribe();
};
}
@@ -3,6 +3,7 @@ import type {
ContractHttpExecutorDependencies,
InstalledHttpOperationExecutor,
} from "../adapters/http/index.ts";
import type { ServiceWorkerActivationOutcome } from "../contracts/service-worker.ts";
import type { FeaturePlatformCapabilities } from "../features/feature-adapter-contribution.ts";
import type { RuntimeConfig } from "./runtime-config-schema.ts";
@@ -78,6 +79,27 @@ export type TemplatePlatformCapabilityId = "http" | "telemetry";
export type ProductCredentialProvider =
ContractHttpExecutorDependencies["attachCredentials"];
/**
* 1112/07-01. The template's own credentials for a request the product sends
* itself rather than through `http`, such as a Fileserver upload
* (`FileserverUploadClientDependencies`): spread it into that capability.
*
* - `attachCredentials` decides as the V3 executor's does: the scope fence,
* then the ANONYMOUS profile, then `credentialProviders`, then the template
* session (an `EXTERNAL_BEARER` upload gets the session owner's bearer this
* way), then the fence again.
* - `onUnauthenticated` takes the server's 401 to that request the same way
* a V3 401 goes: to `onCredentialRejected` for a product provider's
* credential, to the template session for its own, to nobody for an
* ANONYMOUS one.
*/
export type ProductRequestCredentials = Readonly<{
attachCredentials: ProductCredentialProvider;
onUnauthenticated(
binding: Readonly<{ operationId: string; authProfileId: string }>,
): void;
}>;
export type ProductCompositionContext = Readonly<{
/** Validated runtime config, product keys included. */
config: RuntimeConfig;
@@ -98,6 +120,11 @@ export type ProductCompositionContext = Readonly<{
* credential is not the session's, such as another API's token.
*/
notifySessionUnauthenticated(): void;
/**
* 1112/07-01. Call it per request: called while `composeProduct` runs it
* throws a `TypeError`.
*/
credentials: ProductRequestCredentials;
}>;
/**
@@ -136,6 +163,21 @@ export type ProductServiceWorkerWiring = Readonly<{
* `client_drain`, ...), each with its outcome. A throw is ignored.
*/
observe?(observation: Readonly<{ event: string; outcome: string }>): void;
/**
* 1103/09-05. An update finished installing and waits for this tab, found
* when the worker starts or later: show the product's "new version" notice
* and call `activate()` when the user agrees. `activate()` is
* `requestActivation()`, so `blockers` still apply. A throw is ignored.
*/
onUpdateWaiting?(
activate: () => Promise<ServiceWorkerActivationOutcome>,
): void;
/**
* 1103/09-05. A worker of another build took over (this tab asked, or
* another one did), so this page runs old code: ask the user to reload, or
* reload. A throw is ignored.
*/
onReloadRequired?(): void;
}>;
export type ProductComposition = Readonly<{
+96 -62
View File
@@ -68,6 +68,7 @@ import {
} from "./product-composition.ts";
import type {
ProductComposition,
ProductCredentialProvider,
ProductScopeParticipant,
} from "./product-composition-contract.ts";
import { createProductSessionOwnerContext } from "./product-session-owner-context.ts";
@@ -535,60 +536,83 @@ export async function createRuntimeAdapters(
diagnostics,
telemetry,
});
const contractHttp = createRuntimeContractHttpExecutor(config, {
fetcher: context.fetcher,
async attachCredentials(operation, authContext) {
/**
* 1112/02-10. Who supplies the credential of an auth profile, and so who
* hears the server's 401 to it. `attachCredentials` and
* `reportServerUnauthenticated` both read this one decision. 09-01: an
* ANONYMOUS profile admits no credential header at all, so nobody supplies
* one. 09-02: a product provider answers for its own profiles before the
* session. Every other profile needs the session and never downgrades to
* anonymous. `productCredentialProviders` is set below, before any request
* can run.
*/
let productComposed = false;
function credentialOwner(authProfileId: string): "NONE" | "PRODUCT" | "SESSION" {
// `context.credentials` is for requests: called while `composeProduct`
// runs, the provider table does not exist yet.
if (!productComposed) {
throw new TypeError(
"context.credentials is called per request, not while composeProduct runs.",
);
}
if (INSTALLED_REST_AUTH_PROFILES.get(authProfileId)?.transport === "ANONYMOUS") {
return "NONE";
}
return Object.hasOwn(productCredentialProviders, authProfileId)
? "PRODUCT"
: "SESSION";
}
const attachCredentials: ProductCredentialProvider = async (
operation,
authContext,
) => {
// Decided first (it reads no state); nothing is asked before the fence.
const owner = credentialOwner(operation.authProfileId);
if (serverStateScope.getPhase() !== "READY") {
return Object.freeze({ kind: "SCOPE_FENCED" as const });
}
if (owner === "NONE") {
return Object.freeze({ kind: "READY" as const, headers: {} });
}
// A throw is left to the executor, which closes it as
// CREDENTIAL_OWNER_FAILED.
if (owner === "PRODUCT") {
const provider = productCredentialProviders[operation.authProfileId];
const answer = await provider(operation, authContext);
return serverStateScope.getPhase() === "READY"
? answer
: Object.freeze({ kind: "SCOPE_FENCED" as const });
}
const state = authSession.getState();
if (state === "integration-failed") {
return Object.freeze({ kind: "UNAVAILABLE" as const });
}
if (state !== "authenticated") {
return Object.freeze({ kind: "UNAUTHENTICATED" as const });
}
try {
const patch = await authSession.credentialPatch(
{
origin: new URL(config.API_BASE_URL).origin,
method: operation.method,
operationId: operation.operationId,
},
authContext,
);
if (serverStateScope.getPhase() !== "READY") {
return Object.freeze({ kind: "SCOPE_FENCED" as const });
}
// 09-01. The operation's installed profile decides first, the session
// second. An ANONYMOUS profile admits no credential header at all, so it
// goes out bare in every session state and never reaches the owner. Every
// other profile still needs a session and never downgrades to anonymous.
if (
INSTALLED_REST_AUTH_PROFILES.get(operation.authProfileId)?.transport ===
"ANONYMOUS"
) {
return Object.freeze({ kind: "READY" as const, headers: {} });
}
// 09-02. A product provider answers for its own profiles, between the
// checks above and the session. A throw is left to the executor, which
// closes it as CREDENTIAL_OWNER_FAILED. `productCredentialProviders` is
// set below, before any request can run.
if (Object.hasOwn(productCredentialProviders, operation.authProfileId)) {
const provider = productCredentialProviders[operation.authProfileId];
const answer = await provider(operation, authContext);
return serverStateScope.getPhase() === "READY"
? answer
: Object.freeze({ kind: "SCOPE_FENCED" as const });
}
const state = authSession.getState();
if (state === "integration-failed") {
return Object.freeze({ kind: "UNAVAILABLE" as const });
}
if (state !== "authenticated") {
return Object.freeze({ kind: "UNAUTHENTICATED" as const });
}
try {
const patch = await authSession.credentialPatch(
{
origin: new URL(config.API_BASE_URL).origin,
method: operation.method,
operationId: operation.operationId,
},
authContext,
);
if (serverStateScope.getPhase() !== "READY") {
return Object.freeze({ kind: "SCOPE_FENCED" as const });
}
return Object.freeze({
kind: "READY" as const,
headers: patch.headers,
});
} catch {
return Object.freeze({ kind: "UNAVAILABLE" as const });
}
},
return Object.freeze({
kind: "READY" as const,
headers: patch.headers,
});
} catch {
return Object.freeze({ kind: "UNAVAILABLE" as const });
}
};
const contractHttp = createRuntimeContractHttpExecutor(config, {
fetcher: context.fetcher,
attachCredentials,
observe: observeHttpExecution,
});
// 15-01. Filled one feature at a time as feature runtimes load; an
@@ -597,21 +621,24 @@ export async function createRuntimeAdapters(
const contractRegistry = createInstalledContractRegistry();
/**
* 1103/09-01. A 401 judges the credential the request carried, so it goes to
* whoever supplied it, decided in the same order as `attachCredentials`. An
* ANONYMOUS request carried none: nobody is told. A product provider's
* credential: the product is told, the session is not. Only the session's
* own credential signs the session out.
* whoever supplied it (`credentialOwner`). An ANONYMOUS request carried
* none: nobody is told. A product provider's credential: the product is
* told, the session is not. Only the session's own credential signs the
* session out.
*/
function reportServerUnauthenticated(
authProfileId: string,
binding: Readonly<{ operationId: string; authProfileId: string }>,
): void {
if (INSTALLED_REST_AUTH_PROFILES.get(authProfileId)?.transport === "ANONYMOUS") {
return;
}
if (Object.hasOwn(productCredentialProviders, authProfileId)) {
const owner = credentialOwner(binding.authProfileId);
if (owner === "NONE") return;
if (owner === "PRODUCT") {
try {
onProductCredentialRejected?.(Object.freeze(binding));
onProductCredentialRejected?.(
Object.freeze({
operationId: binding.operationId,
authProfileId: binding.authProfileId,
}),
);
} catch {
// A product hook defect cannot change the contract execution outcome.
}
@@ -673,7 +700,7 @@ export async function createRuntimeAdapters(
// dispatch for lack of a credential carries no response metadata; telling
// the owner would overwrite a recovering session and re-fence the scope.
if (outcome.kind === "UNAUTHENTICATED" && outcome.metadata !== undefined) {
reportServerUnauthenticated(executableContract.frontend.authProfileId, {
reportServerUnauthenticated({
operationId: executableContract.contract.operationId,
authProfileId: executableContract.frontend.authProfileId,
});
@@ -703,12 +730,19 @@ export async function createRuntimeAdapters(
// credential: the verdict reportServerUnauthenticated gives the session's
// own 401.
notifySessionUnauthenticated: () => authSession.onUnauthenticated(),
// 1112/07-01. The same owner and 401 routing for a request the product
// sends itself, such as a Fileserver upload.
credentials: Object.freeze({
attachCredentials,
onUnauthenticated: reportServerUnauthenticated,
}),
}) satisfies ProductComposition;
// Read through the contract type: the product's own return type omits the
// optional fields when the product does not use them, and `product` keeps
// its narrow type above so a missing capability still fails the typecheck.
const productContract: ProductComposition = product;
const productCredentialProviders = productContract.credentialProviders;
productComposed = true;
const onProductCredentialRejected = productContract.onCredentialRejected;
for (const participant of productContract.scopeParticipants ?? []) {
// 1105/02-01. The label names the participant in diagnostics, so it must
-6
View File
@@ -23,9 +23,6 @@ export const SERVICE_WORKER_BOUNDS = Object.freeze({
*/
activationReplySlackMs: 5_000,
updateCheckIntervalMs: 6 * 60 * 60 * 1_000,
retainedPreviousCaches: 1,
reloadGuardBytes: 512,
reloadGuardTtlMs: 10 * 60 * 1_000,
});
export type ServiceWorkerHandlerId =
@@ -64,9 +61,6 @@ export type ServiceWorkerProtocolIdentity = Readonly<{
}>;
export type ServiceWorkerMessageKind =
| "PAGE_HELLO"
| "WORKER_HELLO_ACK"
| "UPDATE_READY"
| "ACTIVATE_REQUEST"
| "ACTIVATE_ACCEPTED"
| "ACTIVATE_REJECTED"
@@ -3,6 +3,7 @@ import type {
ApplicationFeatureInputs,
} from "../application/ports/in/application-api.ts";
import type {
FileserverUploadClientDependencies,
InstalledHttpOperationExecutor,
} from "../adapters/http/index.ts";
import type { TelemetryPort } from "../platform/telemetry/telemetry-port.ts";
@@ -57,6 +58,16 @@ export interface FeaturePlatformCapabilities
extends ProductFeaturePlatformCapabilities {
readonly http: InstalledHttpOperationExecutor;
readonly indexedDb: IndexedDbRepositoryProvider;
/**
* 1112/09-01. Opt-in like `indexedDb`: the template types it and never
* builds it. A product that uploads to the paired backend's Fileserver
* returns it from `src/bootstrap/product-composition.ts` (manual 02 §7),
* and a feature that lists it in `needs` calls `createFileserverUploadClient`
* with it. Typed here rather than in `product-capabilities.ts`, which this
* file imports: that file reading the type from here would be an import
* cycle.
*/
readonly fileserverUpload: FileserverUploadClientDependencies;
/** scale-architecture.md §24. Provider-neutral, bounded, fail-open feature telemetry. */
readonly telemetry: TelemetryPort;
}
@@ -2,6 +2,7 @@
import { describe, expect, it, vi } from "vitest";
import { createServiceWorkerMessage } from "../../src/adapters/service-worker/service-worker-protocol.ts";
import { createRuntimeComposition } from "../../src/bootstrap/create-runtime-composition.ts";
import type { ProductComposition } from "../../src/bootstrap/product-composition-contract.ts";
@@ -16,6 +17,9 @@ import type { ProductComposition } from "../../src/bootstrap/product-composition
const product = vi.hoisted(() => ({
observed: [] as Array<Readonly<{ event: string; outcome: string }>>,
dirty: true,
/** 1103/09-05. Each `activate` the product's update notice received. */
updates: [] as Array<() => Promise<unknown>>,
reloads: 0,
}));
vi.mock("../../src/features/installed-runtime-capabilities.ts", async (importOriginal) => {
@@ -46,6 +50,14 @@ vi.mock("../../src/bootstrap/product-composition.ts", () => ({
// The composition drops a throwing product sink.
throw new Error("product sink failure");
},
onUpdateWaiting(activate) {
product.updates.push(activate);
throw new Error("product notice failure");
},
onReloadRequired() {
product.reloads += 1;
throw new Error("product prompt failure");
},
},
}),
}));
@@ -98,7 +110,10 @@ async function fetcher(input: RequestInfo | URL): Promise<Response> {
}
/** This page's worker is active and the next build's is waiting. */
function updateWaitingContainer(): ServiceWorkerContainer {
function updateWaitingContainer(): ServiceWorkerContainer & {
/** Delivers a worker message to the page, as from the waiting worker. */
dispatchFromWaiting(data: unknown): void;
} {
const worker = (scriptURL: string, state: string) => ({
scriptURL,
state,
@@ -106,13 +121,16 @@ function updateWaitingContainer(): ServiceWorkerContainer {
addEventListener() {},
removeEventListener() {},
});
let waiting: ReturnType<typeof worker> | null = null;
const messageListeners = new Set<(event: MessageEvent) => void>();
const register = vi.fn(
async (scriptURL: string | URL, options?: RegistrationOptions) => {
const script = new URL(scriptURL, origin).href;
waiting = worker(script, "installed");
return {
scope: new URL(options?.scope ?? "/", origin).href,
installing: null,
waiting: worker(script, "installed"),
waiting,
active: worker(script, "activated"),
addEventListener() {},
removeEventListener() {},
@@ -125,9 +143,17 @@ function updateWaitingContainer(): ServiceWorkerContainer {
register,
getRegistration: vi.fn(async () => undefined),
getRegistrations: vi.fn(async () => []),
addEventListener() {},
removeEventListener() {},
} as unknown as ServiceWorkerContainer;
addEventListener(type: string, listener: (event: MessageEvent) => void) {
if (type === "message") messageListeners.add(listener);
},
removeEventListener(type: string, listener: (event: MessageEvent) => void) {
if (type === "message") messageListeners.delete(listener);
},
dispatchFromWaiting(data: unknown) {
const event = { data, origin, source: waiting } as unknown as MessageEvent;
for (const listener of messageListeners) listener(event);
},
} as unknown as ServiceWorkerContainer & { dispatchFromWaiting(data: unknown): void };
}
describe("1103/09-05 the product wires the worker in product-composition.ts", () => {
@@ -160,3 +186,64 @@ describe("1103/09-05 the product wires the worker in product-composition.ts", ()
}
});
});
describe("1103/09-05 the product's update notice and reload prompt", () => {
it("are called from product-composition.ts alone, and their throws are dropped", async () => {
product.updates = [];
product.reloads = 0;
product.dirty = false;
const container = updateWaitingContainer();
const composition = await createRuntimeComposition({
fetcher,
host: {
location: { origin },
navigator: { serviceWorker: container },
},
});
try {
await composition.optional.startAfterMount();
// The update was waiting when the worker started.
expect(product.updates).toHaveLength(1);
container.dispatchFromWaiting(
createServiceWorkerMessage({
kind: "ACTIVATED_RELOAD_REQUIRED",
sourceBuildId: "next-build",
}),
);
expect(product.reloads).toBe(1);
} finally {
await composition.dispose();
product.dirty = true;
}
// Disposed: the product hears nothing more.
container.dispatchFromWaiting(
createServiceWorkerMessage({
kind: "ACTIVATED_RELOAD_REQUIRED",
sourceBuildId: "next-build",
}),
);
expect(product.reloads).toBe(1);
});
it("hands the notice an activate that is requestActivation, blockers included", async () => {
product.updates = [];
const composition = await createRuntimeComposition({
fetcher,
host: {
location: { origin },
navigator: { serviceWorker: updateWaitingContainer() },
},
});
try {
await composition.optional.startAfterMount();
await expect(product.updates[0]?.()).resolves.toEqual({
kind: "BLOCKED_DIRTY_CLIENT",
});
} finally {
await composition.dispose();
}
});
});
+35 -1
View File
@@ -16,7 +16,7 @@ import type { RestAuthProfile } from "../../src/contracts/rest-profiles.ts";
/**
* 2026-11-03 01-01. The paired backend Fileserver's `POST /v1/files`, answered
* as clean-architecture-backend-template `45d2a478` (the pin) answers it in
* as clean-architecture-backend-template at the pinned commit answers it in
* code, not only as its docs/fileserver/http-contract.md lists it.
*
* 1105/01-01. The document lists 202 VERIFYING alone. The code verifies the
@@ -381,6 +381,8 @@ describe("Fileserver multipart upload — Envelope failures", () => {
// 1105/01-02. As the V3 table reads it: only an unknown result keeps the key.
{ status: 503, code: "IDEMPOTENCY_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false },
{ status: 503, code: "IDEMPOTENCY_COMPLETION_UNKNOWN", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false },
// 1112/02-05. A full server, refused before the work runs (backend 697e62e8c).
{ status: 503, code: "SERVER_BUSY", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "NOT_APPLIED", clientRetryable: true },
{ status: 507, code: "STORAGE_FULL", category: "TRANSIENT_DEPENDENCY", retryable: false, kind: "SERVER_FAILURE", effect: "NOT_APPLIED", clientRetryable: false },
// 1105/01-02. Raised by the waiting thread at any stage of the work, which
// may still publish the file: the backend's own retryable:true does not
@@ -409,6 +411,38 @@ describe("Fileserver multipart upload — Envelope failures", () => {
},
);
// 1112/07-01. A 401 is the server's verdict on the credential the upload
// carried; the composition hears it through `onUnauthenticated`.
it("tells onUnauthenticated once about a 401, and about nothing else", async () => {
const onUnauthenticated = vi.fn();
answer({ status: 401, body: failureEnvelope("UNAUTHENTICATED", "AUTH", false) });
const result = await client({ onUnauthenticated }).client.upload(upload());
expect(result).toMatchObject({ ok: false, error: { kind: "AUTH_REQUIRED" } });
expect(onUnauthenticated).toHaveBeenCalledExactlyOnceWith({
operationId: "FILESERVER_UPLOAD",
authProfileId: expect.any(String),
});
onUnauthenticated.mockClear();
answer({ status: 403, body: failureEnvelope("ACCESS_DENIED", "AUTHZ", false) });
await client({ onUnauthenticated }).client.upload(upload());
expect(onUnauthenticated).not.toHaveBeenCalled();
});
it("keeps the 401 outcome when onUnauthenticated throws", async () => {
answer({ status: 401, body: failureEnvelope("UNAUTHENTICATED", "AUTH", false) });
const result = await client({
onUnauthenticated: () => {
throw new Error("hook defect");
},
}).client.upload(upload());
expect(result).toMatchObject({ ok: false, error: { kind: "AUTH_REQUIRED" } });
});
it("carries no traceId when the failure Envelope has none", async () => {
const envelope = failureEnvelope("STORAGE_UNAVAILABLE", "TRANSIENT_DEPENDENCY", true);
answer({
+52 -2
View File
@@ -113,6 +113,16 @@ const SCAFFOLD_SOURCES = [
copiedTo: { file: "scripts/create-feature-write-slice.ts", symbol: "BACKEND_NAME_MAX_LENGTH" },
},
];
/** 1105/01-02. A backend code file the frontend reads a code table from. */
const FILESERVER_CODES =
"src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java";
const CODE_SOURCE = {
path: FILESERVER_CODES,
fact: "5xx before publishing",
copiedTo: { file: "src/adapters/http/fileserver-upload.ts", symbol: "NOT_APPLIED_5XX_CODES" },
codes: ["PARTIAL_WRITE"],
};
const CODE_SOURCES = [CODE_SOURCE];
async function commitFiles(
backend: string,
@@ -139,6 +149,10 @@ async function drift(
scaffoldHead?: string;
/** 1105/16-02. A file the pin does not name, in that later commit. */
otherHead?: string;
/** 1105/01-02. The Fileserver code file in that later commit. */
codeHead?: string;
/** S-05. Code sources the pin names, by default the one the backend has. */
codeSources?: readonly (typeof CODE_SOURCE)[];
/** Where the script looks for the backend instead of the fake one. */
backend?: string;
flags?: readonly string[];
@@ -153,6 +167,7 @@ async function drift(
{
[DOCUMENT]: contractDocument(SECTIONS),
[AGGREGATE]: "public static final int NAME_MAX_LENGTH = 100;\n",
[FILESERVER_CODES]: "PARTIAL_WRITE(500)\n",
"README.md": "backend\n",
},
"pinned",
@@ -161,6 +176,7 @@ async function drift(
...(options.head === undefined ? {} : { [DOCUMENT]: options.head }),
...(options.scaffoldHead === undefined ? {} : { [AGGREGATE]: options.scaffoldHead }),
...(options.otherHead === undefined ? {} : { "README.md": options.otherHead }),
...(options.codeHead === undefined ? {} : { [FILESERVER_CODES]: options.codeHead }),
};
if (Object.keys(later).length > 0) await commitFiles(backend, later, "after the pin");
@@ -175,7 +191,12 @@ async function drift(
};
await write("config/contracts/backend-contract-pin.json", {
schemaVersion: 1,
backend: { ...source, sectionsCompared: ["1", "2", "4"], scaffoldSources: SCAFFOLD_SOURCES },
backend: {
...source,
sectionsCompared: ["1", "2", "4"],
scaffoldSources: SCAFFOLD_SOURCES,
codeSources: options.codeSources ?? CODE_SOURCES,
},
frontend: {
contractDocument: "docs/architecture/backend-api-and-server-state-contract.md",
contractSections: ["4.1", "6", "6.1"],
@@ -328,6 +349,35 @@ describe("check:backend-contract-drift scaffold sources (1105/16-02)", { timeout
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
expect(result.stdout).toContain("1 scaffold sources unchanged");
expect(result.stdout).toContain("1 scaffold sources and 1 code sources unchanged");
});
});
/**
* 1105/01-02. The upload client reads some Fileserver 5xx codes as refused
* before publishing. That table was read by hand from the backend, outside
* every pin comparison, so a backend code change left it with no signal.
*
* 1112/02-05. A source path the pinned commit does not have (the backend moved
* its folders) was read as a deletion between the pin and HEAD, and a pin
* that named the old path at the new commit compared nothing.
*/
describe("check:backend-contract-drift code sources (1105/01-02, 1112/02-05)", { timeout: childProcessTimeout(502) }, () => {
it("reports a code source the frontend copies a table from, with where the copy is", async () => {
const result = await drift({ codeHead: "PARTIAL_WRITE(503)\n" });
expect(result.status, result.stdout + result.stderr).toBe(1);
expect(result.stderr).toContain(`code source ${FILESERVER_CODES} changed`);
expect(result.stderr).toContain(
"recheck NOT_APPLIED_5XX_CODES in src/adapters/http/fileserver-upload.ts",
);
});
it("fails on a source the pinned commit does not have", async () => {
const moved = "src/application-fileserver/FileserverErrorCode.java";
const result = await drift({ codeSources: [{ ...CODE_SOURCE, path: moved }] });
expect(result.status, result.stdout + result.stderr).toBe(1);
expect(result.stderr).toContain(`${moved} is not in the pinned`);
});
});
@@ -39,20 +39,12 @@ function codesPossiblyAfterWrite(): ReadonlySet<string> {
}
/**
* Rows of that table whose stage the endpoint decides: the reference domain's
* codes and web-advanced's patch codes ("부르는 코드가 단계를 정한다"). A
* feature author who checked the endpoint may declare them.
* Rows of that table whose stage the endpoint decides: web-advanced's patch
* codes ("부르는 코드가 단계를 정한다"). A feature author who checked the
* endpoint may declare them. 1112/02-05: the reference domain's codes went
* with the backend sample module, and with them their row.
*/
const FEATURE_DECIDED_CODES: readonly string[] = [
"WORKLOG_INVALID",
"POSTER_INVALID_STATE",
"POSTER_IMAGE_REQUIRED",
"WORKLOG_CONFLICT",
"POSTER_ALREADY_EXISTS",
"POSTER_IMAGE_ALREADY_PUBLISHED",
"PATCH_REJECTED",
"PATCH_TEST_FAILED",
];
const FEATURE_DECIDED_CODES: readonly string[] = ["PATCH_REJECTED", "PATCH_TEST_FAILED"];
describe("platform codes no operation may declare as refused before its write", () => {
it("are the 6.1 table's possibly-after-write codes outside the feature-decided rows", () => {
+39
View File
@@ -13,6 +13,7 @@ import {
maybeAppliedAnswerRows,
refusedBeforeWriteRows,
} from "../../src/adapters/http/backend-envelope.ts";
import { notAppliedFileserver5xxCodes } from "../../src/adapters/http/fileserver-upload.ts";
/**
* 1103/12-06. The paired backend's contract is pinned in a file a machine
@@ -56,6 +57,22 @@ const pinSchema = z
.strict(),
)
.min(1),
// 1105/01-02. Backend code files the frontend reads a code table from;
// `codes` is the copied table where the frontend keeps one.
codeSources: z
.array(
z
.object({
path: z.string().min(1),
fact: z.string().min(1),
copiedTo: z
.object({ file: z.string().min(1), symbol: z.string().min(1) })
.strict(),
codes: z.array(z.string().regex(/^[A-Z0-9_]{1,64}$/u)).min(1).optional(),
})
.strict(),
)
.min(1),
})
.strict(),
frontend: z
@@ -211,6 +228,28 @@ describe("paired backend contract pin", () => {
);
});
/**
* 1105/01-02. The upload client reads some Fileserver 5xx codes as refused
* before publishing. The pin keeps that table beside the backend files it
* was read from, so a code that changes on either side fails here, and
* check:backend-contract-drift says when one of those files changes.
*/
it("holds the upload client's Fileserver 5xx table to the pin's copy", () => {
const paths = pin.backend.codeSources.map((source) => source.path);
expect(new Set(paths).size).toBe(paths.length);
for (const source of pin.backend.codeSources) {
expect(readFileSync(source.copiedTo.file, "utf8"), source.path).toContain(
source.copiedTo.symbol,
);
expect(pin.frontend.readers, source.path).toContain(source.copiedTo.file);
}
const tables = pin.backend.codeSources.filter(
(source) => source.copiedTo.symbol === "NOT_APPLIED_5XX_CODES" && source.codes !== undefined,
);
expect(tables).toHaveLength(1);
expect([...notAppliedFileserver5xxCodes()].sort()).toEqual([...(tables[0]?.codes ?? [])].sort());
});
it("copies each backend answer once", () => {
const keys = table.answers.map((answer) => `${answer.status} ${answer.code}`);
expect(new Set(keys).size).toBe(keys.length);
+15 -1
View File
@@ -30,12 +30,22 @@ import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
* well have built `invoice-feature`. So the copy gets the reserved probe
* feature instead, and every block and check is renamed to it on the way in
* (`renameFeatureText`): paths, constants, types and words alike.
*
* 1112/09-01. A block may also be a whole product-owned file the template
* ships empty, such as the upload composition of manual 02 §7: it replaces
* that file in the copy.
*/
const MANUAL = "docs/manual";
const FEATURE_ID = MANUAL_PROBE_FEATURE_ID;
const toProbe = (text: string) => renameFeatureText(text, MANUAL_EXAMPLE_FEATURE_ID, FEATURE_ID);
const CHECKS = "tests/fixtures/manual-code-blocks";
const MARKED_BLOCK = /<!-- manual-code-block: (\S+) -->\n```tsx?\n([\s\S]*?)\n```/gu;
/** Product-owned files a block may replace whole; every other block adds a file. */
const PRODUCT_OWNED_FILES: ReadonlySet<string> = new Set([
"src/bootstrap/product-composition.ts",
"src/contracts/product-contracts.ts",
"src/features/product-capabilities.ts",
]);
async function manualDocuments(directory: string): Promise<string[]> {
const documents: string[] = [];
@@ -90,6 +100,8 @@ describe("docs/manual code blocks, pasted into a generated feature", () => {
const targets = [...(await markedBlocks()).keys()].sort();
expect(targets).toEqual([
"src/bootstrap/product-composition.ts",
"src/features/invoice-feature/adapters/invoice-attachment-uploads.ts",
"src/features/invoice-feature/adapters/invoice-problem-mapping.ts",
"src/features/invoice-feature/contracts/invoice-list-search.ts",
"src/features/invoice-feature/contracts/invoice-problem-details.ts",
@@ -114,7 +126,9 @@ describe("docs/manual code blocks, pasted into a generated feature", () => {
for (const [target, block] of blocks) {
const file = path.join(root, toProbe(target));
// A block adds a file; it never stands in for one the command wrote.
expect(existsSync(file), `${target} exists before the block is pasted`).toBe(false);
expect(existsSync(file), `${target} exists before the block is pasted`).toBe(
PRODUCT_OWNED_FILES.has(target),
);
await mkdir(path.dirname(file), { recursive: true });
await writeFile(file, toProbe(block));
}
@@ -1,7 +1,14 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts";
import type { ProductCredentialProvider } from "../../src/bootstrap/product-composition-contract.ts";
import {
createFileserverUploadClient,
type InstalledHttpOperationExecutor,
} from "../../src/adapters/http/index.ts";
import type {
ProductCompositionContext,
ProductCredentialProvider,
} from "../../src/bootstrap/product-composition-contract.ts";
import { REST_AUTH_PROFILES } from "../../src/contracts/rest-profiles.ts";
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts";
import { testRuntimeConfig } from "../helpers/runtime-config.ts";
@@ -22,6 +29,8 @@ const fixture = vi.hoisted(() => ({
http: undefined as InstalledHttpOperationExecutor | undefined,
providers: {} as Record<string, unknown>,
onCredentialRejected: undefined as ((binding: unknown) => void) | undefined,
context: undefined as unknown,
onCompose: undefined as ((context: unknown) => void) | undefined,
withProfile<T extends { contract: object; frontend: object }>(
contract: T,
operationId: string,
@@ -80,13 +89,17 @@ vi.mock("../../src/features/installed-feature-adapters.ts", async (importOrigina
/** The product-owned file, filled the way a product fills it. */
vi.mock("../../src/bootstrap/product-composition.ts", () => ({
composeProductSessionOwner: () => null,
composeProduct: () => ({
composeProduct: (context: unknown) => {
fixture.context = context;
fixture.onCompose?.(context);
return {
capabilities: {},
credentialProviders: fixture.providers,
...(fixture.onCredentialRejected === undefined
? {}
: { onCredentialRejected: fixture.onCredentialRejected }),
}),
};
},
}));
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
@@ -178,6 +191,8 @@ afterEach(() => {
fixture.http = undefined;
fixture.providers = {};
fixture.onCredentialRejected = undefined;
fixture.context = undefined;
fixture.onCompose = undefined;
});
async function compose(
@@ -418,3 +433,168 @@ describe("1103/09-01 a 401 to a product provider's credential", () => {
expect(rejected).not.toHaveBeenCalled();
});
});
/**
* 1112/02-10, 1112/07-01. Whoever supplies a request's credential hears the
* server's 401 to it, for a V3 request and for an upload the product sends
* through `context.credentials`, one profile kind per row. The two answers
* come from one decision in the composition root; an order changed on one
* side only fails a row here.
*/
describe("1112/02-10 the credential's owner is the 401's owner", () => {
const unauthorized = () =>
Response.json(
{
success: false,
error: { code: "UNAUTHENTICATED", category: "AUTH", message: "x", retryable: false },
meta: { requestId: "req-1" },
},
{ status: 401 },
);
function uploadSource() {
const bytes = new TextEncoder().encode("file");
return {
byteLength: bytes.byteLength,
async *stream() {
yield { ok: true as const, value: bytes };
},
};
}
async function upload(
authProfile: (typeof REST_AUTH_PROFILES)[keyof typeof REST_AUTH_PROFILES],
fetcher: typeof fetch,
) {
const context = fixture.context as ProductCompositionContext | undefined;
if (!context) throw new Error("The product composition was not called");
const client = createFileserverUploadClient({
...context.credentials,
baseUrl: "http://localhost:8080/",
authProfile,
maxFileBytes: 1024,
fetcher,
});
return client.upload({ source: uploadSource(), signal: new AbortController().signal });
}
const ROWS = [
{
owner: "nobody, for an ANONYMOUS profile",
providers: {} as Record<string, ProductCredentialProvider>,
operation: ANONYMOUS_OPERATION,
profile: REST_AUTH_PROFILES.ANONYMOUS,
sentAuthorization: null,
product: 0,
session: 0,
},
{
owner: "the product, for a provider's profile",
providers: { EXTERNAL_BEARER: productToken },
operation: PROFILE_OPERATION,
profile: REST_AUTH_PROFILES.EXTERNAL_BEARER,
sentAuthorization: "Bearer product-token",
product: 1,
session: 0,
},
{
owner: "the session, for its own profile",
providers: {},
operation: PROFILE_OPERATION,
profile: REST_AUTH_PROFILES.EXTERNAL_BEARER,
sentAuthorization: "Bearer owner-token",
product: 0,
session: 1,
},
] as const;
it.each(ROWS)("V3: $owner", async (row) => {
const owner = externalOwner();
const session = vi.spyOn(owner, "notifyUnauthenticated");
const product = vi.fn();
fixture.providers = row.providers;
fixture.onCredentialRejected = product;
const { http, fetcher } = await compose(
"external",
{ __CA_FRONTEND_AUTH_OWNER__: owner },
unauthorized,
);
const outcome = await http.execute(row.operation, { limit: 1 }, { routeId: "TEST_ROUTE" });
expect(outcome.kind).toBe("UNAUTHENTICATED");
expect(new Headers(fetcher.mock.calls[0]?.[1]?.headers).get("authorization")).toBe(
row.sentAuthorization,
);
expect(product).toHaveBeenCalledTimes(row.product);
expect(session).toHaveBeenCalledTimes(row.session);
});
it.each(ROWS)("upload: $owner", async (row) => {
const owner = externalOwner();
const session = vi.spyOn(owner, "notifyUnauthenticated");
const product = vi.fn();
fixture.providers = row.providers;
fixture.onCredentialRejected = product;
await compose("external", { __CA_FRONTEND_AUTH_OWNER__: owner });
const uploads = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
unauthorized(),
);
const result = await upload(row.profile, uploads as unknown as typeof fetch);
expect(result).toMatchObject({ ok: false, error: { kind: "AUTH_REQUIRED" } });
expect(uploads).toHaveBeenCalledOnce();
expect(new Headers(uploads.mock.calls[0]?.[1]?.headers).get("authorization")).toBe(
row.sentAuthorization,
);
expect(product).toHaveBeenCalledTimes(row.product);
if (row.product === 1) {
expect(product).toHaveBeenCalledWith({
operationId: "FILESERVER_UPLOAD",
authProfileId: "EXTERNAL_BEARER",
});
}
expect(session).toHaveBeenCalledTimes(row.session);
});
it("upload: a fenced scope sends nothing, with the session's bearer profile", async () => {
// The demo session's sign-in fences the scope synchronously (row 1 above).
const { adapters } = await compose("demo");
void adapters.outputPorts.session.beginSignIn();
const uploads = vi.fn(async () => unauthorized());
const result = await upload(
REST_AUTH_PROFILES.EXTERNAL_BEARER,
uploads as unknown as typeof fetch,
);
expect(result).toMatchObject({ ok: false, error: { kind: "SCOPE_GENERATION_CHANGED" } });
expect(uploads).not.toHaveBeenCalled();
});
});
describe("1112/07-01 context.credentials while composing", () => {
it("says it is called per request instead of failing on the provider table", async () => {
let attempt: Promise<unknown> | undefined;
let reported: unknown;
fixture.onCompose = (context) => {
const { credentials } = context as ProductCompositionContext;
attempt = Promise.resolve(
credentials.attachCredentials(
{ operationId: "X", authProfileId: "EXTERNAL_BEARER", method: "POST" },
{ signal: new AbortController().signal, deadlineAtMonotonicMs: 0 },
),
);
try {
credentials.onUnauthenticated({ operationId: "X", authProfileId: "EXTERNAL_BEARER" });
} catch (error) {
reported = error;
}
};
await compose("demo");
await expect(attempt).rejects.toThrow(/per request/u);
expect(reported).toBeInstanceOf(TypeError);
});
});
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { BUILD_ASSET_DIRECTORY } from "../../src/contracts/service-worker.ts";
import viteConfig from "../../vite.config.ts";
/**
* 0925/06-08. The Service Worker precache, its previous-release fallback and
* the hosting probe read `BUILD_ASSET_DIRECTORY`; Vite writes the hashed
* files to `build.assetsDir`. A product that changed only the Vite setting
* got a worker with an empty precache and a probe that checked nothing, with
* every gate green. The two are held equal here, and the worker generator and
* install refuse an empty asset set besides.
*/
const VITE_DEFAULT_ASSETS_DIR = "assets";
describe("0925/06-08 the build's asset directory is the worker's", () => {
it("vite.config.ts build.assetsDir names BUILD_ASSET_DIRECTORY", async () => {
const config =
typeof viteConfig === "function"
? await viteConfig({ command: "build", mode: "production", isSsrBuild: false, isPreview: false })
: viteConfig;
expect(`${config.build?.assetsDir ?? VITE_DEFAULT_ASSETS_DIR}/`).toBe(BUILD_ASSET_DIRECTORY);
});
});
@@ -0,0 +1,239 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createServiceWorkerPageController } from "../../src/adapters/service-worker/index.ts";
import { installStaticAssets } from "../../src/adapters/service-worker/service-worker-static-assets.ts";
import {
SERVICE_WORKER_BOUNDS,
SERVICE_WORKER_SCRIPT_PATH,
} from "../../src/contracts/service-worker.ts";
/**
* 0925/06-05. An update that failed to install (the new worker went
* `redundant`) and a periodic update check that failed left no record: the
* page stayed on its build and nothing said why.
*
* 1103/09-05. An update already waiting when the page registered was reported
* only as the start outcome, so a product notice subscribed to
* `onUpdateWaiting` never heard of it.
*/
const ORIGIN = "https://app.example";
class FakeWorker extends EventTarget {
readonly scriptURL = `${ORIGIN}/${SERVICE_WORKER_SCRIPT_PATH}`;
constructor(public state: ServiceWorkerState) {
super();
}
postMessage(): void {}
move(state: ServiceWorkerState): void {
this.state = state;
this.dispatchEvent(new Event("statechange"));
}
}
function browser(options: Readonly<{ waiting?: boolean; update?: () => Promise<void> }> = {}) {
const registration = Object.assign(new EventTarget(), {
scope: `${ORIGIN}/`,
installing: null as FakeWorker | null,
waiting: options.waiting ? new FakeWorker("installed") : null,
active: new FakeWorker("activated"),
update: vi.fn(options.update ?? (async () => {})),
});
const container = {
controller: registration.active,
register: vi.fn(async () => registration),
addEventListener() {},
removeEventListener() {},
};
return { registration, container };
}
function controllerFor(container: unknown) {
const observed: Array<Readonly<{ event: string; outcome: string }>> = [];
const controller = createServiceWorkerPageController({
selection: { mode: "ACTIVE", scriptPath: SERVICE_WORKER_SCRIPT_PATH, handlers: [] },
disabledCleanup: false,
routerBasePath: "/",
origin: ORIGIN,
buildId: "page-build",
container: container as ServiceWorkerContainer,
observe: (observation) => observed.push(observation),
});
return { controller, observed };
}
afterEach(() => {
vi.useRealTimers();
});
describe("0925/06-05 update failures are observed", () => {
it("records an update whose install failed", async () => {
const { registration, container } = browser();
const { controller, observed } = controllerFor(container);
await controller.start();
const update = new FakeWorker("installing");
registration.installing = update;
registration.dispatchEvent(new Event("updatefound"));
update.move("redundant");
expect(observed).toContainEqual({ event: "update_install", outcome: "REDUNDANT" });
await controller.stop();
});
it("records a periodic update check that failed", async () => {
vi.useFakeTimers();
const { container } = browser({
update: async () => {
throw new TypeError("network");
},
});
const { controller, observed } = controllerFor(container);
await controller.start();
await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.updateCheckIntervalMs);
expect(observed).toContainEqual({ event: "update_check", outcome: "FAILED" });
await controller.stop();
});
it("records nothing for an update that installed", async () => {
const { registration, container } = browser();
const { controller, observed } = controllerFor(container);
const waiting = vi.fn();
controller.onUpdateWaiting?.(waiting);
await controller.start();
const update = new FakeWorker("installing");
registration.installing = update;
registration.dispatchEvent(new Event("updatefound"));
registration.waiting = update;
update.move("installed");
expect(waiting).toHaveBeenCalledOnce();
expect(observed.some(({ event }) => event.startsWith("update_"))).toBe(false);
await controller.stop();
});
});
describe("1103/09-05 an update waiting at start reaches onUpdateWaiting", () => {
it("tells the listener once, with the UPDATE_WAITING start outcome", async () => {
const { container } = browser({ waiting: true });
const { controller } = controllerFor(container);
const waiting = vi.fn();
controller.onUpdateWaiting?.(waiting);
await expect(controller.start()).resolves.toEqual({ kind: "UPDATE_WAITING" });
expect(waiting).toHaveBeenCalledOnce();
await controller.stop();
});
});
/**
* 1101/06-05. Every release downloaded the whole asset set again with
* `no-store`, even the files whose content-hashed names it shared with the
* release before. A verified copy in an earlier release's cache is reused;
* the download stays for a file that is new, missing or no longer matches.
*/
describe("1101/06-05 an earlier release's verified asset is reused", () => {
const CURRENT = `ca-static-v1-${"a".repeat(16)}`;
const PREVIOUS = `ca-static-v1-${"c".repeat(16)}`;
const kept = new TextEncoder().encode("kept");
const fresh = new TextEncoder().encode("fresh");
/** A fake digest: one hex digit per content. */
const DIGESTS: Readonly<Record<string, string>> = { kept: "1", fresh: "2", tamp: "3" };
const digestOf = (bytes: Uint8Array) =>
`sha256:${(DIGESTS[new TextDecoder().decode(bytes)] ?? "f").repeat(64)}`;
const asset = (name: string, bytes: Uint8Array) => ({
url: `${ORIGIN}/assets/${name}`,
sha256: digestOf(bytes) as `sha256:${string}`,
bytes: bytes.byteLength,
contentType: "text/javascript",
});
const manifest = {
schemaVersion: 1 as const,
buildId: "worker-build",
releaseId: "release-2",
setDigest: `sha256:${"a".repeat(64)}` as const,
assets: [asset("kept", kept), asset("fresh", fresh)],
};
async function install(
previous: Readonly<Record<string, Uint8Array>>,
previousContentType = "text/javascript",
) {
const put = vi.fn(async () => {});
const previousCache = {
match: vi.fn(async (url: string) => {
const bytes = previous[url];
return bytes
? new Response(bytes.slice(), { headers: { "content-type": previousContentType } })
: undefined;
}),
};
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
const bytes = String(input).endsWith("kept") ? kept : fresh;
return new Response(bytes.slice(), { headers: { "content-type": "text/javascript" } });
});
const result = await installStaticAssets(manifest, {
caches: {
open: vi.fn(async (name: string) =>
(name === PREVIOUS ? previousCache : { put }) as unknown as Cache,
),
delete: vi.fn(async () => true),
keys: vi.fn(async () => [PREVIOUS]),
},
fetcher: fetcher as unknown as typeof fetch,
digest: vi.fn(async (bytes: Uint8Array) => digestOf(bytes)),
});
return { result, fetched: fetcher.mock.calls.map(([input]) => String(input)), put };
}
it("copies the unchanged file and downloads only the new one", async () => {
const { result, fetched, put } = await install({ [`${ORIGIN}/assets/kept`]: kept });
expect(result).toEqual({ kind: "INSTALLED", cacheName: CURRENT, assets: 2 });
expect(fetched).toEqual([`${ORIGIN}/assets/fresh`]);
expect(put).toHaveBeenCalledTimes(2);
});
it("downloads a file whose earlier copy was stored with another content type", async () => {
const { fetched } = await install({ [`${ORIGIN}/assets/kept`]: kept }, "text/css");
expect(fetched.sort()).toEqual([`${ORIGIN}/assets/fresh`, `${ORIGIN}/assets/kept`]);
});
it("downloads a file whose earlier copy no longer matches its digest", async () => {
const { result, fetched } = await install({
[`${ORIGIN}/assets/kept`]: new TextEncoder().encode("tamp"),
});
expect(result).toMatchObject({ kind: "INSTALLED" });
expect(fetched.sort()).toEqual([`${ORIGIN}/assets/fresh`, `${ORIGIN}/assets/kept`]);
});
});
describe("0925/06-08 an empty asset manifest is refused", () => {
it("does not install a worker that would serve nothing", async () => {
const fetcher = vi.fn();
await expect(
installStaticAssets(
{
schemaVersion: 1,
buildId: "worker-build",
releaseId: "release-2",
setDigest: `sha256:${"a".repeat(64)}`,
assets: [],
},
{
caches: { open: vi.fn(), delete: vi.fn(async () => true) },
fetcher: fetcher as unknown as typeof fetch,
digest: vi.fn(),
},
),
).resolves.toEqual({ kind: "REJECTED", code: "MANIFEST_INVALID" });
expect(fetcher).not.toHaveBeenCalled();
});
});