fix(contracts): 짝 백엔드 pin을 백엔드 main d32b4b53으로 옮긴다

문제: pin(45d2a478)이 백엔드 main보다 한참 뒤라 drift 검사가 exit 1이다.
그사이 백엔드가 폴더를 다시 배치하고(scaffold 원본 셋의 경로) 샘플을
지웠다. 계약 문서 6.1절 근거 파일 넷과 위치 목록이 main에 없고, 매뉴얼
04는 pin과 다른 bbe944bd를 기준이라 적는다. Fileserver 업로드 client의
게시 전 5xx 표는 pin 대조 밖이다(1105/01-02). 백엔드 697e62e8c부터
fileserver의 permit·pool 포화가 429에서 503 SERVER_BUSY로 바뀌어, client는
작업 전에 거절된 업로드를 결과 불명으로 읽는다.

고른 방법(R9-D4):
- pin, 답 표 source, 표 사본(--write-excerpt)을 d32b4b53으로 옮긴다.
  §4의 새 행 404 OPERATION_NOT_FOUND는 durable operation 조회의 답이라
  notCopied에 이유와 함께 둔다.
- scaffold 원본 세 경로를 새 위치로 고친다(내용 0줄 변경 확인).
- pin에 backend.codeSources를 더한다. Fileserver code 파일과 게시 전
  5xx 표(codes)를 적고, readers에 fileserver-upload.ts를 넣는다. drift
  검사가 그 파일들의 변경과, pin 커밋에 없는 경로(옮겨진 파일)를 알린다.
  pin 시험이 client 표와 pin 사본을 양쪽으로 대조한다.
- NOT_APPLIED_5XX_CODES에 SERVER_BUSY를 더한다. raise 자리 둘
  (TransferAdmissionController, BlockingTransferExecutor)이 모두 작업 전이다.
- 6.1절 표의 백엔드 파일:줄을 d32b4b53에서 다시 찾았다. 판정은 같다.
  샘플과 함께 사라진 근거(참조 도메인 행, WorkLogWebMapper 등)는 뺐고,
  새 출처(PatchBodies, 알림 컨트롤러 필드 거절)를 적었다.
- 매뉴얼 04의 기준을 pin으로 바꾸고 백엔드 경로 셋을 고친다.
버린 대안: 문서만 옛 pin 기준으로 맞추기 — drift 검사는 계속 막힌다.

위험·한계: V3 경로의 503 SERVER_BUSY는 상태만 정해진 모든 503에도 붙어
code로 단계를 가를 수 없다. 그래서 V3 표에 넣지 않고 결과 불명 쪽에
둔다(6.1절). 백엔드 main은 계속 움직이므로 다음 백엔드 병합 뒤 drift가
다시 1일 수 있다(설계된 신호).

검증: 노트북, 공유 clone(d32b4b53)으로
node scripts/check-backend-contract-drift.ts --backend <clone>: 옮기기 전
exit 1(문서·scaffold 4건), 옮긴 뒤 exit 0. desktop RED — pin·drift·
업로드 표 시험이 고치기 전 코드에서 실패
(/tmp/claude-gates/r9b-pr1-red/exec_node.log). merge 단계는 PR 본문.

Refs: 1112/02-05, 1112/08-18, 1105/01-02
This commit is contained in:
DongHyeonka
2026-11-13 19:02:07 +09:00
parent 803d0f45aa
commit 762393a940
13 changed files with 244 additions and 77 deletions
+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 안에서도 나온다.
백엔드에는 이것을 막는 검사가 없다.
+2 -2
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`: 서버는 만들었다고 답했지만 응답을 읽지 못했다. 다시 올리지 않는다.
@@ -520,5 +520,5 @@ export function createInvoiceAttachmentUploads({
- 파일이 `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`만 적는다).
+5 -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`).
@@ -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;
}
+21 -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.
*/
@@ -189,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
@@ -205,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
+3 -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
+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);