diff --git a/docs/architecture/graphql-api-surface.txt b/docs/architecture/graphql-api-surface.txt index cd61da7e..5857b247 100644 --- a/docs/architecture/graphql-api-surface.txt +++ b/docs/architecture/graphql-api-surface.txt @@ -1,8 +1,8 @@ # GraphQL leaf public API surface — every public top-level type in src/main/java. # A public type in a single-jar leaf is reachable from every adopter's code, so -# additions are reviewed rather than discovered. `api` and `spi` are the intended -# external surface; the rest are candidates to become internal when this leaf is -# split into capability artifacts. +# additions are reviewed rather than discovered. `api` is the intended external +# surface; the rest are candidates to become internal when this leaf is split into +# capability artifacts. # Update only after review with: # ./gradlew :adapter:inbound:graphql:updateGraphQlApiSurface -PapproveGraphQlApiSurfaceChange # types: 161 diff --git a/docs/fileserver/http-contract.md b/docs/fileserver/http-contract.md index a5fb6aa6..3178e907 100644 --- a/docs/fileserver/http-contract.md +++ b/docs/fileserver/http-contract.md @@ -9,7 +9,7 @@ |---|---|---|---| | POST | `/v1/files` | `201` READY, `202` VERIFYING | multipart 단일 업로드 | | POST | `/v1/files:raw` | `201`, `202` | 요청 본문 전체가 파일이다 | -| POST | `/v1/files:batch` | `200` | part별 결과를 순서대로 준다. 명시적으로 원자적이지 않다 | +| POST | `/v1/files:batch` | `200` | 공용 bulk envelope(`docs/web/http-contract.md` 1절). 명시적으로 원자적이지 않다 | | GET | `/v1/files/{fileId}` | `200` | 공개 metadata. content key나 경로는 절대 주지 않는다 | | GET | `/v1/files/{fileId}/content` | `200`, `206`, `304` | 다운로드 | | HEAD | `/v1/files/{fileId}/content` | `200`, `304` | 같은 헤더, 본문 없음 | @@ -76,7 +76,6 @@ servlet chain에서 `app.fileserver-platform.security.admin-roles`로 막고, ```json { "success": false, - "data": null, "error": { "code": "UPLOAD_OFFSET_MISMATCH", "category": "CONFLICT", @@ -97,8 +96,10 @@ servlet chain에서 `app.fileserver-platform.security.admin-roles`로 막고, `ambiguous`는 client가 재시도 전에 읽어야 하는 필드다. 결과를 모르는 실패는 이미 효과가 났을 수 있다. `retryable`은 이번 발생에 대한 판단이고, 그 code가 허락하는 범위보다 넓어지지 않는다. -batch 업로드에서 거부된 part는 `results[]` 항목에 같은 `error` 객체(`code`, `category`, `message`, -`retryable`)를 담는다. +batch 업로드는 공용 bulk envelope다. 모든 part가 성공하면 `success: true`와 `results[]`(part마다 `clientPartId`, +`status`, `fileId`)다. 한 part라도 거부되면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`, `error.details[]`다. +`details[]` 항목은 part 순서의 `index`, `status`(`ok`·`error`), 성공한 part의 `id`(fileId), 거부된 part의 `code`와 +category 고정 문구 `message`다. 부분 실패에서 part는 요청에 보낸 순서의 `index`로 짚는다(`clientPartId`는 전부 성공한 `results[]`에만 있다). 성공한 part는 되돌리지 않는다. ### Envelope 규칙의 프로토콜 예외 @@ -111,6 +112,43 @@ batch 업로드에서 거부된 part는 `results[]` 항목에 같은 `error` 객 `409 application/problem+json`, `type = https://iana.org/assignments/http-problem-types#mismatching-upload-offset`, `expectedOffset`과 `providedOffset`. Envelope가 아닌 실패 본문은 이것 하나뿐이다. +## 오류 코드 + +`error.code`는 `FileserverErrorCode`(application-fileserver)가 정한다. 아래 표가 그 전부이고, client는 이 값으로 +분기한다. `retryable`은 그 code가 허락하는 최대치다. 실제 응답의 `retryable`은 그 발생에 대한 판단이라 `true`인 +code도 `false`로 올 수 있다(위 「실패 본문」). `Retry-After`는 retryable인 발생에만 붙는다. + +| code | status | category | retryable | `Retry-After` | 언제 | +| --- | --- | --- | --- | --- | --- | +| `BAD_REQUEST` | 400 | `VALIDATION` | false | — | 헤더나 헤더 조합이 잘못됐다 | +| `UNAUTHENTICATED` | 401 | `AUTH` | false | — | 인증하지 않았다 | +| `ACCESS_DENIED` | 403 | `AUTHZ` | false | — | 권한이 없다. 존재를 숨기는 profile에서는 `FILE_NOT_FOUND`로 온다 | +| `FILE_NOT_FOUND` | 404 | `NOT_FOUND` | false | — | 파일이 없거나 숨겼다 | +| `FILE_ALREADY_EXISTS` | 409 | `CONFLICT` | false | — | 대상 이름이 이미 있다(copy·move는 새로 만들기만 한다) | +| `FILE_NOT_READY` | 409 | `CONFLICT` | true | 2 | 검증이 끝나지 않아 아직 읽을 수 없다 | +| `UPLOAD_OFFSET_MISMATCH` | 409 | `CONFLICT` | true | — | 이어 쓰기 offset이 서버 offset과 다르다. `details.currentOffset`부터 다시 보낸다 | +| `CONCURRENT_MODIFICATION` | 409 | `CONFLICT` | true | 1 | 같은 자원을 다른 요청이 바꾸는 중이다 | +| `UPLOAD_EXPIRED` | 410 | `CONFLICT` | false | — | 만료되거나 끝난(취소, 거부, 격리) 업로드다 | +| `CONTENT_LENGTH_REQUIRED` | 411 | `VALIDATION` | false | — | `require-content-length` profile인데 길이가 없다 | +| `PRECONDITION_FAILED` | 412 | `CONFLICT` | false | — | `If-Match`·`If-Unmodified-Since`가 맞지 않는다 | +| `FILE_TOO_LARGE` | 413 | `VALIDATION` | false | — | 파일 크기 정책을 넘었다 | +| `QUOTA_EXCEEDED` | 413 | `CONFLICT` | false | — | 저장 할당량을 넘었다 | +| `UNSUPPORTED_MEDIA_TYPE` | 415 | `VALIDATION` | false | — | 받지 않는 media type이다 | +| `RANGE_NOT_SATISFIABLE` | 416 | `VALIDATION` | false | — | Range를 만족할 수 없다. `Content-Range: bytes */<길이>`를 싣는다 | +| `INTEGRITY_MISMATCH` | 422 | `DATA_INTEGRITY` | false | — | 선언한 digest와 받은 바이트가 다르다 | +| `MALWARE_DETECTED` | 422 | `DATA_INTEGRITY` | false | — | 검사기가 거부했다 | +| `INVALID_PATH` | 422 | `VALIDATION` | false | — | 경로 형식이 틀렸다 | +| `PATH_OUTSIDE_NAMESPACE` | 422 | `VALIDATION` | false | — | 경로가 namespace 밖을 가리킨다 | +| `TRANSFER_ADMISSION_REJECTED` | 429 | `RATE_LIMIT` | true | 1 | 호출자 자신의 동시 전송 permit이 찼다. 자기 전송이 끝나면 풀린다 | +| `CHECKSUM_MISMATCH` | 460 | `DATA_INTEGRITY` | false | — | tus `Upload-Checksum`이 그 요청의 바이트와 다르다. 그 chunk만 버린다 | +| `PARTIAL_WRITE` | 500 | `TRANSIENT_DEPENDENCY` | false | — | 쓰기가 중간에 끊겼다 | +| `AMBIGUOUS_COMPLETION` | 500 | `DATA_INTEGRITY` | false | — | 결과를 모른다. 이미 효과가 났을 수 있어 그대로 재시도하지 않는다 | +| `ATOMIC_PUBLISH_UNSUPPORTED` | 503 | `PERMANENT_DEPENDENCY` | false | — | 저장소가 원자적 게시를 지원하지 않는다(배포 설정 결함) | +| `STORAGE_UNAVAILABLE` | 503 | `TRANSIENT_DEPENDENCY` | true | 30 | 저장소나 검사기를 쓸 수 없다 | +| `SERVER_BUSY` | 503 | `TRANSIENT_DEPENDENCY` | true | 1 | instance 전체의 전송 permit이나 전송 worker pool이 찼다. 공용 서버 포화 코드와 같다 | +| `TRANSFER_TIMEOUT` | 504 | `TRANSIENT_DEPENDENCY` | true | 5 | 전송이 시간 안에 끝나지 않았다 | +| `STORAGE_FULL` | 507 | `TRANSIENT_DEPENDENCY` | false | — | 저장 용량이 없다 | + ## 헤더 계약 | 헤더 | 계약 | diff --git a/docs/fileserver/upgrade-guide.md b/docs/fileserver/upgrade-guide.md index af27de87..a8f12e31 100644 --- a/docs/fileserver/upgrade-guide.md +++ b/docs/fileserver/upgrade-guide.md @@ -63,7 +63,10 @@ V1__create_fileserver_metadata.sql → capability_schema_registry: jpa-fileser - **content가 아직 있으면 삭제는 `204`가 아니라 `202`로 답한다.** 파일은 이미 읽을 수 없고, 물리 회수는 미뤘다. `202`를 실패로 다루면 쓸데없이 재시도한다. - **batch 업로드는 part가 실패해도 `200`으로 답한다.** batch는 명시적으로 원자적이지 않고, 상태 코드 하나로는 - 부분 결과를 정직하게 알릴 수 없다. `results[].error`를 읽는다. + 부분 결과를 정직하게 알릴 수 없다. 판별은 `success`다. 모두 성공하면 `success: true`와 `results[]`, 하나라도 + 실패하면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`와 part별 `error.details[]`(`index`, `status`, + 성공한 part의 `id`, 실패한 part의 `code`·`message`)다. 2026-11-12 전에는 실패가 있어도 `success: true`였다 + (`docs/upgrade/2026-11-round9-contracts.md`). - **결과를 모르는 실패는 재시도하면 안 된다.** 실패 Envelope의 `error.details`에서 `"ambiguous": true`를 본다. - **`If-Match`는 version 숫자가 아니라 strong ETag를 받는다.** client는 실제로 받은 표현에 대해서만 주장할 수 있다. diff --git a/docs/manual/11-checklist.md b/docs/manual/11-checklist.md index fff17a68..128f1ccc 100644 --- a/docs/manual/11-checklist.md +++ b/docs/manual/11-checklist.md @@ -34,7 +34,7 @@ ## inbound - [ ] 컨트롤러는 변환만 한다. repository·엔티티를 모른다. -- [ ] 경로는 lowerCamel 복수형(AIP-122). 생성은 201 + `Location`. +- [ ] 경로는 lowerCamel 복수형(AIP-122). 생성은 201 + `Location`. 만든 것을 읽는 endpoint가 없으면 `Location`을 싣지 않고 controller 주석에 그 이유를 적는다. - [ ] 도메인 규칙을 DTO bean validation에 다시 쓰지 않았다. - [ ] 엔드포인트를 더했으면 **요청률 제한**을 어디서 거는지(ingress/app) 배포 설계에 있다. 앱 기본 off·켜는 법은 [docs/security/rate-limiting.md](../security/rate-limiting.md). diff --git a/docs/registries/error-codes.yaml b/docs/registries/error-codes.yaml index 134ffd8f..d3d531db 100644 --- a/docs/registries/error-codes.yaml +++ b/docs/registries/error-codes.yaml @@ -380,6 +380,21 @@ errors: compatibility_impact: none required_test: contract-verification:rate-limit + # source: 2026-11-12 리뷰 결정 ② — 서버 포화(허가 상한, 꽉 찬 work pool)는 전송마다 다른 코드였다(web-advanced + # ADMISSION_REFUSED 503, fileserver TRANSFER_ADMISSION_REJECTED 429, gRPC RATE_LIMIT_EXCEEDED). 이 코드 하나로 모은다. + # 호출자 자신의 빈도·동시성 초과만 429(RATE_LIMIT_EXCEEDED, fileserver TRANSFER_ADMISSION_REJECTED)다. + - code: SERVER_BUSY + category: TRANSIENT_DEPENDENCY + http_status: 503 + retryable: true + retry_after_seconds: 1 + owner_branch: 2026-11-12-round9-review + owner_layer: presentation + client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." + runbook_link: "runbook://server/busy" + compatibility_impact: behavior-change + required_test: contract-verification:server-saturation + # source: docs/web/http-contract.md §2 (2026-11-01 소유자 결정, 리뷰 02-01 대안 A) — 결과 불명. 같은 Idempotency-Key로 Retry-After 뒤 재전송. 새 키 금지. # 2초 = 기본 processing lease(30s)보다 짧은 고정값. 이전 "client는 polling"(retryable=false)은 조회 엔드포인트가 없어 폐기. # 값 하나: IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER. processing-lease가 이 값 이하면 기동 실패(재리뷰 RR-02-05). diff --git a/docs/runbooks/server-busy.md b/docs/runbooks/server-busy.md new file mode 100644 index 00000000..cc3e2513 --- /dev/null +++ b/docs/runbooks/server-busy.md @@ -0,0 +1,46 @@ +--- +title: Runbook — 서버 포화(SERVER_BUSY) +category: TRANSIENT_DEPENDENCY +error_codes: [SERVER_BUSY] +severity: P2 +owner: oncall +last_updated: 2026-11-13 +status: 운영 +--- + +# Runbook: 서버 포화 (`runbook://server/busy`) + +이 instance가 요청을 더 받을 자리가 없어 바로 거절했다. 호출자의 빈도 초과(`RATE_LIMIT_EXCEEDED` 429)와 다르다. 이 +코드는 서버 쪽 상한이 찼다는 뜻이다. + +## 증상 + +- HTTP `503`과 `error.code = SERVER_BUSY`, `Retry-After: 1`. gRPC는 `UNAVAILABLE`와 trailer `error-code: SERVER_BUSY`. +- `http_server_requests_seconds_count{status="503"}`이 오르고, 같은 때 p95 지연은 오르지 않는다. 거절은 일을 하기 전에 + 나기 때문이다. +- 이 코드를 내는 곳은 셋이다. + +| 내는 곳 | 찬 상한 | 설정 | +| --- | --- | --- | +| web-advanced `VirtualThreadAdmissionFilter` | 동시에 처리하는 요청 수 | `app.web.advanced.mvc-virtual-threads.admission-limit` | +| fileserver 전송 허가 | instance 전체 업로드·직접 다운로드 permit, 전송 worker pool | `app.fileserver-platform.quota.instance-upload-permits`, `…direct-download-permits` | +| gRPC `GrpcCallAdmission` | feature 호출 worker와 대기열 | `app.grpc.server.executor-max-pool-size`, `executor-queue-capacity` | + +## 진단 + +1. 거절이 한 instance에만 몰리는지 본다. 한 instance만이면 부하 분산이 고르지 않거나 그 instance의 하류가 느리다. +2. 같은 때 하류 지연(DB pool 대기, 외부 HTTP 지연)을 본다. 하류가 느리면 허가를 쥔 요청이 오래 머물러 상한이 찬다. + 이때 상한을 올리면 하류 pool 앞의 줄만 길어진다. +3. 정상 부하에서 상한 자체가 작은지 본다. 거절률이 트래픽에 비례하고 하류가 건강하면 상한이 작다. + +## 조치 + +- 하류가 느린 경우: 하류 runbook(`db-unavailable`, `dependency-timeout`)을 먼저 따른다. 상한은 그대로 둔다. +- 상한이 작은 경우: instance를 늘리거나 위 표의 설정을 올린다. virtual thread `admission-limit`은 DB pool과 외부 + bulkhead를 넘지 않게 둔다(`docs/web/virtual-thread-profile.md`). +- client는 `Retry-After` 뒤에 같은 요청을 다시 보낸다. 고칠 것이 없으면 거절은 1초 안에 풀린다. + +## 에스컬레이션 + +- 5분 넘게 거절률이 전체 요청의 5%를 넘으면 P1으로 올리고 인프라 당번을 부른다. +- 모든 instance가 같이 거절하고 하류가 건강하면 용량 문제다. 배포 소유자에게 scale-out을 요청한다. diff --git a/docs/upgrade/2026-11-round9-contracts.md b/docs/upgrade/2026-11-round9-contracts.md new file mode 100644 index 00000000..650bcc8c --- /dev/null +++ b/docs/upgrade/2026-11-round9-contracts.md @@ -0,0 +1,32 @@ +# 업그레이드 안내 — 2026-11 HTTP 계약·오류 코드 정리 + +- 범위: web-advanced(patch·stream·virtual thread), fileserver·notification HTTP, 전송 오류 코드를 약속한 계약에 맞춘 + 변경. 응답 코드·모양이 바뀐 곳이 있다. 아래 표가 그 목록이다. +- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 계약·오류 코드 발견 + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스와, 그 서비스의 HTTP 응답을 읽는 client 팀이 읽는다. + +## 2. 할 일 + +| # | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | +| 1 | `JsonMergePatchApplier`·`JsonPatchApplier`를 만드는 코드에 셋째 인자로 Boot의 `jakarta.validation.Validator` bean을 넘긴다 | 컴파일이 실패한다 | web-advanced patch를 쓰는 서비스 | +| 2 | patch 거부를 읽는 client는 `PATCH_REJECTED`(400) 하나로 본다. 전에는 JSON이 아닌 본문이 `500 INTERNAL_ERROR`, 빈 문서·연산 모양 오류·merge 깊이 초과가 `400 BAD_PARAMETER`, 너무 깊은 pointer가 `403 PATCH_PATH_FORBIDDEN`이었다 | client가 옛 코드로 분기하던 곳이 다른 코드를 받는다 | patch route를 둔 서비스와 그 client | +| 3 | patch 결과가 Bean Validation 제약을 어기면 `400 VALIDATION_FAILED`와 필드별 `details`가 나간다. patch 대상 타입의 제약을 확인한다 | 전에는 제약을 어긴 객체가 그대로 저장 경로로 갔다 | web-advanced patch를 쓰는 서비스 | +| 4 | 스트림 `Failure` 기록의 `code`가 실패의 코드(예: `STREAM_ITEM_TOO_LARGE`) 또는 `INTERNAL_ERROR`다. `DEPENDENCY_FAILURE`로 분기하던 client를 고친다 | 그 분기가 다시는 맞지 않는다 | NDJSON·JSON-seq stream을 읽는 client | +| 5 | virtual thread profile을 켠 배포는 이제 실제로 허가 상한을 건다. `admission-limit`이 부하에 맞는지 본다 | 전에는 상한이 없어 모든 요청이 들어왔다. 이제 넘치면 `503 SERVER_BUSY`와 `Retry-After: 1`이다 | `app.web.advanced.mvc-virtual-threads.enabled=true`인 배포 | +| 6 | fileserver batch(`POST /v1/files:batch`)를 읽는 client는 `success`로 가른다. 모두 성공하면 `success: true`와 최상위 `results[]`, 하나라도 실패하면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`, part별 `error.details[]`(`index`, `status`, `id`, `code`, `message`)다. 부분 실패에서는 part를 요청 순서 `index`로 짚는다(`clientPartId`는 전부 성공한 `results[]`에만 있다) | 전에는 실패가 있어도 `success: true`이고 결과가 `data.results[]`에 있었다. 옛 경로로 읽던 client는 결과를 못 찾는다 | fileserver를 쓰는 서비스와 그 client | +| 7 | `BulkItemResult.error(index, code, message)`를 부르던 코드를 `BulkItemResult.error(index, ApiErrorCode)`로 바꾼다. 문구는 code의 category 고정 문구가 된다 | 컴파일이 실패한다 | bulk endpoint를 둔 서비스 | +| 8 | 서버 포화 거절을 읽는 client는 `SERVER_BUSY`(503, retryable, `Retry-After: 1`)로 본다. web-advanced `ADMISSION_REFUSED`, fileserver instance·전송 pool 포화의 `TRANSFER_ADMISSION_REJECTED`(429), gRPC 포화의 `RESOURCE_EXHAUSTED`/`RATE_LIMIT_EXCEEDED`가 이 코드로 바뀌었다(gRPC status는 `UNAVAILABLE`). 호출자 자신의 동시 전송 초과만 `TRANSFER_ADMISSION_REJECTED` 429로 남는다 | 옛 코드로 분기하던 재시도 로직이 맞지 않는다. 자바에서 `WebAdvancedError.ADMISSION_REFUSED`를 참조하던 코드는 컴파일이 실패한다 | 세 전송의 client, web-advanced 코드를 참조하던 서비스 | +| 9 | 컨테이너가 넘긴 503(필터의 `sendError(503)` 등)은 `SERVER_BUSY`다. 비동기 요청 시간 초과만 `REQUEST_TIMEOUT`이다 | 전에는 모든 503이 `REQUEST_TIMEOUT`이었다 | web을 쓰는 모든 서비스의 client | +| 10 | 알림 template 게시 경로를 `/notification-templates`에서 `/notificationTemplates`로 바꾼다(prefix 뒤) | 옛 경로는 404다 | 알림 template을 게시하는 client와 배포 스크립트 | +| 11 | 알림 제출·template 게시의 모르는 `channel`·`slot`·`locale`·`fallbackLocale`은 `400 VALIDATION_FAILED`와 그 필드를 짚는 `details`다(전에는 details 없는 `BAD_PARAMETER`) | `BAD_PARAMETER`로 분기하던 client가 다른 코드를 받는다 | 알림 HTTP client | +| 12 | 이름 없이 올린 파일의 표시 이름이 `upload.bin`에서 `file`이 된다(모든 전송에서 같다) | 표시 이름이 바뀐다. 동작은 같다 | fileserver를 쓰는 서비스 | +| 13 | fileserver `ATOMIC_PUBLISH_UNSUPPORTED`(재시도 불가 code)는 더 이상 `Retry-After`를 싣지 않는다. 본문 `retryable=false`와 맞춘 것이다 | 그 헤더로 재시도하던 client가 재시도하지 않는다(원래 재시도해도 소용없는 실패다) | fileserver client | +| 14 | 브라우저 client는 `Content-Range`를 읽을 수 있다(CORS 노출 목록에 더함) | — 더하기만 한 변경 | fileserver 다운로드를 이어 받는 브라우저 client | +| 15 | bulk 부분 실패의 `error.message`가 영어 문구에서 category 고정 문구(`ClientErrorMessages`)로 바뀌었다. 항목(`details[]`)은 자기 상태에 맞는 키만 싣는다(성공 항목에 `code`·`message` 키 없음, 실패 항목에 `id` 키 없음) | 문구로 분기하던 client(원래 하면 안 된다)나 null 키를 기대하던 strict client가 다르게 본다 | bulk endpoint를 둔 서비스의 client | +| 16 | 스트림에서 위치가 앞 항목보다 크지 않은 항목은 이제 나가지 않고, 스트림이 `INTERNAL_ERROR` `Failure` 기록으로 끝난다(전에는 그 항목을 쓴 뒤 끝났다) | 서버 결함이 있는 source의 client가 마지막 항목을 받지 않는다 | NDJSON·JSON-seq stream을 읽는 client | +| 17 | 상태만 아는 503·429(Spring이 던진 `ResponseStatusException` 등)도 registry의 `Retry-After`를 싣는다 | — 헤더를 더하기만 한 변경 | web을 쓰는 서비스의 client | +| 18 | virtual thread admission filter가 Spring Security chain 뒤에서 돈다. 인증·권한에서 거절된 요청은 허가를 쓰지 않고, 거절 503에 CORS 헤더가 붙는다 | — | virtual thread profile을 켠 배포 | diff --git a/docs/web/advanced-capabilities.md b/docs/web/advanced-capabilities.md index 731c048f..719adfc9 100644 --- a/docs/web/advanced-capabilities.md +++ b/docs/web/advanced-capabilities.md @@ -10,7 +10,7 @@ Advanced capability는 따로 된 leaf `adapter:inbound:web-advanced`(`src/adapt | Capability | 켜는 법 | 더하는 것 | 테스트 | | --- | --- | --- | --- | -| MVC virtual thread | `app.web.advanced.mvc-virtual-threads.enabled=true`(+ 허가 상한과 예산) | **모든** 요청에 대한 다른 스케줄링 모델 | `MvcAdvancedConfigurationTest`, `VirtualThreadAdmissionTest` | +| MVC virtual thread | `app.web.advanced.mvc-virtual-threads.enabled=true`(+ 허가 상한과 예산) | **모든** 요청에 대한 다른 스케줄링 모델과 요청마다 거는 허가 상한(`VirtualThreadAdmissionFilter`) | `MvcAdvancedConfigurationTest`, `VirtualThreadAdmissionTest`, `VirtualThreadAdmissionFilterTest` | | NDJSON 스트리밍 | `app.web.advanced.ndjson.enabled=true` | 오래 사는 connection | `MvcStreamingWiringTest`, `WebStreamCoreTest`, `WebStreamDrainTest`, `WebStreamingSoakIT` | | JSON text sequence(RFC 7464) | `app.web.advanced.json-sequence.enabled=true` | 오래 사는 connection | NDJSON과 같다 | | JSON Merge Patch(RFC 7396) | 라이브러리 — `JsonMergePatchApplier` | 부분 문서 | `JsonMergePatchApplierTest` | diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index 1f66a154..4b324818 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -177,7 +177,7 @@ CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의 `traceparent`, `Location`, `ETag`, `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` - fileserver를 실은 배포: `Tus-Resumable`, `Tus-Version`, `Tus-Extension`, `Tus-Max-Size`, `Upload-Offset`, `Upload-Length`, `Upload-Defer-Length`, `Upload-Expires`, `Upload-Complete`, - `Upload-Limit`, `Content-Disposition`, `Accept-Ranges` + `Upload-Limit`, `Content-Disposition`, `Accept-Ranges`, `Content-Range` 새 응답 헤더를 쓰는 모듈은 `CorsExposedHeaders` bean으로 자기 헤더를 기여한다. @@ -187,15 +187,18 @@ CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의 | 코드 | 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 제공자가 계약과 맞지 않음 | +| `OPERATION_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | durable operation 조회(`DurableOperationController`)에서 그 operation이 없거나 다른 호출자의 것이다. 둘을 가르지 않는다 | - 컨트롤러 파라미터 제약 위반(`@RequestParam @Max(10)`)은 요청 본문 위반과 같은 `400 VALIDATION_FAILED`이고 `details`는 `[{field, code, message}]`다. 거절된 값은 싣지 않는다. -- web-advanced를 실은 서비스의 예외 코드(`ADMISSION_REFUSED` 503 등 10종)는 +- web-advanced를 실은 서비스의 예외 코드(`PATCH_REJECTED` 400 등)는 `src/adapter/inbound/web-advanced/README.md` 「오류 응답」이 정본이다. +- 서버 포화(허가 상한, 꽉 찬 work pool)는 모든 전송이 공용 `SERVER_BUSY`(503, retryable, `Retry-After: 1`) + 하나로 답한다. 호출자 자신의 빈도 초과만 `RATE_LIMIT_EXCEEDED` 429다(`docs/registries/error-codes.yaml`). - 직접 쓰는 거부 응답(401·403·429·503)도 컨트롤러 응답과 같이 `application/json;charset=UTF-8`이다. ## 5. 바꿀 때 diff --git a/docs/web/patch-contract.md b/docs/web/patch-contract.md index 5cb64725..5ab4cdb2 100644 --- a/docs/web/patch-contract.md +++ b/docs/web/patch-contract.md @@ -38,6 +38,10 @@ route는 정확히 하나만 받고, 다른 것을 보내면 최선의 짐작 **한도.** 연산은 최대 100개, pointer 깊이는 최대 16, merge patch 중첩 깊이는 최대 32. 앞의 둘은 곱해진다. 연산마다 서버가 먼저 깊이 복사한 문서 위로 pointer를 따라 걷는다. +**거부 코드.** 형식이 틀린 문서(JSON이 아닌 본문, 빈 문서, 한도 초과, 연산 모양 오류)는 모두 `400 PATCH_REJECTED`다. +허용 목록 밖의 경로만 `403 PATCH_PATH_FORBIDDEN`이고, 실패한 `test`는 `409 PATCH_TEST_FAILED`다. 너무 깊은 pointer는 +권한 문제가 아니라 형식 문제라 400이다. + ## 원자성 JSON Patch 문서는 전부 적용되거나 하나도 적용되지 않는다. 모든 연산은 작업 사본에서 돈다. 모든 연산이 성공하고 @@ -60,8 +64,13 @@ JSON Patch 문서는 전부 적용되거나 하나도 적용되지 않는다. ## 검증 patch를 적용한 결과는 필드 하나씩이 아니라 문서 전체로 검증한다. 필드 하나하나는 모두 유효한 patch가 유효하지 않은 -객체를 만들 수 있다. 서로 맞아야 하는 두 필드, 허락되지 않은 상태 전이 같은 것이다. 바뀐 것만 검증하면 그중 아무것도 -보지 못한다. +객체를 만들 수 있다. 서로 맞아야 하는 두 필드가 그런 예다. 바뀐 것만 검증하면 그것을 보지 못한다. + +- 두 applier는 서비스의 Bean Validation `Validator`를 생성자로 받고, 결과 객체 전체를 검증한 뒤에 돌려준다. 위반은 + `@Valid` 본문과 같은 `400 VALIDATION_FAILED`와 필드별 `details`다. +- 결과가 자원 타입으로 읽히지 않으면(숫자 자리에 문자열) `400 PATCH_REJECTED`다. +- 검증하는 대상은 web 표현 DTO이고, 제약은 요청 문법이다(web AGENTS B4·C1). 상태 전이처럼 업무 규칙인 검증은 여기서 + 하지 않는다. 결과를 command로 바꿔 받은 유스케이스가 한다. ## 선행 조건 diff --git a/docs/web/streaming-contract.md b/docs/web/streaming-contract.md index b2ccb6a8..01283585 100644 --- a/docs/web/streaming-contract.md +++ b/docs/web/streaming-contract.md @@ -12,8 +12,9 @@ writer는 `adapter:inbound:web-advanced`(골라 쓰는 leaf, `app.web.advanced.n connection은 결과를 알 수 없다. 끝은 셋이다. 1. **`Complete` envelope.** stream이 끝났다. `lastSequence`가 마지막 위치다. -2. **`Failure` 기록.** commit 뒤에 무언가 실패했다. 오류 code와 client에게 보여도 되는 메시지를 담는다. 상태는 여전히 - 200이다. +2. **`Failure` 기록.** commit 뒤에 무언가 실패했다. 상태는 여전히 200이다. `code`는 실패한 예외의 코드다(예: + `STREAM_ITEM_TOO_LARGE`). 코드가 없는 실패는 등록된 `INTERNAL_ERROR`다. `message`는 그 category의 고정 문구다. commit 전에 + 던져졌다면 받았을 코드·문구와 같다. 3. **둘 다 아님.** stream 중간에 connection이 닫혔다. 서버는 이것을 `ABRUPT_CLOSE`로 기록한다. client 쪽에서는 *끝 envelope를 찾지 않는 한* 끝난 stream과 구분할 수 없다. @@ -23,7 +24,7 @@ connection은 결과를 알 수 없다. 끝은 셋이다. ## 위치 모든 `Item`은 1부터 세는 `sequence`를 가진다. 위치는 엄격히 증가하고, 서버가 그것을 강제한다. 반복이나 후퇴는 client가 -견뎌야 할 것이 아니라 서버 쪽 오류다. +견뎌야 할 것이 아니라 서버 쪽 오류다. writer는 그런 항목을 쓰지 않고 stream을 `INTERNAL_ERROR` `Failure` 기록으로 끝낸다. 0은 절대 유효한 위치가 아니다. 첫 항목이 0을 주장한 stream과 sequence를 아예 정하지 않은 stream이 똑같아 보이기 때문이다. @@ -55,21 +56,25 @@ resnapshot은 자원을 보통 endpoint에서 다시 읽고 새 stream을 시작 ## Heartbeat와 시간 초과 -서버는 `heartbeatInterval`마다 keepalive를 쓴다. 그보다 오래 아무것도 보지 못한 client는 connection이 죽었다고 봐야 -한다. socket에서는 조용한 connection과 끊긴 connection이 같고, heartbeat가 둘을 가른다. +writer(`MvcStreamWriter`)는 요청 thread에서 source를 차례로 쓴다. 그래서 heartbeat를 보내지 않고, `idleTimeout`· +`maxStreamAge`로 stream을 닫지도 않는다. 그 값은 `WebStreamPolicy`에 있고, 자기 stream을 `WebStreamRegistry`에 올려 +돌리는 서비스가 쓴다. -stream은 `idleTimeout`(만든 것이 없음)과 `maxStreamAge`(활동과 상관없음)에 닫힌다. 둘 다 보통의 끝이고, connection이 -허락하면 둘 다 끝 envelope를 보낸다. +- client는 heartbeat를 기대하지 않는다. 자기 읽기 시간 초과를 두고, 그 시간에 아무것도 오지 않으면 끝 envelope 없이 + 닫힌 것으로 보고 이어 받기 cursor로 다시 연결한다. +- socket에서는 조용한 connection과 끊긴 connection이 같다. heartbeat가 필요한 route는 서비스가 그것을 더하고 이 문서의 + route 설명에 적는다. ## 느린 소비자 -서버는 뒤처진 소비자를 위해 최대 `maxBufferedItems`까지만 버퍼링한다. 그것을 넘으면 버퍼를 키우지 않고 connection을 -닫는다. 따라가지 못하는 client는 서버가 밀린 것을 쥐고 있기를 기대하지 말고, 이어 받기 cursor로 다시 연결한다. +writer는 버퍼를 두지 않는다. 느린 소비자는 서버의 쓰기를 막고, 그동안 source도 멈춘다. 서버 heap에 밀린 항목이 쌓이지 +않는다. `maxBufferedItems`는 버퍼를 두는 서비스 구현의 한도다. 따라가지 못하는 client는 이어 받기 cursor로 다시 연결한다. ## 종료 -rolling 배포 중에는 노드가 받기를 멈추기 전에 열린 stream이 다시 연결하라는 요청을 받는다. 바로 다시 연결한다. 노드는 -drain 기한에 아직 열린 것을 강제로 닫고, 그것은 갑작스러운 닫힘으로 도착한다. +drain 순서(받기를 멈추고, 다시 연결을 요청하고, 기한에 강제로 닫기)는 `WebStreamDrainCoordinator`에 있다. 서비스가 +자기 stream을 `WebStreamRegistry`에 등록하고 그 조정기를 종료 순서에 넣었을 때만 돈다. 기본 writer만 쓰는 배포에서는 +종료 때 열린 stream이 갑작스러운 닫힘으로 끝난다. 갑작스러운 닫힘에 backoff와 jitter 없이 바로 다시 연결하지 않는다. 노드의 stream이 한꺼번에 끊겼을 때 모든 client가 한꺼번에 다시 연결하면 그것이 교체 노드를 쓰러뜨린다. diff --git a/docs/web/virtual-thread-profile.md b/docs/web/virtual-thread-profile.md index 599927db..aac36da7 100644 --- a/docs/web/virtual-thread-profile.md +++ b/docs/web/virtual-thread-profile.md @@ -36,7 +36,12 @@ app: `VirtualThreadAdmissionGuard`는 pool이 아니라 공정한 semaphore다. 스레드를 제한하면 기다림을 되돌려 놓고 virtual thread로 얻은 것을 버리게 된다. virtual thread 만 개가 있어도 백 개만 허가를 쥐고 나머지는 문 앞에서 거부된다. -거부는 **`Retry-After`가 붙은 503**이고, 상한이 만들려는 결과가 바로 그것이다. 1밀리초 만에 거부된 요청이, 받아들여진 뒤 +상한은 `VirtualThreadAdmissionFilter`가 모든 요청에 건다. Spring Security chain 바로 뒤라, 거절 응답에도 CORS 헤더가 +붙어 브라우저가 503과 `Retry-After`를 읽고, 보안 chain이 거절한 요청(인증 없음, 권한 없음)은 허가를 쓰지 않는다. 거절된 +요청은 handler에 닿지 않는다. async 요청은 async 일이 끝날 때까지 허가를 쥔다. 넘겨준 순간 돌려주면 넘기는 일만 제한하고 정작 +하류 pool을 쓰는 일은 제한하지 못한다. + +거부는 **`Retry-After`가 붙은 503**(공용 코드 `SERVER_BUSY`)이고, 상한이 만들려는 결과가 바로 그것이다. 1밀리초 만에 거부된 요청이, 받아들여진 뒤 가득 찬 pool 뒤에서 30초 뒤에 시간 초과가 난 같은 요청보다 client에게 확실히 낫다. semaphore는 일부러 공정하다. 불공정한 것이 빠르지만, 새로 온 요청이 기다리던 요청을 앞지르게 두고, 앞지름당한 diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index 67cb64e1..3e565afb 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -116,6 +116,9 @@ | GraphQL 인자 변환 실패 | Spring GraphQL 인자 binder의 `BindException`(`@Argument` 값이 파라미터 타입으로 바뀌지 않음)은 `BAD_PARAMETER`(`REQUEST`)로 답하고, WARN 한 줄(예외 타입만, 입력값 없음)을 남긴다. web이 바뀌지 않는 경로 변수에 답하는 것과 같다 | 소유자 | 2026-11-07 같은 전달, r8-f1 보고 「범위 밖」 2 | | 약속한 응답으로 맞추기 | 레지스트리·`docs/web/http-contract.md`·Javadoc이 이미 약속한 응답으로 코드를 맞추는 것은 결함 수정이다. 고치기 전에 묻지 않고, 응답이 바뀌니 업그레이드 안내 행은 적는다. 약속한 곳끼리 다르면 묻는다 | 소유자(2026-11-07, 기본값 확인) | `docs/work/improve.md` 7절, `docs/work/evidence.md` 11절 | | STOMP 필수 header 누락 | 필수 header·destination 변수가 없을 때 Spring이 던지는 `MessageHandlingException`은 ERROR 그대로 둔다. 메시지에 입력값이 없고, Spring이 같은 타입으로 서버 실패(handler의 `Error` 등)도 감싸서 타입만으로는 클라이언트 탓을 가를 수 없다 | 기본값(2026-11-07) | 2026-11-07 총괄 지시, r8-f1 보고 「범위 밖」 3 | +| 서버 포화 코드 | 서버 쪽 상한(요청 허가, 꽉 찬 work pool)이 찬 거절은 모든 전송이 공용 `SERVER_BUSY`(503, `TRANSIENT_DEPENDENCY`, retryable, `Retry-After: 1`) 하나다. 호출자 자신의 빈도·동시성 초과만 429(`RATE_LIMIT_EXCEEDED`, fileserver `TRANSFER_ADMISSION_REJECTED`)다. 상태만 아는 503도 `SERVER_BUSY`이고, 비동기 요청 시간 초과만 `REQUEST_TIMEOUT`이다 | 기본값(2026-11-12, 소유자가 뒤집을 수 있다) | 2026-11-12 전체 리뷰 기록 README 6절 ② | +| batch 부분 실패 | fileserver batch도 공용 bulk envelope(web AGENTS B8)다. 하나라도 실패하면 `success:false` + `BATCH_PARTIAL_FAILURE` + 항목별 `details` | 기본값(2026-11-12) | 같은 README 6절 ① | +| PATCH 정본 | `docs/web/patch-contract.md`가 merge patch·JSON Patch의 정본이다. web AGENTS B2는 `application/json` PATCH DTO만 다루고 그쪽을 가리킨다 | 기본값(2026-11-12) | 같은 README 6절 ③ | ### 2.4 멱등성 diff --git a/src/adapter/inbound/graphql/build.gradle b/src/adapter/inbound/graphql/build.gradle index 53bbe3a2..1f2b622b 100644 --- a/src/adapter/inbound/graphql/build.gradle +++ b/src/adapter/inbound/graphql/build.gradle @@ -139,17 +139,17 @@ strictTestLanes { // be. // // A snapshot does not shrink the surface. It makes each addition visible in review, which is the -// prerequisite for shrinking it: the `api` and `spi` packages are the surface an adopter is meant -// to use, and everything else in this file is a candidate for becoming internal when the leaf is -// split into capability artifacts. Until then the number cannot grow by accident. +// prerequisite for shrinking it: the `api` package is the surface an adopter is meant to use, and +// everything else in this file is a candidate for becoming internal when the leaf is split into +// capability artifacts. Until then the number cannot grow by accident. apiSurface { label = 'GraphQl' baseline = rootProject.file('docs/architecture/graphql-api-surface.txt') description = 'GraphQL leaf public API surface — every public top-level type in src/main/java.' rationale = [ 'A public type in a single-jar leaf is reachable from every adopter\'s code, so', - 'additions are reviewed rather than discovered. `api` and `spi` are the intended', - 'external surface; the rest are candidates to become internal when this leaf is', - 'split into capability artifacts.', + 'additions are reviewed rather than discovered. `api` is the intended external', + 'surface; the rest are candidates to become internal when this leaf is split into', + 'capability artifacts.', ] } diff --git a/src/adapter/inbound/grpc/README.md b/src/adapter/inbound/grpc/README.md index c37282f5..80733703 100644 --- a/src/adapter/inbound/grpc/README.md +++ b/src/adapter/inbound/grpc/README.md @@ -95,7 +95,8 @@ executor, 서버 deadline 없음, 연결 수명 무제한이다. 어댑터 서 health/reflection 에는 적용하지 않는다(`Health/Watch` 는 원래 오래 사는 스트림이다). - **포화 시 동작(`GrpcCallAdmission`).** feature 호출은 `executor-max-pool-size + executor-queue-capacity` 개까지만 받고, 넘친 호출은 handler 를 시작하지 않고 즉시 - `RESOURCE_EXHAUSTED`(`RATE_LIMIT_EXCEEDED`, retryable)로 닫는다. 구현: io.grpc + `UNAVAILABLE`(`SERVER_BUSY`, retryable)로 닫는다. 서버 포화는 모든 전송이 이 공용 코드 하나다(2026-11-12 전에는 + `RESOURCE_EXHAUSTED`/`RATE_LIMIT_EXCEEDED`였다). 구현: io.grpc `ServerCallExecutorSupplier`(`@ExperimentalApi`, 1.39부터)가 호출 시작 전에 permit 을 확인해 받은 호출만 고정 크기 work pool 로 옮기고, 못 받은 호출은 가장 바깥 인터셉터가 닫는다. 메서드 조회·context 정리·health·reflection 은 작은 dispatch pool 에서 돈다. 버린 대안: diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCallAdmission.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCallAdmission.java index 1a8c8b77..f86c4012 100644 --- a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCallAdmission.java +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCallAdmission.java @@ -28,9 +28,11 @@ import java.util.concurrent.atomic.AtomicBoolean; * dispatch executor, before the call starts. A feature call that gets a permit is moved to the * bounded work pool; one that does not stays on the dispatch executor and is marked, and this same * object, installed as the outermost feature interceptor, closes the marked call with {@code - * RATE_LIMIT_EXCEEDED} without starting the handler. The permit is returned once, when the admitted - * call completes or is cancelled. Health and reflection are not feature calls: they take no permit - * and run on the dispatch executor, so a saturated pool cannot make health lie. + * SERVER_BUSY} ({@code UNAVAILABLE}) without starting the handler: the shared code every transport + * answers server saturation with, not the caller-rate {@code RATE_LIMIT_EXCEEDED} it used to be. + * The permit is returned once, when the admitted call completes or is cancelled. Health and + * reflection are not feature calls: they take no permit and run on the dispatch executor, so a + * saturated pool cannot make health lie. * *

Each admitted call has at most one task in the work pool at a time (io.grpc serializes a * call's callbacks), so a work queue as deep as the permit count can never reject. @@ -79,8 +81,8 @@ final class GrpcCallAdmission implements ServerCallExecutorSupplier, ServerInter ServerCall call, Metadata headers, ServerCallHandler next) { if (refused.remove(headers)) { call.close( - statusMapper.statusFor(OperationalError.RATE_LIMIT_EXCEEDED), - statusMapper.trailersFor(OperationalError.RATE_LIMIT_EXCEEDED)); + statusMapper.statusFor(OperationalError.SERVER_BUSY), + statusMapper.trailersFor(OperationalError.SERVER_BUSY)); return new ServerCall.Listener<>() {}; } AtomicBoolean released = new AtomicBoolean(); diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcStatusMapper.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcStatusMapper.java index 1fa5c57a..0e7b1b36 100644 --- a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcStatusMapper.java +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcStatusMapper.java @@ -17,9 +17,7 @@ import io.grpc.Status; */ public class GrpcStatusMapper { - /** - * Trailer key carrying the stable {@link ApiErrorCode#code()} (e.g. {@code WORKLOG_NOT_FOUND}). - */ + /** Trailer key carrying the stable {@link ApiErrorCode#code()} (e.g. {@code SERVER_BUSY}). */ static final Metadata.Key CODE_KEY = Metadata.Key.of("error-code", Metadata.ASCII_STRING_MARSHALLER); diff --git a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcP1BoundaryWireTest.java b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcP1BoundaryWireTest.java index 97fd4735..cbd20d75 100644 --- a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcP1BoundaryWireTest.java +++ b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcP1BoundaryWireTest.java @@ -329,8 +329,8 @@ class GrpcP1BoundaryWireTest { } @Test - @DisplayName("스레드와 대기열이 모두 찬 서버는 넘친 호출을 기다리게 두지 않고 즉시 RESOURCE_EXHAUSTED로 거절한다") - void aCallBeyondTheExecutorAndQueueIsRefusedAtOnceAsResourceExhausted() { + @DisplayName("스레드와 대기열이 모두 찬 서버는 넘친 호출을 기다리게 두지 않고 즉시 UNAVAILABLE(SERVER_BUSY)로 거절한다") + void aCallBeyondTheExecutorAndQueueIsRefusedAtOnceAsServerBusy() { withChannel( contextRunner.withPropertyValues( "app.grpc.server.executor-max-pool-size=1", @@ -351,12 +351,11 @@ class GrpcP1BoundaryWireTest { // then assertThat(outcomes) .extracting(Status::getCode) - .containsExactlyInAnyOrder( - Status.Code.OK, Status.Code.OK, Status.Code.RESOURCE_EXHAUSTED); + .containsExactlyInAnyOrder(Status.Code.OK, Status.Code.OK, Status.Code.UNAVAILABLE); assertThat(outcomes) .filteredOn(status -> !status.isOk()) .extracting(Status::getDescription) - .containsExactly(ClientErrorMessages.of(Category.RATE_LIMIT)); + .containsExactly(ClientErrorMessages.of(Category.TRANSIENT_DEPENDENCY)); }); } diff --git a/src/adapter/inbound/web-advanced/README.md b/src/adapter/inbound/web-advanced/README.md index 3b854a88..9ae11896 100644 --- a/src/adapter/inbound/web-advanced/README.md +++ b/src/adapter/inbound/web-advanced/README.md @@ -51,14 +51,14 @@ virtual thread 실행기는 `TaskDecorator` bean 을 요구한다(요청 상관 이 leaf 의 예외는 모두 `ApiErrorCarrier` 다. 코드는 `error.WebAdvancedError` 한 enum 이 정하고, web 의 `GlobalExceptionHandler.handleCarrier` 한 분기가 Envelope 로 답한다(별도 `@RestControllerAdvice` 없음). -예전에는 10종 모두 `500 INTERNAL_ERROR` 였다(리뷰 2026-11-01 02-07). 아래 표와 enum 은 같은 값을 말하고, +예전에는 10종 모두 `500 INTERNAL_ERROR` 였다(리뷰 2026-11-01 02-07). admission 거절은 2026-11-12부터 공용 `SERVER_BUSY`다. 아래 표와 enum 은 같은 값을 말하고, `WebAdvancedErrorMappingTest` 가 실제 응답으로 확인한다. | 예외 | `error.code` | status | category | retryable | 응답에 더 실리는 것 | 클라이언트 행동 | | --- | --- | --- | --- | --- | --- | --- | -| `AdmissionRefusedException` | `ADMISSION_REFUSED` | 503 | `TRANSIENT_DEPENDENCY` | true | `Retry-After: 1` | 잠시 뒤 같은 요청 | +| `AdmissionRefusedException` | `SERVER_BUSY`(공용 `OperationalError`) | 503 | `TRANSIENT_DEPENDENCY` | true | `Retry-After: 1` | 잠시 뒤 같은 요청. 서버 포화는 모든 전송이 이 코드 하나다 | | `JsonPatchTestFailedException` | `PATCH_TEST_FAILED` | 409 | `CONFLICT` | false | `details.pointer`(서버 값은 없음) | 다시 읽고 새 patch | -| `JsonPatchRejectedException` | `PATCH_REJECTED` | 400 | `VALIDATION` | false | — | patch 문서를 고친다 | +| `JsonPatchRejectedException` | `PATCH_REJECTED` | 400 | `VALIDATION` | false | — | patch 문서를 고친다. JSON이 아닌 본문, 빈 문서, 한도·깊이 초과, 연산 모양 오류, 결과가 자원 타입으로 읽히지 않는 patch가 모두 이 코드다 | | `PatchAuthorizationException` | `PATCH_PATH_FORBIDDEN` | 403 | `AUTHZ` | false | `details.refusedPaths` | 해당 경로를 빼거나 권한 확보 | | `UnsupportedApiVersionException` | `API_VERSION_UNSUPPORTED` | 404 | `NOT_FOUND` | false | — | 지원 버전 경로로 | | `SunsetViolationException` | `API_DEPRECATION_INVALID` | 500 | `INTERNAL` | false | — | 서버 설정 결함(등록 시점 오류) | diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedError.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedError.java index 7729b0f0..d6ef5439 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedError.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedError.java @@ -11,16 +11,14 @@ import dev.caskeleton.shared.error.Category; * leaf README's "오류 응답" section; it states the same values. * *

Before this existed every one of these reached the client as {@code 500 INTERNAL_ERROR} with - * an ERROR log line, including an admission refusal the profile documents as a 503 (review - * 2026-11-01 02-07). + * an ERROR log line (review 2026-11-01 02-07). The admission refusal it used to name is now the + * shared {@code OperationalError.SERVER_BUSY} (review 2026-11-12). * *

Like {@code RateLimitTransportError}, these are not in {@code * docs/registries/error-codes.yaml}, which is the {@code OperationalError} SSOT. */ public enum WebAdvancedError implements ApiErrorCode, RetryAfterHint { - /** The virtual-thread admission limit was full. A refusal in a millisecond; come back shortly. */ - ADMISSION_REFUSED(Category.TRANSIENT_DEPENDENCY, 503, true, 1), /** A JSON Patch {@code test} did not hold; nothing was applied. Re-read, then retry. */ PATCH_TEST_FAILED(Category.CONFLICT, 409, false, 0), /** The patch document is malformed or over a limit; nothing was applied. */ diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java index c836c18f..aee74a29 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java @@ -6,6 +6,10 @@ import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamTermination; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.NdjsonRecord; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamFraming; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.ClientErrorMessages; +import dev.caskeleton.shared.error.OperationalError; import java.io.IOException; import java.io.OutputStream; import java.time.Clock; @@ -20,6 +24,16 @@ import java.util.Objects; * terminal record before closing, and classify a write failure rather than letting it become a 500 * on a response that is already 200. * + *

Positions are enforced before each write, by {@code WebStreamEvidence#requireNext}: an item + * whose sequence is not above the previous one is a server fault, and the stream ends with a + * terminal failure record instead of handing the client a repeat or a rewind it would apply. + * + *

What this writer does not do: it writes synchronously from an iterator on the request thread, + * so it sends no heartbeat while the source is blocked, enforces no idle timeout or maximum age, + * and keeps no buffer (a slow consumer blocks the source instead). Those bounds are in {@code + * WebStreamPolicy} and the drain in {@code WebStreamDrainCoordinator} for a service that runs its + * streams through {@code WebStreamRegistry}; {@code docs/web/streaming-contract.md} says which. + * *

**Flushing after every record is not optional.** Without it the container buffers, and a * streaming response that arrives in one chunk at the end is a slow non-streaming response — which * passes every test that checks the body and fails the only thing the client wanted. @@ -58,6 +72,10 @@ public final class MvcStreamWriter { try { while (records.hasNext()) { NdjsonRecord record = records.next(); + if (record instanceof NdjsonRecord.Item item) { + // WebStreamEvidence owns the rule; asked before the write so the item never leaves. + evidence.requireNext(new StreamSequence(item.sequence())); + } writeRecord(record, output); if (record instanceof NdjsonRecord.Item item) { evidence.recordDelivered(new StreamSequence(item.sequence())); @@ -91,13 +109,17 @@ public final class MvcStreamWriter { } // Otherwise the source failed after commit. The status is already 200, so the failure goes // into the stream as a terminal record — and if even that cannot be written, it is an abrupt - // close and is recorded as one rather than counted as a completion. + // close and is recorded as one rather than counted as a completion. The record carries the + // failure's own code when it has one (a carrier anywhere in the cause chain, such as + // STREAM_ITEM_TOO_LARGE), else the registered INTERNAL_ERROR, and the category's fixed message: + // the same code and wording a client would have read before commit. + ApiErrorCode code = + ApiErrorCarrier.firstIn(failure) + .map(carrier -> ((ApiErrorCarrier) carrier).errorCode()) + .orElse(OperationalError.INTERNAL_ERROR); try { writeRecord( - new NdjsonRecord.Failure( - lastSequence, - "DEPENDENCY_FAILURE", - "the stream ended early because a dependency failed"), + new NdjsonRecord.Failure(lastSequence, code.code(), ClientErrorMessages.of(code)), output); evidence.recordTermination(WebStreamTermination.TERMINAL_ERROR_RECORD, clock.instant()); return WebStreamTermination.TERMINAL_ERROR_RECORD; diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java new file mode 100644 index 00000000..87f4344c --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java @@ -0,0 +1,119 @@ +package dev.caskeleton.adapter.inbound.web.advanced.mvc; + +import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.AdmissionRefusedException; +import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadAdmissionGuard; +import dev.caskeleton.adapter.inbound.web.error.EnvelopeResponseWriter; +import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; +import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor; +import jakarta.servlet.AsyncEvent; +import jakarta.servlet.AsyncListener; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Objects; +import org.springframework.core.Ordered; +import org.springframework.web.filter.OncePerRequestFilter; +import tools.jackson.databind.ObjectMapper; + +/** + * Puts every request under the virtual-thread admission limit. + * + *

The guard alone was a bean nothing called: the profile promised a {@code 503} with {@code + * Retry-After} past the limit, and a deployment that switched it on admitted every arrival (review + * 2026-11-12). A filter, not an interceptor, so the limit covers the handler and its async work; + * ordered after the security chain (see {@link #ORDER}). + * + *

A request that goes async keeps its permit until the async work ends: releasing when this + * thread returns would bound only the hand-off, and the work the limit protects the downstream + * pools from happens after it. + */ +public final class VirtualThreadAdmissionFilter extends OncePerRequestFilter implements Ordered { + + /** + * Right after the Spring Security filter chain (Boot's {@code SecurityProperties + * .DEFAULT_FILTER_ORDER}, -100). Two reasons. The chain applies CORS, so a cross-origin refusal + * carries {@code Access-Control-Allow-Origin} and the browser can read its 503 and {@code + * Retry-After}; in front of the chain it reached the page as a network error. And a request the + * chain refuses (unauthenticated, forbidden) never takes a permit from the admitted ones (review + * 2026-11-12). + */ + public static final int ORDER = -99; + + private final VirtualThreadAdmissionGuard guard; + private final ObjectMapper objectMapper; + + public VirtualThreadAdmissionFilter( + VirtualThreadAdmissionGuard guard, ObjectMapper objectMapper) { + this.guard = Objects.requireNonNull(guard, "guard"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); + } + + @Override + public int getOrder() { + return ORDER; + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + VirtualThreadAdmissionGuard.Permit permit; + try { + permit = guard.enter(); + } catch (AdmissionRefusedException refused) { + RetryAfterAdvisor.retryAfterSeconds(refused.errorCode()) + .ifPresent( + seconds -> response.setHeader(ApiHeaders.RETRY_AFTER, Integer.toString(seconds))); + EnvelopeResponseWriter.write(response, refused.errorCode(), objectMapper); + return; + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new ServletException("interrupted while waiting for admission", interrupted); + } + boolean handedToAsync = false; + try { + chain.doFilter(request, response); + if (request.isAsyncStarted()) { + request.getAsyncContext().addListener(new ReleaseWhenDone(permit)); + handedToAsync = true; + } + } finally { + if (!handedToAsync) { + permit.close(); + } + } + } + + /** Releases the permit when the async request ends, however it ends. */ + private static final class ReleaseWhenDone implements AsyncListener { + + private final VirtualThreadAdmissionGuard.Permit permit; + + ReleaseWhenDone(VirtualThreadAdmissionGuard.Permit permit) { + this.permit = permit; + } + + @Override + public void onComplete(AsyncEvent event) { + permit.close(); + } + + @Override + public void onTimeout(AsyncEvent event) { + permit.close(); + } + + @Override + public void onError(AsyncEvent event) { + permit.close(); + } + + @Override + public void onStartAsync(AsyncEvent event) { + // A restarted async cycle drops the listeners of the previous one. + event.getAsyncContext().addListener(this); + } + } +} diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java index 2273845c..617513f5 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java @@ -13,6 +13,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.core.task.TaskDecorator; import org.springframework.core.task.support.TaskExecutorAdapter; +import tools.jackson.databind.ObjectMapper; /** * Wires the virtual-thread executor and, in the same configuration, the admission limit. @@ -57,6 +58,17 @@ public class VirtualThreadMvcConfiguration { properties.getAdmissionLimit(), properties.getAdmissionWait()); } + /** + * The request path through the guard: without this the guard is a bean nothing calls, and the + * profile admits every arrival while promising a 503 past the limit. + */ + @Bean + @ConditionalOnMissingBean + public VirtualThreadAdmissionFilter virtualThreadAdmissionFilter( + VirtualThreadAdmissionGuard guard, ObjectMapper objectMapper) { + return new VirtualThreadAdmissionFilter(guard, objectMapper); + } + /** * The executor Spring MVC dispatches async request handling onto. * diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java index ce301568..11ddfe0a 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch; +import jakarta.validation.Validator; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -23,14 +24,19 @@ import tools.jackson.databind.node.ObjectNode; public final class JsonMergePatchApplier { private final ObjectMapper mapper; + private final Validator validator; private final PatchFieldAuthorization authorization; /** * @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean) * @param authorization which fields may be modified + * @param validator the service's Bean Validation validator (Boot's {@code Validator} bean); the + * patched document is validated whole before it is returned */ - public JsonMergePatchApplier(ObjectMapper mapper, PatchFieldAuthorization authorization) { + public JsonMergePatchApplier( + ObjectMapper mapper, PatchFieldAuthorization authorization, Validator validator) { this.mapper = Objects.requireNonNull(mapper, "mapper"); + this.validator = Objects.requireNonNull(validator, "validator"); this.authorization = Objects.requireNonNull(authorization, "authorization"); } @@ -52,7 +58,8 @@ public final class JsonMergePatchApplier { authorization.validate(patch.fieldNames()); JsonNode before = mapper.valueToTree(current); if (!before.isObject()) { - throw new IllegalArgumentException("a merge patch target must serialize to a JSON object"); + // The target type is the server's choice, so this is a server fault, not a bad request. + throw new IllegalStateException("a merge patch target must serialize to a JSON object"); } ObjectNode after = merge((ObjectNode) before.deepCopy(), patch.root()); List modified = new ArrayList<>(); @@ -63,7 +70,7 @@ public final class JsonMergePatchApplier { modified.add(field); } } - return new PatchResult<>(mapper.treeToValue(after, type), modified); + return new PatchResult<>(PatchBodies.toTarget(mapper, validator, after, type), modified); } private static ObjectNode merge(ObjectNode target, ObjectNode patch) { diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java index 4aad82e0..87ffb87d 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java @@ -25,7 +25,7 @@ public record JsonMergePatchDocument(ObjectNode root) { Objects.requireNonNull(root, "root"); int depth = depthOf(root, 1); if (depth > MAX_DEPTH) { - throw new IllegalArgumentException( + throw new JsonPatchRejectedException( "a merge patch nested " + depth + " deep exceeds the " @@ -56,17 +56,17 @@ public record JsonMergePatchDocument(ObjectNode root) { * * @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean) * @param body the request body - * @throws IllegalArgumentException if the body is not a JSON object + * @throws JsonPatchRejectedException if the body is not JSON or not a JSON object */ public static JsonMergePatchDocument parse(ObjectMapper mapper, byte[] body) { Objects.requireNonNull(mapper, "mapper"); Objects.requireNonNull(body, "body"); - JsonNode parsed = mapper.readTree(body); + JsonNode parsed = PatchBodies.readTree(mapper, body); if (!parsed.isObject()) { // RFC 7396 permits a scalar or an array as a whole-document replacement. Refused here: a // merge patch that replaces the entire resource is a PUT, and routing it through the patch // path skips the full-document validation a PUT gets. - throw new IllegalArgumentException( + throw new JsonPatchRejectedException( "a merge patch must be a JSON object; a scalar or array patch replaces the whole " + "resource, which is a PUT and belongs on the PUT route with its validation"); } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java index 04a2e8ba..5803aac4 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch; +import jakarta.validation.Validator; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -27,14 +28,19 @@ import tools.jackson.databind.node.ObjectNode; public final class JsonPatchApplier { private final ObjectMapper mapper; + private final Validator validator; private final JsonPointerAuthorization authorization; /** * @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean) * @param authorization which pointers may be modified + * @param validator the service's Bean Validation validator (Boot's {@code Validator} bean); the + * patched document is validated whole before it is returned */ - public JsonPatchApplier(ObjectMapper mapper, JsonPointerAuthorization authorization) { + public JsonPatchApplier( + ObjectMapper mapper, JsonPointerAuthorization authorization, Validator validator) { this.mapper = Objects.requireNonNull(mapper, "mapper"); + this.validator = Objects.requireNonNull(validator, "validator"); this.authorization = Objects.requireNonNull(authorization, "authorization"); } @@ -61,9 +67,9 @@ public final class JsonPatchApplier { } } if (working.equals(before)) { - return new PatchResult<>(mapper.treeToValue(working, type), List.of()); + return new PatchResult<>(PatchBodies.toTarget(mapper, validator, working, type), List.of()); } - return new PatchResult<>(mapper.treeToValue(working, type), touched); + return new PatchResult<>(PatchBodies.toTarget(mapper, validator, working, type), touched); } private JsonNode applyOne(JsonNode root, JsonPatchOperation operation) { diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java index b461b6c0..d560b4fd 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java @@ -24,7 +24,7 @@ public record JsonPatchDocument(List operations) { public JsonPatchDocument { operations = List.copyOf(Objects.requireNonNull(operations, "operations")); if (operations.isEmpty()) { - throw new IllegalArgumentException( + throw new JsonPatchRejectedException( "an empty patch document changes nothing; sending one is a client bug and answering 200 " + "hides it"); } @@ -43,11 +43,12 @@ public record JsonPatchDocument(List operations) { * * @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean) * @param body the request body + * @throws JsonPatchRejectedException if the body is not JSON or not a valid patch document */ public static JsonPatchDocument parse(ObjectMapper mapper, byte[] body) { Objects.requireNonNull(mapper, "mapper"); Objects.requireNonNull(body, "body"); - JsonNode root = mapper.readTree(body); + JsonNode root = PatchBodies.readTree(mapper, body); if (!root.isArray()) { throw new JsonPatchRejectedException( "an RFC 6902 patch is an array of operations; an object here is a merge patch sent to " diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperation.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperation.java index 79d2c290..65c7ab4e 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperation.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperation.java @@ -26,22 +26,22 @@ public record JsonPatchOperation( Objects.requireNonNull(value, "value"); Objects.requireNonNull(from, "from"); if (!path.isEmpty() && !path.startsWith("/")) { - throw new IllegalArgumentException("a JSON Pointer is empty or starts with '/': " + path); + throw new JsonPatchRejectedException("a JSON Pointer is empty or starts with '/': " + path); } if (kind.requiresValue() != value.isPresent()) { - throw new IllegalArgumentException( + throw new JsonPatchRejectedException( kind.wireName() + (kind.requiresValue() ? " requires a value member" : " carries no value member, and one here means the client meant a different op")); } if (kind.requiresFrom() != from.isPresent()) { - throw new IllegalArgumentException( + throw new JsonPatchRejectedException( kind.wireName() + (kind.requiresFrom() ? " requires a from member" : " carries no from member")); } if (from.isPresent() && !from.get().isEmpty() && !from.get().startsWith("/")) { - throw new IllegalArgumentException("a JSON Pointer is empty or starts with '/'"); + throw new JsonPatchRejectedException("a JSON Pointer is empty or starts with '/'"); } if (kind == JsonPatchOperationKind.MOVE && from.isPresent() @@ -49,7 +49,7 @@ public record JsonPatchOperation( // RFC 6902 section 4.4: the target cannot be inside the source. Moving a subtree into itself // is not a thing that has a result, and an implementation that tries produces either an // infinite structure or a silently truncated one. - throw new IllegalArgumentException("a move cannot target a location inside its own source"); + throw new JsonPatchRejectedException("a move cannot target a location inside its own source"); } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPointerAuthorization.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPointerAuthorization.java index bf47c21b..3e6b2273 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPointerAuthorization.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPointerAuthorization.java @@ -66,10 +66,21 @@ public final class JsonPointerAuthorization { /** * Check every pointer a document names, including {@code from} pointers. * - * @throws PatchAuthorizationException naming all of them + * @throws JsonPatchRejectedException if a pointer is deeper than {@link #MAX_POINTER_DEPTH}: a + * malformed document, not a permission question + * @throws PatchAuthorizationException naming every pointer the caller may not modify */ public void validate(List operations) { Objects.requireNonNull(operations, "operations"); + for (JsonPatchOperation operation : operations) { + boolean tooDeep = + depthOf(operation.path()) > MAX_POINTER_DEPTH + || operation.from().filter(from -> depthOf(from) > MAX_POINTER_DEPTH).isPresent(); + if (tooDeep) { + throw new JsonPatchRejectedException( + "a JSON Pointer deeper than " + MAX_POINTER_DEPTH + " segments is over the limit"); + } + } List refused = new ArrayList<>(); for (JsonPatchOperation operation : operations) { if (operation.kind().mutating() && !writable(operation.path())) { diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java new file mode 100644 index 00000000..63853ad5 --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java @@ -0,0 +1,55 @@ +package dev.caskeleton.adapter.inbound.web.advanced.patch; + +import jakarta.validation.ConstraintViolation; +import jakarta.validation.ConstraintViolationException; +import jakarta.validation.Validator; +import java.util.Set; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * The two places a patch meets Jackson, answered as the patch's fault rather than the server's. + * + *

A body that is not JSON, and a patched tree that no longer reads as the target type (a string + * where a number was), are both the client's document. Left to Jackson they reached the web + * adapter's catch-all as {@code 500 INTERNAL_ERROR}; here they are {@code 400 PATCH_REJECTED} like + * every other patch the server will not apply (review 2026-11-12). + */ +final class PatchBodies { + + private PatchBodies() {} + + static JsonNode readTree(ObjectMapper mapper, byte[] body) { + try { + return mapper.readTree(body); + } catch (JacksonException notJson) { + throw new JsonPatchRejectedException("the patch body is not a JSON document"); + } + } + + /** + * The patched tree as the target type, validated as a whole document. + * + *

Whole, not field by field: two fields whose values must agree are invisible to a check of + * the changed fields alone. {@code T} is the web representation DTO, whose constraints are + * request syntax (web AGENTS B4·C1); business rules such as allowed state transitions belong to + * the use case the caller hands the result to as a command. A violation is the same {@link + * ConstraintViolationException} a {@code @Valid} body raises, so the client gets {@code 400 + * VALIDATION_FAILED} with the per-field details it already knows. + */ + static T toTarget(ObjectMapper mapper, Validator validator, JsonNode patched, Class type) { + T result; + try { + result = mapper.treeToValue(patched, type); + } catch (JacksonException wrongShape) { + throw new JsonPatchRejectedException( + "the patched document no longer reads as the resource: a value has the wrong type"); + } + Set> violations = validator.validate(result); + if (!violations.isEmpty()) { + throw new ConstraintViolationException(violations); + } + return result; + } +} diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java index f02a2b1f..10927ca7 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java @@ -38,6 +38,22 @@ public final class WebStreamEvidence { return streamId; } + /** + * Refuse a position before it is written: the same check {@link #recordDelivered} makes after the + * write, so a writer can keep a repeat or a rewind off the wire instead of only recording it. + * + * @throws IllegalStateException if the position does not advance, or the stream already ended + */ + public void requireNext(StreamSequence sequence) { + Objects.requireNonNull(sequence, "sequence"); + lock.lock(); + try { + requireAdvances(sequence); + } finally { + lock.unlock(); + } + } + /** * Record that an item reached the transport. * @@ -47,20 +63,7 @@ public final class WebStreamEvidence { Objects.requireNonNull(sequence, "sequence"); lock.lock(); try { - if (termination != null) { - throw new IllegalStateException( - "an item was delivered after the stream ended as " - + termination - + "; the terminal envelope has already told the client there is nothing more"); - } - if (lastDelivered != null && sequence.compareTo(lastDelivered) <= 0) { - throw new IllegalStateException( - "stream position went from " - + lastDelivered.value() - + " to " - + sequence.value() - + "; a client deduplicating on position would silently drop this item"); - } + requireAdvances(sequence); lastDelivered = sequence; deliveredCount++; } finally { @@ -68,6 +71,24 @@ public final class WebStreamEvidence { } } + /** Callers hold the lock. */ + private void requireAdvances(StreamSequence sequence) { + if (termination != null) { + throw new IllegalStateException( + "an item was delivered after the stream ended as " + + termination + + "; the terminal envelope has already told the client there is nothing more"); + } + if (lastDelivered != null && sequence.compareTo(lastDelivered) <= 0) { + throw new IllegalStateException( + "stream position went from " + + lastDelivered.value() + + " to " + + sequence.value() + + "; a client deduplicating on position would silently drop this item"); + } + } + /** Record how the stream ended. The first call wins; the end happens once. */ public void recordTermination(WebStreamTermination how, Instant at) { Objects.requireNonNull(how, "how"); diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java index 36912a06..aa75b2d0 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java @@ -1,8 +1,8 @@ package dev.caskeleton.adapter.inbound.web.advanced.virtualthread; -import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError; import dev.caskeleton.shared.error.ApiErrorCarrier; import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.OperationalError; /** * An arrival was refused because the concurrency limit was full. @@ -27,9 +27,12 @@ public final class AdmissionRefusedException extends RuntimeException implements return limit; } - /** {@link WebAdvancedError#ADMISSION_REFUSED}; see the leaf README for the client contract. */ + /** + * {@link OperationalError#SERVER_BUSY}, the one code every transport answers server saturation + * with; see the leaf README for the client contract. + */ @Override public ApiErrorCode errorCode() { - return WebAdvancedError.ADMISSION_REFUSED; + return OperationalError.SERVER_BUSY; } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionGuard.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionGuard.java index b66aed53..707391a5 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionGuard.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionGuard.java @@ -4,6 +4,7 @@ import java.time.Duration; import java.util.Objects; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; @@ -57,17 +58,42 @@ public final class VirtualThreadAdmissionGuard { */ public T run(java.util.concurrent.Callable work) throws Exception { Objects.requireNonNull(work, "work"); + try (Permit permit = enter()) { + return work.call(); + } + } + + /** + * Take a permit for work that does not end on this thread, such as an async request. + * + * @return the permit; closing it releases, and closing it twice releases once + * @throws AdmissionRefusedException if no permit became available in time + * @throws InterruptedException if interrupted while waiting + */ + public Permit enter() throws InterruptedException { if (!permits.tryAcquire(acquireTimeout.toMillis(), TimeUnit.MILLISECONDS)) { rejected.incrementAndGet(); throw new AdmissionRefusedException(limit); } int current = active.incrementAndGet(); peakActive.accumulateAndGet(current, Math::max); - try { - return work.call(); - } finally { - active.decrementAndGet(); - permits.release(); + return new Permit(); + } + + /** One admitted unit of work. */ + public final class Permit implements AutoCloseable { + + private final AtomicBoolean released = new AtomicBoolean(); + + private Permit() {} + + /** Release, once. An async request ends through more than one listener callback. */ + @Override + public void close() { + if (released.compareAndSet(false, true)) { + active.decrementAndGet(); + permits.release(); + } } } diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedErrorMappingTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedErrorMappingTest.java index 6e810ebf..f2e85e17 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedErrorMappingTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedErrorMappingTest.java @@ -62,7 +62,7 @@ class WebAdvancedErrorMappingTest { static Stream documentedMappings() { return Stream.of( - Arguments.of("admission", 503, "ADMISSION_REFUSED", "TRANSIENT_DEPENDENCY", true), + Arguments.of("admission", 503, "SERVER_BUSY", "TRANSIENT_DEPENDENCY", true), Arguments.of("patch-test", 409, "PATCH_TEST_FAILED", "CONFLICT", false), Arguments.of("patch-rejected", 400, "PATCH_REJECTED", "VALIDATION", false), Arguments.of("patch-forbidden", 403, "PATCH_PATH_FORBIDDEN", "AUTHZ", false), diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java index ee30ac31..20c76e91 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java @@ -68,6 +68,7 @@ class MvcAdvancedConfigurationTest { .hasNotFailed() .doesNotHaveBean(StreamRecordEncoder.class) .doesNotHaveBean(VirtualThreadAdmissionGuard.class) + .doesNotHaveBean(VirtualThreadAdmissionFilter.class) .doesNotHaveBean(AsyncTaskExecutor.class)); } @@ -125,6 +126,7 @@ class MvcAdvancedConfigurationTest { .hasNotFailed() .hasSingleBean(VirtualThreadProfile.class) .hasSingleBean(VirtualThreadAdmissionGuard.class) + .hasSingleBean(VirtualThreadAdmissionFilter.class) .hasBean("applicationTaskExecutor"); assertThat(context.getBean(VirtualThreadAdmissionGuard.class).limit()).isEqualTo(100); assertThat(context.getBean(VirtualThreadProfile.class).databasePoolSize()) diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java index c738bbbe..f9e25a24 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java @@ -92,7 +92,10 @@ class MvcStreamingWiringTest { writer.write(failingAfter(NdjsonRecord.item(1, "a")), output, evidence); assertThat(how).isEqualTo(WebStreamTermination.TERMINAL_ERROR_RECORD); - assertThat(output.text()).contains("DEPENDENCY_FAILURE"); + assertThat(output.text()) + .as("a failure without a code of its own is the registered INTERNAL_ERROR") + .contains("\"code\":\"INTERNAL_ERROR\"") + .doesNotContain("DEPENDENCY_FAILURE"); assertThat(evidence.termination()).contains(WebStreamTermination.TERMINAL_ERROR_RECORD); } @@ -129,6 +132,58 @@ class MvcStreamingWiringTest { .hasMessageContaining("exceeds the 16 byte ceiling"); } + @Test + @DisplayName("commit 뒤 실패 기록은 실패한 예외의 코드와 고정 문구를 싣는다") + void aTerminalRecordCarriesTheFailuresOwnCode() { + // given + CountingStream output = new CountingStream(); + WebStreamPolicy small = + new WebStreamPolicy( + Duration.ofSeconds(15), Duration.ofSeconds(60), Duration.ofMinutes(30), 8, 200); + MvcStreamWriter writer = + new MvcStreamWriter(encoder(small), StreamFraming.NDJSON, Clock.systemUTC()); + WebStreamEvidence evidence = new WebStreamEvidence(new StreamId("feed"), NOW); + + // when + WebStreamTermination how = + writer.write( + List.>of( + NdjsonRecord.item(1, "a"), NdjsonRecord.item(2, "x".repeat(1_000))) + .iterator(), + output, + evidence); + + // then + assertThat(how).isEqualTo(WebStreamTermination.TERMINAL_ERROR_RECORD); + assertThat(output.text()) + .contains("\"code\":\"STREAM_ITEM_TOO_LARGE\"") + .contains(dev.caskeleton.shared.error.ClientErrorMessages.OPAQUE); + } + + @Test + @DisplayName("위치가 앞 항목보다 크지 않으면 서버 오류로 끝내고 그 항목은 쓰지 않는다") + void aRepeatedPositionEndsTheStreamInsteadOfReachingTheClient() { + // given + CountingStream output = new CountingStream(); + MvcStreamWriter writer = + new MvcStreamWriter( + encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON, Clock.systemUTC()); + WebStreamEvidence evidence = new WebStreamEvidence(new StreamId("feed"), NOW); + + // when + WebStreamTermination how = + writer.write( + List.>of( + NdjsonRecord.item(1, "a"), NdjsonRecord.item(2, "b"), NdjsonRecord.item(2, "c")) + .iterator(), + output, + evidence); + + // then + assertThat(how).isEqualTo(WebStreamTermination.TERMINAL_ERROR_RECORD); + assertThat(output.text()).doesNotContain("\"c\"").contains("\"code\":\"INTERNAL_ERROR\""); + } + /** A stream that counts flushes and can fail on a chosen write. */ private static final class CountingStream extends OutputStream { diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java new file mode 100644 index 00000000..18dbb94d --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java @@ -0,0 +1,150 @@ +package dev.caskeleton.adapter.inbound.web.advanced.mvc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.AdmissionRefusedException; +import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadAdmissionGuard; +import jakarta.servlet.AsyncEvent; +import jakarta.servlet.AsyncListener; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockAsyncContext; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import tools.jackson.databind.json.JsonMapper; + +/** + * The request path through the admission guard. + * + *

required_test: {@code contract-verification:server-saturation} — a full limit answers the + * shared {@code SERVER_BUSY} 503 with {@code Retry-After}, before any handler runs. + */ +@Tag("web-advanced") +class VirtualThreadAdmissionFilterTest { + + @Test + @DisplayName("한도가 차면 요청은 controller에 닿지 않고 503 SERVER_BUSY와 Retry-After를 받는다") + void aFullLimitRefusesWith503AndRetryAfter() throws Exception { + // given + VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO); + VirtualThreadAdmissionFilter filter = + new VirtualThreadAdmissionFilter(guard, JsonMapper.shared()); + AtomicInteger reached = new AtomicInteger(); + MockHttpServletResponse response = new MockHttpServletResponse(); + + // when + try (VirtualThreadAdmissionGuard.Permit held = guard.enter()) { + filter.doFilter( + new MockHttpServletRequest("GET", "/orders"), + response, + (request, servletResponse) -> reached.incrementAndGet()); + } + + // then + assertThat(reached).as("the guard was a bean nothing called").hasValue(0); + assertThat(response.getStatus()).isEqualTo(503); + assertThat(response.getHeader("Retry-After")).isEqualTo("1"); + assertThat(response.getContentAsString()).contains("SERVER_BUSY"); + assertThat(guard.rejectedCount()).isEqualTo(1); + } + + @Test + @DisplayName("동기 요청은 끝나면 permit을 돌려준다") + void aSynchronousRequestReleasesItsPermit() throws Exception { + // given + VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO); + VirtualThreadAdmissionFilter filter = + new VirtualThreadAdmissionFilter(guard, JsonMapper.shared()); + AtomicInteger activeInside = new AtomicInteger(-1); + + // when + filter.doFilter( + new MockHttpServletRequest("GET", "/orders"), + new MockHttpServletResponse(), + (request, response) -> activeInside.set(guard.active())); + + // then + assertThat(activeInside).hasValue(1); + assertThat(guard.active()).isZero(); + } + + @Test + @DisplayName("async 요청은 async 일이 끝날 때까지 permit을 쥔다") + void anAsyncRequestHoldsItsPermitUntilTheAsyncWorkEnds() throws Exception { + // given + VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO); + VirtualThreadAdmissionFilter filter = + new VirtualThreadAdmissionFilter(guard, JsonMapper.shared()); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/orders"); + request.setAsyncSupported(true); + MockHttpServletResponse response = new MockHttpServletResponse(); + + // when + filter.doFilter(request, response, (req, res) -> request.startAsync(req, res)); + int activeAfterHandOff = guard.active(); + request.getAsyncContext().complete(); + + // then + assertThat(activeAfterHandOff) + .as("releasing on hand-off would bound only the hand-off, not the work") + .isEqualTo(1); + assertThat(guard.active()).isZero(); + } + + @Test + @DisplayName("async 시간 초과 뒤 완료가 또 와도 permit은 한 번만 돌아가 상한이 늘지 않는다") + void aTimeoutFollowedByCompletionReleasesThePermitOnce() throws Exception { + // given + VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO); + VirtualThreadAdmissionFilter filter = + new VirtualThreadAdmissionFilter(guard, JsonMapper.shared()); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/orders"); + request.setAsyncSupported(true); + filter.doFilter( + request, new MockHttpServletResponse(), (req, res) -> request.startAsync(req, res)); + MockAsyncContext async = (MockAsyncContext) request.getAsyncContext(); + AsyncEvent event = new AsyncEvent(async); + + // when — a container calls onTimeout, then onComplete, for one timed-out request + for (AsyncListener listener : async.getListeners()) { + listener.onTimeout(event); + listener.onComplete(event); + } + + // then + assertThat(guard.active()).isZero(); + try (VirtualThreadAdmissionGuard.Permit only = guard.enter()) { + assertThat(catchThrowable(guard::enter)) + .as("a permit released twice would let a second request past a limit of one") + .isInstanceOf(AdmissionRefusedException.class); + } + } + + @Test + @DisplayName("async가 다시 시작되면 새 cycle에도 permit을 돌려주는 listener가 붙는다") + void aRestartedAsyncCycleKeepsTheReleaseListener() throws Exception { + // given + VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO); + VirtualThreadAdmissionFilter filter = + new VirtualThreadAdmissionFilter(guard, JsonMapper.shared()); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/orders"); + request.setAsyncSupported(true); + MockHttpServletResponse response = new MockHttpServletResponse(); + filter.doFilter(request, response, (req, res) -> request.startAsync(req, res)); + MockAsyncContext first = (MockAsyncContext) request.getAsyncContext(); + MockAsyncContext restarted = new MockAsyncContext(request, response); + + // when + for (AsyncListener listener : first.getListeners()) { + listener.onStartAsync(new AsyncEvent(restarted)); + } + restarted.complete(); + + // then + assertThat(guard.active()).isZero(); + } +} diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java index 2795f20c..4e829b76 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java @@ -2,7 +2,12 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import jakarta.validation.ConstraintViolationException; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.constraints.NotNull; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; @@ -20,12 +25,15 @@ import tools.jackson.databind.json.JsonMapper; class JsonMergePatchApplierTest { private static final ObjectMapper MAPPER = JsonMapper.shared(); + private static final Validator VALIDATOR = + Validation.buildDefaultValidatorFactory().getValidator(); /** A target with a mandatory field and two optional ones. */ record Profile(String displayName, String description, String nickname) {} private static JsonMergePatchApplier applier(String... writableFields) { - return new JsonMergePatchApplier(MAPPER, PatchFieldAuthorization.allow(writableFields)); + return new JsonMergePatchApplier( + MAPPER, PatchFieldAuthorization.allow(writableFields), VALIDATOR); } private static JsonMergePatchDocument patch(String json) { @@ -118,7 +126,7 @@ class JsonMergePatchApplierTest { // A whole-document replacement is a PUT, and routing it through the patch path skips the // full-document validation a PUT gets. assertThatThrownBy(() -> patch("[1,2,3]")) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(JsonPatchRejectedException.class) .hasMessageContaining("belongs on the PUT route"); } @@ -135,7 +143,7 @@ class JsonMergePatchApplierTest { deep.append("}".repeat(40)); assertThatThrownBy(() -> patch(deep.toString())) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(JsonPatchRejectedException.class) .hasMessageContaining("can turn into a 400"); } @@ -153,4 +161,38 @@ class JsonMergePatchApplierTest { assertThat(PatchMediaType.MERGE_PATCH).isEqualTo("application/merge-patch+json"); assertThat(PatchMediaType.JSON_PATCH).isEqualTo("application/json-patch+json"); } + + @Test + @DisplayName("JSON이 아닌 merge patch 본문은 400 PATCH_REJECTED로 거절된다") + void aMergePatchBodyThatIsNotJsonIsRejected() { + // given + String notJson = "displayName=new"; + + // when + Throwable thrown = catchThrowable(() -> patch(notJson)); + + // then + assertThat(thrown).isInstanceOf(JsonPatchRejectedException.class); + } + + /** A target whose field may be patched but not deleted. */ + record Required(@NotNull String displayName, String nickname) {} + + @Test + @DisplayName("merge patch 결과는 문서 전체로 검증되고 위반은 VALIDATION_FAILED가 받는 예외로 나간다") + void theMergedDocumentIsValidatedWhole() { + // given + JsonMergePatchApplier applier = + new JsonMergePatchApplier(MAPPER, PatchFieldAuthorization.allow("displayName"), VALIDATOR); + JsonMergePatchDocument deleting = patch("{\"displayName\":null}"); + + // when + Throwable thrown = + catchThrowable(() -> applier.apply(new Required("old", "n"), deleting, Required.class)); + + // then + assertThat(thrown) + .as("the patch is allowed field by field; only the whole document breaks the constraint") + .isInstanceOf(ConstraintViolationException.class); + } } diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java index 1b1c538f..55b02e60 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java @@ -2,7 +2,12 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import jakarta.validation.ConstraintViolationException; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.constraints.NotBlank; import java.nio.charset.StandardCharsets; import java.util.List; import org.junit.jupiter.api.DisplayName; @@ -21,6 +26,8 @@ import tools.jackson.databind.json.JsonMapper; class JsonPatchApplierTest { private static final ObjectMapper MAPPER = JsonMapper.shared(); + private static final Validator VALIDATOR = + Validation.buildDefaultValidatorFactory().getValidator(); /** A target with a scalar, a nested object and a list. */ record Profile(String displayName, int version, Address address, List tags) {} @@ -33,7 +40,8 @@ class JsonPatchApplierTest { } private static JsonPatchApplier applier(String... writablePrefixes) { - return new JsonPatchApplier(MAPPER, JsonPointerAuthorization.allow(writablePrefixes)); + return new JsonPatchApplier( + MAPPER, JsonPointerAuthorization.allow(writablePrefixes), VALIDATOR); } private static JsonPatchDocument patch(String json) { @@ -212,10 +220,10 @@ class JsonPatchApplierTest { // Discovered halfway through, it would be a document that has already modified the working // copy. assertThatThrownBy(() -> patch("[{\"op\":\"replace\",\"path\":\"/displayName\"}]")) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(JsonPatchRejectedException.class) .hasMessageContaining("requires a value member"); assertThatThrownBy(() -> patch("[{\"op\":\"move\",\"path\":\"/displayName\"}]")) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(JsonPatchRejectedException.class) .hasMessageContaining("requires a from member"); } @@ -224,7 +232,7 @@ class JsonPatchApplierTest { void moveIntoOwnSourceIsRefused() { assertThatThrownBy( () -> patch("[{\"op\":\"move\",\"from\":\"/address\",\"path\":\"/address/self\"}]")) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(JsonPatchRejectedException.class) .hasMessageContaining("inside its own source"); } @@ -232,7 +240,75 @@ class JsonPatchApplierTest { @DisplayName("an empty patch document is refused") void emptyDocumentIsRefused() { assertThatThrownBy(() -> patch("[]")) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(JsonPatchRejectedException.class) .hasMessageContaining("client bug"); } + + @Test + @DisplayName("JSON이 아닌 본문은 400 PATCH_REJECTED로 거절된다") + void aBodyThatIsNotJsonIsRejectedAsAPatch() { + // given + String notJson = "op=replace&path=/displayName"; + + // when + Throwable thrown = catchThrowable(() -> patch(notJson)); + + // then + assertThat(thrown) + .as("left to Jackson the parse error reached the catch-all as 500 INTERNAL_ERROR") + .isInstanceOf(JsonPatchRejectedException.class); + } + + @Test + @DisplayName("너무 깊은 pointer는 권한 거절(403)이 아니라 문서 거절(400)이다") + void aTooDeepPointerIsAMalformedDocumentNotAPermissionRefusal() { + // given + String deep = "/displayName" + "/x".repeat(JsonPointerAuthorization.MAX_POINTER_DEPTH); + JsonPatchDocument document = + patch("[{\"op\":\"replace\",\"path\":\"" + deep + "\",\"value\":\"v\"}]"); + + // when + Throwable thrown = + catchThrowable(() -> applier("/displayName").apply(profile(), document, Profile.class)); + + // then + assertThat(thrown).isInstanceOf(JsonPatchRejectedException.class); + } + + @Test + @DisplayName("patch 결과가 대상 타입으로 읽히지 않으면 400 PATCH_REJECTED다") + void aPatchThatBreaksTheTargetTypeIsRejected() { + // given + JsonPatchDocument document = + patch("[{\"op\":\"replace\",\"path\":\"/version\",\"value\":\"not-a-number\"}]"); + + // when + Throwable thrown = + catchThrowable(() -> applier("/version").apply(profile(), document, Profile.class)); + + // then + assertThat(thrown).isInstanceOf(JsonPatchRejectedException.class); + } + + /** A target with a constraint across the whole document. */ + record Named(@NotBlank String displayName, String nickname) {} + + @Test + @DisplayName("patch 결과는 문서 전체로 검증되고 위반은 VALIDATION_FAILED가 받는 예외로 나간다") + void thePatchedDocumentIsValidatedWhole() { + // given + JsonPatchApplier applier = + new JsonPatchApplier(MAPPER, JsonPointerAuthorization.allow("/displayName"), VALIDATOR); + JsonPatchDocument blanking = + patch("[{\"op\":\"replace\",\"path\":\"/displayName\",\"value\":\" \"}]"); + + // when + Throwable thrown = + catchThrowable(() -> applier.apply(new Named("old", "n"), blanking, Named.class)); + + // then + assertThat(thrown) + .as("each operation is well formed, and only the whole document breaks the constraint") + .isInstanceOf(ConstraintViolationException.class); + } } diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutor.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutor.java index 8b3516b3..17eb4410 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutor.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutor.java @@ -58,7 +58,7 @@ public final class BlockingTransferExecutor { throw new FileserverException( "transfer pool is saturated", rejected, - FileserverFailureContext.of(FileserverErrorCode.TRANSFER_ADMISSION_REJECTED, true)); + FileserverFailureContext.of(FileserverErrorCode.SERVER_BUSY, true)); } try { return future.get(awaitSeconds, TimeUnit.SECONDS); diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java index 569f66c5..5ba1126c 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java @@ -36,7 +36,9 @@ public class FileserverHttpSurfaceConfiguration { /** * The response headers the upload and download routes write that a cross-origin browser must be - * allowed to read: without {@code Upload-Offset} a tus or draft-12 client cannot resume. + * allowed to read: without {@code Upload-Offset} a tus or draft-12 client cannot resume, and + * without {@code Content-Range} a browser that resumes a download with {@code Range} cannot tell + * which bytes a {@code 206} carries or how long the representation is from a {@code 416}. */ @Bean CorsExposedHeaders fileserverCorsExposedHeaders() { @@ -53,6 +55,7 @@ public class FileserverHttpSurfaceConfiguration { Draft12Headers.UPLOAD_COMPLETE, Draft12Headers.UPLOAD_LIMIT, HttpHeaders.CONTENT_DISPOSITION, - HttpHeaders.ACCEPT_RANGES)); + HttpHeaders.ACCEPT_RANGES, + HttpHeaders.CONTENT_RANGE)); } } diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java index d7ee6fad..9ae7d824 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java @@ -4,12 +4,12 @@ import dev.caskeleton.adapter.inbound.web.core.OwnsAbsoluteWebRoute; import dev.caskeleton.adapter.inbound.web.fileserver.config.BlockingTransferExecutor; import dev.caskeleton.adapter.inbound.web.fileserver.config.FileserverWebProperties; import dev.caskeleton.adapter.inbound.web.fileserver.dto.BatchUploadItemResult; -import dev.caskeleton.adapter.inbound.web.fileserver.dto.BatchUploadResponse; import dev.caskeleton.adapter.inbound.web.fileserver.dto.UploadedFileResponse; import dev.caskeleton.adapter.inbound.web.fileserver.mapper.MultipartUploadRequestMapper; import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapper; import dev.caskeleton.adapter.inbound.web.fileserver.mapper.UploadIntent; import dev.caskeleton.adapter.inbound.web.fileserver.security.FileserverRequestContextFactory; +import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory; import dev.caskeleton.application.fileserver.api.FileState; import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.FileserverException; @@ -21,6 +21,9 @@ import dev.caskeleton.application.fileserver.port.in.UploadFileUseCase; import dev.caskeleton.application.fileserver.upload.CreateUploadRequest; import dev.caskeleton.application.fileserver.upload.FileView; import dev.caskeleton.application.fileserver.upload.FinalizeUploadRequest; +import dev.caskeleton.shared.response.BulkEnvelope; +import dev.caskeleton.shared.response.BulkItemResult; +import dev.caskeleton.shared.response.ResponseMeta; import jakarta.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.InputStream; @@ -117,23 +120,41 @@ public class FileUploadController { /** * Bounded multi-file upload. * - *

The batch is explicitly non-atomic: each part is an independent file, a failure never rolls - * back a sibling that already succeeded, and the response is always {@code 200} carrying the - * ordered per-part outcome. + *

The batch is explicitly non-atomic: each part is an independent file and a failure never + * rolls back a sibling that already succeeded. The response is {@code 200} and the shared bulk + * envelope (web AGENTS B8): every part succeeded → {@code success = true} and {@code results}; + * any part failed → {@code success = false}, {@code BATCH_PARTIAL_FAILURE} and the per-part + * outcome in {@code error.details[]}. It used to answer {@code success = true} with the failures + * inside {@code data}, so a client reading the discriminator saw a batch that worked (review + * 2026-11-12). */ @PostMapping( path = "/v1/files:batch", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity uploadBatch( + public ResponseEntity> uploadBatch( @RequestParam("files") List files) { requirePartCountWithinPolicy(files.size()); RequestContext context = contextFactory.current(); - List results = new ArrayList<>(files.size()); + List outcomes = new ArrayList<>(files.size()); for (int index = 0; index < files.size(); index++) { - results.add(uploadPart(files.get(index), index, context)); + outcomes.add(uploadPart(files.get(index), index, context)); + } + ResponseMeta meta = ResponseMetaFactory.fromMdc(); + if (outcomes.stream().allMatch(PartOutcome::succeeded)) { + return ResponseEntity.ok( + BulkEnvelope.allOk(outcomes.stream().map(PartOutcome::result).toList(), meta)); + } + return ResponseEntity.ok( + BulkEnvelope.partial(outcomes.stream().map(PartOutcome::detail).toList(), meta)); + } + + /** One part's result in both shapes the bulk envelope may need. */ + private record PartOutcome(BatchUploadItemResult result, BulkItemResult detail) { + + boolean succeeded() { + return result.error() == null; } - return ResponseEntity.ok(new BatchUploadResponse(results)); } /** @@ -142,7 +163,7 @@ public class FileUploadController { *

A part failure is converted to a per-part problem instead of aborting the request, which is * what makes the endpoint's non-atomic contract observable rather than merely documented. */ - private BatchUploadItemResult uploadPart(MultipartFile part, int index, RequestContext context) { + private PartOutcome uploadPart(MultipartFile part, int index, RequestContext context) { String clientPartId = partId(part, index); try (InputStream body = part.getInputStream()) { UploadIntent intent = multipartMapper.map(part); @@ -150,14 +171,21 @@ public class FileUploadController { FileView view = transferExecutor.call( () -> upload(intent, content, part.getSize(), context, UploadMode.BATCH)); - return BatchUploadItemResult.accepted(clientPartId, view); + return new PartOutcome( + BatchUploadItemResult.accepted(clientPartId, view), + BulkItemResult.ok(index, view.fileId().canonicalText())); } catch (FileserverException failure) { - return BatchUploadItemResult.rejected(clientPartId, failure.code()); + return rejected(clientPartId, index, failure.code()); } catch (IOException failure) { - return BatchUploadItemResult.rejected(clientPartId, FileserverErrorCode.STORAGE_UNAVAILABLE); + return rejected(clientPartId, index, FileserverErrorCode.STORAGE_UNAVAILABLE); } } + private static PartOutcome rejected(String clientPartId, int index, FileserverErrorCode code) { + return new PartOutcome( + BatchUploadItemResult.rejected(clientPartId, code), BulkItemResult.error(index, code)); + } + /** * Records the application upload mode represented by this HTTP endpoint. * diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java index 74638fc0..ea0c6b5c 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java @@ -239,8 +239,9 @@ public class Draft12UploadController { } } + /** The header's name, or empty: the application's {@code OriginalFilenamePolicy} names it. */ private static String filename(HttpServletRequest request) { String header = request.getHeader("X-Filename"); - return header == null || header.isBlank() ? "upload.bin" : header; + return header == null ? "" : header; } } diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadItemResult.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadItemResult.java index b2131c4c..72bbf272 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadItemResult.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadItemResult.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.inbound.web.fileserver.dto; +import com.fasterxml.jackson.annotation.JsonInclude; import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.upload.FileView; import dev.caskeleton.shared.error.ClientErrorMessages; @@ -12,7 +13,11 @@ import dev.caskeleton.shared.response.ApiError; * rolls back a sibling that already succeeded. A rejected part carries the same {@link ApiError} * the single-file endpoints put in their Envelope: stable code, category, the shared client message * and {@code retryable}. The server-side message never crosses this boundary. + * + *

Absent members are omitted on the wire, like every envelope field (http-contract §1): an + * accepted part has no {@code error} key rather than {@code "error": null}. */ +@JsonInclude(JsonInclude.Include.NON_NULL) public record BatchUploadItemResult( String clientPartId, String status, String fileId, ApiError error) { diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadResponse.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadResponse.java deleted file mode 100644 index a79599a9..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadResponse.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.dto; - -import java.util.List; - -/** - * Ordered per-part outcome of one batch upload. - * - *

The endpoint answers {@code 200} even when some parts failed: the batch has no request-wide - * atomicity, and pretending otherwise with a single status would hide the parts that succeeded. - */ -public record BatchUploadResponse(List results) { - - public BatchUploadResponse { - results = List.copyOf(results); - } - - /** True when every part succeeded, which the envelope layer reports as a plain success. */ - public boolean fullySucceeded() { - return results.stream().allMatch(result -> result.error() == null); - } -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/MultipartUploadRequestMapper.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/MultipartUploadRequestMapper.java index 365dc63f..844ae34d 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/MultipartUploadRequestMapper.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/MultipartUploadRequestMapper.java @@ -13,16 +13,18 @@ import org.springframework.web.multipart.MultipartFile; */ public final class MultipartUploadRequestMapper { - private static final String FALLBACK_FILENAME = "upload.bin"; - public UploadIntent map(MultipartFile part) { return new UploadIntent( filename(part), claimedMediaType(part), OptionalLong.of(part.getSize()), Optional.empty()); } + /** + * The submitted name, or empty when there is none. Naming an unnamed upload is the application's + * {@code OriginalFilenamePolicy}, one place for every transport (review 2026-11-12). + */ private static String filename(MultipartFile part) { String submitted = part.getOriginalFilename(); - return submitted == null || submitted.isBlank() ? FALLBACK_FILENAME : submitted; + return submitted == null ? "" : submitted; } private static Optional claimedMediaType(MultipartFile part) { diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/RawUploadRequestMapper.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/RawUploadRequestMapper.java index c06b5d06..4e6a96ae 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/RawUploadRequestMapper.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/RawUploadRequestMapper.java @@ -20,8 +20,6 @@ public final class RawUploadRequestMapper { public static final String FILENAME_HEADER = "X-Filename"; public static final String DIGEST_HEADER = "X-Content-Sha256"; - private static final String FALLBACK_FILENAME = "upload.bin"; - private final boolean contentLengthRequired; public RawUploadRequestMapper(boolean contentLengthRequired) { @@ -39,9 +37,10 @@ public final class RawUploadRequestMapper { filename(request), claimedMediaType(request), declaredLength, digest(request)); } + /** The header's name, or empty: the application's {@code OriginalFilenamePolicy} names it. */ private static String filename(HttpServletRequest request) { String header = request.getHeader(FILENAME_HEADER); - return header == null || header.isBlank() ? FALLBACK_FILENAME : header; + return header == null ? "" : header; } private static Optional claimedMediaType(HttpServletRequest request) { diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java index bbc0d182..6d68a418 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java @@ -1,10 +1,13 @@ package dev.caskeleton.adapter.inbound.web.fileserver.problem; +import dev.caskeleton.adapter.inbound.web.error.ErrorResponseFactory; import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpRangeNotSatisfiableException; +import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor; import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.FileserverException; import java.util.LinkedHashMap; import java.util.Map; +import java.util.OptionalInt; /** * The headers a Fileserver failure carries, owned once for every transport. @@ -31,7 +34,6 @@ public final class FileserverProblemHeaders { Map.of( FileserverErrorCode.TRANSFER_ADMISSION_REJECTED, 1, FileserverErrorCode.STORAGE_UNAVAILABLE, 30, - FileserverErrorCode.ATOMIC_PUBLISH_UNSUPPORTED, 30, FileserverErrorCode.TRANSFER_TIMEOUT, 5, FileserverErrorCode.FILE_NOT_READY, 2, FileserverErrorCode.CONCURRENT_MODIFICATION, 1); @@ -45,11 +47,17 @@ public final class FileserverProblemHeaders { */ public static Map of(FileserverException failure) { Map headers = new LinkedHashMap<>(); - Integer retryAfter = RETRY_AFTER_SECONDS.get(failure.code()); // Only a failure the server itself called retryable advertises a retry: telling a client to - // come back after a permanent rejection is worse than saying nothing. - if (retryAfter != null && failure.context().retryable()) { - headers.put("Retry-After", String.valueOf(retryAfter)); + // come back after a permanent rejection is worse than saying nothing. The body's own rule + // (ErrorResponseFactory.effectiveRetryable): the occurrence can only narrow its code, so a code + // that is never retryable never carries the header, whatever the occurrence said. A code that + // shares its name with an operational one (SERVER_BUSY) takes the registry's value from + // RetryAfterAdvisor rather than a second copy here. + if (ErrorResponseFactory.effectiveRetryable(failure.code(), failure.context().retryable())) { + Integer own = RETRY_AFTER_SECONDS.get(failure.code()); + OptionalInt seconds = + own != null ? OptionalInt.of(own) : RetryAfterAdvisor.retryAfterSeconds(failure.code()); + seconds.ifPresent(value -> headers.put("Retry-After", String.valueOf(value))); } if (failure instanceof HttpRangeNotSatisfiableException unsatisfiable) { headers.put("Content-Range", "bytes */" + unsatisfiable.representationLength()); diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java index ab2f3093..e40a0eba 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java @@ -112,7 +112,8 @@ public class TusController { create.handle( new CreateUploadCommand( new CreateUploadRequest( - parser.filename(request).orElse("upload.bin"), + // Empty when absent: OriginalFilenamePolicy names it, for every transport. + parser.filename(request).orElse(""), Optional.ofNullable(parser.metadata(request).get("filetype")), parser.declaredLength(request), Optional.empty(), diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java index 78d58122..d22b4b54 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test; class FileserverCorsExposedHeadersTest { @Test - @DisplayName("fileserver HTTP 표면은 업로드 재개에 필요한 헤더를 CORS 노출 목록에 기여한다") + @DisplayName("fileserver HTTP 표면은 업로드·다운로드 재개에 필요한 헤더를 CORS 노출 목록에 기여한다") void theSurfaceContributesTheHeadersAResumingClientMustRead() { // when CorsExposedHeaders contributed = @@ -23,6 +23,7 @@ class FileserverCorsExposedHeadersTest { "Upload-Length", "Upload-Expires", "Upload-Complete", - "Content-Disposition"); + "Content-Disposition", + "Content-Range"); } } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/MvcUploadExecutorSaturationTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/MvcUploadExecutorSaturationTest.java index 0a65bcca..4ded8b41 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/MvcUploadExecutorSaturationTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/MvcUploadExecutorSaturationTest.java @@ -23,6 +23,7 @@ class MvcUploadExecutorSaturationTest { BlockingTransferExecutor executor = new BlockingTransferExecutor(pool, bounds.awaitSeconds()); CountDownLatch release = new CountDownLatch(1); AtomicInteger rejections = new AtomicInteger(); + CountDownLatch firstRejection = new CountDownLatch(1); List callers = new ArrayList<>(); for (int index = 0; index < 8; index++) { @@ -34,21 +35,25 @@ class MvcUploadExecutorSaturationTest { } catch (FileserverException failure) { // A caller that outlived the budget (TRANSFER_TIMEOUT) is not a saturation // signal; only an admission rejection is. - if (failure.code() == FileserverErrorCode.TRANSFER_ADMISSION_REJECTED) { + if (failure.code() == FileserverErrorCode.SERVER_BUSY) { rejections.incrementAndGet(); + firstRejection.countDown(); } } }); callers.add(caller); caller.start(); } - Thread.sleep(200); + // Held until the pool has refused someone, rather than for a guessed 200 ms: under load the + // callers may not have arrived yet, and then the release lets every one of them through. + boolean refused = firstRejection.await(10, TimeUnit.SECONDS); release.countDown(); for (Thread caller : callers) { caller.join(TimeUnit.SECONDS.toMillis(10)); } pool.shutdown(); + assertThat(refused).as("a pool of 1 with a queue of 1 refused within the wait").isTrue(); assertThat(rejections.get()) .as("a pool of 1 with a queue of 1 cannot absorb 8 concurrent transfers") .isPositive(); @@ -102,8 +107,7 @@ class MvcUploadExecutorSaturationTest { .satisfies( failure -> { FileserverException rejected = (FileserverException) failure; - assertThat(rejected.code()) - .isEqualTo(FileserverErrorCode.TRANSFER_ADMISSION_REJECTED); + assertThat(rejected.code()).isEqualTo(FileserverErrorCode.SERVER_BUSY); assertThat(rejected.context().retryable()).isTrue(); }); } @@ -115,7 +119,10 @@ class MvcUploadExecutorSaturationTest { BlockingTransferExecutor executor = new BlockingTransferExecutor(pool, bounds.awaitSeconds()); assertThatThrownBy(() -> executor.call(() -> await(new CountDownLatch(1)))) - .isInstanceOf(FileserverException.class); + .isInstanceOf(FileserverException.class) + .extracting(failure -> ((FileserverException) failure).code()) + .as("the overrun is answered as the timeout it is, not as some other transfer failure") + .isEqualTo(FileserverErrorCode.TRANSFER_TIMEOUT); pool.shutdown(); } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java index 70ae0c27..fde11716 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java @@ -7,6 +7,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeWireFormatConfig; import dev.caskeleton.adapter.inbound.web.fileserver.mapper.MultipartUploadRequestMapper; import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapper; import dev.caskeleton.adapter.inbound.web.fileserver.testkit.FileserverWebFixtures; @@ -17,12 +18,19 @@ import dev.caskeleton.application.fileserver.api.error.FileserverException; import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; import dev.caskeleton.application.fileserver.upload.CreateUploadRequest; import java.nio.charset.StandardCharsets; +import java.util.Set; +import java.util.TreeSet; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; +import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; class FileUploadControllerTest { @@ -41,6 +49,11 @@ class FileUploadControllerTest { FileserverWebFixtures.contextFactory(), FileserverWebFixtures.transferExecutor(), FileserverWebFixtures.properties())) + // The envelope wire rules a deployment's mapper carries, so a key the wire omits is + // asserted absent rather than merely null. + .setMessageConverters( + new JacksonJsonHttpMessageConverter( + JsonMapper.builder().addModule(EnvelopeWireFormatConfig.module()).build())) .build(); } @@ -89,15 +102,19 @@ class FileUploadControllerTest { } @Test - void aRawUploadWithoutAFilenameHeaderStillGetsASafeDisplayName() throws Exception { + @DisplayName("이름 헤더 없는 raw 업로드는 전송이 이름을 지어 넣지 않고 앱 정책에 빈 이름을 넘긴다") + void aRawUploadWithoutAFilenameHeaderLeavesTheNameToTheApplicationPolicy() throws Exception { + // when mvc.perform( post("/v1/files:raw").contentType(MediaType.APPLICATION_OCTET_STREAM).content("abc")) .andExpect(status().isCreated()); + // then assertThat(uploadService.requests()) .singleElement() .extracting(CreateUploadRequest::originalFilename) - .isEqualTo("upload.bin"); + .as("OriginalFilenamePolicy names an unnamed upload, once for every transport") + .isEqualTo(""); } @Test @@ -127,7 +144,9 @@ class FileUploadControllerTest { } @Test + @DisplayName("모든 part가 성공한 batch는 success=true와 part별 results를 순서대로 준다") void batchReturnsPerPartResultsAndIsExplicitlyNonAtomic() throws Exception { + // when / then mvc.perform( multipart("/v1/files:batch") .file( @@ -137,13 +156,22 @@ class FileUploadControllerTest { new MockMultipartFile( "files", "b.txt", "text/plain", "b".getBytes(StandardCharsets.UTF_8)))) .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) .andExpect(jsonPath("$.results.length()").value(2)) .andExpect(jsonPath("$.results[0].clientPartId").value("a.txt")) - .andExpect(jsonPath("$.results[1].clientPartId").value("b.txt")); + .andExpect(jsonPath("$.results[1].clientPartId").value("b.txt")) + .andExpect( + result -> + assertThat(keys(json(result).get("results").get(0))) + .as("an accepted part carries no error key, not \"error\": null") + .containsExactlyInAnyOrder("clientPartId", "status", "fileId")); } @Test + @DisplayName( + "한 part가 실패한 batch는 success=false, BATCH_PARTIAL_FAILURE, part별 details이고 성공한 part는 되돌리지 않는다") void aFailedBatchPartNeverRollsBackTheSiblingThatSucceeded() throws Exception { + // given uploadService.failWith( body -> "b".equals(body) @@ -152,6 +180,7 @@ class FileUploadControllerTest { FileserverFailureContext.of(FileserverErrorCode.FILE_TOO_LARGE, false)) : null); + // when / then mvc.perform( multipart("/v1/files:batch") .file( @@ -161,10 +190,18 @@ class FileUploadControllerTest { new MockMultipartFile( "files", "b.txt", "text/plain", "b".getBytes(StandardCharsets.UTF_8)))) .andExpect(status().isOk()) - .andExpect(jsonPath("$.results[0].status").value("READY")) - .andExpect(jsonPath("$.results[1].status").value("REJECTED")) - .andExpect(jsonPath("$.results[1].error.code").value("FILE_TOO_LARGE")) - .andExpect(jsonPath("$.results[1].error.category").value("VALIDATION")); + .andExpect(jsonPath("$.success").value(false)) + .andExpect( + result -> + assertThat(keys(json(result))) + .as("a partial failure has no results key at all") + .containsExactlyInAnyOrder("success", "error", "meta")) + .andExpect(jsonPath("$.error.code").value("BATCH_PARTIAL_FAILURE")) + .andExpect(jsonPath("$.error.details[0].status").value("ok")) + .andExpect(jsonPath("$.error.details[0].id").isNotEmpty()) + .andExpect(jsonPath("$.error.details[1].index").value(1)) + .andExpect(jsonPath("$.error.details[1].status").value("error")) + .andExpect(jsonPath("$.error.details[1].code").value("FILE_TOO_LARGE")); } @Test @@ -181,4 +218,14 @@ class FileUploadControllerTest { assertThat(body).doesNotContain("/tmp").doesNotContain("multipart").doesNotContain("staging"); } + + private static JsonNode json(MvcResult result) throws Exception { + return JsonMapper.shared().readTree(result.getResponse().getContentAsString()); + } + + private static Set keys(JsonNode node) { + Set keys = new TreeSet<>(); + node.properties().forEach(entry -> keys.add(entry.getKey())); + return keys; + } } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java index 92b92605..caf1be7c 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java @@ -48,6 +48,59 @@ class FileserverProblemHeaderParityTest { assertThat(headers).doesNotContainKey("Retry-After"); } + @Test + @org.junit.jupiter.api.DisplayName( + "본문이 retryable=false로 좁히는 code는 발생이 retryable이어도 Retry-After를 싣지 않는다") + void aCodeThatIsNeverRetryableAdvertisesNoRetryWhateverTheOccurrenceSaid() { + // given + FileserverException failure = + new FileserverException( + "no atomic publish", + FileserverFailureContext.of(FileserverErrorCode.ATOMIC_PUBLISH_UNSUPPORTED, true)); + + // when + Map headers = FileserverProblemHeaders.of(failure); + + // then + assertThat(headers) + .as("the body says retryable=false for this code; the header must not say otherwise") + .doesNotContainKey("Retry-After"); + } + + @Test + @org.junit.jupiter.api.DisplayName( + "공용 이름의 SERVER_BUSY는 registry 값(RetryAfterAdvisor)으로 Retry-After를 싣는다") + void aSharedSaturationCodeTakesTheRegistrysRetryAfter() { + // given + FileserverException failure = + new FileserverException( + "pool full", FileserverFailureContext.of(FileserverErrorCode.SERVER_BUSY, true)); + + // when + Map headers = FileserverProblemHeaders.of(failure); + + // then + assertThat(headers).containsEntry("Retry-After", "1"); + } + + @org.junit.jupiter.params.ParameterizedTest(name = "{0}") + @org.junit.jupiter.params.provider.EnumSource(FileserverErrorCode.class) + @org.junit.jupiter.api.DisplayName("재시도 불가 code는 발생이 재시도 가능이라고 해도 Retry-After를 싣지 않는다") + void aNonRetryableCodeNeverAdvertisesARetry(FileserverErrorCode code) { + // given + org.junit.jupiter.api.Assumptions.assumeFalse(code.retryable(), "a retryable code may"); + FileserverException failure = + new FileserverException("refused", FileserverFailureContext.of(code, true)); + + // when + Map headers = FileserverProblemHeaders.of(failure); + + // then + assertThat(headers) + .as("the body narrows retryable to false for %s; the header must agree", code) + .doesNotContainKey("Retry-After"); + } + @Test void anUnsatisfiableRangeDisclosesTheRepresentationLength() { Map headers = diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejectedException.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejectedException.java new file mode 100644 index 00000000..b3a2d2c9 --- /dev/null +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejectedException.java @@ -0,0 +1,42 @@ +package dev.caskeleton.adapter.inbound.web.notification.platform.submission; + +import dev.caskeleton.adapter.inbound.web.error.ClientSafeErrorDetails; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.OperationalError; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * A request field whose value is outside the vocabulary this transport parses (a channel, a slot, a + * language tag). + * + *

The same answer a body constraint gets — {@code 400 VALIDATION_FAILED} with one {@code {field, + * code, message}} detail — rather than the {@code BAD_PARAMETER} a bare {@code + * IllegalArgumentException} reaches, which named nothing the client could correct (review + * 2026-11-12). The detail uses web's validation vocabulary for a value no rule names ({@code + * INVALID}, its fixed wording). The rejected value is not echoed. + */ +final class NotificationFieldRejectedException extends RuntimeException + implements ApiErrorCarrier, ClientSafeErrorDetails { + + private static final long serialVersionUID = 1L; + + private final String field; + + NotificationFieldRejectedException(String field, String reason, Throwable cause) { + super(reason, cause); + this.field = Objects.requireNonNull(field, "field"); + } + + @Override + public ApiErrorCode errorCode() { + return OperationalError.VALIDATION_FAILED; + } + + @Override + public Object clientDetails() { + return List.of(Map.of("field", field, "code", "INVALID", "message", "값이 올바르지 않습니다.")); + } +} diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java index 16434929..9bc663d0 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java @@ -1,7 +1,6 @@ package dev.caskeleton.adapter.inbound.web.notification.platform.submission; import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory; -import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationCommand; import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationUseCase; import dev.caskeleton.shared.response.Envelope; @@ -70,7 +69,7 @@ public final class NotificationSubmissionController { new AcceptNotificationCommand( Optional.empty(), request.recipientRef(), - channel(request.channel()), + NotificationVocabulary.channel(request.channel()), request.address(), request.template(), // An omitted version or locale stays omitted: the use case owns both defaults. @@ -89,36 +88,10 @@ public final class NotificationSubmissionController { ResponseMetaFactory.fromMdc())); } - /** - * The channel a caller named. - * - *

Parsed here rather than bound by Jackson so an unknown name fails as a validation error - * naming the vocabulary, instead of as a deserialization error naming a Java enum. - */ - private static Channel channel(String name) { - try { - return Channel.valueOf(name.trim().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException unknown) { - throw new IllegalArgumentException( - "channel must be one of " + java.util.Arrays.toString(Channel.values()), unknown); - } - } - - /** - * The locale a caller named, or none. - * - *

{@link Locale#forLanguageTag} answers {@code Locale.ROOT} for anything it cannot parse - * rather than failing, so an unparseable tag is refused explicitly — silently rendering a Korean - * notification in the root locale is the kind of wrong that reaches a recipient. - */ private static Optional locale(String tag) { if (tag == null || tag.isBlank()) { return Optional.empty(); } - Locale parsed = Locale.forLanguageTag(tag.trim()); - if (parsed.equals(Locale.ROOT)) { - throw new IllegalArgumentException("locale must be a BCP 47 language tag"); - } - return Optional.of(parsed); + return Optional.of(NotificationVocabulary.locale("locale", tag)); } } diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java index 598dc701..5b61ddc7 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java @@ -1,16 +1,11 @@ package dev.caskeleton.adapter.inbound.web.notification.platform.submission; import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory; -import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.port.in.PublishNotificationTemplateCommand; import dev.caskeleton.application.notification.platform.port.in.PublishNotificationTemplateUseCase; -import dev.caskeleton.application.notification.platform.template.TemplateSlot; import dev.caskeleton.shared.response.Envelope; import jakarta.validation.Valid; -import java.util.EnumMap; import java.util.List; -import java.util.Locale; -import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -32,7 +27,12 @@ import org.springframework.web.bind.annotation.RestController; * publish} and no application or transport ever called it. * *

{@code 201}, unlike a submission's {@code 202}: a published version is an immutable resource - * that exists when the call returns, with nothing deferred to a worker. + * that exists when the call returns, with nothing deferred to a worker. The response carries no + * {@code Location}: there is no endpoint that reads a template version, and a {@code Location} that + * answers 404 is worse than none. The body names the version and its digest. + * + *

The path is lowerCamel plural like every other collection (manual 11, AIP-122); it was {@code + * /notification-templates} until 2026-11-12. * *

Authorized by {@code notification-template:publish}, which is deliberately not {@code * notification:submit}. Publishing a template changes what every future submission renders, and a @@ -45,7 +45,7 @@ import org.springframework.web.bind.annotation.RestController; name = "enabled", havingValue = "true", matchIfMissing = true) -@RequestMapping("/notification-templates") +@RequestMapping("/notificationTemplates") public final class NotificationTemplateController { private final PublishNotificationTemplateUseCase publish; @@ -73,12 +73,12 @@ public final class NotificationTemplateController { new PublishNotificationTemplateCommand( request.templateId(), Optional.ofNullable(request.version()), - channel(request.channel()), - locale(request.locale()), + NotificationVocabulary.channel(request.channel()), + NotificationVocabulary.locale("locale", request.locale()), Optional.ofNullable(request.fallbackLocale()) .filter(tag -> !tag.isBlank()) - .map(NotificationTemplateController::locale), - slots(request.slots()), + .map(tag -> NotificationVocabulary.locale("fallbackLocale", tag)), + NotificationVocabulary.slots(request.slots()), names(request.requiredVariables()), names(request.sensitiveVariables())); @@ -89,47 +89,7 @@ public final class NotificationTemplateController { ResponseMetaFactory.fromMdc())); } - /** - * The slots a caller named. - * - *

An unknown slot name is refused rather than dropped. Silently ignoring it publishes a - * template missing the content the caller wrote, and the failure then arrives at render time as a - * missing required slot for a template that looks published and complete. - */ - private static Map slots(Map source) { - Map slots = new EnumMap<>(TemplateSlot.class); - source.forEach( - (name, content) -> { - TemplateSlot slot; - try { - slot = TemplateSlot.valueOf(name.trim().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException unknown) { - throw new IllegalArgumentException( - "slot must be one of " + java.util.Arrays.toString(TemplateSlot.values()), unknown); - } - slots.put(slot, content); - }); - return slots; - } - private static Set names(List source) { return source == null ? Set.of() : Set.copyOf(source); } - - private static Channel channel(String name) { - try { - return Channel.valueOf(name.trim().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException unknown) { - throw new IllegalArgumentException( - "channel must be one of " + java.util.Arrays.toString(Channel.values()), unknown); - } - } - - private static Locale locale(String tag) { - Locale parsed = Locale.forLanguageTag(tag.trim()); - if (parsed.equals(Locale.ROOT)) { - throw new IllegalArgumentException("locale must be a BCP 47 language tag"); - } - return parsed; - } } diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationVocabulary.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationVocabulary.java new file mode 100644 index 00000000..6dd9784d --- /dev/null +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationVocabulary.java @@ -0,0 +1,65 @@ +package dev.caskeleton.adapter.inbound.web.notification.platform.submission; + +import dev.caskeleton.application.notification.platform.api.routing.Channel; +import dev.caskeleton.application.notification.platform.template.TemplateSlot; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; + +/** + * The names a notification request may use for a channel, a template slot and a locale, parsed once + * for both controllers. + * + *

Parsed here rather than bound by Jackson so an unknown name fails as a validation error on its + * field ({@link NotificationFieldRejectedException}, {@code VALIDATION_FAILED}) instead of as a + * deserialization error naming a Java enum. + */ +final class NotificationVocabulary { + + private NotificationVocabulary() {} + + static Channel channel(String name) { + try { + return Channel.valueOf(name.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException unknown) { + throw new NotificationFieldRejectedException( + "channel", "channel must be one of " + Arrays.toString(Channel.values()), unknown); + } + } + + /** + * A BCP 47 tag. {@link Locale#forLanguageTag} answers {@code Locale.ROOT} for anything it cannot + * parse rather than failing, so an unparseable tag is refused explicitly: silently rendering in + * the root locale is the kind of wrong that reaches a recipient. + */ + static Locale locale(String field, String tag) { + Locale parsed = Locale.forLanguageTag(tag.trim()); + if (parsed.equals(Locale.ROOT)) { + throw new NotificationFieldRejectedException( + field, field + " must be a BCP 47 language tag", null); + } + return parsed; + } + + /** + * The slots a caller named. An unknown slot is refused rather than dropped: ignoring it publishes + * a template missing the content the caller wrote, which then fails at render time as a missing + * required slot of a template that looks published and complete. + */ + static Map slots(Map source) { + Map slots = new EnumMap<>(TemplateSlot.class); + source.forEach( + (name, content) -> { + TemplateSlot slot; + try { + slot = TemplateSlot.valueOf(name.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException unknown) { + throw new NotificationFieldRejectedException( + "slots", "slot must be one of " + Arrays.toString(TemplateSlot.values()), unknown); + } + slots.put(slot, content); + }); + return slots; + } +} diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java index 771c7cd3..2c1d3805 100644 --- a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java @@ -31,6 +31,19 @@ class NotificationRoutePrefixTest { assertThat(prefixed.test(NotificationTemplateController.class)).isTrue(); } + @org.junit.jupiter.api.Test + @org.junit.jupiter.api.DisplayName("template 게시 경로는 다른 collection처럼 lowerCamel 복수형이다") + void theTemplateCollectionPathIsLowerCamelPlural() { + // when + String[] paths = + NotificationTemplateController.class + .getAnnotation(org.springframework.web.bind.annotation.RequestMapping.class) + .value(); + + // then + assertThat(paths).containsExactly("/notificationTemplates"); + } + private static final class InspectablePathMatchConfigurer extends PathMatchConfigurer { Predicate> prefix(String path) { diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java index 2270c921..6cb97c21 100644 --- a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java @@ -2,13 +2,17 @@ package dev.caskeleton.adapter.inbound.web.notification.platform.submission; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationCommand; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -47,4 +51,35 @@ class NotificationSubmissionControllerTest { // then assertThat(List.of(status, accepted.size())).containsExactly(400, 0); } + + @ParameterizedTest(name = "{0}") + @CsvSource({ + "channel, '\"channel\":\"PIGEON\",\"locale\":\"ko-KR\"'", + "locale, '\"channel\":\"EMAIL\",\"locale\":\"%%%\"'" + }) + @DisplayName("모르는 channel·locale은 그 필드를 짚는 400 VALIDATION_FAILED이고 use case에 닿지 않는다") + void anUnknownVocabularyValueIsAValidationFailureNamingTheField(String field, String fields) + throws Exception { + // given + String body = + "{\"recipientRef\":\"r-1\"," + + fields + + ",\"address\":\"a@example.com\",\"template\":\"welcome\",\"category\":\"TRANSACTIONAL\"}"; + + // when + String response = + mvc.perform(post("/notifications").contentType(MediaType.APPLICATION_JSON).content(body)) + .andExpect(status().isBadRequest()) + .andReturn() + .getResponse() + .getContentAsString(); + + // then + assertThat(response) + .contains("\"code\":\"VALIDATION_FAILED\"") + .contains("\"field\":\"" + field + "\"") + .doesNotContain("PIGEON") + .doesNotContain("%%%"); + assertThat(accepted).isEmpty(); + } } diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateControllerTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateControllerTest.java new file mode 100644 index 00000000..f3ae6828 --- /dev/null +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateControllerTest.java @@ -0,0 +1,67 @@ +package dev.caskeleton.adapter.inbound.web.notification.platform.submission; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; +import dev.caskeleton.application.notification.platform.port.in.PublishNotificationTemplateCommand; +import dev.caskeleton.shared.tracing.SpanErrorRecorder; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +class NotificationTemplateControllerTest { + + private final List published = new ArrayList<>(); + + private final MockMvc mvc = + MockMvcBuilders.standaloneSetup( + new NotificationTemplateController( + command -> { + published.add(command); + throw new IllegalStateException("the probe stops after recording"); + })) + .setControllerAdvice(new GlobalExceptionHandler(SpanErrorRecorder.NOOP)) + .build(); + + @ParameterizedTest(name = "{0}") + @CsvSource( + delimiter = '|', + value = { + "channel|\"channel\":\"PIGEON\",\"locale\":\"ko-KR\",\"slots\":{\"SUBJECT\":\"s\"}", + "locale|\"channel\":\"EMAIL\",\"locale\":\"%%%\",\"slots\":{\"SUBJECT\":\"s\"}", + "fallbackLocale|\"channel\":\"EMAIL\",\"locale\":\"ko-KR\",\"fallbackLocale\":\"%%%\",\"slots\":{\"SUBJECT\":\"s\"}", + "slots|\"channel\":\"EMAIL\",\"locale\":\"ko-KR\",\"slots\":{\"FOOTNOTE\":\"s\"}" + }) + @DisplayName("template 게시의 모르는 값은 그 필드를 짚는 400 VALIDATION_FAILED이고 use case에 닿지 않는다") + void anUnknownVocabularyValueIsAValidationFailureNamingTheField(String field, String fields) + throws Exception { + // given + String body = "{\"templateId\":\"welcome\"," + fields + "}"; + + // when + String response = + mvc.perform( + post("/notificationTemplates") + .contentType(MediaType.APPLICATION_JSON) + .content(body)) + .andExpect(status().isBadRequest()) + .andReturn() + .getResponse() + .getContentAsString(); + + // then + assertThat(response) + .contains("\"code\":\"VALIDATION_FAILED\"") + .contains("\"field\":\"" + field + "\"") + .doesNotContain("PIGEON") + .doesNotContain("FOOTNOTE"); + assertThat(published).isEmpty(); + } +} diff --git a/src/adapter/inbound/web/AGENTS.md b/src/adapter/inbound/web/AGENTS.md index 3983047a..7a3e72a7 100644 --- a/src/adapter/inbound/web/AGENTS.md +++ b/src/adapter/inbound/web/AGENTS.md @@ -62,9 +62,11 @@ bridge, `JsonIdempotentResponseCodec`, route 목록)는 골라 쓰는 leaf `adap **않는다** — ArchUnit 규칙 `REQUEST_DTOS_DO_NOT_SILENCE_UNKNOWN_FIELDS`가 막는다. 요청 record에는 wrapper 타입(`Integer`, `Long`, `Boolean`, `Optional`)을 써서 JSON `null`이 primitive `0`이 되지 못하게 한다. -- **B2 — PATCH 뜻.** RFC 7396 `application/merge-patch+json`(`null = 삭제`)을 쓰지 않는다. PATCH endpoint는 - *없음*(바꾸지 않음), *명시한 null*(필드 비움), *값*(바꿈)을 구별해야 한다. 요청 record에 - `org.openapitools:jackson-databind-nullable`(`JsonNullable`)이나 `Optional` wrapper를 쓴다. +- **B2 — PATCH 뜻.** 이 leaf의 `application/json` PATCH DTO는 *없음*(바꾸지 않음), *명시한 null*(필드 비움), + *값*(바꿈)을 구별해야 한다. 요청 record에 `org.openapitools:jackson-databind-nullable`(`JsonNullable`)이나 + `Optional` wrapper를 쓴다. RFC 7396 merge patch(`application/merge-patch+json`, `null = 삭제`)와 RFC 6902 JSON + Patch는 `adapter:inbound:web-advanced`의 applier로 받는다. 어느 것을 언제 쓰는지와 거부 규칙의 정본은 + `docs/web/patch-contract.md`다. - **B3 — mapper 안의 실패.** record 정규 생성자의 `IllegalArgumentException`, MapStruct가 생성한 NPE, ACL 정규화 실패 등은 `MappingException`을 던져 대응시킨다. 전역 handler가 그것을 `MAPPING_FAILED`(HTTP 400)로 보내고, `BAD_PARAMETER`나 `INTERNAL_ERROR`로 보내지 않는다. mapper가 아닌 호출자의 평범한 diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 62439653..6792c246 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -532,7 +532,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML 이 advisor 가 유일한 Retry-After 노출 지점이라 여기 중앙화한다. `DEPENDENCY_4XX_CLIENT` 는 비재시도(retryable=false)라 `shouldAdvise` 가드로 empty 반환. - 다른 leaf 가 소유한 코드는 이 표에 이름으로 넣지 않고 `RetryAfterHint` 를 구현해 값을 스스로 말한다 - (web-advanced `ADMISSION_REFUSED` = 1초). + (web-advanced `WebAdvancedError`). 서버 포화는 공용 `SERVER_BUSY`(1초)이고 이 표에 있다. - `IDEMPOTENT_IN_FLIGHT` 는 2초: 기본 processing lease(30s)보다 짧아 첫 시도가 끝날 수 있는 동안 같은 키로 다시 묻게 한다. 근거와 클라이언트 행동은 `docs/web/http-contract.md` §2. - 표는 레지스트리의 `retry_after_seconds` 가 있는 행마다 한 줄이다(`LOCK_ACQUISITION_TIMEOUT` 1초, DB·outbox·job diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java index f75421a4..0967f597 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.envelope; import com.fasterxml.jackson.annotation.JsonInclude; import dev.caskeleton.shared.response.ApiError; import dev.caskeleton.shared.response.BulkEnvelope; +import dev.caskeleton.shared.response.BulkItemResult; import dev.caskeleton.shared.response.Envelope; import dev.caskeleton.shared.response.ResponseMeta; import org.springframework.context.annotation.Bean; @@ -33,6 +34,7 @@ public class EnvelopeWireFormatConfig { SimpleModule module = new SimpleModule("EnvelopeWireFormatModule"); module.setMixInAnnotation(Envelope.class, OmitNullFields.class); module.setMixInAnnotation(BulkEnvelope.class, OmitNullFields.class); + module.setMixInAnnotation(BulkItemResult.class, OmitNullFields.class); module.setMixInAnnotation(ApiError.class, OmitNullFields.class); module.setMixInAnnotation(ResponseMeta.class, OmitNullFields.class); return module; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ErrorResponseFactory.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ErrorResponseFactory.java index 8864d64e..62f5821e 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ErrorResponseFactory.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ErrorResponseFactory.java @@ -31,6 +31,14 @@ public final class ErrorResponseFactory { return body(code, code.retryable(), details); } + /** + * Whether this occurrence may be retried: the occurrence can only narrow its code. The one rule + * for the body's {@code retryable} and for any {@code Retry-After} a transport adds beside it. + */ + public static boolean effectiveRetryable(ApiErrorCode code, boolean occurrenceRetryable) { + return code.retryable() && occurrenceRetryable; + } + /** * Body whose {@code retryable} is decided for this occurrence. * @@ -39,7 +47,7 @@ public final class ErrorResponseFactory { */ public static Envelope body(ApiErrorCode code, boolean retryable, Object details) { String message = ClientErrorMessages.of(code); - boolean effectiveRetryable = code.retryable() && retryable; + boolean effectiveRetryable = effectiveRetryable(code, retryable); ApiError err = details == null ? ApiError.of(code.code(), code.category().name(), message, effectiveRetryable) diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java index 22563880..617b1500 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java @@ -412,12 +412,25 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { return null; } } - ApiErrorCode code = HttpStatusErrorCodes.forStatus(statusCode); + ApiErrorCode code = HttpStatusErrorCodes.forException(ex, statusCode); if (code.httpStatus() >= 500) { log.error("spring mvc failure classified as {}", code.code(), ex); spanErrorRecorder.recordException(ex, code.code()); } + // The code's registry Retry-After, as the error dispatch (EnvelopeErrorController) adds it: a + // 503 classified SERVER_BUSY or a 429 RATE_LIMIT_EXCEEDED left without it here (review + // 2026-11-12). A header Spring already prepared wins. + // Copied: the headers Spring hands over may be read-only. + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.putAll(headers); + if (!responseHeaders.containsHeader(ApiHeaders.RETRY_AFTER)) { + RetryAfterAdvisor.retryAfterSeconds(code) + .ifPresent( + seconds -> responseHeaders.set(ApiHeaders.RETRY_AFTER, String.valueOf(seconds))); + } return new ResponseEntity<>( - ErrorResponseFactory.body(code, null), headers, HttpStatusCode.valueOf(code.httpStatus())); + ErrorResponseFactory.body(code, null), + responseHeaders, + HttpStatusCode.valueOf(code.httpStatus())); } } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/HttpStatusErrorCodes.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/HttpStatusErrorCodes.java index e37d6948..47ae06a8 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/HttpStatusErrorCodes.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/HttpStatusErrorCodes.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.error; import dev.caskeleton.shared.error.ApiErrorCode; import dev.caskeleton.shared.error.OperationalError; import org.springframework.http.HttpStatusCode; +import org.springframework.web.context.request.async.AsyncRequestTimeoutException; /** * The operational code a bare HTTP status stands for, when a status is all that is known. @@ -15,6 +16,17 @@ final class HttpStatusErrorCodes { private HttpStatusErrorCodes() {} + /** + * The code for a Spring MVC exception that carries only a status. An async request timeout is + * {@code REQUEST_TIMEOUT}; anything else is classified by its status. + */ + static ApiErrorCode forException(Exception failure, HttpStatusCode status) { + if (failure instanceof AsyncRequestTimeoutException) { + return WebTransportError.REQUEST_TIMEOUT; + } + return forStatus(status); + } + static ApiErrorCode forStatus(HttpStatusCode status) { return switch (status.value()) { case 401 -> OperationalError.UNAUTHENTICATED; @@ -27,8 +39,10 @@ final class HttpStatusErrorCodes { case 414 -> OperationalError.URI_TOO_LONG; case 415 -> OperationalError.UNSUPPORTED_MEDIA_TYPE; case 429 -> OperationalError.RATE_LIMIT_EXCEEDED; - // Spring answers its async request timeout with 503: transient, not an internal fault. - case 503 -> WebTransportError.REQUEST_TIMEOUT; + // A bare 503 is the server saying it cannot serve now (RFC 9110 15.6.4). An async request + // timeout is also a 503, and forException tells it apart; every other one used to be + // labelled REQUEST_TIMEOUT whatever it was (review 2026-11-12). + case 503 -> OperationalError.SERVER_BUSY; default -> status.is4xxClientError() ? OperationalError.BAD_PARAMETER diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java index cdc4aed4..f1a14374 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java @@ -19,6 +19,7 @@ public final class RetryAfterAdvisor { private static final Map RETRY_AFTER_SECONDS = Map.ofEntries( Map.entry("RATE_LIMIT_EXCEEDED", 1), + Map.entry("SERVER_BUSY", 1), // The application's value, which the processing-lease check also reads: the resend // arrives while the first attempt can still finish. docs/web/http-contract.md §2. Map.entry( diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java index 8f7abc31..d2495607 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java @@ -5,6 +5,8 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; import dev.caskeleton.application.idempotency.IdempotencyInFlightException; +import dev.caskeleton.shared.error.ClientErrorMessages; +import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.observability.MdcKeys; import dev.caskeleton.shared.response.BulkEnvelope; import dev.caskeleton.shared.response.BulkItemResult; @@ -26,6 +28,7 @@ import org.springframework.boot.security.autoconfigure.SecurityAutoConfiguration import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -77,6 +80,33 @@ class EnvelopeWireShapeTest { new ResponseMeta("req-1", "trace-1", "corr-1").withPage(new PageMeta(0, 20, 1, "id"))); } + @GetMapping("/probe/null-data") + public Envelope nullData() { + return Envelope.ok(null, new ResponseMeta("req-1", "trace-1", "corr-1")); + } + + @GetMapping("/probe/text") + public String text() { + ids(true); + return "hello"; + } + + @GetMapping("/probe/page-unsorted") + public Envelope> pageUnsorted() { + return Envelope.ok( + List.of("a"), + new ResponseMeta("req-1", "trace-1", "corr-1").withPage(new PageMeta(0, 20, 1, null))); + } + + @GetMapping("/probe/bulk-partial-items") + public BulkEnvelope bulkPartialItems() { + return BulkEnvelope.partial( + List.of( + BulkItemResult.ok(0, "item-1"), + BulkItemResult.error(1, OperationalError.MAPPING_FAILED)), + new ResponseMeta("req-1", "trace-1", "corr-1")); + } + @GetMapping("/probe/in-flight") public Map inFlight() { ids(false); @@ -178,6 +208,60 @@ class EnvelopeWireShapeTest { assertThat(details.isArray() && details.isEmpty()).isTrue(); } + @Test + @DisplayName("성공인데 data가 null이면 data 키도 없다") + void aNullDataOmitsTheDataKey() throws Exception { + // when + JsonNode body = rawBody("/probe/null-data"); + + // then + assertThat(keys(body)).containsExactlyInAnyOrder("success", "meta"); + } + + @Test + @DisplayName("JSON을 요청하면 String 반환도 같은 Envelope의 data로 나간다") + void aStringBodyIsAnEnvelopeWhenJsonIsAsked() throws Exception { + // when + JsonNode body = + READER.readTree( + mvc.perform(get("/probe/text").accept(MediaType.APPLICATION_JSON)) + .andReturn() + .getResponse() + .getContentAsString()); + + // then + assertThat(keys(body)).containsExactlyInAnyOrder("success", "data", "meta"); + assertThat(body.get("data").asString()).isEqualTo("hello"); + } + + @Test + @DisplayName("정렬 없는 목록의 page는 sort 키를 null로 싣는다") + void anUnsortedPageCarriesSortNull() throws Exception { + // when + JsonNode page = rawBody("/probe/page-unsorted").get("meta").get("page"); + + // then + assertThat(keys(page)).containsExactlyInAnyOrder("number", "size", "total", "sort"); + assertThat(page.get("sort").isNull()).isTrue(); + } + + @Test + @DisplayName("bulk 부분 실패의 message는 고정 문구이고 항목은 자기 상태에 맞는 키만 싣는다") + void aPartialFailureCarriesFixedWordingAndItemsWithoutNullKeys() throws Exception { + // when + JsonNode error = rawBody("/probe/bulk-partial-items").get("error"); + + // then + assertThat(error.get("message").asString()) + .isEqualTo(ClientErrorMessages.of(OperationalError.BATCH_PARTIAL_FAILURE)); + assertThat(keys(error.get("details").get(0))) + .containsExactlyInAnyOrder("index", "status", "id"); + assertThat(keys(error.get("details").get(1))) + .containsExactlyInAnyOrder("index", "status", "code", "message"); + assertThat(error.get("details").get(1).get("message").asString()) + .isEqualTo(ClientErrorMessages.of(OperationalError.MAPPING_FAILED)); + } + private JsonNode rawBody(String path) throws Exception { String text = mvc.perform(get(path)).andReturn().getResponse().getContentAsString(); return READER.readTree(text); diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorControllerTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorControllerTest.java index 074f8f8d..436a3bb6 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorControllerTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorControllerTest.java @@ -28,6 +28,7 @@ class EnvelopeErrorControllerTest { "401, 401, UNAUTHENTICATED", "404, 404, ROUTE_NOT_FOUND", "429, 429, RATE_LIMIT_EXCEEDED", + "503, 503, SERVER_BUSY", "409, 400, BAD_PARAMETER", "422, 400, BAD_PARAMETER", "500, 500, INTERNAL_ERROR", diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java index 85e9c0b7..f6eb8918 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java @@ -124,6 +124,32 @@ class TransportErrorHandlingTest { .andExpect(jsonPath("$.error.code").value("BAD_PARAMETER")); } + @Test + @DisplayName("상태만 아는 503은 SERVER_BUSY이고 registry의 Retry-After를 싣는다") + void aBare503IsServerBusyWithItsRetryAfter() throws Exception { + // when + var result = mvc.perform(get("/t/status-503")); + + // then + result + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.error.code").value("SERVER_BUSY")) + .andExpect(header().string("Retry-After", "1")); + } + + @Test + @DisplayName("상태만 아는 429도 RATE_LIMIT_EXCEEDED의 Retry-After를 싣는다") + void aBare429CarriesItsRetryAfter() throws Exception { + // when + var result = mvc.perform(get("/t/status-429")); + + // then + result + .andExpect(status().isTooManyRequests()) + .andExpect(jsonPath("$.error.code").value("RATE_LIMIT_EXCEEDED")) + .andExpect(header().string("Retry-After", "1")); + } + @Test @DisplayName("비동기 요청 시간 초과는 500이 아니라 재시도 가능한 503 REQUEST_TIMEOUT이다") void anAsyncTimeoutIsARetryable503NotAnInternalError() throws Exception { @@ -199,6 +225,18 @@ class TransportErrorHandlingTest { throw new AsyncRequestTimeoutException(); } + @GetMapping("/t/status-503") + Map status503() { + throw new org.springframework.web.server.ResponseStatusException( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE); + } + + @GetMapping("/t/status-429") + Map status429() { + throw new org.springframework.web.server.ResponseStatusException( + org.springframework.http.HttpStatus.TOO_MANY_REQUESTS); + } + @GetMapping("/t/bounded") Map bounded(@RequestParam("limit") @Max(10) int limit) { return Map.of("limit", limit); diff --git a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java index 24c64ea0..1fe66959 100644 --- a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java +++ b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java @@ -17,10 +17,10 @@ import dev.caskeleton.shared.error.Category; * servlet transport, the reactive transport and the Nginx delegation path cannot answer the same * failure three different ways. * - *

{@code UNAUTHENTICATED}, {@code PRECONDITION_FAILED} and {@code UNSUPPORTED_MEDIA_TYPE} share - * their name with an {@code OperationalError}; they are kept here so the failure context stays one - * enum, and {@code FileserverExceptionTest} pins that each means exactly what the operational code - * means on the wire (category, status, retryability). + *

{@code UNAUTHENTICATED}, {@code PRECONDITION_FAILED}, {@code UNSUPPORTED_MEDIA_TYPE} and + * {@code SERVER_BUSY} share their name with an {@code OperationalError}; they are kept here so the + * failure context stays one enum, and {@code FileserverExceptionTest} pins that each means exactly + * what the operational code means on the wire (category, status, retryability). */ public enum FileserverErrorCode implements ApiErrorCode { BAD_REQUEST(400, Category.VALIDATION, false), @@ -42,6 +42,7 @@ public enum FileserverErrorCode implements ApiErrorCode { MALWARE_DETECTED(422, Category.DATA_INTEGRITY, false), INVALID_PATH(422, Category.VALIDATION, false), PATH_OUTSIDE_NAMESPACE(422, Category.VALIDATION, false), + // The caller's own transfers fill its scope's permits: the caller's rate, so 429. TRANSFER_ADMISSION_REJECTED(429, Category.RATE_LIMIT, true), // tus checksum extension status: one request's bytes did not match the checksum the client sent // for them. The chunk is rolled back before its offset commits, so the upload stays resumable. @@ -52,6 +53,9 @@ public enum FileserverErrorCode implements ApiErrorCode { AMBIGUOUS_COMPLETION(500, Category.DATA_INTEGRITY, false), ATOMIC_PUBLISH_UNSUPPORTED(503, Category.PERMANENT_DEPENDENCY, false), STORAGE_UNAVAILABLE(503, Category.TRANSIENT_DEPENDENCY, true), + // The instance's permits or its transfer pool are full: server saturation, the shared code every + // transport answers it with (decisions 2.3, 2026-11-12). + SERVER_BUSY(503, Category.TRANSIENT_DEPENDENCY, true), TRANSFER_TIMEOUT(504, Category.TRANSIENT_DEPENDENCY, true), STORAGE_FULL(507, Category.TRANSIENT_DEPENDENCY, false); diff --git a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionController.java b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionController.java index d9969dba..b4c28d67 100644 --- a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionController.java +++ b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionController.java @@ -15,9 +15,11 @@ import java.util.concurrent.atomic.AtomicBoolean; * In-process admission control backed by bounded semaphores. * *

The failure vocabulary is deliberately distinct so a client can tell a permanent policy denial - * from a transient one: an exhausted pool is {@code STORAGE_FULL}, and running out of concurrency - * permits — for the caller's scope or for the whole instance — is a retryable admission rejection. - * Stored bytes over a quota ({@code QUOTA_EXCEEDED}) are decided by the quota service, not here. + * from a transient one: an exhausted pool is {@code STORAGE_FULL}; running out of the caller's own + * scope permits is a retryable {@code TRANSFER_ADMISSION_REJECTED} (429, the caller's rate); + * running out of the whole instance's permits is the shared server-saturation {@code SERVER_BUSY} + * (503). Stored bytes over a quota ({@code QUOTA_EXCEEDED}) are decided by the quota service, not + * here. */ public final class TransferAdmissionController { @@ -74,7 +76,7 @@ public final class TransferAdmissionController { scopePermits.release(); throw new FileserverException( "instance upload permits are exhausted", - FileserverFailureContext.of(FileserverErrorCode.TRANSFER_ADMISSION_REJECTED, true)); + FileserverFailureContext.of(FileserverErrorCode.SERVER_BUSY, true)); } return new SemaphorePermit(scopePermits, instanceUploads); } @@ -83,7 +85,7 @@ public final class TransferAdmissionController { if (!directDownloads.tryAcquire()) { throw new FileserverException( "instance direct download permits are exhausted", - FileserverFailureContext.of(FileserverErrorCode.TRANSFER_ADMISSION_REJECTED, true)); + FileserverFailureContext.of(FileserverErrorCode.SERVER_BUSY, true)); } return new SemaphorePermit(directDownloads); } diff --git a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadRequest.java b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadRequest.java index 91dcaef5..51c03330 100644 --- a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadRequest.java +++ b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadRequest.java @@ -9,7 +9,9 @@ import java.util.OptionalLong; * Client intent when starting an upload. * *

{@code originalFilename} and {@code claimedMediaType} are untrusted: they are sanitized and - * stored as display metadata, never used to build a physical key or to decide safety. + * stored as display metadata, never used to build a physical key or to decide safety. A transport + * that received no name passes an empty string; the display name of an unnamed upload is {@code + * OriginalFilenamePolicy}'s to choose, not each transport's. * *

The request carries only what the client decides. The namespace and the session lifetime are * {@link UploadPolicy}'s, so no transport can pick its own. diff --git a/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionControllerTest.java b/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionControllerTest.java index 74a675dc..9c31a867 100644 --- a/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionControllerTest.java +++ b/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionControllerTest.java @@ -119,7 +119,12 @@ class TransferAdmissionControllerTest { assertThatThrownBy(() -> narrow.acquireUpload(scope("tenant-b"), 10)) .isInstanceOf(FileserverException.class) .satisfies( - failure -> assertThat(((FileserverException) failure).context().retryable()).isTrue()); + failure -> { + assertThat(((FileserverException) failure).context().retryable()).isTrue(); + assertThat(((FileserverException) failure).context().code()) + .as("the whole instance is full: server saturation, not the caller's rate") + .isEqualTo(FileserverErrorCode.SERVER_BUSY); + }); held.close(); TransferPermit afterRelease = narrow.acquireUpload(scope("tenant-b"), 10); @@ -197,7 +202,9 @@ class TransferAdmissionControllerTest { TransferPermit download = narrow.acquireDirectDownload(scope("tenant-a")); assertThatThrownBy(() -> narrow.acquireDirectDownload(scope("tenant-a"))) - .isInstanceOf(FileserverException.class); + .isInstanceOf(FileserverException.class) + .extracting(failure -> ((FileserverException) failure).context().code()) + .isEqualTo(FileserverErrorCode.SERVER_BUSY); assertThat(narrow.acquireUpload(scope("tenant-a"), 10).isHeld()).isTrue(); download.close(); diff --git a/src/bootstrap/app/compose-lanes/smoke/notification-smoke.sh b/src/bootstrap/app/compose-lanes/smoke/notification-smoke.sh index f2850e4a..fe37d5bd 100755 --- a/src/bootstrap/app/compose-lanes/smoke/notification-smoke.sh +++ b/src/bootstrap/app/compose-lanes/smoke/notification-smoke.sh @@ -49,7 +49,7 @@ case "${NOTIFICATION_SMOKE_PHASE}" in # reruns against a surviving volume is not a different lane; a 409 here means the platform # holds a version with this id and different content, which is a real failure. PUBLISH_STATUS="$(curl -s -o /tmp/publish.json -w '%{http_code}' \ - -X POST "${APP_BASE_URL}${BASE_PATH}/notification-templates" \ + -X POST "${APP_BASE_URL}${BASE_PATH}/notificationTemplates" \ -H "Authorization: Bearer ${ACCESS_TOKEN}" \ -H 'Content-Type: application/json' \ -d "{\"templateId\":\"${TEMPLATE_ID}\",\"version\":1,\"channel\":\"EMAIL\",\"locale\":\"en\", diff --git a/src/bootstrap/notification-platform/README.md b/src/bootstrap/notification-platform/README.md index 30345276..962b47b1 100644 --- a/src/bootstrap/notification-platform/README.md +++ b/src/bootstrap/notification-platform/README.md @@ -19,7 +19,7 @@ composition:notification-platform ├─ adapter:outbound:notification provider(SMTP·SES), 저장 외 런타임, NotificationPlatformAutoConfiguration ├─ adapter:outbound:persistence-notification (runtimeOnly) 알림 entity·저장소·Flyway stream ├─ adapter:outbound:persistence-jpa (runtimeOnly) DataSource·Flyway core·TransactionPort - └─ adapter:inbound:web-notification POST /notifications, POST /notification-templates, + └─ adapter:inbound:web-notification POST /notifications, POST /notificationTemplates, POST /internal/notification/callbacks/{provider}/{profile} ``` diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java index 37d5ed02..70270688 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java @@ -44,6 +44,12 @@ public enum OperationalError implements ApiErrorCode { ROUTE_NOT_FOUND(Category.NOT_FOUND, 404, false), // rate-limit / idempotency RATE_LIMIT_EXCEEDED(Category.RATE_LIMIT, 429, true), + /** + * This instance has no capacity for another request right now: an admission limit, a full work + * pool. Every transport answers server saturation with this one code; {@link + * #RATE_LIMIT_EXCEEDED} is the caller's own rate (decisions 2.3, 2026-11-12). + */ + SERVER_BUSY(Category.TRANSIENT_DEPENDENCY, 503, true), IDEMPOTENT_IN_FLIGHT(Category.CONFLICT, 409, true), IDEMPOTENT_REQUEST_MISMATCH(Category.VALIDATION, 422, false), IDEMPOTENCY_UNAVAILABLE(Category.TRANSIENT_DEPENDENCY, 503, true), diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkEnvelope.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkEnvelope.java index 511ebdc8..76da7106 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkEnvelope.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkEnvelope.java @@ -1,5 +1,6 @@ package dev.caskeleton.shared.response; +import dev.caskeleton.shared.error.ClientErrorMessages; import dev.caskeleton.shared.error.OperationalError; import java.util.List; @@ -25,7 +26,7 @@ public record BulkEnvelope(boolean success, List results, ApiError error, ApiError.withDetails( OperationalError.BATCH_PARTIAL_FAILURE.code(), OperationalError.BATCH_PARTIAL_FAILURE.category().name(), - "One or more items failed; see details[] for the per-item outcome.", + ClientErrorMessages.of(OperationalError.BATCH_PARTIAL_FAILURE), OperationalError.BATCH_PARTIAL_FAILURE.retryable(), details); return new BulkEnvelope<>(false, null, err, meta); diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkItemResult.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkItemResult.java index 1f802f1d..1e2719c1 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkItemResult.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkItemResult.java @@ -1,14 +1,20 @@ package dev.caskeleton.shared.response; +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.ClientErrorMessages; + /** * Per-item result inside a bulk endpoint's {@code error.details[]} array. * *

* - *

No debug payload — keeps the envelope safe to log/ship. + *

No debug payload — keeps the envelope safe to log/ship. Absent members are omitted on the wire + * like every other envelope field. */ public record BulkItemResult(int index, String status, String id, String code, String message) { @@ -16,7 +22,7 @@ public record BulkItemResult(int index, String status, String id, String code, S return new BulkItemResult(index, "ok", id, null, null); } - public static BulkItemResult error(int index, String code, String message) { - return new BulkItemResult(index, "error", null, code, message); + public static BulkItemResult error(int index, ApiErrorCode code) { + return new BulkItemResult(index, "error", null, code.code(), ClientErrorMessages.of(code)); } } diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/response/EnvelopeTest.java b/src/shared-contract/src/test/java/dev/caskeleton/shared/response/EnvelopeTest.java index 69e1ccd2..d7d75737 100644 --- a/src/shared-contract/src/test/java/dev/caskeleton/shared/response/EnvelopeTest.java +++ b/src/shared-contract/src/test/java/dev/caskeleton/shared/response/EnvelopeTest.java @@ -2,7 +2,10 @@ package dev.caskeleton.shared.response; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.shared.error.ClientErrorMessages; +import dev.caskeleton.shared.error.OperationalError; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class EnvelopeTest { @@ -31,16 +34,39 @@ class EnvelopeTest { } @Test - void bulkAllOkAndPartialCarryMeta() { - BulkEnvelope ok = BulkEnvelope.allOk(List.of("a"), META); + @DisplayName("bulk 전체 성공은 success=true와 meta를 싣는다") + void aFullySucceededBulkCarriesMeta() { + // given + List results = List.of("a"); + + // when + BulkEnvelope ok = BulkEnvelope.allOk(results, META); + + // then assertThat(ok.success()).isTrue(); assertThat(ok.meta().requestId()).isEqualTo("req-1"); + } - BulkEnvelope partial = - BulkEnvelope.partial(List.of(BulkItemResult.error(0, "MAPPING_FAILED", "x")), META); + @Test + @DisplayName("bulk 부분 실패는 BATCH_PARTIAL_FAILURE와 category 고정 문구, 항목 코드의 고정 문구를 싣는다") + void aPartiallyFailedBulkCarriesTheFixedWording() { + // given + List details = + List.of( + BulkItemResult.ok(0, "f-1"), BulkItemResult.error(1, OperationalError.MAPPING_FAILED)); + + // when + BulkEnvelope partial = BulkEnvelope.partial(details, META); + + // then assertThat(partial.success()).isFalse(); assertThat(partial.error().code()).isEqualTo("BATCH_PARTIAL_FAILURE"); assertThat(partial.error().category()).isEqualTo("VALIDATION"); + assertThat(partial.error().message()) + .isEqualTo(ClientErrorMessages.of(OperationalError.BATCH_PARTIAL_FAILURE)); + assertThat(details.get(1).message()) + .as("an item carries its code's wording, never text the caller chose") + .isEqualTo(ClientErrorMessages.of(OperationalError.MAPPING_FAILED)); assertThat(partial.meta().correlationId()).isEqualTo("corr-1"); } }