review-followup Wave 3 라운드 1(P15): 에러 어휘를 Envelope·ApiErrorCode·한국어 Category 문구 표 하나로

- HTTP 에러는 Envelope 하나(결정 2): fileserver problem+json 제거, tus 헤더만 유지, Draft-12 offset 문서는 프로토콜 예외(결정 12)
- shared-contract `ClientErrorMessages`(Category별 한국어, 결정 11), shared 예외 `ApiErrorCarrier`, web 일반 carrier 분기
- GraphQL: category switch 3개 → 표 하나, 요청 단계·body-limit·DataLoader 코드가 mapper 경유, 등록된 코드만 노출(결정 25)
- gRPC trailer `retryable`, STOMP carrier 코드 보존, IAE는 모든 전송 400 계열, JpaPersistenceException → PersistenceFailureException
- sample 이벤트 JSON escape를 `EventJson` 하나로
- 통합 충돌 3건(gRPC 인터셉터 import, sample 409 핸들러·테스트를 새 문구 표 방식으로), P14 GraphQL 테스트 import 경로 수정

검증: ./gradlew check architectureCheck verifyPublicPathSnapshot verifyDependencyLocks --continue 통과(598 task)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
donghyeon-ka
2026-09-28 15:53:29 +09:00
co-authored by Claude Opus 5.5
parent 9fdb0af417
commit c4a066df41
116 changed files with 2149 additions and 1254 deletions
+3 -3
View File
@@ -60,7 +60,10 @@ dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode
dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext
dev.caskeleton.adapter.inbound.graphql.error.GraphQlExceptionResolver
dev.caskeleton.adapter.inbound.graphql.error.GraphQlInternalErrorMasker
dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection
dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireError
dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper
dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrors
dev.caskeleton.adapter.inbound.graphql.execution.BoundedPreparsedDocumentProvider
dev.caskeleton.adapter.inbound.graphql.execution.GraphQlAnonymousOperationException
dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionPipeline
@@ -138,13 +141,10 @@ dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionHandler
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionRequest
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlOperationSelectionHandler
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformInstrumentation
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformRejectionMapper
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformWebInterceptor
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPreparsedDocumentAdapter
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPrincipalResolver
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlRequestObservationConventionAdapter
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlWireErrorMapper
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlWireErrors
dev.caskeleton.adapter.inbound.graphql.runtime.servlet.GraphQlRequestBodyLimitFilter
dev.caskeleton.adapter.inbound.graphql.scalar.BigDecimalScalar
dev.caskeleton.adapter.inbound.graphql.scalar.DateScalar
+10
View File
@@ -358,3 +358,13 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap
| `GrpcStreamProfile` | `src/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/streaming/GrpcStreamProfile.java` | `6d27356e` | 테스트에서만 쓰였고 `GrpcFlowControlPolicy`의 256/8 MiB를 복제(N-10b) |
| `GrpcAuthenticationPolicy.isAuthenticated(Metadata)` | `src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcAuthenticationPolicy.java` | `6d27356e` | `authenticate(Metadata): Optional<Principal>`로 교체(K-10a) |
| `GrpcCredentialRotationManager.completeDrain()`(무인자) | `src/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/security/GrpcCredentialRotationManager.java` | `6d27356e` | `completeDrain(GrpcCredentialGeneration)`로 교체(P5-new-3) |
| `ClientSafeErrorMessages` (web 코드별 영어 문구 표) | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeErrorMessages.java` | `016597ac` | 결정 11: shared `ClientErrorMessages`(Category별 한국어) 하나로 |
| `PortfolioClientSafeErrorMessages` (sample 영어 문구) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioClientSafeErrorMessages.java` | `016597ac` | 같은 이유(`ErrorResponseFactory`가 message 인자를 받지 않음) |
| `FileserverProblem` | `src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblem.java` | `016597ac` | 결정 2: fileserver 실패도 Envelope |
| `FileserverProblemFactory` (+ composition `fileserverProblemFactory` bean) | `src/adapter/inbound/web-fileserver/.../problem/FileserverProblemFactory.java`, `src/composition/fileserver-platform/.../FileserverWebAssemblyConfiguration.java` | `016597ac` | 같은 이유 |
| `FileserverProblemTitles` (영어 title 표) | `src/adapter/inbound/web-fileserver/.../problem/FileserverProblemTitles.java` | `016597ac` | 같은 이유 + 결정 11 |
| `BatchUploadItemProblem` | `src/adapter/inbound/web-fileserver/.../dto/BatchUploadItemProblem.java` | `016597ac` | batch 항목도 `ApiError` |
| `FileserverErrorCode.problemType()` (URN) | `src/application-fileserver/.../api/error/FileserverErrorCode.java` | `016597ac` | problem 문서가 없어져 호출자 0 |
| `GraphQlPlatformRejectionMapper` (instanceof 사슬) | `src/adapter/inbound/graphql/.../runtime/GraphQlPlatformRejectionMapper.java` | `016597ac` | S5-#6d: 예외가 `GraphQlPlatformRejection` 구현 |
| `runtime/GraphQlWireErrorMapper`, `runtime/GraphQlWireErrors` (이동) | `src/adapter/inbound/graphql/.../runtime/` → `.../error/` | `016597ac` | 삭제가 아니라 `error/` 패키지로 이동(S5-#6d). `classificationOf`·`category`·`clientMessage` switch는 `RENDERINGS` 표로 대체 |
| sample publisher별 JSON escape 사본 3개 | `PosterEventPublisher`·`PosterImagePublicationEventPublisher`·`WorkLogReservedIntegrationEventMapper`(`escape`/`field`/`jsonField`) | `016597ac` | X2-P1-6: `EventJson` 하나로 |
+37 -10
View File
@@ -71,23 +71,50 @@ port rather than the public one.
## Failure body
Every failure answers `application/problem+json` with a stable code and its URN:
Every failure answers the application's one error shape, the `Envelope` (`application/json`), with
the stable code, its category, the shared Korean client message for that category and the
identifying values in `error.details`:
```json
{
"type": "urn:fileserver:problem:upload-offset-mismatch",
"title": "Upload offset mismatch",
"status": 409,
"code": "UPLOAD_OFFSET_MISMATCH",
"retryable": true,
"ambiguous": false,
"reconciliationRequired": false,
"traceId": "..."
"success": false,
"data": null,
"error": {
"code": "UPLOAD_OFFSET_MISMATCH",
"category": "CONFLICT",
"message": "현재 상태에서는 요청을 처리할 수 없습니다.",
"retryable": true,
"details": {
"uploadId": "...",
"expectedOffset": 1024,
"currentOffset": 2048
}
},
"meta": { "requestId": "...", "traceId": "...", "correlationId": "..." }
}
```
`details` carries only what the failure context holds: `fileId`, `uploadId`, `expectedOffset`,
`currentOffset`, `state`, and the flags `ambiguous` and `reconciliationRequired` when they are true.
The server-side exception message never appears. `ambiguous` is the field a client must read before
retrying: an ambiguous failure may already have taken effect.
retrying: an ambiguous failure may already have taken effect. `retryable` is this occurrence's
decision and is never wider than the code allows.
A batch upload part that is rejected carries the same `error` object (`code`, `category`,
`message`, `retryable`) in its `results[]` entry.
### Protocol exceptions to the Envelope rule
Owner decision 2 keeps one HTTP error shape; the protocol pieces below are not error vocabulary and
stay as the protocol defines them (owner decision 12):
- tus protocol headers (`Tus-Resumable`, `Upload-Offset`, `Upload-Length`, …) on every tus
response, success or failure.
- `Retry-After` and the unsatisfied-range `Content-Range` on a failure (see the header contract).
- The IETF resumable-upload draft's offset-mismatch response
(`Draft12UploadController#offsetMismatch`): `409 application/problem+json` with
`type = https://iana.org/assignments/http-problem-types#mismatching-upload-offset`,
`expectedOffset` and `providedOffset`. It is the only non-Envelope failure body.
## Header contract
+114 -57
View File
@@ -1,7 +1,7 @@
# Registry: Error Codes
# Schema owner: feature-contract-registry-governance
# Category enum owner: feature-operational-error-observability-foundation
# Last updated: 2026-09-21
# Last updated: 2026-09-28
# Scope: skeleton-wide OperationalError SSOT. Product/fork ApiErrorCode enums own local registries/contracts.
#
# Schema (per row):
@@ -13,7 +13,8 @@
# retryable: bool
# retry_after_seconds: int | null (RATE_LIMIT/TRANSIENT 권고 backoff)
# owner_layer: presentation | application | domain | infrastructure | crosscut
# client_safe_message: no token / no principal raw / no internal path / no stack trace
# client_safe_message: = shared-contract ClientErrorMessages.of(category) — category별 한국어 문구 표
# 하나(소유자 결정 11). no token / no principal raw / no internal path / no stack trace
# log_level: ERROR | WARN | INFO
# runbook_link: runbook://area/scenario OR null (client-error만 null 허용)
# compatibility_impact: none | additive | behavior-change | breaking
@@ -39,7 +40,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-security-operational-baseline
owner_layer: presentation
client_safe_message: "Authentication required"
client_safe_message: "인증이 필요합니다."
log_level: WARN
runbook_link: "runbook://auth/token-missing"
compatibility_impact: none
@@ -53,7 +54,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-security-operational-baseline
owner_layer: presentation
client_safe_message: "Authentication failed"
client_safe_message: "인증이 필요합니다."
log_level: WARN
runbook_link: "runbook://auth/token-malformed"
compatibility_impact: none
@@ -67,7 +68,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-security-operational-baseline
owner_layer: presentation
client_safe_message: "Authentication expired"
client_safe_message: "인증이 필요합니다."
log_level: WARN
runbook_link: "runbook://auth/token-expired"
compatibility_impact: none
@@ -81,7 +82,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-security-operational-baseline
owner_layer: presentation
client_safe_message: "Authentication failed"
client_safe_message: "인증이 필요합니다."
log_level: ERROR
runbook_link: "runbook://auth/token-invalid-signature"
compatibility_impact: none
@@ -95,7 +96,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-security-operational-baseline
owner_layer: presentation
client_safe_message: "Authentication failed"
client_safe_message: "인증이 필요합니다."
log_level: ERROR
runbook_link: "runbook://auth/issuer-mismatch"
compatibility_impact: none
@@ -109,7 +110,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-security-operational-baseline
owner_layer: presentation
client_safe_message: "Authentication failed"
client_safe_message: "인증이 필요합니다."
log_level: ERROR
runbook_link: "runbook://auth/audience-mismatch"
compatibility_impact: none
@@ -124,7 +125,7 @@ errors:
retry_after_seconds: 5
owner_branch: feature-security-operational-baseline
owner_layer: presentation
client_safe_message: "Authentication failed, please retry"
client_safe_message: "인증이 필요합니다."
log_level: WARN
runbook_link: "runbook://auth/kid-unknown"
compatibility_impact: none
@@ -138,7 +139,7 @@ errors:
retry_after_seconds: 30
owner_branch: feature-security-operational-baseline
owner_layer: infrastructure
client_safe_message: "Authentication service temporarily unavailable"
client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요."
log_level: ERROR
runbook_link: "runbook://auth/jwks-unavailable"
compatibility_impact: none
@@ -152,7 +153,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-security-operational-baseline
owner_layer: presentation
client_safe_message: "Authentication failed"
client_safe_message: "인증이 필요합니다."
log_level: ERROR
runbook_link: "runbook://auth/claim-mapping-failed"
compatibility_impact: none
@@ -170,7 +171,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-security-operational-baseline
owner_layer: presentation
client_safe_message: "Permission denied"
client_safe_message: "이 작업을 수행할 권한이 없습니다."
log_level: WARN
runbook_link: "runbook://authz/insufficient-permission"
compatibility_impact: none
@@ -184,7 +185,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-security-operational-baseline
owner_layer: presentation
client_safe_message: "Permission denied"
client_safe_message: "이 작업을 수행할 권한이 없습니다."
log_level: ERROR
runbook_link: "runbook://authz/tenant-mismatch"
compatibility_impact: none
@@ -202,7 +203,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-security-operational-baseline
owner_layer: crosscut
client_safe_message: "Internal server error"
client_safe_message: "요청을 처리할 수 없습니다."
log_level: ERROR
runbook_link: "runbook://auth/public-path-misconfiguration"
compatibility_impact: none
@@ -216,7 +217,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-container-runtime-contract
owner_layer: infrastructure
client_safe_message: "Internal server error"
client_safe_message: "요청을 처리할 수 없습니다."
log_level: ERROR
runbook_link: "runbook://runtime/jvm-oom"
compatibility_impact: none
@@ -234,7 +235,7 @@ errors:
retry_after_seconds: 5
owner_branch: feature-persistence-failure-baseline
owner_layer: infrastructure
client_safe_message: "Service temporarily unavailable"
client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요."
log_level: ERROR
runbook_link: "runbook://db/unavailable"
compatibility_impact: none
@@ -248,7 +249,7 @@ errors:
retry_after_seconds: 1
owner_branch: feature-persistence-failure-baseline
owner_layer: infrastructure
client_safe_message: "Request conflicted with another transaction, please retry"
client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다."
log_level: WARN
runbook_link: "runbook://db/serialization-failure"
compatibility_impact: none
@@ -262,7 +263,7 @@ errors:
retry_after_seconds: 1
owner_branch: feature-persistence-failure-baseline
owner_layer: infrastructure
client_safe_message: "Request conflicted, please retry"
client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다."
log_level: WARN
runbook_link: "runbook://db/deadlock"
compatibility_impact: none
@@ -276,7 +277,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-persistence-failure-baseline
owner_layer: infrastructure
client_safe_message: "Request violates a required field constraint"
client_safe_message: "요청을 처리할 수 없습니다."
log_level: WARN
runbook_link: null
compatibility_impact: none
@@ -290,7 +291,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-persistence-failure-baseline
owner_layer: infrastructure
client_safe_message: "Request references missing resource"
client_safe_message: "요청을 처리할 수 없습니다."
log_level: WARN
runbook_link: null
compatibility_impact: none
@@ -304,7 +305,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-persistence-failure-baseline
owner_layer: infrastructure
client_safe_message: "Resource already exists"
client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다."
log_level: WARN
runbook_link: null
compatibility_impact: none
@@ -318,7 +319,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-persistence-failure-baseline
owner_layer: infrastructure
client_safe_message: "Request violates a value constraint"
client_safe_message: "요청을 처리할 수 없습니다."
log_level: WARN
runbook_link: null
compatibility_impact: none
@@ -332,7 +333,7 @@ errors:
retry_after_seconds: 2
owner_branch: feature-persistence-failure-baseline
owner_layer: infrastructure
client_safe_message: "Service temporarily unavailable"
client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요."
log_level: ERROR
runbook_link: "runbook://db/idle-in-tx-timeout"
compatibility_impact: none
@@ -346,12 +347,40 @@ errors:
retry_after_seconds: null
owner_branch: feature-persistence-failure-baseline
owner_layer: infrastructure
client_safe_message: "Request was canceled, please retry later"
client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요."
log_level: WARN
runbook_link: "runbook://db/query-canceled"
compatibility_impact: none
required_test: contract-verification:persistence-mapping
# source: review-followup P15 (S2-lead-4) — JPA OPTIMISTIC_CONFLICT (@Version check failed at flush/commit)
- code: DB_OPTIMISTIC_CONFLICT
category: CONFLICT
http_status: 409
retryable: false
retry_after_seconds: null
owner_branch: feature-persistence-failure-baseline
owner_layer: infrastructure
client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다."
log_level: WARN
runbook_link: null
compatibility_impact: additive
required_test: persistence-jpa:JpaPersistenceExceptionCodeTest
# source: review-followup P15 (S2-lead-4) — JPA COMPLETION_UNKNOWN (40003 / commit-phase connection loss)
- code: DB_COMPLETION_UNKNOWN
category: DATA_INTEGRITY
http_status: 500
retryable: false
retry_after_seconds: null
owner_branch: feature-persistence-failure-baseline
owner_layer: infrastructure
client_safe_message: "요청을 처리할 수 없습니다."
log_level: ERROR
runbook_link: null
compatibility_impact: additive
required_test: persistence-jpa:JpaPersistenceExceptionCodeTest
# ============================================================
# Rate limit / Idempotency (feature-rate-limit-idempotency-contract)
# ============================================================
@@ -364,7 +393,7 @@ errors:
retry_after_seconds: 1
owner_branch: feature-rate-limit-idempotency-contract
owner_layer: presentation
client_safe_message: "Too many requests, please retry after the indicated interval"
client_safe_message: "요청이 너무 잦습니다. 잠시 후 다시 시도해 주세요."
log_level: WARN
runbook_link: "runbook://rate-limit/exceeded"
compatibility_impact: none
@@ -378,7 +407,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-rate-limit-idempotency-contract
owner_layer: application
client_safe_message: "A previous identical request is still being processed, please poll for result"
client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다."
log_level: INFO
runbook_link: null
compatibility_impact: none
@@ -392,12 +421,40 @@ errors:
retry_after_seconds: null
owner_branch: feature-rate-limit-idempotency-contract
owner_layer: application
client_safe_message: "Idempotency key reused with different request body"
client_safe_message: "요청 값이 올바르지 않습니다."
log_level: WARN
runbook_link: null
compatibility_impact: none
required_test: contract-verification:idempotency
# source: review-followup P15 (X2-P2-2a) — IdempotencyExecutor fail-closed refusal before the action
- code: IDEMPOTENCY_UNAVAILABLE
category: TRANSIENT_DEPENDENCY
http_status: 503
retryable: true
retry_after_seconds: null
owner_branch: feature-rate-limit-idempotency-contract
owner_layer: application
client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요."
log_level: WARN
runbook_link: "runbook://idempotency/unavailable"
compatibility_impact: additive
required_test: contract-verification:idempotency
# source: review-followup P15 (X2-P2-2a) — replay cannot decide whether an external effect happened
- code: IDEMPOTENCY_RECOVERY_REQUIRED
category: DATA_INTEGRITY
http_status: 500
retryable: false
retry_after_seconds: null
owner_branch: feature-rate-limit-idempotency-contract
owner_layer: application
client_safe_message: "요청을 처리할 수 없습니다."
log_level: ERROR
runbook_link: "runbook://idempotency/unavailable"
compatibility_impact: additive
required_test: contract-verification:idempotency
# ============================================================
# File / Resource (feature-file-resource-handling-contract)
# ============================================================
@@ -420,7 +477,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-api-contract-baseline
owner_layer: presentation
client_safe_message: "HTTP method not allowed for this resource"
client_safe_message: "요청 값이 올바르지 않습니다."
log_level: INFO
runbook_link: null
compatibility_impact: none
@@ -434,7 +491,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-api-contract-baseline
owner_layer: presentation
client_safe_message: "No acceptable representation for the requested Accept header"
client_safe_message: "요청 값이 올바르지 않습니다."
log_level: INFO
runbook_link: null
compatibility_impact: none
@@ -448,7 +505,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-api-contract-baseline
owner_layer: presentation
client_safe_message: "Resource was modified by another request; refetch and retry"
client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다."
log_level: INFO
runbook_link: null
compatibility_impact: none
@@ -462,7 +519,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-api-contract-baseline
owner_layer: presentation
client_safe_message: "Request payload is too large"
client_safe_message: "요청 값이 올바르지 않습니다."
log_level: WARN
runbook_link: null
compatibility_impact: none
@@ -479,7 +536,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-api-contract-baseline
owner_layer: presentation
client_safe_message: "Request URI is too long"
client_safe_message: "요청 값이 올바르지 않습니다."
log_level: WARN
runbook_link: null
compatibility_impact: none
@@ -493,7 +550,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-api-contract-baseline
owner_layer: presentation
client_safe_message: "Request Content-Type is not supported"
client_safe_message: "요청 값이 올바르지 않습니다."
log_level: INFO
runbook_link: null
compatibility_impact: none
@@ -531,7 +588,7 @@ errors:
retry_after_seconds: 2
owner_branch: feature-outbound-http-client-baseline
owner_layer: infrastructure
client_safe_message: "Upstream service did not respond in time, please retry"
client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요."
log_level: ERROR
runbook_link: "runbook://dependency/timeout"
compatibility_impact: none
@@ -545,7 +602,7 @@ errors:
retry_after_seconds: 2
owner_branch: feature-outbound-http-client-baseline
owner_layer: infrastructure
client_safe_message: "Upstream service unreachable, please retry"
client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요."
log_level: ERROR
runbook_link: "runbook://dependency/connect-failed"
compatibility_impact: none
@@ -559,7 +616,7 @@ errors:
retry_after_seconds: 5
owner_branch: feature-outbound-http-client-baseline
owner_layer: infrastructure
client_safe_message: "Upstream service unreachable, please retry"
client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요."
log_level: ERROR
runbook_link: "runbook://dependency/dns-failed"
compatibility_impact: none
@@ -573,7 +630,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-outbound-http-client-baseline
owner_layer: infrastructure
client_safe_message: "Upstream service rejected the request"
client_safe_message: "요청을 처리할 수 없습니다."
log_level: ERROR
runbook_link: "runbook://dependency/4xx-client"
compatibility_impact: none
@@ -587,7 +644,7 @@ errors:
retry_after_seconds: 2
owner_branch: feature-outbound-http-client-baseline
owner_layer: infrastructure
client_safe_message: "Upstream service error, please retry"
client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요."
log_level: ERROR
runbook_link: "runbook://dependency/5xx-server"
compatibility_impact: none
@@ -601,7 +658,7 @@ errors:
retry_after_seconds: 10
owner_branch: feature-outbound-http-client-baseline
owner_layer: infrastructure
client_safe_message: "Upstream service temporarily unavailable, please retry later"
client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요."
log_level: WARN
runbook_link: "runbook://dependency/circuit-open"
compatibility_impact: none
@@ -619,7 +676,7 @@ errors:
retry_after_seconds: 30
owner_branch: feature-domain-event-outbox-contract
owner_layer: infrastructure
client_safe_message: "Internal server error"
client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요."
log_level: ERROR
runbook_link: "runbook://outbox/publish-failed"
compatibility_impact: none
@@ -633,7 +690,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-domain-event-outbox-contract
owner_layer: infrastructure
client_safe_message: "Internal server error"
client_safe_message: "요청을 처리할 수 없습니다."
log_level: ERROR
runbook_link: "runbook://outbox/dead-letter"
compatibility_impact: none
@@ -651,7 +708,7 @@ errors:
retry_after_seconds: 5
owner_branch: feature-background-job-async-contract
owner_layer: infrastructure
client_safe_message: "Service temporarily unavailable"
client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요."
log_level: ERROR
runbook_link: "runbook://job/executor-rejected"
compatibility_impact: none
@@ -665,7 +722,7 @@ errors:
retry_after_seconds: 10
owner_branch: feature-background-job-async-contract
owner_layer: infrastructure
client_safe_message: "Internal server error"
client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요."
log_level: ERROR
runbook_link: "runbook://job/timeout"
compatibility_impact: none
@@ -679,7 +736,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-background-job-async-contract
owner_layer: infrastructure
client_safe_message: "Internal server error"
client_safe_message: "요청을 처리할 수 없습니다."
log_level: ERROR
runbook_link: "runbook://job/dead-letter"
compatibility_impact: none
@@ -704,7 +761,7 @@ errors:
retry_after_seconds: 1
owner_branch: feature-distributed-lock-contract
owner_layer: infrastructure
client_safe_message: "Resource is busy, please retry"
client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다."
log_level: WARN
runbook_link: "runbook://lock/acquisition-timeout"
compatibility_impact: none
@@ -722,7 +779,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-integration-adapter-templates
owner_layer: infrastructure
client_safe_message: "Internal server error"
client_safe_message: "요청을 처리할 수 없습니다."
log_level: ERROR
runbook_link: "runbook://adapter/adapter-disabled"
compatibility_impact: none
@@ -741,7 +798,7 @@ errors:
retry_after_seconds: null
owner_branch: feature-management-actuator-security-contract
owner_layer: presentation
client_safe_message: "Permission denied"
client_safe_message: "이 작업을 수행할 권한이 없습니다."
log_level: WARN
runbook_link: "runbook://management/actuator-forbidden"
compatibility_impact: none
@@ -760,7 +817,7 @@ errors:
retry_after_seconds: null
owner_branch: 2026-09-21-core-web-review-remediation
owner_layer: application
client_safe_message: "Validation failed"
client_safe_message: "요청 값이 올바르지 않습니다."
log_level: INFO
runbook_link: null
compatibility_impact: additive
@@ -773,7 +830,7 @@ errors:
retry_after_seconds: null
owner_branch: 2026-09-21-core-web-review-remediation
owner_layer: presentation
client_safe_message: "Invalid request parameter"
client_safe_message: "요청 값이 올바르지 않습니다."
log_level: INFO
runbook_link: null
compatibility_impact: additive
@@ -786,7 +843,7 @@ errors:
retry_after_seconds: null
owner_branch: 2026-09-21-core-web-review-remediation
owner_layer: presentation
client_safe_message: "Request mapping failed"
client_safe_message: "요청 값이 올바르지 않습니다."
log_level: INFO
runbook_link: null
compatibility_impact: additive
@@ -799,7 +856,7 @@ errors:
retry_after_seconds: null
owner_branch: 2026-09-21-core-web-review-remediation
owner_layer: application
client_safe_message: "Some batch items failed"
client_safe_message: "요청 값이 올바르지 않습니다."
log_level: WARN
runbook_link: null
compatibility_impact: additive
@@ -812,7 +869,7 @@ errors:
retry_after_seconds: null
owner_branch: 2026-09-21-core-web-review-remediation
owner_layer: crosscut
client_safe_message: "Internal server error"
client_safe_message: "요청을 처리할 수 없습니다."
log_level: ERROR
runbook_link: "runbook://internal/error-spike"
compatibility_impact: additive
@@ -825,7 +882,7 @@ errors:
retry_after_seconds: null
owner_branch: 2026-09-21-core-web-review-remediation
owner_layer: presentation
client_safe_message: "Authentication required"
client_safe_message: "인증이 필요합니다."
log_level: WARN
runbook_link: "runbook://auth/token-missing"
compatibility_impact: additive
@@ -838,7 +895,7 @@ errors:
retry_after_seconds: null
owner_branch: 2026-09-21-core-web-review-remediation
owner_layer: presentation
client_safe_message: "Authentication failed"
client_safe_message: "인증이 필요합니다."
log_level: WARN
runbook_link: "runbook://auth/token-malformed"
compatibility_impact: additive
@@ -851,7 +908,7 @@ errors:
retry_after_seconds: null
owner_branch: 2026-09-21-core-web-review-remediation
owner_layer: presentation
client_safe_message: "Access denied"
client_safe_message: "이 작업을 수행할 권한이 없습니다."
log_level: WARN
runbook_link: "runbook://authz/insufficient-permission"
compatibility_impact: additive
@@ -864,7 +921,7 @@ errors:
retry_after_seconds: null
owner_branch: 2026-09-21-core-web-review-remediation
owner_layer: presentation
client_safe_message: "Route not found"
client_safe_message: "요청한 리소스를 찾을 수 없습니다."
log_level: INFO
runbook_link: null
compatibility_impact: additive
@@ -877,7 +934,7 @@ errors:
retry_after_seconds: null
owner_branch: 2026-09-21-core-web-review-remediation
owner_layer: infrastructure
client_safe_message: "Database lock not available"
client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다."
log_level: WARN
runbook_link: null
compatibility_impact: additive
@@ -0,0 +1,109 @@
# W3-P15 — Wave 3 공통 작업 3-A 에러 어휘
worktree `.claude/worktrees/agent-a4f4002365d4073cd`, 커밋 `e71d343c`(에러 어휘), `8ad36211`(sample JSON escape).
## 설계 메모 (구현 전 현재 경로를 읽고 정한 것)
읽은 현재 경로와 문제:
- web `GlobalExceptionHandler`: 타입별 handler(`MappingException`·`AdapterDisabledException`·멱등성 2종·
`PersistenceFailureException`·`DependencyFailureException`)가 따로 있고, **일반 `ApiErrorCarrier` 분기가 없어**
adopter carrier와 V2 멱등성 예외는 `INTERNAL_ERROR`가 됐다. 문구는 `ClientSafeErrorMessages`(코드별 영어)와
handler 안 하드코딩 영어가 섞여 있었다. RESEH의 `handleExceptionInternal`을 override하지 않아 필수
파라미터·헤더·part 누락이 `application/problem+json`으로 나갔다(I-3a).
- web-fileserver: `FileserverExceptionHandler`가 `FileserverProblem`(RFC 9457, 영어 title)을 problem+json으로,
batch 항목은 `BatchUploadItemProblem`으로 보냈다. Draft-12 offset 불일치는 드래프트 규격 problem 문서.
- graphql: `runtime/GraphQlWireErrorMapper`(category·clientMessage switch), `runtime/GraphQlWireErrors.classificationOf`
(세 번째 switch), `runtime/GraphQlPlatformRejectionMapper`(instanceof 9개 + 문구 하드코딩). retryable은
`GraphQlErrorCategory`에서 계산. IAE는 `INTERNAL_ERROR`. DataLoader `GraphQlBatchLoadException`은 문자열 코드라
mapper가 몰라 `INTERNAL_ERROR`로 가려짐. body 크기 초과는 `REQUEST_ERROR`(예외 경로 + servlet 필터의 하드코딩 JSON).
- grpc: `GrpcStatusMapper` trailer는 `error-code`·`error-category`뿐, description=코드 문자열, IAE는 `INTERNAL`.
- websocket: `SafeStompSubProtocolErrorHandler`가 모든 실패를 `WEBSOCKET_REQUEST_REJECTED` 하나로.
- shared-contract: `MappingException`·`AdapterDisabledException`이 carrier가 아님. 레지스트리 `client_safe_message`는
코드별 영어.
정한 모양:
1. **문구 표 하나**: `shared-contract/.../error/ClientErrorMessages` — `EnumMap<Category, String>` 한국어,
`PERMANENT_DEPENDENCY`·`DATA_INTEGRITY`·`INTERNAL`은 불투명 문구 `OPAQUE` 하나. web `ErrorResponseFactory`는
**message 인자를 없애** 호출자가 문구를 만들 수 없게 했다(web·fileserver·sample·rate-limit·auth writer·durable op 전부
표 사용). 더 알릴 것은 `details`(예: type mismatch의 `parameter`). 필드 검증 detail 문구(`ClientSafeValidationDetails`)도
한국어로. 레지스트리 `client_safe_message`를 표와 같게 바꾸고 동등성 테스트를 추가.
2. **carrier 하나**: shared 예외 2종 + application 멱등성 예외 4종이 `ApiErrorCarrier` 구현. V2 멱등성 예외 코드
`IDEMPOTENCY_UNAVAILABLE`(TRANSIENT_DEPENDENCY/503/true), `IDEMPOTENCY_RECOVERY_REQUIRED`(DATA_INTEGRITY/500/false) 신설
(레지스트리 행 + runbook `docs/runbooks/idempotency-unavailable.md`). web은 `handleCarrier` 한 분기.
3. **IAE는 모든 전송 400 계열**: web `BAD_PARAMETER`(유지), GraphQL `BAD_PARAMETER`(wire category `REQUEST`, 분류 `BAD_REQUEST`
— 행의 "BAD_USER_INPUT"은 Spring GraphQL 분류명 `BAD_REQUEST`로 해석, 코드는 전송 공통 `BAD_PARAMETER`),
gRPC `INVALID_ARGUMENT`+`BAD_PARAMETER`, STOMP `error-code: BAD_PARAMETER`. GraphQL에서는 application이 등록한 매핑이 IAE
규칙보다 먼저다(자기 IAE 하위 타입을 모델링한 adopter 보호).
4. **GraphQL**: 매퍼 3개를 `error/`로 옮기고(S5-#6d) `GraphQlPlatformRejectionMapper`는 삭제 — 플랫폼 예외 11종이
`error/GraphQlPlatformRejection`(wireCode·shared Category·필요 시 wireCategory/constraint)을 구현. Category → (wire category,
ErrorType) 렌더링은 `GraphQlWireErrorMapper.RENDERINGS` 표 하나(S5-#6c), 문구는 shared 표. retryable은
`GraphQlWireError.of(..., retryable, ...)`로 코드 값(X2-P2-1d), 플랫폼 자체 코드만 wire category 기본값.
플랫폼 거부 문구도 표에서 온다("구조 한계 초과" 같은 개별 문구 대신 category 문구 — 무엇이 거부됐는지는 code·constraint).
5. **fileserver**: `FileserverExceptionHandler`가 `ErrorResponseFactory.body(code, context.retryable(), details)`로 Envelope.
`retryable`은 발생 건의 판단이 코드 상한을 넘지 않게 AND. 식별 값·`ambiguous`·`reconciliationRequired`는 `details`.
`FileserverProblemHeaders`(Retry-After·Content-Range)와 tus 헤더 유지, Draft-12 offset 문서만 예외(코드·문서 명시).
6. **gRPC status description**: 코드 문자열 → shared 한국어 문구(결정 11 "모든 전송이 사용"). 코드는 trailer에 그대로 있다.
이것은 wire 동작 변경이다(description을 코드로 파싱하던 클라이언트는 trailer로 옮겨야 함).
## 행 결과
| ID | 결과 | 근거 |
|---|---|---|
| I-3a | 완료 | `TransportErrorHandlingTest.missingRequiredHeaderIsAnEnvelopeNotAProblemDocument`·`missingRequiredQueryParameterIsAnEnvelopeNotAProblemDocument` FAIL(`Content type [application/problem+json] is not compatible with [application/json]`)→PASS. `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java:333`(`handleExceptionInternal` override: 상태→`OperationalError`, 준비된 헤더 유지, committed 응답은 null) |
| J-10e | 완료 | 호출부 전환은 Wave 2 NEW-9a에서 이미 됨(`runtime/GraphQlPlatformWebInterceptor.java:169`, `runtime/GraphQlPlatformInstrumentation.java:91`이 주입된 `GraphQlWireErrorMapper.toGraphQlError` 사용). 이번에 매퍼를 `error/GraphQlWireErrorMapper.java`로 옮기고 `GraphQlPlatformRejectionMapper`를 없애 경로가 정말 하나다. 기존 `GraphQlRequestStageErrorMappingTest` PASS |
| X2-P1-6 | 완료 | sample 3곳의 사본을 `sample-portfolio/.../application/event/EventJson.java:11`(RFC 8259 §7) 하나로. `PosterImagePublicationEventPublisher`의 제어문자 누락 제거. 재현 FAIL은 못 만듦: 그 publisher의 입력(`PosterId`·`ObjectOperationId`·`PosterImageReference`·`ObjectMediaType`)이 모두 형식 검증돼 현재 경로로 제어문자가 들어갈 수 없는 잠재 결함이다. escape 표는 기존 `WorkLogReservedIntegrationEventMapperJsonTest.escapeProducesRfc8259EscapedText`가 `EventJson.escape`를 검증(PASS). 앱 쪽 `OutboxEnvelopeJson`은 지시대로 그대로. 커밋 `8ad36211` |
| X2-P2-1d | 완료 | `GraphQlWireErrorMapperTest.aCarrierIsRetryableOnlyWhenItsCodeIs` FAIL(`["DB_QUERY_CANCELED", true]` 기대 `false`)→PASS. `error/GraphQlWireError.java`의 `of(..., boolean retryable, ...)`, `error/GraphQlWireErrorMapper.java:141`(`code.retryable()`) |
| X2-P2-1e | 완료 | 코드별 영어 표 `ClientSafeErrorMessages` 삭제, `shared-contract/.../error/ClientErrorMessages.java:19` 하나를 web·fileserver·sample·graphql·grpc가 사용. `ClientErrorMessagesTest`(모든 Category 한국어), `OperationalErrorRegistryContractTest.everyRegistryClientMessageIsTheSharedCategoryMessage`(레지스트리 전 행 = 표) PASS. 수정 방향의 "코드별 표"는 결정 11(Category별 표)을 따름 |
| X2-P2-1f | 완료 | `GrpcStatusMapperTest.trailersCarryTheRetryabilityOfTheCodeNotOfItsCategory` FAIL(`expected: "false" but was: null`)→PASS. `adapter/inbound/grpc/.../GrpcStatusMapper.java:34`(`error-retryable`), `:63` |
| X2-P2-2a | 완료 | `SharedExceptionCarrierTest` 2건 FAIL(`Expecting actual throwable to be an instance of: ApiErrorCarrier but was: MappingException`)→PASS, `IdempotencyFailureCodeTest.everyIdempotencyFailureCarriesItsOperationalCode` 4건 FAIL(같은 메시지)→PASS. `shared-contract/.../MappingException.java:11`, `AdapterDisabledException.java:13`, `application-core/.../idempotency/Idempotency{InFlight,RequestMismatch,Unavailable,RecoveryRequired}Exception.java`. web handler 4개 → `GlobalExceptionHandler.java:151` `handleCarrier` 한 분기(+ catch-all이 carrier면 위임). V2 예외 코드 `IDEMPOTENCY_UNAVAILABLE`·`IDEMPOTENCY_RECOVERY_REQUIRED` 신설(레지스트리 행, runbook) |
| X2-P2-2b | 완료 | GraphQL `GraphQlWireErrorMapperTest.anIllegalArgumentIsABadParameterRequestError` FAIL(`["INTERNAL_ERROR", "INTERNAL"]`)→PASS(`error/GraphQlWireErrorMapper.java:174`); gRPC `GrpcExceptionHandlingInterceptorTest.mapsAnIllegalArgumentToInvalidArgumentBadParameter` FAIL(`[INTERNAL, "INTERNAL_ERROR"]`)→PASS(`GrpcExceptionHandlingInterceptor.java:114`); STOMP `SafeStompSubProtocolErrorHandlerTest.anIllegalArgumentReportsBadParameter` FAIL(`but was: "WEBSOCKET_REQUEST_REJECTED"`)→PASS; web은 기존 동작 유지(`GlobalExceptionHandler.java:76`) |
| X2-P2-3a | 완료 | `FileserverHardeningContractTest.aFailureIsTheSharedEnvelopeCarryingTheStableCode` FAIL(`Response header 'Content-Type' expected:<application/json> but was:<application/problem+json>`)→PASS. `web-fileserver/.../problem/FileserverExceptionHandler.java:47`. problem 타입 4개 삭제(아래 표). 이름 중복 3개(`UNAUTHENTICATED`·`PRECONDITION_FAILED`·`UNSUPPORTED_MEDIA_TYPE`)는 **더 작은 수정**: `FileserverFailureContext.code()`가 `FileserverErrorCode` 하나라서 그 3개를 `OperationalError`로 바꾸면 context·header 표·application-fileserver 전반의 타입이 바뀐다(같은 시기 fileserver 상태 전이 묶음과 충돌). 두 enum의 category·status·retryable이 이미 같아 wire는 동일하므로 `FileserverExceptionTest.aCodeNamedLikeAnOperationalErrorMeansTheSameOnTheWire`(28 case PASS)로 동일성을 고정했다 |
| X2-P2-3b | 완료 | 결정 12대로 유지 + 예외 명시: `Draft12UploadController.java:165` Javadoc("Protocol exception to the Envelope rule"), `Draft12OffsetProblem` Javadoc, `docs/fileserver/http-contract.md` 「Protocol exceptions to the Envelope rule」 절, `FileserverExceptionHandler` Javadoc. `Draft12ProtocolTest.offsetMismatchReturnsTheDraftProblemDetailWithBothOffsets` PASS(그대로 problem+json) |
| X2-P2-9a | 완료 | `GraphQlWireErrorMapperTest.anOversizedRequestIsPayloadTooLarge` FAIL(`expected: "PAYLOAD_TOO_LARGE" but was: "REQUEST_ERROR"`)→PASS. `graphql/.../http/GraphQlRequestTooLargeException.java:64`, servlet 필터 `runtime/servlet/GraphQlRequestBodyLimitFilter`의 하드코딩 JSON도 `PAYLOAD_TOO_LARGE`+공용 문구로. `GraphQlPlatformExecutionPathTest.anOversizeDocumentIsRejectedBeforeItIsParsed` 기대값 갱신 PASS. 문서 모양 거부(`GRAPHQL_DOCUMENT_SHAPE_REJECTED`)·fileserver `FILE_TOO_LARGE`는 별도 코드 유지 |
| X2-P2-9b | 완료 | `SafeStompSubProtocolErrorHandlerTest.aWrappedCarrierFailureReportsItsOwnCode` FAIL(`["WEBSOCKET_REQUEST_REJECTED", "WEBSOCKET_REQUEST_REJECTED"]`)→PASS. `SafeStompSubProtocolErrorHandler.java:39`(원인 사슬 16단계까지 carrier/IAE 탐색, `message` 헤더는 고정). websocket `build.gradle`에 `:shared-contract`(registry 허용 edge) 추가 |
| S1-#7 | 남음 | 이유: fileserver `api/error` 서브클래스 22개의 생성 지점이 약 130곳(application-fileserver·persistence-fileserver·outbound fileserver)이고, 같은 시기에 도는 fileserver 상태 전이 묶음이 같은 파일들을 고친다. 에러 어휘(wire)는 이번에 끝났고 이 행은 예외 계층 모양(SRP)이라 충돌 없이 하려면 그 묶음 통합 뒤 Wave 3 구조 작업(SRP 분해)으로 넘긴다. notification 12개도 같은 이유 |
| S2-lead-4 | 완료 | `JpaPersistenceExceptionCodeTest.aJpaFailureCarriesTheOperationalCodeOfItsCategory` 16건 FAIL(`Expecting actual throwable to be an instance of: PersistenceFailureException`)→PASS. `persistence-jpa/.../api/error/JpaPersistenceException.java:22`(상속), `:59`(`FailureCategory`→`DB_*`; 직렬화 후에도 `errorCode()`가 category에서 계산). 대응 코드가 없던 2개는 `DB_OPTIMISTIC_CONFLICT`(CONFLICT/409/false)·`DB_COMPLETION_UNKNOWN`(DATA_INTEGRITY/500/false) 신설, SCHEMA_MISMATCH·DATA_CORRUPTION·ENTITY_NOT_FOUND·UNKNOWN은 이전 catch-all과 같은 `INTERNAL_ERROR`. `LockFailureClassificationContractTest`의 REGISTRY-GAP-1("optimistic 코드 없음") 고정 테스트를 `anOptimisticLockConflictIsANonRetryableConflict`로 승격. testFixtures에 `:shared-contract` 추가(mongo는 edge 없어 유지) |
| S5-#1c | 완료 | X2-P2-3a와 같은 작업·같은 테스트. 식별 필드는 Envelope `details`(`fileId`·`uploadId`·`expectedOffset`·`currentOffset`·`state`·`ambiguous`·`reconciliationRequired`), tus·Retry-After·Content-Range 헤더 유지(`FileserverProblemHeaderParityTest` PASS). batch 항목도 `ApiError`(`FileUploadControllerTest` `$.results[1].error.code` PASS) |
| S5-#1d | 완료 | X2-P2-3b와 같은 작업(결정 12: 유지 + 예외 명시) |
| S5-#6c | 완료 | switch 3개(`category`·`clientMessage`·`classificationOf`)를 `error/GraphQlWireErrorMapper.java:43` `RENDERINGS`(Category → wire category·ErrorType) 하나와 shared 문구 표로 대체. "요청한 리소스를 찾을 수 없습니다." 3곳은 모두 `ClientErrorMessages.of(NOT_FOUND)` 한 곳에서 온다(`GraphQlAuthorizationInterceptor.toWireError`는 `fromRejection` 위임). graphql `check`·`systemTest`·`graphqlTransportQualificationTest` PASS |
| S5-#6d | 완료 | 플랫폼 예외 11종이 `error/GraphQlPlatformRejection` 구현, instanceof 사슬(`GraphQlPlatformRejectionMapper`) 삭제, `GraphQlWireErrorMapper`·`GraphQlWireErrors`를 `runtime/`→`error/`로 이동(테스트도 이동). API surface 재승인(`updateGraphQlApiSurface -PapproveGraphQlApiSurfaceChange`) |
| S5-lead-1 | 완료 | 결정 11: `ClientErrorMessages`(한국어, Category별) 하나를 web·fileserver·GraphQL·gRPC(status description) 모두 사용. gRPC `GrpcExceptionHandlingInterceptorTest.theStatusDescriptionIsTheSharedClientMessageOfTheCategory` FAIL(`expected: "요청한 리소스를 찾을 수 없습니다." but was: "ROUTE_NOT_FOUND"`)→PASS, `GrpcP1BoundaryWireTest` 기대값 갱신 PASS. STOMP `message` 헤더는 X2-P2-9b 지시대로 고정값 유지 |
| P8-new-1 | 완료 | 결정 25: `GraphQlBatchLoadException`이 `ApiErrorCode`만 받고 `ApiErrorCarrier` 구현(`dataloader/GraphQlBatchLoadException.java:16`), `GraphQlBatchValue.Failed(ApiErrorCode)`, `GraphQlBatchResultMapper.map(..., ApiErrorCode)`. `GraphQlWireErrorMapperTest.aFailedBatchKeyKeepsItsRegisteredCode` PASS. FAIL은 API 단계: 이전 생성자는 `String`만 받아 테스트가 컴파일되지 않음(이전 동작은 `INTERNAL_ERROR` 마스킹) |
## 제거된 코드
| 대상 | 경로 | 마지막으로 존재한 커밋 | 이유 |
|---|---|---|---|
| `ClientSafeErrorMessages` (web 코드별 영어 문구 표) | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeErrorMessages.java` | `016597ac` | 결정 11: shared `ClientErrorMessages`(Category별 한국어) 하나로 |
| `PortfolioClientSafeErrorMessages` (sample 영어 문구) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioClientSafeErrorMessages.java` | `016597ac` | 같은 이유(`ErrorResponseFactory`가 message 인자를 받지 않음) |
| `FileserverProblem` | `src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblem.java` | `016597ac` | 결정 2: fileserver 실패도 Envelope |
| `FileserverProblemFactory` (+ composition `fileserverProblemFactory` bean) | `src/adapter/inbound/web-fileserver/.../problem/FileserverProblemFactory.java`, `src/composition/fileserver-platform/.../FileserverWebAssemblyConfiguration.java` | `016597ac` | 같은 이유 |
| `FileserverProblemTitles` (영어 title 표) | `src/adapter/inbound/web-fileserver/.../problem/FileserverProblemTitles.java` | `016597ac` | 같은 이유 + 결정 11 |
| `BatchUploadItemProblem` | `src/adapter/inbound/web-fileserver/.../dto/BatchUploadItemProblem.java` | `016597ac` | batch 항목도 `ApiError` |
| `FileserverErrorCode.problemType()` (URN) | `src/application-fileserver/.../api/error/FileserverErrorCode.java` | `016597ac` | problem 문서가 없어져 호출자 0 |
| `GraphQlPlatformRejectionMapper` (instanceof 사슬) | `src/adapter/inbound/graphql/.../runtime/GraphQlPlatformRejectionMapper.java` | `016597ac` | S5-#6d: 예외가 `GraphQlPlatformRejection` 구현 |
| `runtime/GraphQlWireErrorMapper`, `runtime/GraphQlWireErrors` (이동) | `src/adapter/inbound/graphql/.../runtime/` → `.../error/` | `016597ac` | 삭제가 아니라 `error/` 패키지로 이동(S5-#6d). `classificationOf`·`category`·`clientMessage` switch는 `RENDERINGS` 표로 대체 |
| sample publisher별 JSON escape 사본 3개 | `PosterEventPublisher`·`PosterImagePublicationEventPublisher`·`WorkLogReservedIntegrationEventMapper`(`escape`/`field`/`jsonField`) | `016597ac` | X2-P1-6: `EventJson` 하나로 |
(브리프는 마지막 커밋을 `6d27356e`로 적으라 했지만 이 파일들은 그 뒤 Wave 1–2에서도 바뀌었으므로 실제 마지막 커밋인 `016597ac`를 적었다.)
## 새로 발견한 결함
- `P15-new-1` (고침): web `GlobalExceptionHandler`에 일반 `ApiErrorCarrier` 분기가 없어, shared 두 carrier 외의 carrier(adopter 예외, V2 멱등성 예외)는 web에서 `INTERNAL_ERROR` 500(retryable=true)으로 나갔다. `GlobalExceptionHandler.java:151` `handleCarrier` + catch-all 위임으로 고침.
- `P15-new-2` (고침): GraphQL servlet body-limit 필터(`runtime/servlet/GraphQlRequestBodyLimitFilter`)가 mapper를 거치지 않고 하드코딩 JSON(`REQUEST_ERROR`, `retryable` 없음)을 썼다 — 요청 크기 초과의 두 번째 어휘. `PAYLOAD_TOO_LARGE` + 공용 문구 + `retryable:false`로 고침.
- `P15-new-3` (미수정, 결정 필요 후보): `OperationalError.INTERNAL_ERROR`가 레지스트리에서 `retryable: true`다. JPA의 SCHEMA_MISMATCH·DATA_CORRUPTION 같은 결정적 내부 실패도 이 코드로 나가 클라이언트에게 재시도를 권한다(이전 catch-all도 같았음). 코드 하나를 더 두거나 `INTERNAL_ERROR`를 false로 바꿀지는 소유자 결정 필요. 승인자: 저장소 소유자 결정 필요.
- `P15-new-4` (알림): gRPC status description이 코드 문자열에서 한국어 공용 문구로 바뀌었다(결정 11 적용). description을 코드로 파싱하던 gRPC 클라이언트는 `error-code` trailer를 봐야 한다. `src/grpc*` 플랫폼 leaf는 이 어댑터를 쓰지 않아 영향 없음(grep 확인).
- 통합 주의: `runtime/GraphQlPlatformInstrumentation.java`는 import 한 줄(`error.GraphQlWireErrorMapper`)만 바뀌었다. 같은 파일을 고치는 P8-new-2 묶음과 import 줄에서 충돌할 수 있다.
## 실행한 검증 (모두 `--max-workers=2`, 이 worktree)
- `:shared-contract:check :application-core:check :application-fileserver:check :adapter:inbound:web:check :adapter:inbound:web-fileserver:check :composition:fileserver-platform:check` 통과
- `:adapter:outbound:persistence-jpa:check :sample-portfolio:check :adapter:inbound:graphql:check :adapter:inbound:grpc:check :adapter:inbound:websocket:check` 통과(+ persistence-jpa `compilePostgresqlIntegrationTestJava`·`compileJpaPlatformPerformanceTestJava`)
- `:app-bootstrap:check`(455 tests, 5 skipped) `architectureCheck` `verifyPublicPathSnapshot` 통과
- `:adapter:inbound:graphql:systemTest` `graphqlStableTest` `sampleWebContractCheck` `conditionalTransportQualification`(GraphQL·gRPC·WebSocket 전송 lane + conditional build contract) 통과
- `testClasses`(전 leaf 컴파일) 통과, `verifyDependencyLocks` 통과, 건드린 leaf 11개 `qualityCheck`(SpotBugs) 통과
- API surface: `updateGraphQlApiSurface -PapproveGraphQlApiSurfaceChange`(runtime→error 이동, `GraphQlPlatformRejection` 추가), `verifyJpaApiSurface` 변경 없음
- env 키 변경 없음 → `verifyEnvKeys` 해당 없음. Docker 벤더 lane은 이 묶음이 DB 동작을 바꾸지 않아 돌리지 않음(persistence-jpa는 예외 상속만 변경, 단위 lane 통과)
- 결과 파일: 원본 작업 트리 경로 쓰기가 worktree 격리로 거부돼, 같은 상대 경로(`docs/reviews/2026-09-25-review-followup-results/W3-P15.md`)로 이 worktree 브랜치에 커밋했다
@@ -415,7 +415,7 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
| I-2c | Required | 콜백 크기 테스트가 배열을 직접 넘겨 컨버터 버퍼링 경로를 검증 안 함 | 남음 | `src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcControllerTest.java:118-124`(`aBodyOverTheTransportCeilingIsRefusedBeforeIngress`) | W4 | MockMvc/실서버로 큰 본문(및 Content-Length 없는 chunked)을 보내 413과 ingress 미호출을 단언 |
| I-2d | Required | `backend.web.budgets.enabled=true`면 없는 `BudgetProblemMapper` 빈을 찾아 기동 실패 | 해당 없음(코드 삭제) | 제거 표 「요청 budget 필터 (`WebMvcBudgetFilter`, `BudgetProblemMapper`)」. `WebMvcBudgetExceptionHandler`·`backend.web.budgets` grep 0 | - | - |
| I-2e | Required | 문서가 본문 크기·JSON 깊이를 "Application, always"가 막는다고 기재 | 완료 | `docs/web/repository-adaptation.md:147-151` "Removed 2026-09-25 … no longer enforces the application column" 배너. 커밋 `6d27356e` | - | - |
| I-3a | Required | Envelope 계약에서 override 안 된 Spring MVC 예외(필수 파라미터·헤더·part 누락 등)가 `application/problem+json`으로 새어 나감 | 남음 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java:52`(RESEH 상속, `handleExceptionInternal` override 없음), `.../envelope/EnvelopeBodyAdvice.java:44-46`(비 JSON은 감싸지 않음). 실경로: `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterImagePublicationController.java:58`(필수 `Idempotency-Key`), `LegacyPosterImageController.java:36`(필수 part) | W3 | 소유자 결정(Envelope 통일)대로 `GlobalExceptionHandler`에서 `handleExceptionInternal` 하나를 override해 status → `OperationalError` 매핑 후 `ErrorResponseFactory.body` 반환 |
| I-3a | Required | Envelope 계약에서 override 안 된 Spring MVC 예외(필수 파라미터·헤더·part 누락 등)가 `application/problem+json`으로 새어 나감 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): `TransportErrorHandlingTest.missingRequiredHeaderIsAnEnvelopeNotAProblemDocument`·`missingRequiredQueryParameterIsAnEnvelopeNotAProblemDocument` FAIL(`Content type [application/problem+json] is not compatible with [application/json]`)→PASS. `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java:333`(`handleExceptionInternal` override: 상태→`OperationalError`, 준비된 헤더 유지, committed 응답은 null) | - | 소유자 결정(Envelope 통일)대로 `GlobalExceptionHandler`에서 `handleExceptionInternal` 하나를 override해 status → `OperationalError` 매핑 후 `ErrorResponseFactory.body` 반환 |
| I-3b | Required | `@Valid` 클래스 레벨 제약 위반이 `details: []`로 나감 | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): 커밋 `5c08d3be`(W2). `GlobalExceptionHandlerTest.classLevelConstraintViolationIsReportedAgainstTheRequest` FAIL(`expected: [{code=INVALID, field=request, message=Invalid value}] but was: []`)→PASS. `getAllErrors()`(`GlobalExceptionHandler.java:263`), `ClientSafeValidationDetails.from(ObjectError)`가 global error를 `field=request`로(`ClientSafeValidationDetails.java:56`) | - | `getGlobalErrors()`도 `ClientSafeValidationDetails`로 변환해 details에 합침 |
| I-3c | Required | 필수 파라미터/헤더 누락·`HandlerMethodValidationException` 등의 에러 형식 테스트 0건 | 남음 | web·bootstrap·sample 테스트에 `MissingServletRequestParameter`/`MissingRequestHeader`/`HandlerMethodValidation` grep 0 | W4 | web slice 테스트로 필수 파라미터·헤더 누락 시 Envelope 400(`application/json`)을 단언 |
| I-4a | Required | `RequestLoggingFilter`가 Spring Security 뒤에서 돌아 401/403 응답 meta id가 null, 접근 로그 누락 | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): request/correlation/trace/span id 발급·MDC·응답 헤더를 `WebMvcRequestIdFilter`(HIGHEST+10, Security 앞) 한 곳으로 이동(`src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java:95,103`), ERROR/ASYNC 재디스패치에 같은 값 복원. `SecurityModeWebContractTest.anUnauthenticatedRejectionCarriesTheAssignedRequestIdInItsMeta`(실제 JWT security 체인이 쓴 401 Envelope의 `meta.requestId` = `X-Request-Id`) FAIL(`expected: "13499754-…" but was: null`)→PASS. `WebMvcRequestIdFilterTest.assignedIdentifiersAreOnMdcDuringTheChainAndMatchWhatTheResponseCarries`·`inboundCorrelationIdLosesLineBreaksBeforeReachingMdc` FAIL(`No value present` / `expected "fooFAKE LOG" but was null`)→PASS, `mdcIsClearedWhenTheRequestLeavesTheFilter`·`anErrorRedispatchRestoresTheSameIdentifiersOnMdc` PASS. 순서: `OperationalContractRuntimeTest.requestIdFilterIsRegisteredAheadOfSpringSecurity`(`src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java:135`, 슬라이스에 `SecurityFilterAutoConfiguration`을 넣어 실제 `springSecurityFilterChain` 등록과 비교) PASS. fixture 문제: `PipelineOrderFixtureApplication`은 의미 순서·async 1회 관측만 증명한다고 주석에 적고 실제 순서는 위 두 테스트가 맡음. `RequestLoggingFilter`는 principal을 읽으려고 보안 체인 안쪽에 남음 → 체인이 거절한 요청의 접근 로그 줄은 없고 entry point/access-denied handler의 `security failure` 로그(이제 request_id 포함)가 대신함 | - | MDC(request/correlation/trace id) 채우기를 `WebMvcRequestIdFilter`(HIGHEST+10)로 옮기고 `OperationalContractRuntimeTest`에 "request-id 필터 order < `springSecurityFilterChain` order" 단언 추가 |
@@ -451,7 +451,7 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
| J-10b | Consider | `compat`·`release`·`moduleboundary`(테스트 데이터가 운영 jar에) 도달 불가 | 해당 없음(코드 삭제) | 제거 표 「graphql 스키마 호환성 비교기 `compat/`」「graphql 릴리스 게이트 `release/`」「graphql 모듈 경계 모델 `moduleboundary/`」 | - | - |
| J-10c | Consider | `fetch`·`mutation`(·`pagination`) 패키지가 요청 경로에서 도달 불가 | 완료 | D1(분류 2) 결정대로 라이브러리 API로 등재: `src/adapter/inbound/graphql/README.md:214-226`, `CLAUDE.md:162`. graphql은 opt-in capability라 기본 조립에 실리지 않음. 커밋 `6d27356e` | - | - |
| J-10d | Consider | `http/` 병렬 HTTP 계층이 도달 불가 | 남음 | 9개는 삭제(제거 표 「병렬 HTTP 전송 모델」), 남은 `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestEnvelopeValidator.java`·`GraphQlHttpRequestEnvelope.java`는 테스트(`GraphQlRequestEnvelopeValidatorTest`, `GraphQlRequestBoundsTest`)만 참조, README 라이브러리 목록에도 없음 | W3 | 두 타입을 삭제하고 테스트는 실제 경로(`GraphQlPlatformWebInterceptor.verifyRequestBounds`, `GraphQlRequestSize`, `GraphQlJsonStructurePolicy`) 대상으로 옮김 |
| J-10e | Consider | 두 번째 에러 어휘: 요청 단계 거부가 `GraphQlWireErrorMapper`를 거치지 않아 `ApiErrorCarrier`가 `INTERNAL_ERROR`로 바뀜 | 남음 | `GraphQlRequestErrorMapper`는 삭제(제거 표)됐으나 경로는 여전히 둘: `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptor.java:161-165`, `.../runtime/GraphQlPlatformInstrumentation.java:84-88`이 `GraphQlPlatformRejectionMapper.map` 직접 호출. 사실은 `GraphQlWireErrorMapper.java:23-28` Javadoc이 인정 | W3 | 두 호출부를 `GraphQlWireErrorMapper`(bean 주입)의 요청 단계 메서드로 바꿔 필드·요청 단계가 같은 mapper를 쓰게 |
| J-10e | Consider | 두 번째 에러 어휘: 요청 단계 거부가 `GraphQlWireErrorMapper`를 거치지 않아 `ApiErrorCarrier`가 `INTERNAL_ERROR`로 바뀜 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): 호출부 전환은 Wave 2 NEW-9a에서 이미 됨(`runtime/GraphQlPlatformWebInterceptor.java:169`, `runtime/GraphQlPlatformInstrumentation.java:91`이 주입된 `GraphQlWireErrorMapper.toGraphQlError` 사용). 이번에 매퍼를 `error/GraphQlWireErrorMapper.java`로 옮기고 `GraphQlPlatformRejectionMapper`를 없애 경로가 정말 하나다. 기존 `GraphQlRequestStageErrorMappingTest` PASS | - | 두 호출부를 `GraphQlWireErrorMapper`(bean 주입)의 요청 단계 메서드로 바꿔 필드·요청 단계가 같은 mapper를 쓰게 |
| J-10f | Consider | `GraphQlPlatformActuatorEndpoint`·`…ConfigurationReport`가 bean이 아님 | 해당 없음(코드 삭제) | 제거 표 「`GraphQlPlatformActuatorEndpoint`, `GraphQlPlatformConfigurationReport`」 | - | - |
| J-10g | Consider | `schema/` 19개 중 16개 도달 불가 | 해당 없음(코드 삭제) | 제거 표 「schema gate·병렬 조립기 … 14개」. 남은 `schema/` 3개(`GraphQlScalar*`)는 자동 설정에서 도달 | - | - |
| J-11a | Consider | CLAUDE.md가 Accept negotiation을 `wired`로 표기(`GraphQlMediaTypes` 도달 불가) | 해당 없음(코드 삭제) | 제거 표 「병렬 HTTP 전송 모델(… `GraphQlMediaTypes`, `GraphQlAcceptHeader` …)」, CLAUDE.md 등급 표에서 행 제거됨 | - | - |
@@ -726,26 +726,26 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
| X2-P1-4a | Consider | web `cursor/CursorCodec`(dev key 하드코딩) 삭제 | 완료 | `docs/capability-status.md:94`, `HmacWebCursorCodec`도 삭제(`:97`), 커밋 `6d27356e` | - | - |
| X2-P1-4b | Consider | 서명 계층 하나(inbound에서 서명, persistence는 typed keyset), 남으면 공용 서명 헬퍼 | 남음 | HMAC codec 7 → 4: graphql `HmacGraphQlCursorCodec`, persistence-jpa `SignedJsonCursorCodec`, persistence-mongo `MongoKeysetCursorCodec`, 벤더 `GrpcResumeTokenCodec`. 앱 쪽 3개 모두 production 생성 0(라이브러리 API) | W3 | 결정(2026-09-25): Wave 3 라이브러리 유지 결정을 따름 — 서명 codec 유지, shared-contract에 sign/verify 헬퍼 하나로 중복 제거 |
| X2-P1-5 | Consider | SHA-256 보일러플레이트 → shared-contract `Sha256` | 남음 | `MessageDigest.getInstance` main 72곳/68파일(`208077fd`) → 40곳/36파일(현재, `git grep -c 'MessageDigest.getInstance' -- 'src/**/src/main/java/**'`). shared-contract에 `Sha256` 없음(app-core `application/messaging/contract/Sha256.java` 값 타입만) | W3 | shared-contract `Sha256.hex(String)`·`digest(byte[])` 추가, edge 있는 25파일 교체(objectstorage 12, sample 3, graphql 2, cache-redis 2, fileserver 2, notification 2, persistence-jpa 2); mongo 3·application-objectstorage 2(edge 없음)와 벤더 5는 유지 |
| X2-P1-6 | Consider | JSON 문자열 escape 동작 3가지 | 남음 | fileserver 사본 삭제. 남음: `OutboxEnvelopeJson.java:44-63`, sample `PosterEventPublisher.java:89-101`·`WorkLogReservedIntegrationEventMapper.java:56-68`(RFC 8259), sample `PosterImagePublicationEventPublisher.java:76-78`(`\`·`"`만 → 제어문자가 들어오면 잘못된 JSON), redis-sdk `JsonEnvelopeFraming.java:166-183`·`CanonicalJsonWriter`(유지 대상) | W3 | sample 3곳을 Jackson 직렬화(또는 sample 안 helper 1개)로 통일해 `PosterImagePublicationEventPublisher` 제어문자 누락 수정. 앱 쪽 사본은 `OutboxEnvelopeJson` 1개뿐이라 공용 `JsonStrings`는 만들지 않음 |
| X2-P1-6 | Consider | JSON 문자열 escape 동작 3가지 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): sample 3곳의 사본을 `sample-portfolio/.../application/event/EventJson.java:11`(RFC 8259 §7) 하나로. `PosterImagePublicationEventPublisher`의 제어문자 누락 제거. 재현 FAIL은 못 만듦: 그 publisher의 입력(`PosterId`·`ObjectOperationId`·`PosterImageReference`·`ObjectMediaType`)이 모두 형식 검증돼 현재 경로로 제어문자가 들어갈 수 없는 잠재 결함이다. escape 표는 기존 `WorkLogReservedIntegrationEventMapperJsonTest.escapeProducesRfc8259EscapedText`가 `EventJson.escape`를 검증(PASS). 앱 쪽 `OutboxEnvelopeJson`은 지시대로 그대로. 커밋 `8ad36211` | - | sample 3곳을 Jackson 직렬화(또는 sample 안 helper 1개)로 통일해 `PosterImagePublicationEventPublisher` 제어문자 누락 수정. 앱 쪽 사본은 `OutboxEnvelopeJson` 1개뿐이라 공용 `JsonStrings`는 만들지 않음 |
| X2-P1-7 | Consider | 주입된 Clock을 우회하는 시간 조회 | 남음 | `RoutingObjectMutationAdapter.java:60` `clock` 필드가 있는데 `Instant.now()` 12곳(:128-349), 기본 생성자 `Clock.systemUTC()`(:64); objectstorage 설정 5곳(`ObjectStorageBindingCompiler.java:40`, `ObjectStorageCapabilityConfig.java:110`, `ObjectStorageScanMaintenanceConfig.java:23`, `S3ObjectStorageProviderContribution.java:33,35`); `MvcStreamWriter` 5, `LiveEventStompBroadcaster`·`MongoTenantClientRegistry`·`KeyOperationRequests` 각 1. main 전체 `Instant.now()` 26곳/11파일, `Clock.systemUTC()` 11곳/10파일 | W3 | objectstorage 설정 5곳에 `Clock` bean 주입, `RoutingObjectMutationAdapter` 12곳을 `clock.instant()`로; 나머지 4파일은 생성자로 Clock 주입 |
| X2-P2-1a | Required | `VALIDATION_FAILED`가 Envelope 400 vs problem-catalog 422 (= I-9) | 해당 없음(코드 삭제) | `problem-catalog.yaml`·`ProblemCatalog` 삭제(`docs/capability-status.md:104`), 남은 정의 `OperationalError.java:15` 400 하나 | - | - |
| X2-P2-1b | Required | budget 경로가 `URI_TOO_LONG`·JSON 깊이 초과를 다른 코드·problem+json으로 | 해당 없음(코드 삭제) | `WebMvcBudgetFilter`·`BudgetProblemMapper` 삭제(`docs/capability-status.md:105`) | - | - |
| X2-P2-1c | Required | `ProblemCode`·`ProblemCatalog` 동의어 어휘 제거 | 완료 | `docs/capability-status.md:104`, `git grep -w ProblemCode -- 'src/**/src/main/**'` → 0, 커밋 `6d27356e` | - | - |
| X2-P2-1d | Required | GraphQL `retryable`을 코드가 아니라 category에서 계산 | 남음 | `GraphQlWireError.java:73` `category.retryable()`, `GraphQlWireErrorMapper.java:79-85` `fromApiError`가 `code.retryable()` 안 씀, `GraphQlErrorCategory.java:13-28` | W3 | `GraphQlWireError.of`에 retryable 인자 추가, `fromApiError`는 `code.retryable()`, 플랫폼 자체 코드만 category 기본값 |
| X2-P2-1e | Required | client-safe 메시지 표가 전송마다 다름(web 코드별 영어, GraphQL category별 한국어) | 남음 | `ClientSafeErrorMessages.java:14-40`, `GraphQlWireErrorMapper.java:105-111` | W3 | 코드별 메시지 표 하나를 shared-contract `ApiErrorCode` 옆에 두고 web·graphql 2곳이 사용, 언어 하나로 |
| X2-P2-1f | Required | gRPC trailer에 `retryable` 없음 | 남음 | `GrpcStatusMapper.java:22-27`(키 `error-code`·`error-category`뿐), `trailersFor` :51 | W3 | `error-retryable` trailer 키 추가(`code.retryable()`) |
| X2-P2-2a | Required | shared 예외가 `ApiErrorCarrier`를 구현하지 않아 web에서만 제대로 매핑 | 남음 | `MappingException.java:11`, `AdapterDisabledException.java:13`, `IdempotencyInFlightException.java:8`, `IdempotencyRequestMismatchException.java:9` 모두 평범한 `RuntimeException`(ScopeMissing은 삭제). web 타입별 handler `GlobalExceptionHandler.java:77,89,178,190`; GraphQL `GraphQlWireErrorMapper.java:66`·gRPC `GrpcExceptionHandlingInterceptor.java:121`은 carrier만 봄. V2에서 생긴 `IdempotencyUnavailableException`·`IdempotencyRecoveryRequiredException`은 어느 전송에도 매핑 없음 | W3 | 4종이 `ApiErrorCarrier` 구현(`MAPPING_FAILED`, `ADAPTER_DISABLED`, `IDEMPOTENT_IN_FLIGHT`, `IDEMPOTENT_REQUEST_MISMATCH`), web handler 4개를 carrier 분기 1개로 교체; V2 예외 2종도 코드를 정해 같은 방식 |
| X2-P2-2b | Required | `IllegalArgumentException`: web 400, GraphQL·gRPC `INTERNAL_ERROR` | 남음 | `GlobalExceptionHandler.java:101-106` → `BAD_PARAMETER` 400; GraphQL·gRPC는 carrier가 아니면 INTERNAL | W3 | 결정(2026-09-25): `IllegalArgumentException`은 모든 전송에서 400(GraphQL `BAD_USER_INPUT`, gRPC `INVALID_ARGUMENT`) — web 현재 동작 유지 |
| X2-P2-3a | Required | 같은 servlet 앱에서 Envelope와 fileserver problem+json 혼재(소유자 결정: Envelope 하나) | 남음 | `FileserverExceptionHandler.java:44` `APPLICATION_PROBLEM_JSON`, `FileserverProblem`·`FileserverProblemFactory`·`FileserverProblemTitles`·`BatchUploadItemProblem`. `FileserverErrorCode`는 이미 `ApiErrorCode`인데 `UNAUTHENTICATED`·`PRECONDITION_FAILED`·`UNSUPPORTED_MEDIA_TYPE`가 `OperationalError`와 이름 중복(`FileserverErrorCode.java:26,35,38`). budget·WebFlux 쪽은 삭제로 해소 | W3 | `FileserverExceptionHandler`가 web `ErrorResponseFactory.envelope`로 응답, `FileserverProblemHeaders`(Retry-After·Content-Range·tus 헤더)는 유지, problem 타입 4개 삭제, 이름 중복 3개는 `OperationalError` 사용 |
| X2-P2-3b | Required | Draft-12 upload offset 불일치 응답이 규격 problem 문서 | 남음 | `Draft12UploadController.java:136-143` problem+json, `Draft12OffsetProblem.java` type `…/http-problem-types#mismatching-upload-offset` | W3 | 결정(2026-09-25): Draft-12 offset 불일치 problem 문서는 프로토콜 예외로 유지(tus 헤더와 같은 취급), 예외 목록을 문서에 명시 |
| X2-P2-1d | Required | GraphQL `retryable`을 코드가 아니라 category에서 계산 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): `GraphQlWireErrorMapperTest.aCarrierIsRetryableOnlyWhenItsCodeIs` FAIL(`["DB_QUERY_CANCELED", true]` 기대 `false`)→PASS. `error/GraphQlWireError.java`의 `of(..., boolean retryable, ...)`, `error/GraphQlWireErrorMapper.java:141`(`code.retryable()`) | - | `GraphQlWireError.of`에 retryable 인자 추가, `fromApiError`는 `code.retryable()`, 플랫폼 자체 코드만 category 기본값 |
| X2-P2-1e | Required | client-safe 메시지 표가 전송마다 다름(web 코드별 영어, GraphQL category별 한국어) | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): 코드별 영어 표 `ClientSafeErrorMessages` 삭제, `shared-contract/.../error/ClientErrorMessages.java:19` 하나를 web·fileserver·sample·graphql·grpc가 사용. `ClientErrorMessagesTest`(모든 Category 한국어), `OperationalErrorRegistryContractTest.everyRegistryClientMessageIsTheSharedCategoryMessage`(레지스트리 전 행 = 표) PASS. 수정 방향의 "코드별 표"는 결정 11(Category별 표)을 따름 | - | 코드별 메시지 표 하나를 shared-contract `ApiErrorCode` 옆에 두고 web·graphql 2곳이 사용, 언어 하나로 |
| X2-P2-1f | Required | gRPC trailer에 `retryable` 없음 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): `GrpcStatusMapperTest.trailersCarryTheRetryabilityOfTheCodeNotOfItsCategory` FAIL(`expected: "false" but was: null`)→PASS. `adapter/inbound/grpc/.../GrpcStatusMapper.java:34`(`error-retryable`), `:63` | - | `error-retryable` trailer 키 추가(`code.retryable()`) |
| X2-P2-2a | Required | shared 예외가 `ApiErrorCarrier`를 구현하지 않아 web에서만 제대로 매핑 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): `SharedExceptionCarrierTest` 2건 FAIL(`Expecting actual throwable to be an instance of: ApiErrorCarrier but was: MappingException`)→PASS, `IdempotencyFailureCodeTest.everyIdempotencyFailureCarriesItsOperationalCode` 4건 FAIL(같은 메시지)→PASS. `shared-contract/.../MappingException.java:11`, `AdapterDisabledException.java:13`, `application-core/.../idempotency/Idempotency{InFlight,RequestMismatch,Unavailable,RecoveryRequired}Exception.java`. web handler 4개 → `GlobalExceptionHandler.java:151` `handleCarrier` 한 분기(+ catch-all이 carrier면 위임). V2 예외 코드 `IDEMPOTENCY_UNAVAILABLE`·`IDEMPOTENCY_RECOVERY_REQUIRED` 신설(레지스트리 행, runbook) | - | 4종이 `ApiErrorCarrier` 구현(`MAPPING_FAILED`, `ADAPTER_DISABLED`, `IDEMPOTENT_IN_FLIGHT`, `IDEMPOTENT_REQUEST_MISMATCH`), web handler 4개를 carrier 분기 1개로 교체; V2 예외 2종도 코드를 정해 같은 방식 |
| X2-P2-2b | Required | `IllegalArgumentException`: web 400, GraphQL·gRPC `INTERNAL_ERROR` | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): GraphQL `GraphQlWireErrorMapperTest.anIllegalArgumentIsABadParameterRequestError` FAIL(`["INTERNAL_ERROR", "INTERNAL"]`)→PASS(`error/GraphQlWireErrorMapper.java:174`); gRPC `GrpcExceptionHandlingInterceptorTest.mapsAnIllegalArgumentToInvalidArgumentBadParameter` FAIL(`[INTERNAL, "INTERNAL_ERROR"]`)→PASS(`GrpcExceptionHandlingInterceptor.java:114`); STOMP `SafeStompSubProtocolErrorHandlerTest.anIllegalArgumentReportsBadParameter` FAIL(`but was: "WEBSOCKET_REQUEST_REJECTED"`)→PASS; web은 기존 동작 유지(`GlobalExceptionHandler.java:76`) | - | 결정(2026-09-25): `IllegalArgumentException`은 모든 전송에서 400(GraphQL `BAD_USER_INPUT`, gRPC `INVALID_ARGUMENT`) — web 현재 동작 유지 |
| X2-P2-3a | Required | 같은 servlet 앱에서 Envelope와 fileserver problem+json 혼재(소유자 결정: Envelope 하나) | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): `FileserverHardeningContractTest.aFailureIsTheSharedEnvelopeCarryingTheStableCode` FAIL(`Response header 'Content-Type' expected:<application/json> but was:<application/problem+json>`)→PASS. `web-fileserver/.../problem/FileserverExceptionHandler.java:47`. problem 타입 4개 삭제(아래 표). 이름 중복 3개(`UNAUTHENTICATED`·`PRECONDITION_FAILED`·`UNSUPPORTED_MEDIA_TYPE`)는 **더 작은 수정**: `FileserverFailureContext.code()`가 `FileserverErrorCode` 하나라서 그 3개를 `OperationalError`로 바꾸면 context·header 표·application-fileserver 전반의 타입이 바뀐다(같은 시기 fileserver 상태 전이 묶음과 충돌). 두 enum의 category·status·retryable이 이미 같아 wire는 동일하므로 `FileserverExceptionTest.aCodeNamedLikeAnOperationalErrorMeansTheSameOnTheWire`(28 case PASS)로 동일성을 고정했다 | - | `FileserverExceptionHandler`가 web `ErrorResponseFactory.envelope`로 응답, `FileserverProblemHeaders`(Retry-After·Content-Range·tus 헤더)는 유지, problem 타입 4개 삭제, 이름 중복 3개는 `OperationalError` 사용 |
| X2-P2-3b | Required | Draft-12 upload offset 불일치 응답이 규격 problem 문서 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): 결정 12대로 유지 + 예외 명시: `Draft12UploadController.java:165` Javadoc("Protocol exception to the Envelope rule"), `Draft12OffsetProblem` Javadoc, `docs/fileserver/http-contract.md` 「Protocol exceptions to the Envelope rule」 절, `FileserverExceptionHandler` Javadoc. `Draft12ProtocolTest.offsetMismatchReturnsTheDraftProblemDetailWithBothOffsets` PASS(그대로 problem+json) | - | 결정(2026-09-25): Draft-12 offset 불일치 problem 문서는 프로토콜 예외로 유지(tus 헤더와 같은 취급), 예외 목록을 문서에 명시 |
| X2-P2-4 | Required | 한 요청에서 traceparent를 두 규칙으로 파싱 (= I-4 영역) | 남음 | `WebMvcRequestIdFilter.java:49-50,113-118` 정규식(version 무시, 전부 0인 trace-id 허용) vs `RequestLoggingFilter.java:105-106` `TraceParent.parse`. WebFlux 사본은 삭제. request id는 `RequestLoggingFilter.java:59-60`이 `WebRequestId`를 재사용하도록 바뀜 | W3 | `WebMvcRequestIdFilter`의 `TRACEPARENT` 정규식을 지우고 shared-contract `TraceParent.parse` 사용(1곳) |
| X2-P2-5 | Consider | correlation이 HTTP 밖으로 안 이어짐, `MdcKeys`가 web에 갇힘 | 남음 | `adapter/inbound/web/.../observability/MdcKeys.java`(사용 5파일, web-fileserver 포함), `MDC.put`은 `RequestLoggingFilter.java:65-71,147`뿐, `CorrelationIdPort` 구현은 `MdcCorrelationIdPortAdapter` 1개, GraphQL은 `GraphQlPlatformWebInterceptor.java:157` Spring request id | W3 | `MdcKeys`를 shared-contract로(원본 `docs/registries/mdc-keys.yaml`), 사용 5파일 import 변경; websocket STOMP·gRPC interceptor에 MDC 채우는 코드, GraphQL은 `WebRequestId` 사용 |
| X2-P2-6a | Required | 같은 이름 `TenantContext` 2개, 허용 문법이 다름 | 남음 | web `core/TenantContext.java:20` `[A-Za-z0-9][A-Za-z0-9_.-]{0,63}` vs graphql `context/TenantContext.java:17,30`(비어있지 않고 128자 이하). 그 밖에 persistence-jpa `experimental/tenant/TenantId`, application-notification `TenantId` | W3 | application-core에 tenant id 값 타입 1개(web 문법) 두고 web·graphql `TenantContext` 2곳이 감쌈, notification·jpa `TenantId`도 같은 타입으로 맞춤 |
| X2-P2-7a | Required | 연결 안 된 두 번째 rate-limit stack 삭제 (= I-8 일부) | 완료 | `WebRateLimiter`·`WebMvcThrottleFilter`·`ThrottleProblemWriter` 삭제(`docs/capability-status.md:99-100`), WebFlux throttle은 WebFlux와 함께 삭제(`:88`), 커밋 `6d27356e` | - | - |
| X2-P2-7b | Required | client IP 신뢰 규칙이 두 갈래 (= I-5) | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): I-5a와 같은 결함. client IP 해석 경로가 `getRemoteAddr()` 하나만 남음(XFF를 직접 읽는 main 코드 grep 0건, `ForwardedHeaderClientIpResolver` 삭제). 남은 `web-notification/.../ExternalRequestUrlResolver`는 client IP가 아니라 URL(proto/host) 해석이고 이미 trusted proxy일 때만 읽는다. 그 forwarded 파싱 삭제·설정 통합은 현황표 I-5b(W3)가 소유해서 이번에 건드리지 않음 | - | `ForwardedHeaderClientIpResolver`도 `remoteAddr`가 trusted proxy일 때만 XFF 사용(아니면 `remoteAddr`), 규칙은 `ExternalRequestUrlResolver`와 같은 설정 하나로 |
| X2-P2-8 | Consider | Origin 검증기 3개, env key 3개 기본값 다름 | 해당 없음(코드 삭제) | web `WebCorsPolicyValidator` 삭제(`docs/capability-status.md:206`), websocket platform origin 정책·`APP_WEBSOCKET_PLATFORM_*` 삭제(`:186`); 남은 검증은 `WebSocketSettings.java:25`(+`@AssertTrue`) 1개 | - | - |
| X2-P2-9a | FYI | 크기 제한 위반 코드 이름이 전송마다 다름 | 남음 | web `PAYLOAD_TOO_LARGE`(`GlobalExceptionHandler.java:342`), graphql `REQUEST_TOO_LARGE`(`GraphQlHttpOutcome.java:32`)·`GRAPHQL_DOCUMENT_SHAPE_REJECTED`, fileserver `FILE_TOO_LARGE`(`FileserverErrorCode.java:36`) | W3 | P2-1 정리 때 body 크기 초과는 `PAYLOAD_TOO_LARGE` 하나로(graphql 1곳), 문서 모양 거부·파일 크기는 별도 코드 유지 |
| X2-P2-9b | FYI | STOMP가 모든 실패를 `WEBSOCKET_REQUEST_REJECTED` 하나로 → carrier 코드 소실 | 남음 | `SafeStompSubProtocolErrorHandler.java:12,21-27` | W3 | 원인이 `ApiErrorCarrier`면 그 `code()`를 `error-code` 헤더에(메시지는 고정 유지), 나머지는 현재 값 |
| X2-P2-9a | FYI | 크기 제한 위반 코드 이름이 전송마다 다름 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): `GraphQlWireErrorMapperTest.anOversizedRequestIsPayloadTooLarge` FAIL(`expected: "PAYLOAD_TOO_LARGE" but was: "REQUEST_ERROR"`)→PASS. `graphql/.../http/GraphQlRequestTooLargeException.java:64`, servlet 필터 `runtime/servlet/GraphQlRequestBodyLimitFilter`의 하드코딩 JSON도 `PAYLOAD_TOO_LARGE`+공용 문구로. `GraphQlPlatformExecutionPathTest.anOversizeDocumentIsRejectedBeforeItIsParsed` 기대값 갱신 PASS. 문서 모양 거부(`GRAPHQL_DOCUMENT_SHAPE_REJECTED`)·fileserver `FILE_TOO_LARGE`는 별도 코드 유지 | - | P2-1 정리 때 body 크기 초과는 `PAYLOAD_TOO_LARGE` 하나로(graphql 1곳), 문서 모양 거부·파일 크기는 별도 코드 유지 |
| X2-P2-9b | FYI | STOMP가 모든 실패를 `WEBSOCKET_REQUEST_REJECTED` 하나로 → carrier 코드 소실 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): `SafeStompSubProtocolErrorHandlerTest.aWrappedCarrierFailureReportsItsOwnCode` FAIL(`["WEBSOCKET_REQUEST_REJECTED", "WEBSOCKET_REQUEST_REJECTED"]`)→PASS. `SafeStompSubProtocolErrorHandler.java:39`(원인 사슬 16단계까지 carrier/IAE 탐색, `message` 헤더는 고정). websocket `build.gradle`에 `:shared-contract`(registry 허용 edge) 추가 | - | 원인이 `ApiErrorCarrier`면 그 `code()`를 `error-code` 헤더에(메시지는 고정 유지), 나머지는 현재 값 |
| X-요약-capability 활성화 규칙 | 권고 | 활성화 규칙 6곳·기본값 3가지 → 표 하나(키·기본값·필요 조건·prod secret)에서 validator·endpoint 파생 | 해당 없음(코드 삭제) | `MasterSwitch`·`CapabilityDependencyValidator`·`AdapterActivationEndpoint` 등 삭제(`docs/capability-status.md:248-249`). 지금 규칙은 "모듈이 있으면 켜짐, `enabled`로 끔"(`AGENTS.md:212-213`), 기본값은 각 모듈 `config/module-defaults/<모듈>.yml` | - | - |
**조사 메모**
@@ -771,7 +771,7 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
| S1-#5 | Required | fileserver retire 절차 3곳 복사, admin `forceDelete`는 content 없는 레코드를 DELETING에 남김 (C-4 관련) | 완료 | Wave 1–2 P4 (fcddab7e·Wave 2 커밋): `FileserverAdminServiceTest.forceDeletingAFileThatWasNeverPublishedRetiresItCompletely` FAIL(`expected: DELETED but was: DELETING`)→PASS. 세 호출부가 `src/application-fileserver/.../cleanup/FileRetirement.java:40` 하나를 쓴다: `DefaultFileLifecycleService.java:84`, `DefaultFileserverAdminService.java:167`, `DefaultUploadApplicationService.java:265`. `cleanup` 패키지에 둔 이유: 세 호출 패키지가 이미 cleanup을 의존하고 cleanup은 그들을 의존하지 않아 새 패키지 순환이 생기지 않는다 | - | `retire(FileRecord)` 하나로 합치고 content 없으면 DELETING→DELETED 전이를 세 호출부 모두에 적용 |
| S1-#6a | Required | fileserver 단일 구현 인터페이스 6개(fake 없음) | 남음 | `CleanupService`, `WriterLeaseCoordinator`, `FileLifecycleService`, `TransferAdmissionController`, `FileReconciliationService`, `FileStateMachine` 모두 구현 1개(`Default*`) | W3 | 인터페이스 6개 삭제, `Default*`를 인터페이스 이름으로 개명 |
| S1-#6b | Required | fileserver 인바운드가 use-case 계약 밖(capability gate 미적용) | 남음 | `application-fileserver/src/main/java`에서 `@UseCaseCapability`/`CommandUseCase`/`QueryUseCase` 0건(notification 14파일) | W3 | transport가 부르는 연산을 `*UseCase` + `@UseCaseCapability`로 선언 |
| S1-#7 | Consider | 에러 코드마다 예외 서브클래스, 타입 분기는 몇 개뿐 | 남음 | fileserver `api/error/` 예외 23개 그대로(`FileNotFoundException`·`FileAlreadyExistsException`·`InvalidPathException` JDK 이름 충돌 유지). notification은 throw 0인 12개만 삭제(「제거된 코드」 행), 12개 남음 | W3 | base를 구체 클래스 + `of(code, …)`, 서브클래스는 catch로 타입 분기하는 5개만 남김 |
| S1-#7 | Consider | 에러 코드마다 예외 서브클래스, 타입 분기는 몇 개뿐 | 남음 | fileserver `api/error/` 예외 23개 그대로(`FileNotFoundException`·`FileAlreadyExistsException`·`InvalidPathException` JDK 이름 충돌 유지). notification은 throw 0인 12개만 삭제(「제거된 코드」 행), 12개 남음<br>Wave 3 W3-P15: 미완 — 이유: fileserver `api/error` 서브클래스 22개의 생성 지점이 약 130곳(application-fileserver·persistence-fileserver·outbound fileserver)이고, 같은 시기에 도는 fileserver 상태 전이 묶음이 같은 파일들을 고친다. 에러 어휘(wire)는 이번에 끝났고 이 행은 예외 계층 모양(SRP)이라 충돌 없이 하려면 그 묶음 통합 뒤 Wave 3 구조 작업(SRP 분해)으로 넘긴다. notification 12개도 같은 이유 | W3 | base를 구체 클래스 + `of(code, …)`, 서브클래스는 catch로 타입 분기하는 5개만 남김 |
| S1-#8 | Consider | `PolicyTransactionPort` 계열이 호출 1곳용 | 해당 없음(코드 삭제) | 「제거된 코드」 `PolicyTransactionPort` 계열·`SpringPolicyTransactionPort`·`FileserverCompensationTransaction` 행. grep 0건 | - | - |
| S1-#9 | Consider | 같은 전략만 담은 레지스트리 2개 | 남음 | `application-notification/.../callback/ProviderEventProjectorRegistry.java:7`(Twilio/Ses projector는 `StandardDeliveryProjector` 상속만), `dispatch/TemplateRendererRegistry.java:7` + `adapter/outbound/notification/.../NotificationPlatformProviderConfig.java:57-65`(모든 channel에 같은 engine) | W3 | 레지스트리·`Map*Registry` 삭제, 구현체 직접 주입 |
| S1-#10a | Consider | `NotificationOrchestrator`·Reactor facade (= B-8) | 해당 없음(코드 삭제) | 「제거된 코드」 `NotificationOrchestrator`, Notification Reactor facade 행 | - | - |
@@ -823,7 +823,7 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
| S2-lead-1 | 권고 | app-core 포트 버전이 #4의 원인 | 남음 | V2 포트는 삭제됐으나 `OutboxAppendPort`/`LegacyOutboxAppendPort` 2개 남음(S1-#2b 근거와 같음). 멱등성은 `IdempotencyStorePort` 하나 | W3 | 결정(2026-09-25): canonical 통일(S1-#2b와 같은 작업) |
| S2-lead-2 | 권고 | 멱등성 claim 판정표가 Redis·PG에 따로 (= X1-#3) | 남음 | Redis 판정은 Lua 안(`cache-redis/.../idempotency/IdempotencyScripts.java`) + 응답 매핑 `RedisIdempotencyStoreAdapter.java:135-157`, PG는 `postgresql/idempotency/IdempotencyClaimGateway.java`. 공통 계약 테스트 없음(`application-core/src/testFixtures/.../idempotency/testkit/`에 `InMemoryIdempotencyStore`만) | W4 | application-core testFixtures에 `IdempotencyStoreContract` 추가, InMemory·Redis·PG adapter가 모두 상속 |
| S2-lead-3 | 권고 | 서명 cursor codec 여러 벌 (= X2 P1-4) | 남음 | web `CursorCodec`·`HmacWebCursorCodec` 삭제(「제거된 코드」 서명 커서 코덱·2세대 페이지네이션 행). 남은 3벌: `persistence-jpa/.../api/query/SignedJsonCursorCodec.java`, `persistence-mongo/.../query/pagination/MongoKeysetCursorCodec.java`, `graphql/.../pagination/HmacGraphQlCursorCodec.java` | W3 | X2 P1-4대로 서명은 inbound 한 계층, persistence는 typed keyset만(jpa·mongo codec 삭제 또는 서명 제거) |
| S2-lead-4 | 권고 | persistence 실패 예외 계층 3벌 | 남음 | jpa `api/error/JpaPersistenceException.java:14`(RuntimeException 상속, 21개, 라이브러리 `PostgreSqlExceptionTranslator` 결과), mongo `api/error` 24개, shared `shared-contract/.../error/PersistenceFailureException.java`(web·grpc가 매핑) | W3 | `JpaPersistenceException`이 `PersistenceFailureException`을 상속해 inbound가 한 계층만 매핑(mongo는 edge 없어 유지) |
| S2-lead-4 | 권고 | persistence 실패 예외 계층 3벌 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): `JpaPersistenceExceptionCodeTest.aJpaFailureCarriesTheOperationalCodeOfItsCategory` 16건 FAIL(`Expecting actual throwable to be an instance of: PersistenceFailureException`)→PASS. `persistence-jpa/.../api/error/JpaPersistenceException.java:22`(상속), `:59`(`FailureCategory`→`DB_*`; 직렬화 후에도 `errorCode()`가 category에서 계산). 대응 코드가 없던 2개는 `DB_OPTIMISTIC_CONFLICT`(CONFLICT/409/false)·`DB_COMPLETION_UNKNOWN`(DATA_INTEGRITY/500/false) 신설, SCHEMA_MISMATCH·DATA_CORRUPTION·ENTITY_NOT_FOUND·UNKNOWN은 이전 catch-all과 같은 `INTERNAL_ERROR`. `LockFailureClassificationContractTest`의 REGISTRY-GAP-1("optimistic 코드 없음") 고정 테스트를 `anOptimisticLockConflictIsANonRetryableConflict`로 승격. testFixtures에 `:shared-contract` 추가(mongo는 edge 없어 유지) | - | `JpaPersistenceException`이 `PersistenceFailureException`을 상속해 inbound가 한 계층만 매핑(mongo는 edge 없어 유지) |
| S2-lead-5 | 권고 | sample이 `PostgreSqlPersistenceConfig`의 claim repository bean을 재선언 | 완료 | `sample-portfolio/.../bootstrap/persistence/SamplePostgreSqlPersistenceConfig.java:28-48`은 sample Flyway 전략만 선언, claim repository bean 없음 | - | - |
| S2-lead-6 | 권고 | JPA 조립이 leaf와 bootstrap에 나뉨 | 완료 | 「제거된 코드」 `JpaPlatformAutoConfiguration`·`JpaPlatformRuntimeAutoConfiguration` 행, 조립은 `persistence-jpa/src/main/resources/META-INF/spring/...AutoConfiguration.imports`(3개)에만, `app-bootstrap/.../autoconfigure/`에 jpa 없음 | - | - |
| S3-#1 | Required | httpclient blocking/reactive 병렬 스택이 이미 갈라짐 (= H-5, H-7) | 완료 | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): D 커밋 `06764fcb`에서 reactive 스택(WebClient·Reactor Netty)과 webflux·reactor·reactor-netty·reactor-test·blockhound 의존 삭제. blocking(RestClient) 경로 하나만 남음. `clients[N].api` 설정 키·`ClientApiType`·`TransportType.REACTOR_NETTY` 삭제, env-fields.yaml 행 삭제, lockfile 재생성(httpclient·app-bootstrap). Jetty HTTP/3 실험 transport는 reactive SPI에 묶여 있어 blocking SPI(`JettyClientHttpRequestFactory`)로 옮김(자동 조립 안 됨은 그대로) `HC/http3/JettyHttp3TransportProvider.java:49` | - | 결정(2026-09-25): D4를 outbound에도 적용 — httpclient reactive(WebClient·Reactor Netty) 스택과 webflux·reactor 의존 삭제 |
@@ -901,8 +901,8 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
| S4-lead-5 | 권고 | `ProviderCapabilities` 위치 인자 11개 → named factory | 남음 | S4-#4b와 같음 | W3 | S4-#4b 참조 |
| S5-#1a | Required | WebProblem 어휘(`ProblemCode`·`ProblemCatalog`·yaml·핸들러·writer) (= X2-P2-1) | 완료 | `ProblemCatalog`·`WebProblem`·`problem-catalog.yaml`·`ThrottleProblemWriter`·`WebMvcBudgetExceptionHandler` grep 0건. 「제거된 코드」 표 99·104·105행, `6d27356e` | - | - |
| S5-#1b | Required | 검증 규칙표 두 벌(`ClientSafeValidationDetails` vs `WebValidationIssueMapper`) | 완료 | `W/validation/` 삭제(표 103행). 남은 것은 `web/error/ClientSafeValidationDetails.java` 하나 | - | - |
| S5-#1c | Required | fileserver가 운영에서 problem+json을 보냄(Envelope와 다른 형식) (= X2-P2-3) | 남음 | `web-fileserver/…/problem/FileserverExceptionHandler.java:39-48`가 `APPLICATION_PROBLEM_JSON`과 `FileserverProblem`(필드 15개, `FileserverProblem.java:17-32`)을 보냄. `FileserverErrorCode`는 이미 `ApiErrorCode` 구현(`application-fileserver/…/FileserverErrorCode.java:24`). Retry-After 표도 web `observability/RetryAfterAdvisor.java:14`와 `FileserverProblemHeaders.java:30`에 따로 있음 | W3 | 소유자 결정대로 `ErrorResponseFactory` Envelope로 바꾸고 `FileserverProblem`·`FileserverProblemFactory`·`FileserverProblemTitles`를 삭제. 파일 식별 필드(fileId·uploadId·offset)는 Envelope `details`로. tus 헤더와 Retry-After·`Content-Range` 헤더는 유지(`FileserverProblemHeaders`) |
| S5-#1d | Required | Draft-12 offset mismatch problem 문서 | 남음 | `draft12/Draft12UploadController.java:136-142`가 드래프트가 정한 `Draft12OffsetProblem`을 problem+json으로 보냄. 소유자 결정("Envelope 하나, tus 헤더만 유지")에는 Draft-12 예외가 없음 | W3 | 결정(2026-09-25): 프로토콜 예외로 유지(X2-P2-3b와 같은 작업) |
| S5-#1c | Required | fileserver가 운영에서 problem+json을 보냄(Envelope와 다른 형식) (= X2-P2-3) | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): X2-P2-3a와 같은 작업·같은 테스트. 식별 필드는 Envelope `details`(`fileId`·`uploadId`·`expectedOffset`·`currentOffset`·`state`·`ambiguous`·`reconciliationRequired`), tus·Retry-After·Content-Range 헤더 유지(`FileserverProblemHeaderParityTest` PASS). batch 항목도 `ApiError`(`FileUploadControllerTest` `$.results[1].error.code` PASS) | - | 소유자 결정대로 `ErrorResponseFactory` Envelope로 바꾸고 `FileserverProblem`·`FileserverProblemFactory`·`FileserverProblemTitles`를 삭제. 파일 식별 필드(fileId·uploadId·offset)는 Envelope `details`로. tus 헤더와 Retry-After·`Content-Range` 헤더는 유지(`FileserverProblemHeaders`) |
| S5-#1d | Required | Draft-12 offset mismatch problem 문서 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): X2-P2-3b와 같은 작업(결정 12: 유지 + 예외 명시) | - | 결정(2026-09-25): 프로토콜 예외로 유지(X2-P2-3b와 같은 작업) |
| S5-#2 | Required | WebFlux 쌍둥이 코드는 어떤 조합에서도 안 켜짐 | 완료 | web·web-fileserver main에 `Type.REACTIVE`·`ServerWebExchange`·webflux 의존 0건. `webFluxContractTest`·`webFluxPerformanceTest` gradle 참조 0건. 「제거된 코드」 표 88–92행, `6d27356e` | - | - |
| S5-#3 | Required | `WebMvcPlatformAutoConfiguration` bean 14개 중 9개는 읽는 곳 없음, startup check는 실패 불가 | 완료 | `web/…/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java` 75줄, bean 3개(`globalExceptionHandler`, `webMvcRequestIdFilter`, `webMvcRequestContextConfigurer`). `WebMvcEvidenceFilter`·`WebMvcPlatformStartupCheck`·`WebPlatformSnapshot` grep 0건. 표 102행 | - | - |
| S5-#4a | Required | 조건부 요청 1·2세대 두 벌 (= I-8) | 완료 | `web/conditional/`에 `ETags`·`PreconditionFailedException`만 남음. `EntityTag` 등 grep 0건. 표 96행 | - | - |
@@ -914,8 +914,8 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
| S5-#5 | Required | Retry-After 초 계산 3벌, 결과가 다름 | 해당 없음(코드 삭제) | `ThrottleProblemWriter`·`OperationHttpController`·`ReactiveOperationHttpController` 삭제. Duration→초 계산은 `RateLimitInterceptor.java:107-111`(올림) 하나만 남음 | - | - |
| S5-#6a | Required | GraphQL 요청 단계 에러가 `GraphQlWireErrorMapper`를 거치지 않음 → adopter `ApiErrorCarrier`가 요청 단계에서 `INTERNAL_ERROR`로 바뀜 | 완료 | Wave 1–2 P8 (fcddab7e·Wave 2 커밋): `runtime/GraphQlRequestStageErrorMappingTest.anApiErrorCarrierFromThePrincipalResolverKeepsItsCode`, `anApiErrorCarrierFromAPipelineStageKeepsItsCode` FAIL(`expected "TENANT_SUSPENDED" but was "INTERNAL_ERROR"`) → PASS. 두 테스트 모두 auto-configuration이 만든 bean으로 돌려 "세 곳이 mapper bean을 받는다"를 검증. `GraphQlWireErrorMapper.map(Throwable, ctx)`(플랫폼 거부 → ApiErrorCarrier → application 매핑) + `toGraphQlError`(carrier는 category로 classification) 하나로 interceptor·instrumentation·field resolver가 모두 이것을 씀. `.../runtime/GraphQlWireErrorMapper.java:61,79`, `GraphQlPlatformWebInterceptor.java:168`, `GraphQlPlatformInstrumentation.java:89`, `GraphQlDataFetcherExceptionResolver`, 주입 `GraphQlPlatformAutoConfiguration.java:357,413`. 호출자가 없어진 `GraphQlPlatformRejectionMapper.map` 삭제. 커밋 `aa5f4d90` | - | 두 호출부가 `GraphQlWireErrorMapper`의 `map(Throwable, ctx)` 하나(플랫폼 거부 → `ApiErrorCarrier` → application mapping 순서)를 쓰게 한다. principal resolver가 `ApiErrorCarrier`를 던지는 테스트 추가 |
| S5-#6b | Required | 호출처 0인 `mapRequestRejection`과 참조 0인 error 클래스 | 완료 | `mapRequestRejection`·`GraphQlRequestErrorMapper`·`GraphQlSubscriptionExceptionResolver`·`GraphQlNullabilityContract` grep 0건. 표 "`GraphQlWireErrorMapper.mapRequestRejection`" 행과 `error/` 행 | - | - |
| S5-#6c | Required | Category switch 3개와 client 문구 중복 | 남음 | `GraphQlWireErrorMapper.java:94`(category), `:104`(clientMessage), `GraphQlWireErrors.java:56`. "요청한 리소스를 찾을 수 없습니다." 3곳(`GraphQlWireErrorMapper.java:108`, `GraphQlPlatformRejectionMapper.java:69`, `security/GraphQlAuthorizationInterceptor.java:50`) | W3 | `EnumMap<Category, Rendering(wireCategory, message, classification)>` 표 하나로 switch 3개를 대체하고 문구 상수를 한 곳에 둔다 |
| S5-#6d | Required | 플랫폼 예외 `instanceof` 사슬 9개, 실제 매퍼가 `runtime/`에 있음 | 남음 | `GraphQlPlatformRejectionMapper.java:55-114`에 instanceof 9개. `GraphQlWireErrorMapper`·`GraphQlPlatformRejectionMapper`·`GraphQlWireErrors`가 `runtime/`에 있음(`error/`에는 타입만) | W3 | 플랫폼 예외가 code·category·message 인터페이스를 구현하게 해 instanceof 사슬을 없애고, 매퍼 3개를 `error/`로 옮긴다 |
| S5-#6c | Required | Category switch 3개와 client 문구 중복 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): switch 3개(`category`·`clientMessage`·`classificationOf`)를 `error/GraphQlWireErrorMapper.java:43` `RENDERINGS`(Category → wire category·ErrorType) 하나와 shared 문구 표로 대체. "요청한 리소스를 찾을 수 없습니다." 3곳은 모두 `ClientErrorMessages.of(NOT_FOUND)` 한 곳에서 온다(`GraphQlAuthorizationInterceptor.toWireError`는 `fromRejection` 위임). graphql `check`·`systemTest`·`graphqlTransportQualificationTest` PASS | - | `EnumMap<Category, Rendering(wireCategory, message, classification)>` 표 하나로 switch 3개를 대체하고 문구 상수를 한 곳에 둔다 |
| S5-#6d | Required | 플랫폼 예외 `instanceof` 사슬 9개, 실제 매퍼가 `runtime/`에 있음 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): 플랫폼 예외 11종이 `error/GraphQlPlatformRejection` 구현, instanceof 사슬(`GraphQlPlatformRejectionMapper`) 삭제, `GraphQlWireErrorMapper`·`GraphQlWireErrors`를 `runtime/`→`error/`로 이동(테스트도 이동). API surface 재승인(`updateGraphQlApiSurface -PapproveGraphQlApiSurfaceChange`) | - | 플랫폼 예외가 code·category·message 인터페이스를 구현하게 해 instanceof 사슬을 없애고, 매퍼 3개를 `error/`로 옮긴다 |
| S5-#7a | Consider | `GraphQlPlatformAutoConfiguration` 한 클래스에 bean 약 40개·10가지 기능 | 남음 | `graphql/…/autoconfigure/GraphQlPlatformAutoConfiguration.java` 656줄(706→656), `@Bean` 38개. FQN `@org.springframework.context.annotation.Configuration`(`:78`) | W3 | 기능별 `@Configuration`(검증·runtime 감지·body limit·chain·auth·cost·error·관측·cache·DataLoader)으로 나누고 `GraphQlRootAutoConfiguration`의 `@Import`에 나열 |
| S5-#7b | Consider | 부팅마다 reflection 아키텍처 검사(`architecture/` 969줄) | 완료 | `architecture/` 삭제, `graphQlControllerBoundaryCheck` bean 삭제(표 110·111행). 규칙 2개는 `graphql/src/test/…/GraphQlTransportBoundaryArchitectureTest.java`(ArchUnit)로 옮김 | - | - |
| S5-#7c | Consider | autoconfig Javadoc이 사실과 다름 | 남음 | `GraphQlPlatformAutoConfiguration.java:70-76`은 "A real @AutoConfiguration … ordered after Spring Boot's GraphQL auto-configuration"이라고 적었지만 클래스는 `@Configuration`이고, `GraphQlRootAutoConfiguration`에는 `after` 선언이 없음. `GraphQlRootAutoConfiguration.java:29-30` 주석은 이미 삭제된 "scan 제외 정규식"을 전제로 함 | W5 | Javadoc을 실제 구조(root `@AutoConfiguration`이 import)에 맞추고, 순서가 필요하면 root에 `afterName`을 추가. 낡은 scan 주석 삭제 |
@@ -930,7 +930,7 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
| S5-#14c | Nit | web-fileserver에 CLAUDE.md/README 없음 | 남음 | `src/adapter/inbound/web-fileserver/`에 `*.md` 0개. 새 leaf `web-notification`도 0개(composition 쪽 README만 있음) | W5 | 두 leaf에 README(제공 기능·조립 경로·설정 prefix)와 짧은 CLAUDE.md 추가 |
| S5-#14d | Nit | graphql 주석 과다·이력 서술·"design §"·inline FQN | 남음 | graphql main 12,435줄 중 주석 4,003줄(32%). "design §" 48(92→48), "Task N" 3(17→3), inline FQN 약 50줄(92→약 50, grep 근사). web은 주석 16%, FQN 7줄로 해소 | W5 | 이력·설계서 번호 주석을 줄이고 FQN을 import로 |
| S5-#14e | Nit | `GraphQlPlatformWebInterceptor` 생성자 인자 9개 | 남음 | `GraphQlPlatformWebInterceptor.java:66-75`. anonymous 관련 3개(`anonymousProfile`, `anonymousTenant`, `anonymousProfileProtected`) | W5 | anonymous 3값을 record 하나로 묶는다 |
| S5-lead-1 | 권고 | client 에러 문구 언어가 전송마다 다름(web 영어, graphql 한국어) (= X2-P2-1) | 남음 | web `error/ClientSafeErrorMessages.java:44-50` 영어, graphql `GraphQlWireErrorMapper.java:104-113` 한국어. gRPC `GrpcStatusMapper.java:33`은 status만 매핑(문구 없음). status/분류 매핑은 전송마다 달라서 공유할 수 없음 | W3 | 결정(2026-09-25): client 에러 문구는 한국어 — `Category`별 문구 표 하나를 shared-contract에 두고 모든 전송이 사용 |
| S5-lead-1 | 권고 | client 에러 문구 언어가 전송마다 다름(web 영어, graphql 한국어) (= X2-P2-1) | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): 결정 11: `ClientErrorMessages`(한국어, Category별) 하나를 web·fileserver·GraphQL·gRPC(status description) 모두 사용. gRPC `GrpcExceptionHandlingInterceptorTest.theStatusDescriptionIsTheSharedClientMessageOfTheCategory` FAIL(`expected: "요청한 리소스를 찾을 수 없습니다." but was: "ROUTE_NOT_FOUND"`)→PASS, `GrpcP1BoundaryWireTest` 기대값 갱신 PASS. STOMP `message` 헤더는 X2-P2-9b 지시대로 고정값 유지 | - | 결정(2026-09-25): client 에러 문구는 한국어 — `Category`별 문구 표 하나를 shared-contract에 두고 모든 전송이 사용 |
| S5-lead-2 | 권고 | moduleboundary 세 번째 사본(websocket) | 해당 없음(코드 삭제) | `WebSocketStableModule`·`WebSocketBuildModel` 0건. 표 80행 | - | - |
| S5-lead-3 | 권고 | request/tenant context 타입이 전송마다 따로 있음 (= X2-P2-6) | 남음 | 이름이 같은 `TenantContext` 두 개의 모양·검증이 다름. web `core/TenantContext.java:17,20`은 `(String tenantId)`, `[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`. graphql `context/TenantContext.java:15,17,30`은 `(value, source)`, 비어 있지 않고 128자 이하면 모두 허용. 같은 tenant가 한 전송은 통과하고 다른 전송은 거부됨<br>Wave 1–2 P8: 미완 — 이유: 공통 tenant 값 타입(shared-contract/application-core)을 만들고 web·graphql(그리고 messaging·persistence·notification의 tenant 타입)이 담게 하는 일은 계획서 Wave 3 3-D 「tenant 값 타입」 공통 작업이고 web은 P10 범위. 이번에는 증상만 막음: GraphQL `TenantContext` 검증을 web과 같은 문법 `[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`으로 맞춰 "한 전송만 통과하는 tenant"를 없앰. `context/GraphQlRequestContextTest.aTenantTheWebTransportRefusesIsRefusedHereToo`(4건) FAIL(`Expecting actual not to be null`) → PASS. `.../context/TenantContext.java:38`. 커밋 `aa5f4d90` | W2 | tenant 값 타입 하나(검증 규칙 하나)를 application-core/shared-contract에 두고, 두 전송 context가 그것을 담게 한다 |
| S5-lead-4 | 권고 | release/promotion gate가 websocket/grpc에도 반복되는지 | 남음 | web·graphql·websocket gate는 삭제(표 80·114·115행, web Advanced release 행). grpc에 남음: `grpc/grpc-testkit/…/release/GrpcStableReleaseGate.java`, `grpc-advanced/grpc-advanced-bootstrap/…/release/GrpcAdvancedPromotionGate.java`. 둘 다 main 참조 0건(test만) | W3 | 두 gate와 테스트를 삭제하거나 test source set으로 옮긴다(S6/S7 grpc 항목과 같이) |
@@ -1141,7 +1141,7 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검
| P7-new-2 | 발견 | `IdempotencyExecutor`의 `RetryableNoEffect` 경로도 `markFailed`가 예외를 던지면 원래 action 예외를 잃었다. A-8b와 함께 고쳤다(W2 `3a39b6b5`). | 완료 | Wave 1–2 P7 (fcddab7e·Wave 2 커밋): 결과 파일 `docs/reviews/2026-09-25-review-followup-results/P7.md` | - | - |
| P7-new-3 | 발견 | `src/sample-portfolio/src/main/resources/db/sample-migration/V2__work_log.sql:26-27`의 주석은 "local dev relies on ddl-auto=update"라고 적혀 있다. 실제로는 `SamplePostgreSqlPersistenceConfig.sampleMigrationStrategy`가 sample schema를 migrate한다. 이… | 남음 | 결과 파일 `docs/reviews/2026-09-25-review-followup-results/P7.md` | W5 | 적용된 migration은 못 바꾸므로 sample README에 실제 경로 명시 |
| P7-new-4 | 발견 | L-7a로 `show-details: never`가 되면 `show-components`도 따라서 never가 된다. 그러면 `/actuator/health` 응답에 component가 나오지 않는다. P13 `NEW-1a`(compose smoke가 켜진 capability를 확인)는 health component 대신 `info` 경로를 써야 한다. | 완료 | Wave 1–2 P7 (fcddab7e·Wave 2 커밋): 결과 파일 `docs/reviews/2026-09-25-review-followup-results/P7.md` | - | - |
| P8-new-1 | 발견 | `GraphQlBatchLoadException`(per-key 실패, adopter가 준 `errorCode`)을 mapper가 모른다 → `INTERNAL_ERROR`로 가려지고 adopter code가 사라짐. `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlBatchResu… | 남음 | 결과 파일 `docs/reviews/2026-09-25-review-followup-results/P8.md` | W3 | 결정 25: 등록된 `ApiErrorCode`만 노출(3-A와 함께) |
| P8-new-1 | 발견 | `GraphQlBatchLoadException`(per-key 실패, adopter가 준 `errorCode`)을 mapper가 모른다 → `INTERNAL_ERROR`로 가려지고 adopter code가 사라짐. `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlBatchResu… | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): 결정 25: `GraphQlBatchLoadException`이 `ApiErrorCode`만 받고 `ApiErrorCarrier` 구현(`dataloader/GraphQlBatchLoadException.java:16`), `GraphQlBatchValue.Failed(ApiErrorCode)`, `GraphQlBatchResultMapper.map(..., ApiErrorCode)`. `GraphQlWireErrorMapperTest.aFailedBatchKeyKeepsItsRegisteredCode` PASS. FAIL은 API 단계: 이전 생성자는 `String`만 받아 테스트가 컴파일되지 않음(이전 동작은 `INTERNAL_ERROR` 마스킹) | - | 결정 25: 등록된 `ApiErrorCode`만 노출(3-A와 함께) |
| P8-new-2 | 발견 | instrumentation 이 platform context 없이 온 요청(= interceptor 미배선 설정 오류)을 `INTERNAL_ERROR`+`PLATFORM_CONTEXT`로 거부하지만 로그를 남기지 않아, 잘못 조립된 배포가 모든 요청을 조용히 실패시킨다. `.../runtime/GraphQlPlatformInstrumentation.java:65-70`. | 완료 | Wave 2.5 W2-P14 (Wave 3 라운드 1 커밋): `GraphQlPlatformInstrumentationTest.aRequestWithoutPlatformContextIsLoggedAsAWiringFaultAtWarn` FAIL(`Expected size: 1 but was: 0`)→PASS. `runtime/GraphQlPlatformInstrumentation.java:72` executionId와 함께 WARN. 에러 매퍼는 건드리지 않음 | - | platform context 없는 요청 거부 시 WARN 로그 |
| P8-new-3 | 발견 | graphql `CLAUDE.md` 「Error mapping」 절이 없는 클래스 `GraphqlExceptionResolver`와 "비-carrier 예외는 null 반환"을 설명하고 있었음. 현재 경로(한 mapper, 마스킹+로그)로 고침. 커밋 `aa5f4d90`. | 완료 | Wave 1–2 P8 (fcddab7e·Wave 2 커밋): 결과 파일 `docs/reviews/2026-09-25-review-followup-results/P8.md` | - | - |
| P8-new-4 | 발견 | 이번 D 삭제 대상(`GraphQlRuntimeTransport`, `GraphQlExecutionProfile`, `GraphQlBlockingBridge`)을 설명하는 학습 문서가 남아 있음 — `docs/study/graphql-walkthrough.ko.md:157,461,871,1078`(결정 6 대상), `docs/graphql-superpowers-package/`. | 남음 | 결과 파일 `docs/reviews/2026-09-25-review-followup-results/P8.md` | W5 | 학습 문서 갱신(결정 6) |
@@ -1171,3 +1171,7 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검
| P17-new-2 | 발견 | gRPC starter·advanced leaf가 BOM 없이 versionless `io.grpc:grpc-api`를 받아 lockfile 재생성 시 해석 실패. | 완료 | Wave 3 P17: `ca.grpc-platform-module`로 교체 | - | - |
| P17-new-3 | 발견 | 새 CI job `grpc-proto-buf`(buf lint·breaking)가 `ci-quality-gates.yml` `release-gate.needs`에 없어 병합을 막지 않는다. | 남음 | Wave 3 P17 결과 | W3 | 오케스트레이터가 P16 통합 때 `release-gate.needs`에 추가 |
| ORCH-new-1 | 발견 | `messaging-policy` `MessagingAdmissionControllerTest.aWaitingCallerIsAdmittedOnceAPermitIsReturned`가 에이전트 4개 부하 중 실패, 단독 재실행 통과(타이밍 의존). | 남음 | desktop 기준선 `check`(2026-09-28, `016597ac`) | W4 | 대기 확인을 sleep/시간이 아닌 결정적 신호로 |
| P15-new-1 | 발견 | web `GlobalExceptionHandler`에 일반 `ApiErrorCarrier` 분기가 없어 adopter carrier가 `INTERNAL_ERROR` 500으로 나갔다. | 완료 | Wave 3 P15: `GlobalExceptionHandler.java:151` `handleCarrier` | - | - |
| P15-new-2 | 발견 | GraphQL body-limit 필터가 mapper를 거치지 않고 하드코딩 JSON(`REQUEST_ERROR`)을 썼다. | 완료 | Wave 3 P15: `PAYLOAD_TOO_LARGE` + 공용 문구 + `retryable:false` | - | - |
| P15-new-3 | 발견 | `OperationalError.INTERNAL_ERROR`가 레지스트리에서 `retryable: true` — SCHEMA_MISMATCH·DATA_CORRUPTION 같은 결정적 내부 실패도 재시도를 권한다. | 남음 | Wave 3 P15 결과 파일 | W3 | 결정 필요: `INTERNAL_ERROR`를 non-retryable로 바꾸거나 결정적 실패에 별도 코드 |
| P15-new-4 | 발견 | gRPC status description이 코드 문자열에서 한국어 공용 문구로 바뀜(결정 11) — description을 코드로 파싱하던 클라이언트는 `error-code` trailer를 봐야 한다. | 남음 | Wave 3 P15 결과 파일 | W5 | 이행 안내를 gRPC adapter README·에러 계약 문서에 |
+42
View File
@@ -0,0 +1,42 @@
---
title: Runbook — IDEMPOTENCY_UNAVAILABLE (멱등성 조정 저장소 사용 불가)
category: TRANSIENT_DEPENDENCY
error_codes: [IDEMPOTENCY_UNAVAILABLE, IDEMPOTENCY_RECOVERY_REQUIRED]
severity: P2
owner: oncall
last_updated: 2026-09-28
status: active
---
# Runbook: IDEMPOTENCY_UNAVAILABLE (`runbook://idempotency/unavailable`)
## Symptoms
- HTTP 503 (`error.code=IDEMPOTENCY_UNAVAILABLE`, `retryable=true`) on endpoints that take an
`Idempotency-Key`; the same code on the gRPC `error-code` trailer (`UNAVAILABLE`).
- `IdempotencyExecutor` refused to run the action because the replay store (JPA or Redis, whichever
`app.idempotency` selects) did not answer. Nothing was executed: the refusal happens before the
action, so a client retry is safe.
- HTTP 500 `IDEMPOTENCY_RECOVERY_REQUIRED` (`retryable=false`) means the opposite case: the store
cannot tell whether an earlier attempt's external effect already happened.
## Diagnosis
- Check the health of the idempotency store the service uses (`/actuator/health` component of the
JPA datasource or Redis, depending on the selected provider).
- Look for connection-pool saturation or timeouts on that store in the same time window; the
executor reports saturation as unavailable rather than guessing.
- For `IDEMPOTENCY_RECOVERY_REQUIRED`, find the scope digest in the server log line of the failed
request and inspect that record's state in the store.
## Action
- `IDEMPOTENCY_UNAVAILABLE`: restore the store; clients retry with the same key and backoff.
- `IDEMPOTENCY_RECOVERY_REQUIRED`: do not ask the client to retry blindly. Confirm whether the
downstream effect of the earlier attempt exists, then complete or release the record so the next
request with that key replays or re-executes deterministically.
## Escalation
- P2 → P1 when the store stays unavailable for more than 10 minutes on a write path.
- Page the owner of the idempotency store (database or Redis on-call).
+11 -6
View File
@@ -49,7 +49,7 @@ required-class 검사가 이 테스트가 조용히 사라지는 것을 막는
## Responsibility
- GraphQL 전송 인프라만: 최소 health 스키마(`skeleton.graphqls`) + `HealthGraphqlController`,
프로토콜 에러 매핑(`GraphqlExceptionResolver`). Spring for GraphQL 이 스키마와 컨트롤러를
프로토콜 에러 매핑(`error/GraphQlWireErrorMapper`). Spring for GraphQL 이 스키마와 컨트롤러를
자동 합성/바인딩하도록 얹는 얇은 계층이다.
- 그 위에 **GraphQL API 실행 플랫폼**(`...graphql` 하위 sub-package 군)이 스키마 계약·전송
프로파일·실행 정책·비용 한계·DataLoader·페이지네이션·에러/보안 경계·관측을
@@ -71,7 +71,9 @@ platform wire-code catalogue in `GraphQlErrorCode`.
- GraphQL platform mappers must use `GraphQlErrorCode.platform(...)`. An unregistered platform code
fails immediately.
- application/domain `ApiErrorCode` values remain a separate namespace and pass through with
`GraphQlErrorCode.of(...)`; GraphQL must not rename product errors.
`GraphQlErrorCode.of(...)`; GraphQL must not rename product errors. Only a registered
`ApiErrorCode` reaches the wire this way — a DataLoader per-key failure carries one, never a free
string (owner decision 25).
- new GraphQL-owned platform codes use the `GRAPHQL_` prefix. The existing unprefixed platform
values are frozen legacy wire contracts and are listed explicitly by
`legacyUnprefixedPlatformCodes()`.
@@ -117,11 +119,14 @@ application/platform namespace split.
## Error mapping (`Category → ErrorType`)
모든 client 에러는 `runtime/GraphQlWireErrorMapper` 하나를 거친다 — 전송 interceptor, 실행 전
모든 client 에러는 `error/GraphQlWireErrorMapper` 하나를 거친다 — 전송 interceptor, 실행 전
pipeline(instrumentation), data fetcher resolver 세 곳이 같은 bean 을 받는다. 순서는 플랫폼 거부
(`GraphQlPlatformRejectionMapper.mapKnown`) → `ApiErrorCarrier`(자기 `ApiErrorCode`) → 등록된
application 매핑(`GraphQlExceptionResolver`). 어디에도 안 걸린 예외는 `INTERNAL_ERROR` 로 가려지고,
같은 executionId 로 ERROR 로그 한 줄이 남는다. 표는 [README.md](README.md).
(예외가 구현한 `error/GraphQlPlatformRejection`) → `ApiErrorCarrier`(자기 `ApiErrorCode`) → 등록된
application 매핑(`GraphQlExceptionResolver`) → `IllegalArgumentException`=`BAD_PARAMETER`. 어디에도 안
걸린 예외는 `INTERNAL_ERROR` 로 가려지고, 같은 executionId 로 ERROR 로그 한 줄이 남는다. client 문구는
shared-contract `ClientErrorMessages`(Category 별 한국어 표), `retryable` 은 코드의 값이다. Category →
wire category/`ErrorType` 표는 mapper 의 `RENDERINGS` 하나뿐이고 [README.md](README.md)에 옮겨 둔다.
DataLoader 키 실패는 등록된 `ApiErrorCode` 만 싣는다(`GraphQlBatchLoadException`, 소유자 결정 25).
## 향후 adopter 의 feature 기여 방법
+31 -28
View File
@@ -61,37 +61,40 @@ platform mapper는 반드시 `platform(...)`을 사용하고, application/domain
기존 unprefixed code는 wire compatibility 때문에 동결된 legacy 목록으로 관리한다.
`GraphqlExceptionResolver` 는 `DataFetcherExceptionResolverAdapter` 를 확장해, 데이터 페처가
동기적으로 던진 예외 중 안정적 `ApiErrorCode` 를 실은 것(전송-중립 hook `ApiErrorCarrier` 구현)을
`GraphQLError` 로 변환한다. 데이터 페처는 web 컨트롤러처럼 "그냥 던지기만" 하고, 이 resolver 가
와이어 계약을 단일 소유한다.
모든 client 에러는 `error/GraphQlWireErrorMapper` 하나를 거친다(전송 interceptor, 실행 전
instrumentation, data fetcher resolver 세 곳이 같은 bean 을 받는다). 순서:
- **`ErrorType` 분류**: `errorCode().category()` 를 GraphQL `ErrorType` 으로 매핑한다(아래 표).
정확한 `code`/`category` 는 error `extensions{code, category}` 로 실어 클라이언트가 switch 하게
한다(gRPC 가 status trailer 에 싣는 것과 동형).
- **`ApiErrorCode` 추출**: shared-contract 의 `PersistenceFailureException` /
`DependencyFailureException`(outbound 어댑터에서 올라온 분류된 실패)과 feature 예외(자신의 도메인
`ApiErrorCode` 를 실은 것)를 단일 `instanceof ApiErrorCarrier` 분기로 인식한다.
- **leak 방지**: 인식된 코드는 안정적 `code` 문자열만 error message/extensions 로 노출하고, raw
예외 메시지(SQLState/업스트림 세부를 담을 수 있음)는 절대 클라이언트에 내보내지 않는다.
- **비-`ApiErrorCarrier`** 예외는 `null` 을 반환해 다른
`DataFetcherExceptionResolver` 빈(예: sample 의 도메인 예외 resolver)과 Spring 기본 처리로
넘긴다.
1. **플랫폼 거부** — 플랫폼 예외가 `error/GraphQlPlatformRejection`(wire code·shared `Category`·
필요하면 wire category/constraint)을 구현한다. `instanceof` 사슬로 등록하던 두 번째 목록은 없다.
2. **`ApiErrorCarrier`** — 자기 `ApiErrorCode` 로 매핑. shared-contract 의 `MappingException`·
`AdapterDisabledException`·`PersistenceFailureException`(JPA 예외 포함)·`DependencyFailureException`,
application 의 멱등성 예외, DataLoader 키 실패(`GraphQlBatchLoadException`, **등록된 `ApiErrorCode`
만** — 소유자 결정 25)가 모두 여기로 온다.
3. **등록된 application 매핑**(`GraphQlExceptionResolver`).
4. **`IllegalArgumentException`** → `BAD_PARAMETER`(`REQUEST`, `BAD_REQUEST`) — web·gRPC·STOMP 와 같다.
5. 나머지는 `INTERNAL_ERROR` 로 가려지고 같은 executionId 로 ERROR 로그 한 줄이 남는다.
`Category → ErrorType` 표(설계 스펙 Error Mapping SSOT):
- **client 문구**: shared-contract `ClientErrorMessages`(Category 별 한국어 문구 표 하나, 소유자
결정 11). 예외 메시지는 절대 나가지 않는다.
- **retryable**: 코드의 `retryable()` 이다(category 에서 계산하지 않는다). 플랫폼 자체 코드만 wire
category 기본값을 쓴다.
- **body 크기 초과**: `PAYLOAD_TOO_LARGE`(web 과 같은 코드). 문서 모양 거부(`GRAPHQL_DOCUMENT_SHAPE_REJECTED`)는
별도 코드.
| `Category` | GraphQL `ErrorType` |
|---|---|
| VALIDATION | BAD_REQUEST |
| AUTH | UNAUTHORIZED |
| AUTHZ | FORBIDDEN |
| NOT_FOUND | NOT_FOUND |
| CONFLICT | BAD_REQUEST |
| RATE_LIMIT | BAD_REQUEST |
| TRANSIENT_DEPENDENCY | INTERNAL_ERROR |
| PERMANENT_DEPENDENCY | INTERNAL_ERROR |
| DATA_INTEGRITY | INTERNAL_ERROR |
| INTERNAL | INTERNAL_ERROR |
shared `Category` → GraphQL 렌더링 표(`GraphQlWireErrorMapper.RENDERINGS`, 하나뿐):
| `Category` | wire `category` | GraphQL `ErrorType` |
|---|---|---|
| VALIDATION | REQUEST | BAD_REQUEST |
| AUTH | AUTHORIZATION | UNAUTHORIZED |
| AUTHZ | AUTHORIZATION | FORBIDDEN |
| NOT_FOUND | BUSINESS | NOT_FOUND |
| CONFLICT | BUSINESS | BAD_REQUEST |
| RATE_LIMIT | BUSINESS | BAD_REQUEST |
| TRANSIENT_DEPENDENCY | DEPENDENCY | INTERNAL_ERROR |
| PERMANENT_DEPENDENCY | INTERNAL | INTERNAL_ERROR |
| DATA_INTEGRITY | INTERNAL | INTERNAL_ERROR |
| INTERNAL | INTERNAL | INTERNAL_ERROR |
## 의존성 버전 — strict locking
@@ -8,6 +8,7 @@ import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlDocumentShapeAnalyzer;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimitPolicy;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimits;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlExceptionResolver;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
import dev.caskeleton.adapter.inbound.graphql.execution.BoundedPreparsedDocumentProvider;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionPipeline;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCacheMetrics;
@@ -31,7 +32,6 @@ import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformWebIntercep
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPreparsedDocumentAdapter;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPrincipalResolver;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlRequestObservationConventionAdapter;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlWireErrorMapper;
import dev.caskeleton.adapter.inbound.graphql.runtime.servlet.GraphQlRequestBodyLimitFilter;
import dev.caskeleton.adapter.inbound.graphql.scalar.GraphQlScalarWiringConfigurer;
import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlScalarDefinition;
@@ -1,11 +1,16 @@
package dev.caskeleton.adapter.inbound.graphql.cost;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
/**
* Raised when an operation's estimated cost exceeds the client budget.
*
* <p>Carries the scores, never the document or the variables.
*/
public class GraphQlComplexityRejectedException extends RuntimeException {
public class GraphQlComplexityRejectedException extends RuntimeException
implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L;
@@ -30,4 +35,14 @@ public class GraphQlComplexityRejectedException extends RuntimeException {
public String code() {
return CODE;
}
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.platform(CODE);
}
@Override
public Category failureCategory() {
return Category.VALIDATION;
}
}
@@ -1,12 +1,18 @@
package dev.caskeleton.adapter.inbound.graphql.cost;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
import java.util.Optional;
/**
* Raised when a document exceeds a structural ceiling.
*
* <p>Names the dimension and the two counts so the client can see which budget was hit, without the
* document appearing anywhere.
*/
public class GraphQlStructuralLimitException extends RuntimeException {
public class GraphQlStructuralLimitException extends RuntimeException
implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L;
@@ -40,4 +46,20 @@ public class GraphQlStructuralLimitException extends RuntimeException {
public String code() {
return CODE;
}
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.platform(CODE);
}
@Override
public Category failureCategory() {
return Category.VALIDATION;
}
/** The exceeded dimension, a bounded name. */
@Override
public Optional<String> constraint() {
return Optional.of(limitName);
}
}
@@ -1,29 +1,37 @@
package dev.caskeleton.adapter.inbound.graphql.dataloader;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import java.util.Objects;
/**
* Raised when a single key failed to load.
*
* <p>Carries the stable error code only. Other keys in the same batch are unaffected, which is the
* point of per-key attribution.
* <p>Carries a registered {@link ApiErrorCode} only (owner decision 25). The code used to be a free
* string, which the wire mapper could not recognise and masked as {@code INTERNAL_ERROR} — and
* which, passed through, would have put an unvetted adopter string on the wire. As an {@link
* ApiErrorCarrier} it maps exactly as the same code does from any other stage or transport. Other
* keys in the same batch are unaffected, which is the point of per-key attribution.
*/
public class GraphQlBatchLoadException extends RuntimeException {
public class GraphQlBatchLoadException extends RuntimeException implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
private final transient String errorCode;
private final transient ApiErrorCode errorCode;
/**
* Creates the failure.
*
* @param errorCode stable error code for the failed key
* @param errorCode registered error code for the failed key
*/
public GraphQlBatchLoadException(String errorCode) {
super(errorCode == null ? "GRAPHQL_BATCH_KEY_FAILED" : errorCode);
this.errorCode = errorCode == null ? "GRAPHQL_BATCH_KEY_FAILED" : errorCode;
public GraphQlBatchLoadException(ApiErrorCode errorCode) {
super(Objects.requireNonNull(errorCode, "errorCode").code());
this.errorCode = errorCode;
}
/** The stable error code. */
public String errorCode() {
/** The registered error code for the failed key. */
@Override
public ApiErrorCode errorCode() {
return errorCode;
}
}
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.inbound.graphql.dataloader;
import dev.caskeleton.shared.error.ApiErrorCode;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -40,10 +41,10 @@ public final class GraphQlBatchResultMapper {
* @param keys requested keys, in request order
* @param loaded values the loader returned
* @param failedKeys keys the loader failed on
* @param errorCode stable error code for the failed keys
* @param errorCode registered error code for the failed keys; required when any key failed
*/
public <K, V> GraphQlBatchResult<K, V> map(
List<K> keys, Map<K, V> loaded, Set<K> failedKeys, String errorCode) {
List<K> keys, Map<K, V> loaded, Set<K> failedKeys, ApiErrorCode errorCode) {
requireOnlyRequestedKeys(keys, loaded);
@@ -1,11 +1,17 @@
package dev.caskeleton.adapter.inbound.graphql.dataloader;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCategory;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
/**
* Raised when a batch exceeds its budget.
*
* <p>Names the loader — which is bounded — and never the keys, which are object identifiers.
*/
public class GraphQlBatchTimeoutException extends RuntimeException {
public class GraphQlBatchTimeoutException extends RuntimeException
implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L;
@@ -33,4 +39,23 @@ public class GraphQlBatchTimeoutException extends RuntimeException {
public String code() {
return CODE;
}
/**
* A batch that ran out of budget is the request running out of budget, one level down, so it is
* reported as the request timeout.
*/
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.platform(GraphQlErrorCode.REQUEST_TIMEOUT);
}
@Override
public Category failureCategory() {
return Category.TRANSIENT_DEPENDENCY;
}
@Override
public GraphQlErrorCategory wireCategory() {
return GraphQlErrorCategory.TIMEOUT;
}
}
@@ -1,5 +1,8 @@
package dev.caskeleton.adapter.inbound.graphql.dataloader;
import dev.caskeleton.shared.error.ApiErrorCode;
import java.util.Objects;
/**
* The outcome for one key in a batch (design §13).
*
@@ -31,9 +34,14 @@ public sealed interface GraphQlBatchValue<V>
* Loading the key failed.
*
* @param <V> loaded value type
* @param errorCode stable error code; never the key or the underlying message
* @param errorCode registered error code; never the key or the underlying message
*/
record Failed<V>(String errorCode) implements GraphQlBatchValue<V> {}
record Failed<V>(ApiErrorCode errorCode) implements GraphQlBatchValue<V> {
public Failed {
Objects.requireNonNull(errorCode, "errorCode");
}
}
/** A resolved value. */
static <V> GraphQlBatchValue<V> present(V value) {
@@ -46,7 +54,7 @@ public sealed interface GraphQlBatchValue<V>
}
/** A per-key failure. */
static <V> GraphQlBatchValue<V> failed(String errorCode) {
static <V> GraphQlBatchValue<V> failed(ApiErrorCode errorCode) {
return new Failed<>(errorCode);
}
@@ -1,11 +1,16 @@
package dev.caskeleton.adapter.inbound.graphql.dataloader;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
/**
* Raised when a key is missing and the loader treats that as a field error.
*
* <p>Carries no key: the key is an object identifier, and this message is client-visible.
*/
public class GraphQlMissingKeyException extends RuntimeException {
public class GraphQlMissingKeyException extends RuntimeException
implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L;
@@ -21,4 +26,18 @@ public class GraphQlMissingKeyException extends RuntimeException {
public String code() {
return CODE;
}
/**
* The loader declared this relation always resolvable and it did not resolve. The key is an
* object identifier, so nothing here names it or the loader.
*/
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.platform(CODE);
}
@Override
public Category failureCategory() {
return Category.NOT_FOUND;
}
}
@@ -66,6 +66,16 @@ public final class GraphQlExceptionResolver {
return GraphQlInternalErrorMasker.mask(context);
}
/** Whether the application registered a mapping for this failure or one of its supertypes. */
public boolean maps(Throwable failure) {
for (Class<?> type = failure.getClass(); type != null; type = type.getSuperclass()) {
if (mappings.containsKey(type)) {
return true;
}
}
return false;
}
/** Registers deliberate failure mappings. */
public static final class Builder {
@@ -0,0 +1,46 @@
package dev.caskeleton.adapter.inbound.graphql.error;
import dev.caskeleton.shared.error.Category;
import java.util.Optional;
/**
* A rejection the GraphQL platform itself raises, described by what reaches the wire.
*
* <p>The platform's exceptions implement this instead of being listed in a mapper's {@code
* instanceof} chain. That chain was the second place every new rejection had to be registered, and
* forgetting it turned a deliberate rejection into an opaque {@code INTERNAL_ERROR}; with the
* description on the exception, a rejection cannot exist without saying what the client sees.
*
* <p>The client message is never supplied here. It is the shared category message ({@code
* ClientErrorMessages}), chosen by {@link #failureCategory()}, so a GraphQL rejection reads exactly
* as the same kind of failure does on every other transport.
*/
public interface GraphQlPlatformRejection {
/** The stable, bounded code clients branch on. */
GraphQlErrorCode wireCode();
/** The shared operational category, which chooses the client message. */
Category failureCategory();
/**
* The six-value wire category.
*
* <p>Derived from {@link #failureCategory()} by default. A rejection overrides it only when the
* wire must say something the shared category cannot — a request timeout, or a tenant-isolation
* miss that has to look exactly like an authorization denial.
*/
default GraphQlErrorCategory wireCategory() {
return GraphQlWireErrorMapper.wireCategoryOf(failureCategory());
}
/** Whether retrying the same request is meaningful; the wire category's default. */
default boolean wireRetryable() {
return wireCategory().retryable();
}
/** A safe, bounded constraint identity to attach, if any. */
default Optional<String> constraint() {
return Optional.empty();
}
}
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.inbound.graphql.error;
import dev.caskeleton.shared.error.ClientErrorMessages;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -23,8 +24,8 @@ public record GraphQlWireError(String message, List<Object> path, Map<String, Ob
public static final Set<String> ALLOWED_EXTENSION_KEYS =
Set.of("code", "category", "retryable", "executionId", "constraint", "field");
/** Opaque message used whenever the real cause must not be disclosed. */
public static final String OPAQUE_MESSAGE = "요청을 처리할 수 없습니다.";
/** Opaque message used whenever the real cause must not be disclosed (the shared one). */
public static final String OPAQUE_MESSAGE = ClientErrorMessages.OPAQUE;
public GraphQlWireError {
if (message == null || message.isBlank()) {
@@ -61,16 +62,31 @@ public record GraphQlWireError(String message, List<Object> path, Map<String, Ob
executionId));
}
/** A categorised error with a stable code. */
/** A categorised error with a stable code, retryable as its wire category is by default. */
public static GraphQlWireError of(
String message,
GraphQlErrorCode code,
GraphQlErrorCategory category,
GraphQlErrorContext context) {
return of(message, code, category, category.retryable(), context);
}
/**
* A categorised error with a stable code and an explicit retryability.
*
* <p>A shared {@code ApiErrorCode} decides its own retryability; deriving it from the six-value
* wire category told a client to retry a code the registry marks as not retryable.
*/
public static GraphQlWireError of(
String message,
GraphQlErrorCode code,
GraphQlErrorCategory category,
boolean retryable,
GraphQlErrorContext context) {
Map<String, Object> extensions = new LinkedHashMap<>();
extensions.put("code", code.value());
extensions.put("category", category.name());
extensions.put("retryable", category.retryable());
extensions.put("retryable", retryable);
extensions.put("executionId", context.executionId());
return new GraphQlWireError(message, context.path(), Map.copyOf(extensions));
}
@@ -0,0 +1,178 @@
package dev.caskeleton.adapter.inbound.graphql.error;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import dev.caskeleton.shared.error.OperationalError;
import graphql.ErrorClassification;
import graphql.GraphQLError;
import java.util.EnumMap;
import java.util.Map;
import java.util.Objects;
import org.springframework.graphql.execution.ErrorType;
/**
* The one place a failure becomes something a client can see.
*
* <p>There were two error contracts. The Spring-wired resolver mapped {@link ApiErrorCarrier} to a
* code and a category; a second, richer resolver did masking and registered mappings but was never
* on the Spring path; and the platform's own rejections had a third vocabulary. Which code,
* category, retryability and execution id a client received depended on which of the three paths
* the failure happened to take.
*
* <p>Every stage routes through here: the transport interceptor, the pre-execution pipeline and the
* data-fetcher resolver all receive this bean, so an {@link ApiErrorCarrier} thrown before
* execution keeps its code exactly as it does from a resolver.
*
* <p>How a shared {@link Category} looks on this transport is one table, {@link #RENDERINGS}: its
* wire category and its engine classification. The client message is not in it — that is the shared
* {@link ClientErrorMessages} table every transport uses. Retryability comes from the code ({@link
* ApiErrorCode#retryable()}), never from the category.
*
* <p>An unrecognised failure never contributes its own message. That is the fail-closed direction:
* a new exception type nobody mapped becomes an opaque internal error with a correlation id, and
* the detail goes to the log under that id ({@link GraphQlExceptionResolver}).
*/
public final class GraphQlWireErrorMapper {
/** How one shared category is rendered on the GraphQL wire. */
private record Rendering(GraphQlErrorCategory wireCategory, ErrorClassification classification) {}
/** Exhaustive by construction: a new shared category fails the static check below. */
private static final Map<Category, Rendering> RENDERINGS = new EnumMap<>(Category.class);
static {
RENDERINGS.put(
Category.VALIDATION, new Rendering(GraphQlErrorCategory.REQUEST, ErrorType.BAD_REQUEST));
RENDERINGS.put(
Category.AUTH, new Rendering(GraphQlErrorCategory.AUTHORIZATION, ErrorType.UNAUTHORIZED));
RENDERINGS.put(
Category.AUTHZ, new Rendering(GraphQlErrorCategory.AUTHORIZATION, ErrorType.FORBIDDEN));
RENDERINGS.put(
Category.NOT_FOUND, new Rendering(GraphQlErrorCategory.BUSINESS, ErrorType.NOT_FOUND));
RENDERINGS.put(
Category.CONFLICT, new Rendering(GraphQlErrorCategory.BUSINESS, ErrorType.BAD_REQUEST));
RENDERINGS.put(
Category.RATE_LIMIT, new Rendering(GraphQlErrorCategory.BUSINESS, ErrorType.BAD_REQUEST));
RENDERINGS.put(
Category.TRANSIENT_DEPENDENCY,
new Rendering(GraphQlErrorCategory.DEPENDENCY, ErrorType.INTERNAL_ERROR));
RENDERINGS.put(
Category.PERMANENT_DEPENDENCY,
new Rendering(GraphQlErrorCategory.INTERNAL, ErrorType.INTERNAL_ERROR));
RENDERINGS.put(
Category.DATA_INTEGRITY,
new Rendering(GraphQlErrorCategory.INTERNAL, ErrorType.INTERNAL_ERROR));
RENDERINGS.put(
Category.INTERNAL, new Rendering(GraphQlErrorCategory.INTERNAL, ErrorType.INTERNAL_ERROR));
if (RENDERINGS.size() != Category.values().length) {
throw new ExceptionInInitializerError("every shared category needs a GraphQL rendering");
}
}
private final GraphQlExceptionResolver applicationMappings;
/**
* Creates the mapper.
*
* @param applicationMappings deliberate application failure mappings; may map nothing
*/
public GraphQlWireErrorMapper(GraphQlExceptionResolver applicationMappings) {
this.applicationMappings =
Objects.requireNonNull(applicationMappings, "application mappings are required");
}
/** A mapper with no registered application mappings: everything unknown is masked. */
public static GraphQlWireErrorMapper masking() {
return new GraphQlWireErrorMapper(GraphQlExceptionResolver.defaults());
}
/**
* Maps a failure from any stage.
*
* <p>Order: a platform rejection, then an {@link ApiErrorCarrier}, then the application's
* registered mappings, then {@link IllegalArgumentException} as {@code BAD_PARAMETER} (the same
* answer every transport gives), and finally the masked internal error. Platform rejections come
* first: an authorization denial raised from inside a resolver means the same thing to a client
* as one raised before execution. A registered mapping outranks the argument rule so an
* application that models its own {@code IllegalArgumentException} subtype keeps its code.
*/
public GraphQlWireError map(Throwable failure, GraphQlErrorContext context) {
if (failure instanceof GraphQlPlatformRejection rejection) {
return fromRejection(rejection, context);
}
ApiErrorCode shared = sharedCodeOf(failure);
if (shared != null) {
return fromApiError(shared, context);
}
return applicationMappings.resolve(failure, context);
}
/**
* Maps a failure and renders it as the engine's error type.
*
* <p>A shared code still knows its operational category, which is finer than the six wire
* categories. Classifying from it keeps {@code NOT_FOUND} distinguishable from any other business
* outcome, and does so the same way whichever stage threw.
*/
public GraphQLError toGraphQlError(Throwable failure, GraphQlErrorContext context) {
GraphQlWireError wireError = map(failure, context);
ApiErrorCode shared =
failure instanceof GraphQlPlatformRejection ? null : sharedCodeOf(failure);
if (shared != null) {
return GraphQlWireErrors.toGraphQlError(
wireError, RENDERINGS.get(shared.category()).classification());
}
return GraphQlWireErrors.toGraphQlError(wireError);
}
/**
* Maps a shared operational error code onto the GraphQL wire vocabulary.
*
* <p>Only the stable {@link ApiErrorCode#code()} reaches the client; the exception message never
* does, because it may carry a SQLState or an upstream body. Retryability is the code's own.
*/
public static GraphQlWireError fromApiError(ApiErrorCode code, GraphQlErrorContext context) {
return GraphQlWireError.of(
ClientErrorMessages.of(code),
GraphQlErrorCode.of(code.code()),
wireCategoryOf(code.category()),
code.retryable(),
context);
}
/** Renders a platform rejection from the description it carries. */
public static GraphQlWireError fromRejection(
GraphQlPlatformRejection rejection, GraphQlErrorContext context) {
GraphQlWireError error =
GraphQlWireError.of(
ClientErrorMessages.of(rejection.failureCategory()),
rejection.wireCode(),
rejection.wireCategory(),
rejection.wireRetryable(),
context);
return rejection.constraint().map(error::withConstraint).orElse(error);
}
/** The six-value wire category a shared operational category is rendered as. */
public static GraphQlErrorCategory wireCategoryOf(Category category) {
return RENDERINGS.get(category).wireCategory();
}
/**
* The shared code a failure carries, or {@code null}.
*
* <p>An {@link IllegalArgumentException} the application did not register a mapping for is {@link
* OperationalError#BAD_PARAMETER}, as it is on the web, gRPC and STOMP transports.
*/
private ApiErrorCode sharedCodeOf(Throwable failure) {
if (failure instanceof ApiErrorCarrier carrier) {
return carrier.errorCode();
}
if (failure instanceof IllegalArgumentException && !applicationMappings.maps(failure)) {
return OperationalError.BAD_PARAMETER;
}
return null;
}
}
@@ -1,7 +1,5 @@
package dev.caskeleton.adapter.inbound.graphql.runtime;
package dev.caskeleton.adapter.inbound.graphql.error;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCategory;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireError;
import graphql.ErrorClassification;
import graphql.ErrorType;
import graphql.GraphQLError;
@@ -27,10 +25,9 @@ public final class GraphQlWireErrors {
/**
* Converts an allowlisted wire error, classified explicitly.
*
* <p>The overload exists because the caller sometimes knows more than the wire error does. The
* platform's six wire categories are what a client branches on, but the shared operational
* catalogue has ten, and collapsing {@code NOT_FOUND} into {@code BUSINESS} before choosing the
* engine classification would throw away a distinction the previous resolver did preserve.
* <p>The overload exists because the caller sometimes knows more than the wire error does: the
* shared operational category is finer than the six wire categories ({@link
* GraphQlWireErrorMapper} owns that table).
*/
public static GraphQLError toGraphQlError(
GraphQlWireError error, ErrorClassification classification) {
@@ -45,25 +42,6 @@ public final class GraphQlWireErrors {
return builder.build();
}
/**
* The engine classification for a shared operational category.
*
* <p>Exhaustive, so a new operational category fails to compile until someone decides what the
* engine should call it.
*/
public static ErrorClassification classificationOf(
dev.caskeleton.shared.error.Category category) {
return switch (category) {
case VALIDATION, CONFLICT, RATE_LIMIT ->
org.springframework.graphql.execution.ErrorType.BAD_REQUEST;
case AUTH -> org.springframework.graphql.execution.ErrorType.UNAUTHORIZED;
case AUTHZ -> org.springframework.graphql.execution.ErrorType.FORBIDDEN;
case NOT_FOUND -> org.springframework.graphql.execution.ErrorType.NOT_FOUND;
case TRANSIENT_DEPENDENCY, PERMANENT_DEPENDENCY, DATA_INTEGRITY, INTERNAL ->
org.springframework.graphql.execution.ErrorType.INTERNAL_ERROR;
};
}
/**
* The engine classification for a category.
*
@@ -1,12 +1,17 @@
package dev.caskeleton.adapter.inbound.graphql.execution;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
/**
* Raised when an operation is anonymous where the profile requires a name.
*
* <p>Carries no document text: the reason a name is required is precisely that the document must
* not become the identity used in traces, metrics and usage analytics.
*/
public class GraphQlAnonymousOperationException extends RuntimeException {
public class GraphQlAnonymousOperationException extends RuntimeException
implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L;
@@ -26,4 +31,14 @@ public class GraphQlAnonymousOperationException extends RuntimeException {
public String code() {
return CODE;
}
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.platform(CODE);
}
@Override
public Category failureCategory() {
return Category.VALIDATION;
}
}
@@ -1,11 +1,17 @@
package dev.caskeleton.adapter.inbound.graphql.execution;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCategory;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
/**
* Raised when work continues after the request was cancelled or its budget expired.
*
* <p>Carries the stable timeout error code and no request content.
*/
public class GraphQlRequestCancelledException extends RuntimeException {
public class GraphQlRequestCancelledException extends RuntimeException
implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L;
@@ -18,4 +24,20 @@ public class GraphQlRequestCancelledException extends RuntimeException {
public String code() {
return GraphQlTimeoutPolicy.TIMEOUT_ERROR_CODE;
}
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.platform(GraphQlErrorCode.REQUEST_TIMEOUT);
}
@Override
public Category failureCategory() {
return Category.TRANSIENT_DEPENDENCY;
}
/** {@code TIMEOUT}: the client can retry the same request and should be told so. */
@Override
public GraphQlErrorCategory wireCategory() {
return GraphQlErrorCategory.TIMEOUT;
}
}
@@ -1,5 +1,10 @@
package dev.caskeleton.adapter.inbound.graphql.http;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
import java.util.Optional;
/**
* Raised when the request envelope is structurally wrong.
*
@@ -7,7 +12,8 @@ package dev.caskeleton.adapter.inbound.graphql.http;
* object, an unregistered extension key and a missing operation name where the client policy
* requires one. The message names the field, never its content.
*/
public class GraphQlRequestFormatException extends GraphQlHttpContractException {
public class GraphQlRequestFormatException extends GraphQlHttpContractException
implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L;
@@ -19,4 +25,31 @@ public class GraphQlRequestFormatException extends GraphQlHttpContractException
public GraphQlRequestFormatException(String message) {
super(message, GraphQlHttpOutcome.MALFORMED_REQUEST);
}
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.platform(GraphQlErrorCode.REQUEST_ERROR);
}
@Override
public Category failureCategory() {
return Category.VALIDATION;
}
/**
* The stable constraint identity behind a format rejection.
*
* <p>The message names a field and, for a shape rejection, a dimension and two counts; it never
* carries a variable value. A shape rejection already prefixes its own code; anything else is
* reported under the generic envelope constraint rather than by echoing a message that was
* written for a log.
*/
@Override
public Optional<String> constraint() {
String message = getMessage();
return Optional.of(
message != null && message.startsWith(GraphQlJsonStructurePolicy.CODE)
? GraphQlJsonStructurePolicy.CODE
: "GRAPHQL_REQUEST_ENVELOPE");
}
}
@@ -1,12 +1,18 @@
package dev.caskeleton.adapter.inbound.graphql.http;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.OperationalError;
/**
* Raised when a request exceeds a size limit before the GraphQL document is parsed.
*
* <p>Reports byte counts only. An over-size document or variables object is exactly the input that
* must not be echoed into a log or an error body.
*/
public class GraphQlRequestTooLargeException extends GraphQlHttpContractException {
public class GraphQlRequestTooLargeException extends GraphQlHttpContractException
implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L;
@@ -48,4 +54,18 @@ public class GraphQlRequestTooLargeException extends GraphQlHttpContractExceptio
public long allowedBytes() {
return allowedBytes;
}
/**
* {@code PAYLOAD_TOO_LARGE}, the shared code every transport uses for an oversized body; a
* document that is well-sized but too deep or wide is a separate code, a shape rejection.
*/
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.of(OperationalError.PAYLOAD_TOO_LARGE.code());
}
@Override
public Category failureCategory() {
return OperationalError.PAYLOAD_TOO_LARGE.category();
}
}
@@ -1,6 +1,7 @@
package dev.caskeleton.adapter.inbound.graphql.runtime;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
import graphql.GraphQLError;
import graphql.schema.DataFetchingEnvironment;
import java.util.List;
@@ -3,6 +3,8 @@ package dev.caskeleton.adapter.inbound.graphql.runtime;
import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireError;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrors;
import graphql.ExecutionInput;
import graphql.ExecutionResult;
import graphql.execution.AbortExecutionException;
@@ -1,137 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.runtime;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlComplexityRejectedException;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimitException;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCategory;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireError;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlAnonymousOperationException;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlJsonStructurePolicy;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestFormatException;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestTooLargeException;
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthenticationException;
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationDeniedException;
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationInterceptor;
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlTenantIsolationException;
/**
* Turns a pipeline rejection into the one wire error the client sees.
*
* <p>Every stage rejects by throwing, and every rejection has to arrive on the wire with a stable
* code, a bounded category and no internal detail. Doing that per stage would produce as many error
* vocabularies as there are stages, and the one that forgot would leak an exception message.
*
* <p>This is the platform's catalogue only. {@link GraphQlWireErrorMapper} consults it first and
* falls back to the application's mappings, which mask and log anything unrecognised.
*/
public final class GraphQlPlatformRejectionMapper {
private GraphQlPlatformRejectionMapper() {}
/**
* Maps a rejection this platform raised, or {@code null} when it did not raise it.
*
* <p>Returning {@code null} rather than the opaque internal error is what lets {@code
* GraphQlWireErrorMapper} try the application's own mappings next. Collapsing an unknown failure
* to {@code INTERNAL_ERROR} here would mask exactly the failures the application deliberately
* modelled.
*/
public static GraphQlWireError mapKnown(Throwable failure, GraphQlErrorContext context) {
if (failure instanceof GraphQlAuthorizationDeniedException denied) {
return GraphQlAuthorizationInterceptor.toWireError(denied.decision(), context);
}
if (failure instanceof GraphQlAuthenticationException) {
return GraphQlWireError.of(
"인증이 필요합니다.",
GraphQlErrorCode.platform(GraphQlErrorCode.AUTHENTICATION_REQUIRED),
GraphQlErrorCategory.AUTHORIZATION,
context);
}
if (failure instanceof GraphQlTenantIsolationException) {
// Deliberately the same shape as an authorization denial: telling a caller that the resource
// exists in another tenant is the disclosure the isolation rule exists to prevent.
return GraphQlWireError.of(
"요청한 리소스를 찾을 수 없습니다.",
GraphQlErrorCode.platform(GraphQlErrorCode.RESOURCE_NOT_FOUND),
GraphQlErrorCategory.AUTHORIZATION,
context);
}
if (failure instanceof GraphQlStructuralLimitException violation) {
return GraphQlWireError.of(
"요청 문서가 허용된 구조 한계를 초과했습니다.",
GraphQlErrorCode.platform(GraphQlStructuralLimitException.CODE),
GraphQlErrorCategory.REQUEST,
context)
.withConstraint(violation.limitName());
}
if (failure instanceof GraphQlComplexityRejectedException) {
return GraphQlWireError.of(
"요청의 예상 비용이 허용 한도를 초과했습니다.",
GraphQlErrorCode.platform(GraphQlComplexityRejectedException.CODE),
GraphQlErrorCategory.REQUEST,
context);
}
if (failure instanceof GraphQlAnonymousOperationException) {
return GraphQlWireError.of(
"실행할 operation 을 하나로 특정할 수 없습니다.",
GraphQlErrorCode.platform(GraphQlAnonymousOperationException.CODE),
GraphQlErrorCategory.REQUEST,
context);
}
if (failure instanceof GraphQlRequestFormatException malformed) {
// The message names a field and, for a shape rejection, a dimension and two counts. It never
// carries a variable value — that invariant is the reason it can be surfaced at all, and it
// is enforced where the exception is constructed rather than trusted here.
return GraphQlWireError.of(
"요청 형식이 올바르지 않습니다.",
GraphQlErrorCode.platform(GraphQlErrorCode.REQUEST_ERROR),
GraphQlErrorCategory.REQUEST,
context)
.withConstraint(constraintOf(malformed));
}
if (failure instanceof GraphQlRequestTooLargeException) {
return GraphQlWireError.of(
"요청이 허용된 크기를 초과했습니다.",
GraphQlErrorCode.platform(GraphQlErrorCode.REQUEST_ERROR),
GraphQlErrorCategory.REQUEST,
context);
}
// A batch that ran out of budget is the request running out of budget, one level down: the
// client can retry the same request and should be told so, not handed an opaque failure.
if (failure instanceof GraphQlRequestCancelledException
|| failure instanceof GraphQlBatchTimeoutException) {
return GraphQlWireError.of(
"요청 처리 시간이 초과되었습니다.",
GraphQlErrorCode.platform(GraphQlErrorCode.REQUEST_TIMEOUT),
GraphQlErrorCategory.TIMEOUT,
context);
}
if (failure instanceof GraphQlMissingKeyException) {
// The loader declared this relation always resolvable and it did not resolve. The key is an
// object identifier, so the message names neither it nor the loader.
return GraphQlWireError.of(
"요청한 리소스를 찾을 수 없습니다.",
GraphQlErrorCode.platform(GraphQlMissingKeyException.CODE),
GraphQlErrorCategory.BUSINESS,
context);
}
return null;
}
/**
* The stable constraint identity behind a format rejection.
*
* <p>A shape rejection already prefixes its own code; anything else is reported under the generic
* envelope constraint rather than by echoing a message that was written for a log.
*/
private static String constraintOf(GraphQlRequestFormatException failure) {
String message = failure.getMessage();
return message != null && message.startsWith(GraphQlJsonStructurePolicy.CODE)
? GraphQlJsonStructurePolicy.CODE
: "GRAPHQL_REQUEST_ENVELOPE";
}
}
@@ -5,6 +5,7 @@ import dev.caskeleton.adapter.inbound.graphql.context.GraphQlDeadline;
import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext;
import dev.caskeleton.adapter.inbound.graphql.context.TenantContext;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlExtensionsPolicy;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlJsonStructurePolicy;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestSize;
@@ -1,130 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.runtime;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCategory;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlExceptionResolver;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireError;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.Category;
import graphql.GraphQLError;
import java.util.Objects;
/**
* The one place a failure becomes something a client can see.
*
* <p>There were two error contracts. The Spring-wired resolver mapped {@link ApiErrorCarrier} to a
* code and a category; a second, richer resolver did masking and registered mappings but was never
* on the Spring path; and the platform's own rejections had a third vocabulary. Which code,
* category, retryability and execution id a client received depended on which of the three paths
* the failure happened to take — and the two resolver classes differed only in the case of one
* letter, so importing the wrong one compiled.
*
* <p>Every stage routes through here: the transport interceptor, the pre-execution pipeline and the
* data-fetcher resolver all receive this bean. While the first two called the platform catalogue
* directly, an {@link ApiErrorCarrier} thrown before execution (for example by an adopter's {@code
* GraphQlPrincipalResolver}) became {@code INTERNAL_ERROR} while the same exception from a resolver
* kept its code.
*
* <p>An unrecognised failure never contributes its own message. That is the fail-closed direction:
* a new exception type nobody mapped becomes an opaque internal error with a correlation id, and
* the detail goes to the log under that id ({@link GraphQlExceptionResolver}).
*/
public final class GraphQlWireErrorMapper {
private final GraphQlExceptionResolver applicationMappings;
/**
* Creates the mapper.
*
* @param applicationMappings deliberate application failure mappings; may map nothing
*/
public GraphQlWireErrorMapper(GraphQlExceptionResolver applicationMappings) {
this.applicationMappings =
Objects.requireNonNull(applicationMappings, "application mappings are required");
}
/** A mapper with no registered application mappings: everything unknown is masked. */
public static GraphQlWireErrorMapper masking() {
return new GraphQlWireErrorMapper(GraphQlExceptionResolver.defaults());
}
/**
* Maps a failure from any stage: platform rejection first, then {@link ApiErrorCarrier}, then the
* registered application mappings, which mask anything they do not recognise.
*
* <p>Platform rejections are consulted first: an authorization denial raised from inside a
* resolver means the same thing to a client as one raised before execution, and giving it a
* different code because of where it was thrown would be an implementation detail on the wire.
*/
public GraphQlWireError map(Throwable failure, GraphQlErrorContext context) {
GraphQlWireError platform = GraphQlPlatformRejectionMapper.mapKnown(failure, context);
if (platform != null) {
return platform;
}
if (failure instanceof ApiErrorCarrier carrier) {
return fromApiError(carrier.errorCode(), context);
}
return applicationMappings.resolve(failure, context);
}
/**
* Maps a failure and renders it as the engine's error type.
*
* <p>A carrier still knows its operational category, which is finer than the six wire categories.
* Classifying from it keeps {@code NOT_FOUND} distinguishable from any other business outcome,
* and does so the same way whichever stage threw.
*/
public GraphQLError toGraphQlError(Throwable failure, GraphQlErrorContext context) {
GraphQlWireError wireError = map(failure, context);
if (failure instanceof ApiErrorCarrier carrier) {
return GraphQlWireErrors.toGraphQlError(
wireError, GraphQlWireErrors.classificationOf(carrier.errorCode().category()));
}
return GraphQlWireErrors.toGraphQlError(wireError);
}
/**
* Maps the shared operational error code onto the GraphQL wire vocabulary.
*
* <p>Only the stable {@link ApiErrorCode#code()} reaches the client; the exception message never
* does, because it may carry a SQLState or an upstream body.
*/
public static GraphQlWireError fromApiError(ApiErrorCode code, GraphQlErrorContext context) {
return GraphQlWireError.of(
clientMessage(code.category()),
GraphQlErrorCode.of(code.code()),
category(code.category()),
context);
}
/**
* Maps the ten-value operational category SSOT onto the six-value wire category.
*
* <p>Exhaustive, so a new operational category fails to compile until someone decides what a
* client should be told about it.
*/
public static GraphQlErrorCategory category(Category category) {
return switch (category) {
case VALIDATION -> GraphQlErrorCategory.REQUEST;
case AUTH, AUTHZ -> GraphQlErrorCategory.AUTHORIZATION;
case NOT_FOUND, CONFLICT, RATE_LIMIT -> GraphQlErrorCategory.BUSINESS;
case TRANSIENT_DEPENDENCY -> GraphQlErrorCategory.DEPENDENCY;
case PERMANENT_DEPENDENCY, DATA_INTEGRITY, INTERNAL -> GraphQlErrorCategory.INTERNAL;
};
}
private static String clientMessage(Category category) {
return switch (category) {
case VALIDATION -> "요청 값이 올바르지 않습니다.";
case AUTH -> "인증이 필요합니다.";
case AUTHZ -> "이 작업을 수행할 권한이 없습니다.";
case NOT_FOUND -> "요청한 리소스를 찾을 수 없습니다.";
case CONFLICT -> "현재 상태에서는 요청을 처리할 수 없습니다.";
case RATE_LIMIT -> "요청이 너무 잦습니다.";
case TRANSIENT_DEPENDENCY -> "일시적인 오류입니다. 잠시 후 다시 시도해 주세요.";
case PERMANENT_DEPENDENCY, DATA_INTEGRITY, INTERNAL -> GraphQlWireError.OPAQUE_MESSAGE;
};
}
}
@@ -1,5 +1,7 @@
package dev.caskeleton.adapter.inbound.graphql.runtime.servlet;
import dev.caskeleton.shared.error.ClientErrorMessages;
import dev.caskeleton.shared.error.OperationalError;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
@@ -120,8 +122,11 @@ public final class GraphQlRequestBodyLimitFilter implements Filter {
response
.getWriter()
.write(
"{\"errors\":[{\"message\":\"요청이 허용된 크기를 초과했습니다.\","
+ "\"extensions\":{\"code\":\"REQUEST_ERROR\",\"category\":\"REQUEST\"}}]}");
"{\"errors\":[{\"message\":\""
+ ClientErrorMessages.of(OperationalError.PAYLOAD_TOO_LARGE)
+ "\",\"extensions\":{\"code\":\""
+ OperationalError.PAYLOAD_TOO_LARGE.code()
+ "\",\"category\":\"REQUEST\",\"retryable\":false}}]}");
response.getWriter().flush();
}
@@ -1,11 +1,16 @@
package dev.caskeleton.adapter.inbound.graphql.security;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
/**
* Raised when a request cannot be authenticated for the profile it targets.
*
* <p>Thrown before any resolver runs, and carries no credential material.
*/
public class GraphQlAuthenticationException extends RuntimeException {
public class GraphQlAuthenticationException extends RuntimeException
implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L;
@@ -17,4 +22,14 @@ public class GraphQlAuthenticationException extends RuntimeException {
public GraphQlAuthenticationException(String message) {
super(message);
}
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.platform(GraphQlErrorCode.AUTHENTICATION_REQUIRED);
}
@Override
public Category failureCategory() {
return Category.AUTH;
}
}
@@ -1,12 +1,18 @@
package dev.caskeleton.adapter.inbound.graphql.security;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCategory;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
/**
* Raised when an authorization decision denies the caller.
*
* <p>Carries the stable denial code and whether existence must be hidden — never the object, the
* actor or the tenant.
*/
public class GraphQlAuthorizationDeniedException extends RuntimeException {
public class GraphQlAuthorizationDeniedException extends RuntimeException
implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L;
@@ -26,4 +32,24 @@ public class GraphQlAuthorizationDeniedException extends RuntimeException {
public GraphQlAuthorizationDecision decision() {
return decision;
}
/** {@code RESOURCE_NOT_FOUND} when the decision hides existence, otherwise the denial. */
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.platform(
decision.hideExistence()
? GraphQlErrorCode.RESOURCE_NOT_FOUND
: GraphQlErrorCode.AUTHORIZATION_DENIED);
}
@Override
public Category failureCategory() {
return decision.hideExistence() ? Category.NOT_FOUND : Category.AUTHZ;
}
/** Always {@code AUTHORIZATION}: a hidden resource must look like any other denial. */
@Override
public GraphQlErrorCategory wireCategory() {
return GraphQlErrorCategory.AUTHORIZATION;
}
}
@@ -2,10 +2,9 @@ package dev.caskeleton.adapter.inbound.graphql.security;
import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate;
import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCategory;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireError;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
/**
* Applies operation authorization at the pipeline's authorization stage.
@@ -47,14 +46,7 @@ public final class GraphQlAuthorizationInterceptor {
if (decision.allowed()) {
throw new IllegalArgumentException("an allowed decision has no wire error");
}
String message = decision.hideExistence() ? "요청한 리소스를 찾을 수 없습니다." : "이 작업을 수행할 권한이 없습니다.";
return GraphQlWireError.of(
message,
GraphQlErrorCode.platform(
decision.hideExistence()
? GraphQlErrorCode.RESOURCE_NOT_FOUND
: GraphQlErrorCode.AUTHORIZATION_DENIED),
GraphQlErrorCategory.AUTHORIZATION,
context);
return GraphQlWireErrorMapper.fromRejection(
new GraphQlAuthorizationDeniedException(decision), context);
}
}
@@ -1,12 +1,18 @@
package dev.caskeleton.adapter.inbound.graphql.security;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCategory;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
/**
* Raised when tenant context is missing or would be crossed.
*
* <p>Fail-closed by design: a missing tenant must stop the request rather than fall back to "all
* tenants", which is how a single missing propagation turns into a cross-tenant read.
*/
public class GraphQlTenantIsolationException extends RuntimeException {
public class GraphQlTenantIsolationException extends RuntimeException
implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L;
@@ -18,4 +24,23 @@ public class GraphQlTenantIsolationException extends RuntimeException {
public GraphQlTenantIsolationException(String message) {
super(message);
}
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.platform(GraphQlErrorCode.RESOURCE_NOT_FOUND);
}
@Override
public Category failureCategory() {
return Category.NOT_FOUND;
}
/**
* Deliberately the same shape as an authorization denial: telling a caller that the resource
* exists in another tenant is the disclosure the isolation rule exists to prevent.
*/
@Override
public GraphQlErrorCategory wireCategory() {
return GraphQlErrorCategory.AUTHORIZATION;
}
}
@@ -198,7 +198,7 @@ class GraphQlPlatformExecutionPathTest {
void anOversizeDocumentIsRejectedBeforeItIsParsed() {
ResponseEntity<String> response = post("{ platformStamp } # " + "x".repeat(20_000));
assertThatRejected(response, "REQUEST_ERROR");
assertThatRejected(response, "PAYLOAD_TOO_LARGE");
}
@Test
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.adapter.inbound.graphql.testkit.GraphQlRequestContexts;
import dev.caskeleton.shared.error.OperationalError;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@@ -56,7 +57,11 @@ class GraphQlBatchContractTest {
@Test
void aFailedKeyStaysDistinctFromAMissingOne() {
GraphQlBatchResult<String, String> result =
mapper.map(List.of("a", "b"), Map.of("a", "value-a"), java.util.Set.of("b"), "UPSTREAM");
mapper.map(
List.of("a", "b"),
Map.of("a", "value-a"),
java.util.Set.of("b"),
OperationalError.DEPENDENCY_5XX_SERVER);
assertThat(result.values().get("a")).isInstanceOf(GraphQlBatchValue.Present.class);
assertThat(result.values().get("b")).isInstanceOf(GraphQlBatchValue.Failed.class);
@@ -3,6 +3,8 @@ package dev.caskeleton.adapter.inbound.graphql.dataloader;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.Category;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@@ -12,6 +14,31 @@ import org.junit.jupiter.api.Test;
/** Missing-key and per-key error batch results (Stable plan Task 38). */
class GraphQlBatchResultMapperTest {
/** An adopter-registered code, the only kind a failed key may carry (owner decision 25). */
enum OrderError implements ApiErrorCode {
ORDER_LOAD_FAILED;
@Override
public String code() {
return name();
}
@Override
public Category category() {
return Category.TRANSIENT_DEPENDENCY;
}
@Override
public int httpStatus() {
return 503;
}
@Override
public boolean retryable() {
return true;
}
}
@Test
void distinguishesMissingFromFailure() {
var mapper = new GraphQlBatchResultMapper();
@@ -28,9 +55,14 @@ class GraphQlBatchResultMapperTest {
var mapper = new GraphQlBatchResultMapper();
var result =
mapper.map(List.of("a", "b", "c"), Map.of("a", "value"), Set.of("c"), "ORDER_LOAD_FAILED");
mapper.map(
List.of("a", "b", "c"),
Map.of("a", "value"),
Set.of("c"),
OrderError.ORDER_LOAD_FAILED);
assertThat(result.values().get("c")).isEqualTo(GraphQlBatchValue.failed("ORDER_LOAD_FAILED"));
assertThat(result.values().get("c"))
.isEqualTo(GraphQlBatchValue.failed(OrderError.ORDER_LOAD_FAILED));
assertThat(result.failedKeys()).containsExactly("c");
assertThat(result.values().get("a").resolved()).isTrue();
assertThat(result.values().get("b").failed()).isFalse();
@@ -41,7 +73,8 @@ class GraphQlBatchResultMapperTest {
var mapper = new GraphQlBatchResultMapper();
var result =
mapper.map(List.of("a", "b"), Map.of("a", "value"), Set.of("b"), "ORDER_LOAD_FAILED");
mapper.map(
List.of("a", "b"), Map.of("a", "value"), Set.of("b"), OrderError.ORDER_LOAD_FAILED);
assertThat(result.values().get("a")).isEqualTo(GraphQlBatchValue.present("value"));
}
@@ -89,7 +122,7 @@ class GraphQlBatchResultMapperTest {
@Test
void errorMessagesNeverContainTheKey() {
var mapper = new GraphQlBatchResultMapper();
GraphQlBatchValue<String> failed = GraphQlBatchValue.failed("ORDER_LOAD_FAILED");
GraphQlBatchValue<String> failed = GraphQlBatchValue.failed(OrderError.ORDER_LOAD_FAILED);
assertThatThrownBy(() -> mapper.resolve(failed, GraphQlMissingKeyPolicy.NULL_VALUE))
.isInstanceOf(GraphQlBatchLoadException.class)
@@ -0,0 +1,106 @@
package dev.caskeleton.adapter.inbound.graphql.error;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class GraphQlWireErrorMapperTest {
static Stream<Arguments> dataLoaderFailures() {
return Stream.of(
Arguments.of(
new GraphQlBatchTimeoutException("customer-by-id"), "REQUEST_TIMEOUT", "TIMEOUT"),
Arguments.of(new GraphQlMissingKeyException(), "GRAPHQL_BATCH_KEY_MISSING", "BUSINESS"));
}
@ParameterizedTest
@MethodSource("dataLoaderFailures")
@DisplayName("DataLoader 의 timeout·missing key 는 INTERNAL_ERROR 로 가려지지 않고 플랫폼 code 로 나간다")
void dataLoaderFailuresKeepAPlatformCode(
RuntimeException failure, String expectedCode, String expectedCategory) {
// given
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
// when
GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test());
// then
assertThat(error.extensions())
.extracting(extensions -> extensions.get("code"), extensions -> extensions.get("category"))
.containsExactly(expectedCode, expectedCategory);
}
@org.junit.jupiter.api.Test
void aCarrierIsRetryableOnlyWhenItsCodeIs() {
// given: a transient-dependency code that is deliberately not retryable
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
RuntimeException failure =
new dev.caskeleton.shared.error.PersistenceFailureException(
dev.caskeleton.shared.error.OperationalError.DB_QUERY_CANCELED, "canceled", null);
// when
GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test());
// then
assertThat(error.extensions())
.extracting(extensions -> extensions.get("code"), extensions -> extensions.get("retryable"))
.containsExactly("DB_QUERY_CANCELED", false);
}
@org.junit.jupiter.api.Test
void anIllegalArgumentIsABadParameterRequestError() {
// given
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
// when
GraphQlWireError error =
mapper.map(new IllegalArgumentException("secret"), GraphQlErrorContext.test());
// then
assertThat(error.extensions())
.extracting(extensions -> extensions.get("code"), extensions -> extensions.get("category"))
.containsExactly("BAD_PARAMETER", "REQUEST");
}
@org.junit.jupiter.api.Test
void anOversizedRequestIsPayloadTooLarge() {
// given
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
// when
GraphQlWireError error =
mapper.map(
new dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestTooLargeException(
"query exceeds the document limit"),
GraphQlErrorContext.test());
// then
assertThat(error.extensions().get("code")).isEqualTo("PAYLOAD_TOO_LARGE");
}
@org.junit.jupiter.api.Test
void aFailedBatchKeyKeepsItsRegisteredCode() {
// given
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
RuntimeException failure =
new dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchLoadException(
dev.caskeleton.shared.error.OperationalError.DEPENDENCY_TIMEOUT);
// when
GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test());
// then
assertThat(error.extensions())
.extracting(
extensions -> extensions.get("code"),
extensions -> extensions.get("category"),
extensions -> extensions.get("retryable"))
.containsExactly("DEPENDENCY_TIMEOUT", "DEPENDENCY", true);
}
}
@@ -6,6 +6,7 @@ import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionStage;
import graphql.ExecutionInput;
import graphql.GraphQL;
@@ -1,40 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireError;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class GraphQlWireErrorMapperTest {
static Stream<Arguments> dataLoaderFailures() {
return Stream.of(
Arguments.of(
new GraphQlBatchTimeoutException("customer-by-id"), "REQUEST_TIMEOUT", "TIMEOUT"),
Arguments.of(new GraphQlMissingKeyException(), "GRAPHQL_BATCH_KEY_MISSING", "BUSINESS"));
}
@ParameterizedTest
@MethodSource("dataLoaderFailures")
@DisplayName("DataLoader 의 timeout·missing key 는 INTERNAL_ERROR 로 가려지지 않고 플랫폼 code 로 나간다")
void dataLoaderFailuresKeepAPlatformCode(
RuntimeException failure, String expectedCode, String expectedCategory) {
// given
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
// when
GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test());
// then
assertThat(error.extensions())
.extracting(extensions -> extensions.get("code"), extensions -> extensions.get("category"))
.containsExactly(expectedCode, expectedCategory);
}
}
+5 -2
View File
@@ -76,8 +76,11 @@ handler throw, listener callback throw, `responseObserver.onError(...)`, raw
던지기만" 하고, 이 인터셉터가 와이어 계약을 단일 소유한다.
- **와이어 status(coarse)** 는 `GrpcStatusMapper.toStatus(Category)` 가 결정한다(HTTP status 가
coarse 인 것과 동형). 정확한 `code`/`category` 는 `Status` trailer `Metadata`(`error-code` /
`error-category`)에 실어 클라이언트가 switch 하게 한다.
coarse 인 것과 동형). 정확한 `code`/`category`/`retryable` 은 `Status` trailer `Metadata`
(`error-code` / `error-category` / `error-retryable`)에 실어 클라이언트가 switch 하게 한다.
`retryable` 은 코드의 값이다. status description 은 shared-contract `ClientErrorMessages` 의
Category 별 한국어 문구(web·GraphQL 과 같은 표)다.
- **`IllegalArgumentException`** 은 `BAD_PARAMETER`(`INVALID_ARGUMENT`) — 모든 전송이 같다.
- **`ApiErrorCode` 추출**: feature 예외는 `ApiErrorCarrier`(이 모듈이 제공하는 전송-중립 hook)를
구현해 자신의 `ApiErrorCode` 를 노출한다. shared-contract 의 `PersistenceFailureException` /
`DependencyFailureException`(outbound 어댑터에서 올라온 분류된 실패)도 직접 인식한다.
@@ -7,7 +7,6 @@ import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import java.security.Principal;
import java.util.Optional;
import org.slf4j.Logger;
@@ -41,7 +40,7 @@ final class GrpcAuthenticationInterceptor implements ServerInterceptor {
}
call.close(
Status.UNAUTHENTICATED.withDescription(OperationalError.UNAUTHENTICATED.code()),
statusMapper.statusFor(OperationalError.UNAUTHENTICATED),
statusMapper.trailersFor(OperationalError.UNAUTHENTICATED));
return new ServerCall.Listener<>() {};
}
@@ -23,9 +23,11 @@ import java.util.concurrent.atomic.AtomicBoolean;
* ApiErrorCarrier} hook — implemented by a feature throwable (the gRPC {@link ApiErrorException}
* carrying a mapped domain code) and by the shared-contract {@code PersistenceFailureException} /
* {@code DependencyFailureException}, so a single {@code instanceof ApiErrorCarrier} branch covers
* them all. An unrecognised exception or raw gRPC status maps to {@link Status#INTERNAL} with
* {@link OperationalError#INTERNAL_ERROR}. Only the stable code string reaches the client (via the
* status description and trailers) — raw descriptions and input trailers, which may carry a
* them all. An {@link IllegalArgumentException} maps to {@link OperationalError#BAD_PARAMETER}
* ({@code INVALID_ARGUMENT}), as on every other transport. Any other unrecognised exception or raw
* gRPC status maps to {@link Status#INTERNAL} with {@link OperationalError#INTERNAL_ERROR}. The
* client sees the stable code, category and retryability in the trailers and the shared category
* message as the status description — raw descriptions and input trailers, which may carry a
* SQLState or upstream detail, are never surfaced.
*/
public class GrpcExceptionHandlingInterceptor implements ServerInterceptor {
@@ -107,11 +109,12 @@ public class GrpcExceptionHandlingInterceptor implements ServerInterceptor {
ApiErrorCode code = errorCodeOf(status.getCause());
if (code == null) {
code = OperationalError.INTERNAL_ERROR;
code =
status.getCause() instanceof IllegalArgumentException
? OperationalError.BAD_PARAMETER
: OperationalError.INTERNAL_ERROR;
}
super.close(
statusMapper.toStatus(code.category()).withDescription(code.code()),
statusMapper.trailersFor(code));
super.close(statusMapper.statusFor(code), statusMapper.trailersFor(code));
}
};
}
@@ -2,15 +2,16 @@ package dev.caskeleton.adapter.inbound.grpc;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import io.grpc.Metadata;
import io.grpc.Status;
/**
* Pure translation of the 10-value operational {@link Category} SSOT to an {@link io.grpc.Status},
* plus helpers to carry the machine-readable {@code code} / {@code category} on the response
* trailer {@link Metadata}. This is the gRPC sibling of the web adapter's error contract: the wire
* status (like an HTTP status) is coarse, while the exact {@link ApiErrorCode#code()} and the
* category name ride in the trailers for the client to switch on.
* plus helpers to carry the machine-readable {@code code} / {@code category} / {@code retryable} on
* the response trailer {@link Metadata}. This is the gRPC sibling of the web adapter's error
* contract: the wire status (like an HTTP status) is coarse, while the exact {@link
* ApiErrorCode#code()} and the category name ride in the trailers for the client to switch on.
*
* <p>The classification table is fixed by the design spec's Error Mapping section; see README.
*/
@@ -26,6 +27,13 @@ public class GrpcStatusMapper {
static final Metadata.Key<String> CATEGORY_KEY =
Metadata.Key.of("error-category", Metadata.ASCII_STRING_MARSHALLER);
/**
* Trailer key carrying {@link ApiErrorCode#retryable()} as {@code true} / {@code false} — the
* code's own value, the same one the web Envelope and the GraphQL extension carry.
*/
static final Metadata.Key<String> RETRYABLE_KEY =
Metadata.Key.of("error-retryable", Metadata.ASCII_STRING_MARSHALLER);
/**
* Maps an operational {@link Category} to its gRPC {@link Status} (design Error-Mapping table).
*/
@@ -45,13 +53,23 @@ public class GrpcStatusMapper {
}
/**
* Writes the {@code code} and {@code category} of {@code errorCode} onto a fresh trailer {@link
* Metadata}, returned for {@code ServerCall#close(Status, Metadata)}.
* Writes the {@code code}, {@code category} and {@code retryable} of {@code errorCode} onto a
* fresh trailer {@link Metadata}, returned for {@code ServerCall#close(Status, Metadata)}.
*/
public Metadata trailersFor(ApiErrorCode errorCode) {
Metadata trailers = new Metadata();
trailers.put(CODE_KEY, errorCode.code());
trailers.put(CATEGORY_KEY, errorCode.category().name());
trailers.put(RETRYABLE_KEY, Boolean.toString(errorCode.retryable()));
return trailers;
}
/**
* The status for a code, described by the shared client message of its category ({@link
* ClientErrorMessages}) — the same wording the web and GraphQL transports send. The stable code
* rides in the trailers, never the exception text.
*/
public Status statusFor(ApiErrorCode errorCode) {
return toStatus(errorCode.category()).withDescription(ClientErrorMessages.of(errorCode));
}
}
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
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 dev.caskeleton.shared.error.PersistenceFailureException;
import io.grpc.Metadata;
@@ -58,6 +59,30 @@ class GrpcExceptionHandlingInterceptorTest {
assertThat(call.trailers.get(GrpcStatusMapper.CATEGORY_KEY)).isEqualTo("TRANSIENT_DEPENDENCY");
}
@Test
void mapsAnIllegalArgumentToInvalidArgumentBadParameter() {
// when
CapturingServerCall call = closeAfterThrowing(new IllegalArgumentException("secret value"));
// then
assertThat(call)
.extracting(
captured -> captured.status.getCode(),
captured -> captured.trailers.get(GrpcStatusMapper.CODE_KEY))
.containsExactly(Status.Code.INVALID_ARGUMENT, "BAD_PARAMETER");
}
@Test
void theStatusDescriptionIsTheSharedClientMessageOfTheCategory() {
// when
CapturingServerCall call =
closeAfterThrowing(new CarrierException(OperationalError.ROUTE_NOT_FOUND));
// then
assertThat(call.status.getDescription())
.isEqualTo(ClientErrorMessages.of(OperationalError.ROUTE_NOT_FOUND));
}
@Test
void mapsUnknownRuntimeExceptionToInternal() {
CapturingServerCall call = closeAfterThrowing(new IllegalStateException("boom"));
@@ -3,6 +3,8 @@ package dev.caskeleton.adapter.inbound.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import dev.caskeleton.shared.error.OperationalError;
import io.grpc.BindableService;
import io.grpc.CallOptions;
@@ -265,7 +267,8 @@ class GrpcP1BoundaryWireTest {
assertThat(failure).isNotNull();
assertThat(failure.getStatus().getCode()).isEqualTo(expectedStatus);
assertThat(failure.getStatus().getDescription()).isEqualTo(expectedCode);
assertThat(failure.getStatus().getDescription())
.isEqualTo(ClientErrorMessages.of(Category.valueOf(expectedCategory)));
assertThat(failure.getTrailers()).isNotNull();
assertThat(failure.getTrailers().get(GrpcStatusMapper.CODE_KEY)).isEqualTo(expectedCode);
assertThat(failure.getTrailers().get(GrpcStatusMapper.CATEGORY_KEY))
@@ -52,4 +52,16 @@ class GrpcStatusMapperTest {
assertThat(trailers.get(GrpcStatusMapper.CODE_KEY)).isEqualTo("RATE_LIMIT_EXCEEDED");
assertThat(trailers.get(GrpcStatusMapper.CATEGORY_KEY)).isEqualTo("RATE_LIMIT");
}
@Test
void trailersCarryTheRetryabilityOfTheCodeNotOfItsCategory() {
// given: a transient-dependency code that is deliberately not retryable
Metadata trailers = mapper.trailersFor(OperationalError.DB_QUERY_CANCELED);
// when
String retryable = trailers.get(GrpcStatusMapper.RETRYABLE_KEY);
// then
assertThat(retryable).isEqualTo("false");
}
}
@@ -4,8 +4,9 @@ package dev.caskeleton.adapter.inbound.web.fileserver.draft12;
* The draft's offset-mismatch problem document.
*
* <p>It reports both offsets so the client can resume without a second round trip. This shape is
* the draft's own and is intentionally not the Fileserver problem document: a draft revision must
* be able to change it without touching the Stable contract.
* the draft's own and is the single protocol exception to the application's one error shape, the
* {@code Envelope} (owner decision 12): a draft revision must be able to change it without touching
* the Stable contract.
*/
public record Draft12OffsetProblem(
String type, String title, int status, long expectedOffset, long providedOffset) {
@@ -162,8 +162,12 @@ public class Draft12UploadController {
/**
* Renders the draft's own offset-mismatch problem document.
*
* <p>The draft defines a specific problem type carrying both offsets; mapping this through the
* shared Fileserver problem handler would answer the right status with the wrong body.
* <p><strong>Protocol exception to the Envelope rule.</strong> Every other HTTP failure in this
* application is an {@code Envelope} (owner decision 2); this one response is {@code
* application/problem+json} because the IETF resumable-upload draft registers the problem type
* and its two offset members, and a draft client resumes from them. It is treated like the tus
* protocol headers — part of the protocol, not an error vocabulary (owner decision 12). The
* exception list is kept in {@code docs/fileserver/http-contract.md}.
*/
@ExceptionHandler(UploadOffsetMismatchException.class)
public ResponseEntity<Draft12OffsetProblem> offsetMismatch(
@@ -1,16 +0,0 @@
package dev.caskeleton.adapter.inbound.web.fileserver.dto;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
/**
* Failure of one batch part, in the same vocabulary the single-file endpoints use.
*
* <p>Only the stable code and its problem URN are exposed; the server-side message never crosses
* this boundary.
*/
public record BatchUploadItemProblem(String code, String type, int status) {
public static BatchUploadItemProblem of(FileserverErrorCode code) {
return new BatchUploadItemProblem(code.name(), code.problemType(), code.httpStatus());
}
}
@@ -2,15 +2,19 @@ package dev.caskeleton.adapter.inbound.web.fileserver.dto;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
import dev.caskeleton.application.fileserver.upload.FileView;
import dev.caskeleton.shared.error.ClientErrorMessages;
import dev.caskeleton.shared.response.ApiError;
/**
* Result of one batch part.
*
* <p>A batch is explicitly non-atomic, so each part reports its own outcome and a failure never
* rolls back a sibling that already succeeded.
* 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.
*/
public record BatchUploadItemResult(
String clientPartId, String status, String fileId, BatchUploadItemProblem problem) {
String clientPartId, String status, String fileId, ApiError error) {
public static BatchUploadItemResult accepted(String clientPartId, FileView view) {
return new BatchUploadItemResult(
@@ -19,6 +23,10 @@ public record BatchUploadItemResult(
public static BatchUploadItemResult rejected(String clientPartId, FileserverErrorCode code) {
return new BatchUploadItemResult(
clientPartId, "REJECTED", null, BatchUploadItemProblem.of(code));
clientPartId,
"REJECTED",
null,
ApiError.of(
code.code(), code.category().name(), ClientErrorMessages.of(code), code.retryable()));
}
}
@@ -16,6 +16,6 @@ public record BatchUploadResponse(List<BatchUploadItemResult> results) {
/** True when every part succeeded, which the envelope layer reports as a plain success. */
public boolean fullySucceeded() {
return results.stream().allMatch(result -> result.problem() == null);
return results.stream().allMatch(result -> result.error() == null);
}
}
@@ -1,7 +1,11 @@
package dev.caskeleton.adapter.inbound.web.fileserver.problem;
import dev.caskeleton.adapter.inbound.web.error.ErrorResponseFactory;
import dev.caskeleton.application.fileserver.api.error.FileserverException;
import jakarta.servlet.http.HttpServletRequest;
import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext;
import dev.caskeleton.shared.response.Envelope;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
@@ -11,15 +15,24 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* Maps every Fileserver failure onto its design status and problem document.
* Maps every Fileserver failure onto the application's one error shape, the {@link Envelope}.
*
* <p>It is ordered ahead of the base operational handler, whose catch-all would otherwise resolve
* these to a generic internal error and lose the code. The status comes from the error code itself,
* so Spring MVC and the Nginx delegation path cannot drift apart.
* these to a generic internal error and lose the code. The status and code come from {@link
* dev.caskeleton.application.fileserver.api.error.FileserverErrorCode} itself, and the message from
* the shared category table, so Spring MVC and the Nginx delegation path cannot drift apart and no
* path can echo the server-side exception message.
*
* <p>Two headers are part of the contract rather than decoration: {@code Retry-After} on a
* retryable rejection, and the unsatisfied-range form of {@code Content-Range} on {@code 416},
* which is how a client learns the real representation length.
* <p>The failure's identifying values (file id, upload id, offsets, state) and the two flags a
* client must see before retrying — {@code ambiguous} and {@code reconciliationRequired}: the
* operation may already have taken effect — ride in {@code error.details}. {@code retryable} is
* this occurrence's decision, never wider than the code allows.
*
* <p>Protocol headers stay: {@code Retry-After} on a retryable rejection, the unsatisfied-range
* form of {@code Content-Range} on {@code 416}, and the tus headers the tus controller sets. The
* one body that is not an Envelope is the IETF resumable-upload draft's offset-mismatch problem
* document ({@code Draft12UploadController#offsetMismatch}) — a protocol-mandated shape kept as an
* explicit exception (owner decision 12).
*/
@RestControllerAdvice
@ConditionalOnProperty(
@@ -30,21 +43,31 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
@Order(Ordered.HIGHEST_PRECEDENCE)
public class FileserverExceptionHandler {
private final FileserverProblemFactory problemFactory;
public FileserverExceptionHandler(FileserverProblemFactory problemFactory) {
this.problemFactory = problemFactory;
}
@ExceptionHandler(FileserverException.class)
public ResponseEntity<FileserverProblem> handle(
FileserverException failure, HttpServletRequest request) {
FileserverProblem problem = problemFactory.create(failure.context(), request.getRequestURI());
public ResponseEntity<Envelope<Void>> handle(FileserverException failure) {
FileserverFailureContext context = failure.context();
ResponseEntity.BodyBuilder response =
ResponseEntity.status(problem.status()).contentType(MediaType.APPLICATION_PROBLEM_JSON);
ResponseEntity.status(context.code().httpStatus()).contentType(MediaType.APPLICATION_JSON);
// The header policy lives in FileserverProblemHeaders; this handler does not own it.
FileserverProblemHeaders.of(failure).forEach(response::header);
return response.body(problem);
return response.body(
ErrorResponseFactory.body(context.code(), context.retryable(), details(context)));
}
private static Map<String, Object> details(FileserverFailureContext context) {
Map<String, Object> details = new LinkedHashMap<>();
context.fileId().ifPresent(fileId -> details.put("fileId", fileId.canonicalText()));
context.uploadId().ifPresent(uploadId -> details.put("uploadId", uploadId.canonicalText()));
context.expectedOffset().ifPresent(offset -> details.put("expectedOffset", offset));
context.currentOffset().ifPresent(offset -> details.put("currentOffset", offset));
context.currentState().ifPresent(state -> details.put("state", state.name()));
if (context.ambiguous()) {
details.put("ambiguous", true);
}
if (context.reconciliationRequired()) {
details.put("reconciliationRequired", true);
}
return details.isEmpty() ? null : details;
}
}
@@ -1,32 +0,0 @@
package dev.caskeleton.adapter.inbound.web.fileserver.problem;
import com.fasterxml.jackson.annotation.JsonInclude;
/**
* RFC 9457 problem document for a Fileserver failure.
*
* <p>This is a transport-owned record rather than the framework's problem type, and it carries only
* the stable code plus the correlation fields the client can act on. The server-side exception
* message, physical path, mount, scanner credential, and filename never appear here.
*
* <p>{@code ambiguous} and {@code reconciliationRequired} are exposed deliberately: a client that
* gets an ambiguous failure must not blindly retry, because the operation may already have taken
* effect.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public record FileserverProblem(
String type,
String title,
int status,
String code,
String detail,
String instance,
String traceId,
boolean retryable,
boolean ambiguous,
boolean reconciliationRequired,
String fileId,
String uploadId,
Long expectedOffset,
Long currentOffset,
String state) {}
@@ -1,45 +0,0 @@
package dev.caskeleton.adapter.inbound.web.fileserver.problem;
import dev.caskeleton.adapter.inbound.web.observability.MdcKeys;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext;
import java.util.OptionalLong;
import org.slf4j.MDC;
/**
* Builds the wire problem document from a failure context.
*
* <p>Everything the client sees is derived from the context — never from the exception message — so
* no code path can accidentally widen what a failure discloses.
*/
public final class FileserverProblemFactory {
public FileserverProblem create(FileserverFailureContext context, String instance) {
FileserverErrorCode code = context.code();
return new FileserverProblem(
code.problemType(),
FileserverProblemTitles.titleOf(code),
code.httpStatus(),
code.name(),
FileserverProblemTitles.titleOf(code),
instance,
traceId(),
context.retryable(),
context.ambiguous(),
context.reconciliationRequired(),
context.fileId().map(fileId -> fileId.canonicalText()).orElse(null),
context.uploadId().map(uploadId -> uploadId.canonicalText()).orElse(null),
boxed(context.expectedOffset()),
boxed(context.currentOffset()),
context.currentState().map(Enum::name).orElse(null));
}
private static Long boxed(OptionalLong value) {
return value.isPresent() ? value.getAsLong() : null;
}
private static String traceId() {
String traceId = MDC.get(MdcKeys.TRACE_ID);
return traceId == null || traceId.isBlank() ? null : traceId;
}
}
@@ -1,55 +0,0 @@
package dev.caskeleton.adapter.inbound.web.fileserver.problem;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
import java.util.EnumMap;
import java.util.Map;
/**
* Client-safe wording for every failure code.
*
* <p>The server-side exception message is log-only, so the wire needs its own vocabulary. Keeping
* it in one table is what stops a future handler from quietly echoing {@code getMessage()} — which
* is how storage paths and scanner responses leak into responses.
*/
final class FileserverProblemTitles {
private static final Map<FileserverErrorCode, String> TITLES =
new EnumMap<>(
Map.ofEntries(
Map.entry(FileserverErrorCode.BAD_REQUEST, "Malformed request"),
Map.entry(FileserverErrorCode.UNAUTHENTICATED, "Authentication required"),
Map.entry(FileserverErrorCode.ACCESS_DENIED, "Access denied"),
Map.entry(FileserverErrorCode.FILE_NOT_FOUND, "File not found"),
Map.entry(FileserverErrorCode.FILE_ALREADY_EXISTS, "File already exists"),
Map.entry(FileserverErrorCode.FILE_NOT_READY, "File is not ready"),
Map.entry(FileserverErrorCode.UPLOAD_OFFSET_MISMATCH, "Upload offset mismatch"),
Map.entry(FileserverErrorCode.CONCURRENT_MODIFICATION, "Concurrent modification"),
Map.entry(FileserverErrorCode.UPLOAD_EXPIRED, "Upload resource has expired"),
Map.entry(FileserverErrorCode.CONTENT_LENGTH_REQUIRED, "Content-Length is required"),
Map.entry(FileserverErrorCode.PRECONDITION_FAILED, "Precondition failed"),
Map.entry(FileserverErrorCode.FILE_TOO_LARGE, "File is too large"),
Map.entry(FileserverErrorCode.QUOTA_EXCEEDED, "Storage quota exceeded"),
Map.entry(FileserverErrorCode.UNSUPPORTED_MEDIA_TYPE, "Unsupported media type"),
Map.entry(FileserverErrorCode.RANGE_NOT_SATISFIABLE, "Range not satisfiable"),
Map.entry(FileserverErrorCode.INTEGRITY_MISMATCH, "Content integrity mismatch"),
Map.entry(FileserverErrorCode.MALWARE_DETECTED, "Content was rejected"),
Map.entry(FileserverErrorCode.INVALID_PATH, "Invalid path"),
Map.entry(FileserverErrorCode.PATH_OUTSIDE_NAMESPACE, "Path outside namespace"),
Map.entry(FileserverErrorCode.TRANSFER_ADMISSION_REJECTED, "Too many transfers"),
Map.entry(FileserverErrorCode.CHECKSUM_MISMATCH, "Checksum mismatch"),
Map.entry(FileserverErrorCode.PARTIAL_WRITE, "Transfer did not complete"),
Map.entry(
FileserverErrorCode.AMBIGUOUS_COMPLETION, "Completion could not be confirmed"),
Map.entry(
FileserverErrorCode.ATOMIC_PUBLISH_UNSUPPORTED,
"Storage cannot publish atomically"),
Map.entry(FileserverErrorCode.STORAGE_UNAVAILABLE, "Storage is unavailable"),
Map.entry(FileserverErrorCode.TRANSFER_TIMEOUT, "Transfer timed out"),
Map.entry(FileserverErrorCode.STORAGE_FULL, "Storage is full")));
private FileserverProblemTitles() {}
static String titleOf(FileserverErrorCode code) {
return TITLES.getOrDefault(code, "Request failed");
}
}
@@ -11,7 +11,6 @@ import dev.caskeleton.adapter.inbound.web.fileserver.http.MvcConditionalRequestF
import dev.caskeleton.adapter.inbound.web.fileserver.http.MvcDownloadResponseWriter;
import dev.caskeleton.adapter.inbound.web.fileserver.http.ZeroCopyEligibility;
import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverExceptionHandler;
import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverProblemFactory;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.FileserverWebFixtures;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.StubDownloadService;
import dev.caskeleton.application.fileserver.api.FileState;
@@ -40,7 +39,7 @@ class FileDownloadControllerContractTest {
FileserverWebFixtures.transferExecutor(),
FileserverWebFixtures.noDelegation(),
ZeroCopyEligibility.disabled()))
.setControllerAdvice(new FileserverExceptionHandler(new FileserverProblemFactory()))
.setControllerAdvice(new FileserverExceptionHandler())
.build();
}
@@ -177,20 +176,20 @@ class FileDownloadControllerContractTest {
mvc.perform(get(contentUrl()))
.andExpect(status().isConflict())
.andExpect(header().string("Content-Type", "application/problem+json"));
.andExpect(header().string("Content-Type", "application/json"));
assertThat(downloadService.neverOpened()).isTrue();
}
@Test
void aProblemResponseNeverEchoesTheServerSideMessage() throws Exception {
void aFailureResponseNeverEchoesTheServerSideMessage() throws Exception {
downloadService.fileInState(FileState.QUARANTINED);
String body = mvc.perform(get(contentUrl())).andReturn().getResponse().getContentAsString();
assertThat(body).contains("\"code\":\"FILE_NOT_READY\"");
assertThat(body).contains("urn:fileserver:problem:file-not-ready");
assertThat(body).doesNotContain("publicly readable state");
assertThat(body)
.contains("\"code\":\"FILE_NOT_READY\"")
.doesNotContain("publicly readable state");
}
@Test
@@ -164,8 +164,8 @@ class FileUploadControllerTest {
.andExpect(status().isOk())
.andExpect(jsonPath("$.results[0].status").value("READY"))
.andExpect(jsonPath("$.results[1].status").value("REJECTED"))
.andExpect(jsonPath("$.results[1].problem.code").value("FILE_TOO_LARGE"))
.andExpect(jsonPath("$.results[1].problem.status").value(413));
.andExpect(jsonPath("$.results[1].error.code").value("FILE_TOO_LARGE"))
.andExpect(jsonPath("$.results[1].error.category").value("VALIDATION"));
}
@Test
@@ -8,7 +8,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverExceptionHandler;
import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverProblemFactory;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.FileserverWebFixtures;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.InMemoryUploadApplicationService;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.RecordingFinalizeService;
@@ -41,7 +40,7 @@ class Draft12ProtocolTest {
FileserverWebFixtures.properties(),
DRAFT,
FileserverWebFixtures.clock()))
.setControllerAdvice(new FileserverExceptionHandler(new FileserverProblemFactory()))
.setControllerAdvice(new FileserverExceptionHandler())
.build();
}
@@ -11,7 +11,6 @@ import dev.caskeleton.adapter.inbound.web.fileserver.http.MvcConditionalRequestF
import dev.caskeleton.adapter.inbound.web.fileserver.http.MvcDownloadResponseWriter;
import dev.caskeleton.adapter.inbound.web.fileserver.http.ZeroCopyEligibility;
import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverExceptionHandler;
import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverProblemFactory;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.FileserverWebFixtures;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.StubDownloadService;
import dev.caskeleton.application.fileserver.api.FileState;
@@ -108,7 +107,7 @@ class NginxDownloadDelegationTest {
new NginxDownloadStrategy(
properties, new DefaultNginxInternalUriMapper(properties)),
ZeroCopyEligibility.disabled()))
.setControllerAdvice(new FileserverExceptionHandler(new FileserverProblemFactory()))
.setControllerAdvice(new FileserverExceptionHandler())
.build();
}
@@ -14,7 +14,6 @@ import dev.caskeleton.adapter.inbound.web.fileserver.http.ZeroCopyEligibility;
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.problem.FileserverExceptionHandler;
import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverProblemFactory;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.FileserverWebFixtures;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.RecordingUploadService;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.StubDownloadService;
@@ -42,7 +41,7 @@ class FileserverHardeningContractTest {
FileserverWebFixtures.transferExecutor(),
FileserverWebFixtures.properties(),
FileserverWebFixtures.clock()))
.setControllerAdvice(new FileserverExceptionHandler(new FileserverProblemFactory()))
.setControllerAdvice(new FileserverExceptionHandler())
.build();
private final MockMvc downloadMvc =
@@ -56,7 +55,7 @@ class FileserverHardeningContractTest {
FileserverWebFixtures.transferExecutor(),
FileserverWebFixtures.noDelegation(),
ZeroCopyEligibility.disabled()))
.setControllerAdvice(new FileserverExceptionHandler(new FileserverProblemFactory()))
.setControllerAdvice(new FileserverExceptionHandler())
.build();
@ParameterizedTest
@@ -147,7 +146,7 @@ class FileserverHardeningContractTest {
}
@Test
void aProblemDocumentNeverExposesAPathOrAJavaType() throws Exception {
void aFailureResponseNeverExposesAPathOrAJavaType() throws Exception {
downloads.fileInState(dev.caskeleton.application.fileserver.api.FileState.VERIFYING);
String body =
@@ -166,19 +165,24 @@ class FileserverHardeningContractTest {
}
@Test
void theProblemDocumentCarriesTheStableCodeAndItsUrn() throws Exception {
void aFailureIsTheSharedEnvelopeCarryingTheStableCode() throws Exception {
downloads.fileInState(dev.caskeleton.application.fileserver.api.FileState.VERIFYING);
downloadMvc
.perform(get(contentUrl()))
.andExpect(status().isConflict())
.andExpect(header().string("Content-Type", "application/problem+json"))
.andExpect(header().string("Content-Type", "application/json"))
.andExpect(
org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.code")
org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.success")
.value(false))
.andExpect(
org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath(
"$.error.code")
.value("FILE_NOT_READY"))
.andExpect(
org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.type")
.value("urn:fileserver:problem:file-not-ready"));
org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath(
"$.error.details.state")
.value("VERIFYING"));
}
@Test
@@ -10,7 +10,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverExceptionHandler;
import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverProblemFactory;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.FileserverWebFixtures;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.InMemoryUploadApplicationService;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.RecordingFinalizeService;
@@ -48,7 +47,7 @@ class TusProtocolContractTest {
FileserverWebFixtures.properties(),
TUS,
FileserverWebFixtures.clock()))
.setControllerAdvice(new FileserverExceptionHandler(new FileserverProblemFactory()))
.setControllerAdvice(new FileserverExceptionHandler())
.build();
}
+1 -1
View File
@@ -186,7 +186,7 @@ above and is enforced by ArchUnit + contract tests (not new runtime mechanism).
**client-safe message only**. The raw SQL, constraint/index name, SQLState code,
exception class, and stack frame must never reach `error.message` or
`error.details`. The base `GlobalExceptionHandler` catch-all already replaces the
message with `"Internal server error"` and emits `null` details; the
message with the opaque shared message (`ClientErrorMessages.OPAQUE`) and emits `null` details; the
category-correct mapping (23505 → `CONFLICT/DB_UNIQUE_VIOLATION`, …) is owned by
`feature-persistence-failure-baseline`'s persistence-adapter translator.
- **C8 — Duplicate validation needs a canonical owner.** The same rule MAY be
+22 -12
View File
@@ -176,13 +176,19 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
Spring 이 두 advice 를 합성(compose)한다(CLAUDE.md 의 `@Order(HIGHEST_PRECEDENCE)` 규칙 참조).
- **클라이언트 메시지는 allowlist다.** 예외 메시지, validation interpolated message, rejected
request value, raw request URL은
`error.message`/`details`에 넣지 않는다. `ClientSafeErrorMessages`의 코드별 고정 문구와
정규화된 server-owned field, allowlisted reason code/fixed message, expectedType,
supported-method 같은 bounded 구조 메타데이터만 공개한다. collection/map index와 key는 field
path에서 제거한다.
- 코드별 문구가 명시되지 않은 operational code는 category 기반 고정 문구로 fail-closed 한다. 이
fallback은 새 코드를 실수로 진단 문자열에 연결하는 대신 transient/conflict/data-integrity 또는
`Internal server error`만 공개한다.
`error.message`/`details`에 넣지 않는다. `error.message`는 항상 shared-contract
`ClientErrorMessages`의 Category 별 한국어 문구다(소유자 결정 11 — GraphQL·gRPC 도 같은 표).
`ErrorResponseFactory`는 message 인자를 받지 않으므로 호출자가 문구를 만들 수 없다. 더 알려야 할
것은 정규화된 server-owned field, allowlisted reason code/fixed message, expectedType, parameter,
supported-method 같은 bounded 구조 메타데이터로 `details`에 둔다. collection/map index와 key는
field path에서 제거한다.
- `ApiErrorCarrier`(shared `MappingException`·`AdapterDisabledException`·`PersistenceFailureException`·
`DependencyFailureException`, application 멱등성 예외, adopter 예외)는 `handleCarrier` 분기
하나로 매핑한다. 5xx 는 원인과 함께 로그를 남기고(persistence 는 분류만), retryable 코드는
`RetryAfterAdvisor`로 `Retry-After`를 붙인다.
- 개별 override 가 없는 Spring MVC 예외(필수 파라미터·헤더·part 누락, binding 실패 등)는
`handleExceptionInternal` override 가 상태 코드 → `OperationalError`로 바꿔 같은 Envelope 로 보낸다.
`application/problem+json`은 나가지 않는다(I-3a).
- `adapter-web` 에 위치하는 이유: 실행 앱이 어떤 sample 모듈에도 의존하지 않고 envelope 형식 에러 응답을
제공하도록.
- **`spanErrorRecorder`.** 프로덕션 코드를 특정 트레이서
@@ -196,19 +202,21 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
| 예외 | 코드 | 상태 | 근거 |
|---|---|---|---|
| `MappingException` | `MAPPING_FAILED` | 400 | B3: 매퍼 내부 실패는 `MAPPING_FAILED` 로, `BAD_PARAMETER`/`INTERNAL_ERROR` 로 보내지 않음 |
| `AdapterDisabledException` | `ADAPTER_DISABLED` | 500 (retryable=false) | Layer 3 런타임 fail-fast(integration-adapter-templates §4/D4). 시작-수명주기용 `REQUIRED_ADAPTER_DISABLED` 가 아님(§Audit A2). 예외 메시지의 어댑터 이름은 서버 로그용, 클라이언트는 `client_safe_message` 만 |
| `AdapterDisabledException` | `ADAPTER_DISABLED` | 500 (retryable=false) | Layer 3 런타임 fail-fast(integration-adapter-templates §4/D4). 시작-수명주기용 `REQUIRED_ADAPTER_DISABLED` 가 아님(§Audit A2). 예외 메시지의 어댑터 이름은 서버 로그용, 클라이언트는 category 문구만 |
| `IllegalArgumentException` | `BAD_PARAMETER` | 400 | B3: 매퍼가 아닌 호출자의 일반 예외 |
| `ConstraintViolationException` | `VALIDATION_FAILED` | 400 | 정규화된 field + allowlisted reason code/fixed message 리스트를 details 로. interpolated message와 iterable key/index는 미노출 |
| `MethodArgumentTypeMismatchException` | `BAD_PARAMETER` | 400 | expectedType 을 details 로 |
| `MethodArgumentTypeMismatchException` | `BAD_PARAMETER` | 400 | parameter·expectedType 을 details 로 |
| `InvalidBearerTokenException` | `INVALID_TOKEN` | 코드 상태 | |
| `AuthenticationException` | `UNAUTHENTICATED` | 코드 상태 | |
| `AccessDeniedException` | `SecurityErrorClassifier` 결정(예: `AUTHZ_INSUFFICIENT_PERMISSION`) | 분류기 결정 | 메서드-시큐리티 거부가 컨트롤러를 빠져나오면 여기 도달. 필터 계층 `EnvelopeAccessDeniedHandler` 와 **동일한 세분화 코드**를 내도록 무상태 classifier 에 위임 |
| `PreconditionFailedException` | `PRECONDITION_FAILED` | 412 | D15: `If-Match` 불일치 쓰기 = 낙관적 동시성 충돌 → 412 (raw 409/500 금지) |
| `PageValidationException` | `VALIDATION_FAILED` | 400 | D18/D20/D21: 계약 범위 밖 페이지/정렬/필터 파라미터. field + reasonCode 를 details 로 |
| `IdempotencyUnavailableException` | `IDEMPOTENCY_UNAVAILABLE` | 503 (retryable=true) | 조정 저장소가 응답하지 않아 action 전에 거부. carrier 분기 |
| `IdempotencyRecoveryRequiredException` | `IDEMPOTENCY_RECOVERY_REQUIRED` | 500 (retryable=false) | 이전 시도의 외부 효과 여부를 판단할 수 없음. carrier 분기 |
| `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=false) | 같은 scope 의 다른 시도가 아직 처리 중(executor 는 기다리지 않는다). 진단정보(scope digest)는 클라이언트 미도달 |
| `IdempotencyRequestMismatchException` | `IDEMPOTENT_REQUEST_MISMATCH` | 422 | D8: `Idempotency-Key` 를 다른 본문으로 재사용. fingerprint/scope 노출 금지 |
| `PersistenceFailureException` | `ex.errorCode()` (사전분류 `DB_*`) | 코드 결정 | adapter-persistence translator 가 SQLState→`DB_*` 로 이미 분류. 클라이언트 메시지는 category-derived 안전 문자열, **절대 `ex.getMessage()` 아님**(SQLState/제약명 담음, 서버 로그 전용) |
| `DependencyFailureException` | `ex.errorCode()` (사전분류 `DEPENDENCY_*`) | 코드 결정 | adapter-outbound `OutboundHttpErrorMapper` 가 upstream 실패를 분류. 클라이언트 메시지는 per-code 고정 문자열(error-codes.yaml), **절대 `ex.getMessage()` 아님**. retryable + `retry_after_seconds` 있으면 `RetryAfterAdvisor` 로 `Retry-After` 부착 |
| `PersistenceFailureException` (JPA `JpaPersistenceException` 포함) | `ex.errorCode()` (사전분류 `DB_*`) | 코드 결정 | adapter-persistence translator 가 SQLState→`DB_*` 로 이미 분류, JPA 예외는 `FailureCategory`→`DB_*`. 클라이언트 메시지는 category 문구, **절대 `ex.getMessage()` 아님**(SQLState/제약명 담음, 서버 로그 전용) |
| `DependencyFailureException` | `ex.errorCode()` (사전분류 `DEPENDENCY_*`) | 코드 결정 | adapter-outbound `OutboundHttpErrorMapper` 가 upstream 실패를 분류. 클라이언트 메시지는 category 문구, **절대 `ex.getMessage()` 아님**. retryable + `retry_after_seconds` 있으면 `RetryAfterAdvisor` 로 `Retry-After` 부착 |
| `HttpRequestMethodNotSupportedException` | `METHOD_NOT_ALLOWED` | 405 | D12: 405 는 지원 메서드를 나열한 `Allow` 헤더 필수 |
| `HttpMediaTypeNotSupportedException` | `UNSUPPORTED_MEDIA_TYPE` | 415 | D9: 요청 본문 형식 미지원 — 406 과 구별 |
| `MaxUploadSizeExceededException` | `PAYLOAD_TOO_LARGE` | 413 | D8: 과대 본문은 envelope 내 413, raw 500 금지. 멀티파트 전용 413(`UPLOAD_SIZE_EXCEEDED`)은 이 영역의 책임 — 병합 후 정제 |
@@ -216,7 +224,9 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
| `MethodArgumentNotValidException` | `VALIDATION_FAILED` | 코드 상태 | 정규화된 field + allowlisted reason code/fixed message 리스트를 details 로. rejectedValue/defaultMessage/iterable key/index는 secret/PII 가능성이 있어 미노출 |
| `HttpMessageNotReadableException` | `VALIDATION_FAILED` | 코드 상태 | cause 클래스명을 details 로 |
| `NoHandlerFoundException`, `NoResourceFoundException` | `ROUTE_NOT_FOUND` | 코드 상태 | controller/static-resource 어느 404 경로도 같은 Envelope를 사용하고 raw request URL을 echo하지 않음 |
| `Exception` (catch-all) | `INTERNAL_ERROR` | 500 | span 에러 기록 + "Internal server error" 고정 메시지 |
| 그 밖의 Spring MVC 예외(`MissingServletRequestParameterException`, `MissingRequestHeaderException`, `MissingServletRequestPartException`, `ServletRequestBindingException` …) | 상태 → `OperationalError`(4xx 는 대개 `BAD_PARAMETER`) | 코드 상태 | `handleExceptionInternal` override. problem+json 이 새지 않게 |
| `ApiErrorCarrier` (위에 없는 adopter 예외 포함) | `errorCode()` | 코드 결정 | `handleCarrier` 한 분기 |
| `Exception` (catch-all) | `INTERNAL_ERROR` | 500 | span 에러 기록 + 불투명 문구(`ClientErrorMessages.OPAQUE`) |
### ErrorResponseFactory
- 기반 운영 핸들러와 모든 도메인 핸들러가 **공유**하여 envelope 형식이 정확히 한 곳에서만 만들어지게
@@ -8,7 +8,6 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
@@ -24,16 +23,6 @@ class AuthErrorResponseWriter {
private static final Logger log = LoggerFactory.getLogger(AuthErrorResponseWriter.class);
/** Client-safe messages, aligned with the registry {@code client_safe_message} column. */
private static final Map<OperationalError, String> CLIENT_MESSAGES =
Map.of(
OperationalError.AUTH_TOKEN_MISSING, "Authentication required",
OperationalError.AUTH_TOKEN_EXPIRED, "Authentication expired",
OperationalError.AUTH_KID_UNKNOWN, "Authentication failed, please retry",
OperationalError.AUTH_JWKS_UNAVAILABLE, "Authentication service temporarily unavailable",
OperationalError.AUTHZ_INSUFFICIENT_PERMISSION, "Permission denied",
OperationalError.AUTHZ_TENANT_MISMATCH, "Permission denied");
private final ObjectMapper objectMapper;
AuthErrorResponseWriter(ObjectMapper objectMapper) {
@@ -66,11 +55,7 @@ class AuthErrorResponseWriter {
.ifPresent(
seconds -> response.setHeader(HttpHeaders.RETRY_AFTER, Integer.toString(seconds)));
Envelope<Void> body = ErrorResponseFactory.body(code, clientMessage(code), null);
Envelope<Void> body = ErrorResponseFactory.body(code, null);
objectMapper.writeValue(response.getWriter(), body);
}
private String clientMessage(OperationalError code) {
return CLIENT_MESSAGES.getOrDefault(code, "Authentication failed");
}
}
@@ -1,65 +0,0 @@
package dev.caskeleton.adapter.inbound.web.error;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.Category;
final class ClientSafeErrorMessages {
private ClientSafeErrorMessages() {}
static String forOperational(ApiErrorCode code) {
return switch (code.code()) {
case "MAPPING_FAILED" -> "Request data could not be mapped";
case "BAD_PARAMETER" -> "Request parameter is invalid";
case "VALIDATION_FAILED" -> "Request validation failed";
case "INVALID_TOKEN",
"AUTH_TOKEN_MALFORMED",
"AUTH_TOKEN_EXPIRED",
"AUTH_TOKEN_INVALID_SIGNATURE",
"AUTH_ISSUER_MISMATCH",
"AUTH_AUDIENCE_MISMATCH",
"AUTH_KID_UNKNOWN",
"AUTH_CLAIM_MAPPING_FAILED" ->
"Authentication token is invalid";
case "UNAUTHENTICATED", "AUTH_TOKEN_MISSING" -> "Authentication is required";
case "FORBIDDEN",
"AUTHZ_INSUFFICIENT_PERMISSION",
"AUTHZ_TENANT_MISMATCH",
"ACTUATOR_FORBIDDEN" ->
"Access is denied";
case "AUTH_JWKS_UNAVAILABLE" ->
"Authentication service temporarily unavailable, please retry";
case "PRECONDITION_FAILED" -> "Resource state changed; refresh and retry";
case "METHOD_NOT_ALLOWED" -> "HTTP method is not allowed for this route";
case "NOT_ACCEPTABLE" -> "No acceptable response representation is available";
case "PAYLOAD_TOO_LARGE" -> "Request payload exceeds the maximum allowed size";
case "UNSUPPORTED_MEDIA_TYPE" -> "Request content type is not supported";
case "ROUTE_NOT_FOUND" -> "Requested route was not found";
case "ADAPTER_DISABLED", "INTERNAL_ERROR", "INTERNAL_AUTH_MISCONFIGURATION" ->
"Internal server error";
default -> forPersistence(code.category());
};
}
static String forPersistence(Category category) {
return switch (category) {
case TRANSIENT_DEPENDENCY -> "Service temporarily unavailable, please retry later";
case CONFLICT -> "Request conflicted with the current state, please retry";
case DATA_INTEGRITY -> "Request violates a data constraint";
default -> "Internal server error";
};
}
static String forDependency(ApiErrorCode code) {
return switch (code.code()) {
case "DEPENDENCY_TIMEOUT" -> "Upstream service did not respond in time, please retry";
case "DEPENDENCY_CONNECT_FAILED" -> "Upstream service unreachable, please retry";
case "DEPENDENCY_DNS_FAILED" -> "Upstream service unreachable, please retry";
case "DEPENDENCY_4XX_CLIENT" -> "Upstream service rejected the request";
case "DEPENDENCY_5XX_SERVER" -> "Upstream service error, please retry";
case "DEPENDENCY_CIRCUIT_OPEN" ->
"Upstream service temporarily unavailable, please retry later";
default -> forPersistence(code.category());
};
}
}
@@ -14,33 +14,31 @@ import org.springframework.validation.ObjectError;
*/
final class ClientSafeValidationDetails {
private static final Rule INVALID = new Rule("INVALID", "Invalid value");
private static final Rule INVALID = new Rule("INVALID", "값이 올바르지 않습니다.");
private static final Map<String, Rule> RULES =
Map.ofEntries(
Map.entry("NotNull", new Rule("NOT_NULL", "Required value is missing")),
Map.entry("NotBlank", new Rule("NOT_BLANK", "Value must not be blank")),
Map.entry("NotEmpty", new Rule("NOT_EMPTY", "Value must not be empty")),
Map.entry("Size", new Rule("SIZE", "Value size is outside the allowed range")),
Map.entry("Min", new Rule("MIN", "Value is below the allowed minimum")),
Map.entry("DecimalMin", new Rule("MIN", "Value is below the allowed minimum")),
Map.entry("Max", new Rule("MAX", "Value exceeds the allowed maximum")),
Map.entry("DecimalMax", new Rule("MAX", "Value exceeds the allowed maximum")),
Map.entry("Positive", new Rule("POSITIVE", "Value must be positive")),
Map.entry("PositiveOrZero", new Rule("POSITIVE_OR_ZERO", "Value must not be negative")),
Map.entry("Negative", new Rule("NEGATIVE", "Value must be negative")),
Map.entry("NegativeOrZero", new Rule("NEGATIVE_OR_ZERO", "Value must not be positive")),
Map.entry("Pattern", new Rule("PATTERN", "Value has an invalid format")),
Map.entry("Email", new Rule("EMAIL", "Value has an invalid format")),
Map.entry("Past", new Rule("PAST", "Value must be in the past")),
Map.entry(
"PastOrPresent", new Rule("PAST_OR_PRESENT", "Value must not be in the future")),
Map.entry("Future", new Rule("FUTURE", "Value must be in the future")),
Map.entry(
"FutureOrPresent", new Rule("FUTURE_OR_PRESENT", "Value must not be in the past")),
Map.entry("AssertTrue", new Rule("ASSERT_TRUE", "Value must be true")),
Map.entry("AssertFalse", new Rule("ASSERT_FALSE", "Value must be false")),
Map.entry("typeMismatch", new Rule("TYPE_MISMATCH", "Value has an invalid type")));
Map.entry("NotNull", new Rule("NOT_NULL", "필수 값이 없습니다.")),
Map.entry("NotBlank", new Rule("NOT_BLANK", "값이 비어 있으면 안 됩니다.")),
Map.entry("NotEmpty", new Rule("NOT_EMPTY", "값이 비어 있으면 안 됩니다.")),
Map.entry("Size", new Rule("SIZE", "값의 크기가 허용 범위를 벗어났습니다.")),
Map.entry("Min", new Rule("MIN", "값이 허용된 최솟값보다 작습니다.")),
Map.entry("DecimalMin", new Rule("MIN", "값이 허용된 최솟값보다 작습니다.")),
Map.entry("Max", new Rule("MAX", "값이 허용된 최댓값보다 큽니다.")),
Map.entry("DecimalMax", new Rule("MAX", "값이 허용된 최댓값보다 큽니다.")),
Map.entry("Positive", new Rule("POSITIVE", "값은 양수여야 합니다.")),
Map.entry("PositiveOrZero", new Rule("POSITIVE_OR_ZERO", "값은 음수일 수 없습니다.")),
Map.entry("Negative", new Rule("NEGATIVE", "값은 음수여야 합니다.")),
Map.entry("NegativeOrZero", new Rule("NEGATIVE_OR_ZERO", "값은 양수일 수 없습니다.")),
Map.entry("Pattern", new Rule("PATTERN", "값의 형식이 올바르지 않습니다.")),
Map.entry("Email", new Rule("EMAIL", "값의 형식이 올바르지 않습니다.")),
Map.entry("Past", new Rule("PAST", "값은 과거 시각이어야 합니다.")),
Map.entry("PastOrPresent", new Rule("PAST_OR_PRESENT", "값은 미래 시각일 수 없습니다.")),
Map.entry("Future", new Rule("FUTURE", "값은 미래 시각이어야 합니다.")),
Map.entry("FutureOrPresent", new Rule("FUTURE_OR_PRESENT", "값은 과거 시각일 수 없습니다.")),
Map.entry("AssertTrue", new Rule("ASSERT_TRUE", "값은 true여야 합니다.")),
Map.entry("AssertFalse", new Rule("ASSERT_FALSE", "값은 false여야 합니다.")),
Map.entry("typeMismatch", new Rule("TYPE_MISMATCH", "값의 타입이 올바르지 않습니다.")));
private ClientSafeValidationDetails() {}
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.web.error;
import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.ClientErrorMessages;
import dev.caskeleton.shared.response.ApiError;
import dev.caskeleton.shared.response.Envelope;
import org.springframework.http.HttpStatus;
@@ -12,24 +13,38 @@ import org.springframework.http.ResponseEntity;
* framework-neutral {@code int httpStatus()} to Spring {@link HttpStatus}, carrying {@code
* error.category}, and lifting the {@code meta} object (request/trace/correlation ids) from MDC via
* {@link ResponseMetaFactory}.
*
* <p>The client message is never a parameter: it is always {@link ClientErrorMessages#of(
* ApiErrorCode)}, the one category-keyed table every transport shares. A caller that needs to tell
* the client more puts a bounded value in {@code details}; it cannot put prose on the wire.
*/
public final class ErrorResponseFactory {
private ErrorResponseFactory() {}
public static ResponseEntity<Envelope<Void>> envelope(
ApiErrorCode code, String message, Object details) {
return ResponseEntity.status(HttpStatus.valueOf(code.httpStatus()))
.body(body(code, message, details));
public static ResponseEntity<Envelope<Void>> envelope(ApiErrorCode code, Object details) {
return ResponseEntity.status(HttpStatus.valueOf(code.httpStatus())).body(body(code, details));
}
/** Body-only variant for ResponseEntityExceptionHandler hooks that set status separately. */
public static Envelope<Void> body(ApiErrorCode code, String message, Object details) {
public static Envelope<Void> body(ApiErrorCode code, Object details) {
return body(code, code.retryable(), details);
}
/**
* Body whose {@code retryable} is decided for this occurrence.
*
* <p>The occurrence can only narrow the code: a code that is never retryable stays non-retryable
* whatever the caller says, so a client that sees only the code still gets a safe answer.
*/
public static Envelope<Void> body(ApiErrorCode code, boolean retryable, Object details) {
String message = ClientErrorMessages.of(code);
boolean effectiveRetryable = code.retryable() && retryable;
ApiError err =
details == null
? ApiError.of(code.code(), code.category().name(), message, code.retryable())
? ApiError.of(code.code(), code.category().name(), message, effectiveRetryable)
: ApiError.withDetails(
code.code(), code.category().name(), message, code.retryable(), details);
code.code(), code.category().name(), message, effectiveRetryable, details);
return Envelope.failure(err, ResponseMetaFactory.fromMdc());
}
}
@@ -5,12 +5,9 @@ import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedExceptio
import dev.caskeleton.adapter.inbound.web.http.ApiHeaders;
import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor;
import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException;
import dev.caskeleton.application.idempotency.IdempotencyInFlightException;
import dev.caskeleton.application.idempotency.IdempotencyRequestMismatchException;
import dev.caskeleton.shared.error.AdapterDisabledException;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.DependencyFailureException;
import dev.caskeleton.shared.error.MappingException;
import dev.caskeleton.shared.error.OperationalError;
import dev.caskeleton.shared.error.PersistenceFailureException;
import dev.caskeleton.shared.response.Envelope;
@@ -36,6 +33,7 @@ import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
@@ -74,70 +72,39 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
this.spanErrorRecorder = spanErrorRecorder;
}
@ExceptionHandler(MappingException.class)
public ResponseEntity<Envelope<Void>> handleMapping(MappingException ex) {
return ErrorResponseFactory.envelope(
OperationalError.MAPPING_FAILED,
ClientSafeErrorMessages.forOperational(OperationalError.MAPPING_FAILED),
null);
}
/**
* Runtime fail-fast for a disabled optional adapter that was invoked → 500 {@link
* OperationalError#ADAPTER_DISABLED}. See README for the design rationale.
*/
@ExceptionHandler(AdapterDisabledException.class)
public ResponseEntity<Envelope<Void>> handleAdapterDisabled(AdapterDisabledException ex) {
log.error(
"disabled optional adapter invoked at runtime: adapter={} (Layer 3 fail-fast)",
ex.adapterName(),
ex);
return ErrorResponseFactory.envelope(
OperationalError.ADAPTER_DISABLED,
ClientSafeErrorMessages.forOperational(OperationalError.ADAPTER_DISABLED),
null);
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Envelope<Void>> handleIllegalArgument(IllegalArgumentException ex) {
return ErrorResponseFactory.envelope(
OperationalError.BAD_PARAMETER,
ClientSafeErrorMessages.forOperational(OperationalError.BAD_PARAMETER),
null);
if (ex instanceof ApiErrorCarrier) {
return handleCarrier(ex);
}
return ErrorResponseFactory.envelope(OperationalError.BAD_PARAMETER, null);
}
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<Envelope<Void>> handleConstraintViolation(ConstraintViolationException ex) {
List<Map<String, Object>> violations =
ex.getConstraintViolations().stream().map(ClientSafeValidationDetails::from).toList();
return ErrorResponseFactory.envelope(
OperationalError.VALIDATION_FAILED, "Request validation failed", violations);
return ErrorResponseFactory.envelope(OperationalError.VALIDATION_FAILED, violations);
}
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<Envelope<Void>> handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
Map<String, Object> details =
ex.getRequiredType() == null
? null
: Map.of("expectedType", ex.getRequiredType().getSimpleName());
return ErrorResponseFactory.envelope(
OperationalError.BAD_PARAMETER, "Parameter '" + ex.getName() + "' is invalid", details);
? Map.of("parameter", ex.getName())
: Map.of(
"parameter", ex.getName(), "expectedType", ex.getRequiredType().getSimpleName());
return ErrorResponseFactory.envelope(OperationalError.BAD_PARAMETER, details);
}
@ExceptionHandler(InvalidBearerTokenException.class)
public ResponseEntity<Envelope<Void>> handleInvalidToken(InvalidBearerTokenException ex) {
return ErrorResponseFactory.envelope(
OperationalError.INVALID_TOKEN,
ClientSafeErrorMessages.forOperational(OperationalError.INVALID_TOKEN),
null);
return ErrorResponseFactory.envelope(OperationalError.INVALID_TOKEN, null);
}
@ExceptionHandler(AuthenticationException.class)
public ResponseEntity<Envelope<Void>> handleUnauthenticated(AuthenticationException ex) {
return ErrorResponseFactory.envelope(
OperationalError.UNAUTHENTICATED,
ClientSafeErrorMessages.forOperational(OperationalError.UNAUTHENTICATED),
null);
return ErrorResponseFactory.envelope(OperationalError.UNAUTHENTICATED, null);
}
/**
@@ -148,16 +115,13 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<Envelope<Void>> handleForbidden(AccessDeniedException ex) {
ApiErrorCode code = ACCESS_DENIED_CLASSIFIER.classifyAccessDenied(ex);
return ErrorResponseFactory.envelope(code, ClientSafeErrorMessages.forOperational(code), null);
return ErrorResponseFactory.envelope(code, null);
}
/** Handles a failed {@code If-Match} precondition → 412 PRECONDITION_FAILED. */
@ExceptionHandler(PreconditionFailedException.class)
public ResponseEntity<Envelope<Void>> handlePreconditionFailed(PreconditionFailedException ex) {
return ErrorResponseFactory.envelope(
OperationalError.PRECONDITION_FAILED,
ClientSafeErrorMessages.forOperational(OperationalError.PRECONDITION_FAILED),
null);
return ErrorResponseFactory.envelope(OperationalError.PRECONDITION_FAILED, null);
}
/**
@@ -167,52 +131,54 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(PageValidationException.class)
public ResponseEntity<Envelope<Void>> handlePageValidation(PageValidationException ex) {
Map<String, Object> details = Map.of("field", ex.field(), "code", ex.reasonCode());
return ErrorResponseFactory.envelope(
OperationalError.VALIDATION_FAILED, "Pagination parameter is invalid", details);
return ErrorResponseFactory.envelope(OperationalError.VALIDATION_FAILED, details);
}
/**
* Handles a duplicate request whose original is still in flight → 409 IDEMPOTENT_IN_FLIGHT with a
* fixed client-safe message. See README for the design rationale.
* Maps every {@link ApiErrorCarrier} — the shared-contract carriers ({@code MappingException},
* {@code AdapterDisabledException}, {@code PersistenceFailureException}, {@code
* DependencyFailureException}), the application's idempotency failures and any adopter carrier —
* through its own {@link ApiErrorCode}. One branch, so the web adapter answers a carrier exactly
* as the GraphQL, gRPC and STOMP adapters do.
*
* <p>A persistence carrier's cause can hold SQL values, constraints, credentials and endpoints,
* so its log line and span receive only the stable classification. A server-side (5xx) carrier is
* logged with its cause; a client-side one is not logged, because it is an answer, not an
* incident. A retryable code with a registered delay also carries {@code Retry-After}.
*
* @param failure a throwable that implements {@link ApiErrorCarrier}
*/
@ExceptionHandler(IdempotencyInFlightException.class)
public ResponseEntity<Envelope<Void>> handleIdempotentInFlight(IdempotencyInFlightException ex) {
return ErrorResponseFactory.envelope(
OperationalError.IDEMPOTENT_IN_FLIGHT,
"A previous identical request is still being processed, please poll for result",
null);
}
/**
* Handles an {@code Idempotency-Key} reused with a different body → 422
* IDEMPOTENT_REQUEST_MISMATCH with a client-safe message only.
*/
@ExceptionHandler(IdempotencyRequestMismatchException.class)
public ResponseEntity<Envelope<Void>> handleIdempotentMismatch(
IdempotencyRequestMismatchException ex) {
return ErrorResponseFactory.envelope(
OperationalError.IDEMPOTENT_REQUEST_MISMATCH,
"Idempotency key reused with different request body",
null);
}
/**
* Handles a pre-classified {@link PersistenceFailureException}: its {@link
* PersistenceFailureException#errorCode()} sets the envelope code/status; the client message is a
* category-derived safe string. Logs and traces receive only the stable classification because a
* JDBC cause can contain SQL values, constraints, credentials, and endpoints.
*/
@ExceptionHandler(PersistenceFailureException.class)
public ResponseEntity<Envelope<Void>> handlePersistenceFailure(PersistenceFailureException ex) {
ApiErrorCode code = ex.errorCode();
log.error(
"persistence failure classified as {} (category={}, retryable={})",
code.code(),
code.category(),
code.retryable());
spanErrorRecorder.recordException(sanitizedPersistenceFailure(code), code.code());
return ErrorResponseFactory.envelope(
code, ClientSafeErrorMessages.forPersistence(code.category()), null);
public ResponseEntity<Envelope<Void>> handleCarrier(Exception failure) {
ApiErrorCode code = ((ApiErrorCarrier) failure).errorCode();
if (failure instanceof PersistenceFailureException) {
log.error(
"persistence failure classified as {} (category={}, retryable={})",
code.code(),
code.category(),
code.retryable());
spanErrorRecorder.recordException(sanitizedPersistenceFailure(code), code.code());
} else if (failure instanceof DependencyFailureException dependency) {
log.error(
"dependency failure classified as {} (category={}, retryable={}, dependency={})",
code.code(),
code.category(),
code.retryable(),
dependency.dependencyName(),
failure);
spanErrorRecorder.recordException(failure, code.code());
} else if (code.httpStatus() >= 500) {
log.error(
"failure classified as {} (category={}, retryable={})",
code.code(),
code.category(),
code.retryable(),
failure);
spanErrorRecorder.recordException(failure, code.code());
}
ResponseEntity.BodyBuilder builder = ResponseEntity.status(code.httpStatus());
RetryAfterAdvisor.retryAfterSeconds(code)
.ifPresent(seconds -> builder.header(ApiHeaders.RETRY_AFTER, String.valueOf(seconds)));
return builder.body(ErrorResponseFactory.body(code, null));
}
private static PersistenceFailureException sanitizedPersistenceFailure(ApiErrorCode code) {
@@ -220,37 +186,14 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
code, "persistence failure classified as " + code.code(), null);
}
/**
* Handles a pre-classified {@link DependencyFailureException}: its {@link
* DependencyFailureException#errorCode()} sets the envelope code/status; the client message is a
* per-code safe string and a {@code Retry-After} header is attached via {@link RetryAfterAdvisor}
* when applicable. See README for the design rationale.
*/
@ExceptionHandler(DependencyFailureException.class)
public ResponseEntity<Envelope<Void>> handleDependencyFailure(DependencyFailureException ex) {
ApiErrorCode code = ex.errorCode();
log.error(
"dependency failure classified as {} (category={}, retryable={}, dependency={})",
code.code(),
code.category(),
code.retryable(),
ex.dependencyName(),
ex);
spanErrorRecorder.recordException(ex, code.code());
String message = ClientSafeErrorMessages.forDependency(code);
Envelope<Void> body = ErrorResponseFactory.body(code, message, null);
ResponseEntity.BodyBuilder builder = ResponseEntity.status(code.httpStatus());
RetryAfterAdvisor.retryAfterSeconds(code)
.ifPresent(seconds -> builder.header(ApiHeaders.RETRY_AFTER, String.valueOf(seconds)));
return builder.body(body);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Envelope<Void>> handleUnknown(Exception ex, WebRequest req) {
if (ex instanceof ApiErrorCarrier) {
return handleCarrier(ex);
}
log.error("unhandled exception on {}", req.getDescription(false), ex);
spanErrorRecorder.recordException(ex, OperationalError.INTERNAL_ERROR.code());
return ErrorResponseFactory.envelope(
OperationalError.INTERNAL_ERROR, "Internal server error", null);
return ErrorResponseFactory.envelope(OperationalError.INTERNAL_ERROR, null);
}
@Override
@@ -264,8 +207,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
.map(ClientSafeValidationDetails::from)
.toList();
return new ResponseEntity<>(
ErrorResponseFactory.body(
OperationalError.VALIDATION_FAILED, "Request body failed validation", fields),
ErrorResponseFactory.body(OperationalError.VALIDATION_FAILED, fields),
HttpStatusCode.valueOf(OperationalError.VALIDATION_FAILED.httpStatus()));
}
@@ -285,8 +227,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
Map<String, Object> details =
ex.getCause() != null ? Map.of("cause", ex.getCause().getClass().getSimpleName()) : null;
return new ResponseEntity<>(
ErrorResponseFactory.body(
OperationalError.VALIDATION_FAILED, "Request body is malformed or unparsable", details),
ErrorResponseFactory.body(OperationalError.VALIDATION_FAILED, details),
HttpStatusCode.valueOf(OperationalError.VALIDATION_FAILED.httpStatus()));
}
@@ -308,10 +249,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
"supportedMethods",
ex.getSupportedHttpMethods().stream().map(Object::toString).toList());
return new ResponseEntity<>(
ErrorResponseFactory.body(
OperationalError.METHOD_NOT_ALLOWED,
ClientSafeErrorMessages.forOperational(OperationalError.METHOD_NOT_ALLOWED),
details),
ErrorResponseFactory.body(OperationalError.METHOD_NOT_ALLOWED, details),
responseHeaders,
HttpStatusCode.valueOf(OperationalError.METHOD_NOT_ALLOWED.httpStatus()));
}
@@ -330,10 +268,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
"supportedMediaTypes",
ex.getSupportedMediaTypes().stream().map(Object::toString).toList());
return new ResponseEntity<>(
ErrorResponseFactory.body(
OperationalError.UNSUPPORTED_MEDIA_TYPE,
ClientSafeErrorMessages.forOperational(OperationalError.UNSUPPORTED_MEDIA_TYPE),
details),
ErrorResponseFactory.body(OperationalError.UNSUPPORTED_MEDIA_TYPE, details),
HttpStatusCode.valueOf(OperationalError.UNSUPPORTED_MEDIA_TYPE.httpStatus()));
}
@@ -345,10 +280,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
WebRequest request) {
// An oversized request body — multipart or JSON — classifies as 413 inside the envelope.
return new ResponseEntity<>(
ErrorResponseFactory.body(
OperationalError.PAYLOAD_TOO_LARGE,
"Request payload exceeds the maximum allowed size",
null),
ErrorResponseFactory.body(OperationalError.PAYLOAD_TOO_LARGE, null),
HttpStatusCode.valueOf(OperationalError.PAYLOAD_TOO_LARGE.httpStatus()));
}
@@ -366,10 +298,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
"supportedMediaTypes",
ex.getSupportedMediaTypes().stream().map(Object::toString).toList());
return new ResponseEntity<>(
ErrorResponseFactory.body(
OperationalError.NOT_ACCEPTABLE,
"No acceptable representation for the requested Accept header",
details),
ErrorResponseFactory.body(OperationalError.NOT_ACCEPTABLE, details),
HttpStatusCode.valueOf(OperationalError.NOT_ACCEPTABLE.httpStatus()));
}
@@ -387,10 +316,56 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
private static ResponseEntity<Object> routeNotFound() {
return new ResponseEntity<>(
ErrorResponseFactory.body(
OperationalError.ROUTE_NOT_FOUND,
ClientSafeErrorMessages.forOperational(OperationalError.ROUTE_NOT_FOUND),
null),
ErrorResponseFactory.body(OperationalError.ROUTE_NOT_FOUND, null),
HttpStatusCode.valueOf(OperationalError.ROUTE_NOT_FOUND.httpStatus()));
}
/**
* Every Spring MVC exception this class does not override individually — a missing required
* parameter, header or multipart part, a binding or conversion failure, an async timeout —
* reaches the client as the same {@link Envelope}, never as {@code application/problem+json}.
*
* <p>The status Spring chose is kept as the classification input: it is mapped to the operational
* code of that status, and the response carries that code's status. Headers Spring prepared (for
* example {@code Allow}) are kept.
*/
@Override
protected ResponseEntity<Object> handleExceptionInternal(
Exception ex,
Object body,
HttpHeaders headers,
HttpStatusCode statusCode,
WebRequest request) {
if (request instanceof ServletWebRequest servletRequest
&& servletRequest.getResponse() != null
&& servletRequest.getResponse().isCommitted()) {
return null;
}
OperationalError code = operationalErrorFor(statusCode);
if (code.httpStatus() >= 500) {
log.error("spring mvc failure classified as {}", code.code(), ex);
spanErrorRecorder.recordException(ex, code.code());
}
return new ResponseEntity<>(
ErrorResponseFactory.body(code, null), headers, HttpStatusCode.valueOf(code.httpStatus()));
}
private static OperationalError operationalErrorFor(HttpStatusCode status) {
return switch (status.value()) {
case 401 -> OperationalError.UNAUTHENTICATED;
case 403 -> OperationalError.FORBIDDEN;
case 404 -> OperationalError.ROUTE_NOT_FOUND;
case 405 -> OperationalError.METHOD_NOT_ALLOWED;
case 406 -> OperationalError.NOT_ACCEPTABLE;
case 412 -> OperationalError.PRECONDITION_FAILED;
case 413 -> OperationalError.PAYLOAD_TOO_LARGE;
case 414 -> OperationalError.URI_TOO_LONG;
case 415 -> OperationalError.UNSUPPORTED_MEDIA_TYPE;
case 429 -> OperationalError.RATE_LIMIT_EXCEEDED;
default ->
status.is4xxClientError()
? OperationalError.BAD_PARAMETER
: OperationalError.INTERNAL_ERROR;
};
}
}
@@ -151,8 +151,6 @@ public class DurableOperationController {
private static ResponseEntity<Envelope<?>> notFound() {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(
ErrorResponseFactory.body(
OperationErrorCode.OPERATION_NOT_FOUND, "Operation was not found", null));
.body(ErrorResponseFactory.body(OperationErrorCode.OPERATION_NOT_FOUND, null));
}
}
@@ -24,13 +24,6 @@ import tools.jackson.databind.ObjectMapper;
*/
public final class RateLimitInterceptor implements HandlerInterceptor {
private static final String DENIED_MESSAGE =
"Too many requests, please retry after the indicated interval";
private static final String UNAVAILABLE_MESSAGE =
"Rate-limit enforcement is temporarily unavailable";
private static final String INCOMPATIBLE_MESSAGE =
"Rate-limit enforcement is unavailable due to an incompatible provider";
private final EdgeRateLimitTransportBridge bridge;
private final ObjectMapper objectMapper;
@@ -72,19 +65,19 @@ public final class RateLimitInterceptor implements HandlerInterceptor {
return true;
}
response.setHeader(ApiHeaders.RETRY_AFTER, retryAfterSeconds(decision.retryAfter()));
reject(response, OperationalError.RATE_LIMIT_EXCEEDED, DENIED_MESSAGE);
reject(response, OperationalError.RATE_LIMIT_EXCEEDED);
return false;
}
private boolean rejectUnavailable(HttpServletResponse response, Duration retryAfter)
throws Exception {
response.setHeader(ApiHeaders.RETRY_AFTER, retryAfterSeconds(retryAfter));
reject(response, RateLimitTransportError.RATE_LIMIT_UNAVAILABLE, UNAVAILABLE_MESSAGE);
reject(response, RateLimitTransportError.RATE_LIMIT_UNAVAILABLE);
return false;
}
private boolean rejectIncompatible(HttpServletResponse response) throws Exception {
reject(response, RateLimitTransportError.RATE_LIMIT_INCOMPATIBLE, INCOMPATIBLE_MESSAGE);
reject(response, RateLimitTransportError.RATE_LIMIT_INCOMPATIBLE);
return false;
}
@@ -96,11 +89,10 @@ public final class RateLimitInterceptor implements HandlerInterceptor {
ApiHeaders.X_RATELIMIT_RESET, DateTimeFormatter.ISO_INSTANT.format(decision.resetAt()));
}
private void reject(HttpServletResponse response, ApiErrorCode error, String message)
throws Exception {
private void reject(HttpServletResponse response, ApiErrorCode error) throws Exception {
response.setStatus(error.httpStatus());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
Envelope<Void> body = ErrorResponseFactory.body(error, message, null);
Envelope<Void> body = ErrorResponseFactory.body(error, null);
objectMapper.writeValue(response.getWriter(), body);
}
@@ -2,6 +2,8 @@ package dev.caskeleton.adapter.inbound.web.auth;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -33,6 +35,7 @@ class EnvelopeAccessDeniedHandlerTest {
assertThat(body.path("error").path("code").asString())
.isEqualTo("AUTHZ_INSUFFICIENT_PERMISSION");
assertThat(body.path("error").path("category").asString()).isEqualTo("AUTHZ");
assertThat(body.path("error").path("message").asString()).isEqualTo("Permission denied");
assertThat(body.path("error").path("message").asString())
.isEqualTo(ClientErrorMessages.of(Category.AUTHZ));
}
}
@@ -2,6 +2,8 @@ package dev.caskeleton.adapter.inbound.web.auth;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -47,7 +49,8 @@ class EnvelopeAuthenticationEntryPointTest {
assertThat(body.get("success").asBoolean()).isFalse();
assertThat(body.path("error").path("code").asString()).isEqualTo("AUTH_TOKEN_MISSING");
assertThat(body.path("error").path("category").asString()).isEqualTo("AUTH");
assertThat(body.path("error").path("message").asString()).isEqualTo("Authentication required");
assertThat(body.path("error").path("message").asString())
.isEqualTo(ClientErrorMessages.of(Category.AUTH));
}
@Test
@@ -16,6 +16,8 @@ import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import dev.caskeleton.adapter.inbound.web.settings.CorsSettings;
import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import jakarta.servlet.Filter;
import java.io.IOException;
import java.io.OutputStream;
@@ -198,7 +200,7 @@ class JwtJwksSecurityFilterIntegrationTest {
.andExpect(jsonPath("$.error.code").value("INTERNAL_AUTH_MISCONFIGURATION"))
.andExpect(jsonPath("$.error.category").value("INTERNAL"))
.andExpect(jsonPath("$.error.retryable").value(false))
.andExpect(jsonPath("$.error.message").value("Authentication failed"))
.andExpect(jsonPath("$.error.message").value(ClientErrorMessages.OPAQUE))
.andReturn();
assertSafe(
result, token, sentinel, issuer.issuer(), issuer.discoveryIssuer(), PRIMARY_KID);
@@ -218,7 +220,8 @@ class JwtJwksSecurityFilterIntegrationTest {
.andExpect(jsonPath("$.error.category").value("TRANSIENT_DEPENDENCY"))
.andExpect(jsonPath("$.error.retryable").value(true))
.andExpect(
jsonPath("$.error.message").value("Authentication service temporarily unavailable"))
jsonPath("$.error.message")
.value(ClientErrorMessages.of(Category.TRANSIENT_DEPENDENCY)))
.andReturn();
}
@@ -6,6 +6,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter;
import dev.caskeleton.shared.error.ClientErrorMessages;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
@@ -52,7 +53,7 @@ class EnvelopeMetaIntegrationTest {
.andExpect(status().isInternalServerError())
.andExpect(jsonPath("$.success").value(false))
.andExpect(jsonPath("$.error.category").value("INTERNAL"))
.andExpect(jsonPath("$.error.message").value("Internal server error"))
.andExpect(jsonPath("$.error.message").value(ClientErrorMessages.OPAQUE))
.andExpect(jsonPath("$.error.retryable").value(true))
.andExpect(jsonPath("$.meta.traceId").isNotEmpty());
}
@@ -11,6 +11,8 @@ import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedExceptio
import dev.caskeleton.adapter.inbound.web.http.ApiHeaders;
import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException;
import dev.caskeleton.shared.error.AdapterDisabledException;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import dev.caskeleton.shared.error.DependencyFailureException;
import dev.caskeleton.shared.error.MappingException;
import dev.caskeleton.shared.error.OperationalError;
@@ -56,7 +58,7 @@ class GlobalExceptionHandlerTest {
@Test
void mappingExceptionRoutesToMappingFailedEnvelope() {
String secret = "SECRET_MAPPING_DIAGNOSTIC";
ResponseEntity<Envelope<Void>> response = handler.handleMapping(new MappingException(secret));
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(new MappingException(secret));
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
Envelope<Void> body = response.getBody();
@@ -64,7 +66,7 @@ class GlobalExceptionHandlerTest {
assertThat(body.success()).isFalse();
assertThat(body.error().code()).isEqualTo("MAPPING_FAILED");
assertThat(body.error().category()).isEqualTo("VALIDATION");
assertThat(body.error().message()).isEqualTo("Request data could not be mapped");
assertThat(body.error().message()).isEqualTo(ClientErrorMessages.of(Category.VALIDATION));
assertThat(body.error().message()).doesNotContain(secret);
assertThat(body.error().retryable()).isFalse();
}
@@ -78,7 +80,8 @@ class GlobalExceptionHandlerTest {
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().error().code()).isEqualTo("BAD_PARAMETER");
assertThat(response.getBody().error().message()).isEqualTo("Request parameter is invalid");
assertThat(response.getBody().error().message())
.isEqualTo(ClientErrorMessages.of(Category.VALIDATION));
assertThat(response.getBody().error().message()).doesNotContain(secret);
}
@@ -88,7 +91,7 @@ class GlobalExceptionHandlerTest {
// distinct from the startup REQUIRED_ADAPTER_DISABLED.
String secret = "SECRET_INTERNAL_BROKER_ENDPOINT";
ResponseEntity<Envelope<Void>> response =
handler.handleAdapterDisabled(new AdapterDisabledException("kafka", secret));
handler.handleCarrier(new AdapterDisabledException("kafka", secret));
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(response.getBody()).isNotNull();
@@ -96,7 +99,7 @@ class GlobalExceptionHandlerTest {
assertThat(response.getBody().error().code()).isEqualTo("ADAPTER_DISABLED");
assertThat(response.getBody().error().category()).isEqualTo("INTERNAL");
assertThat(response.getBody().error().retryable()).isFalse();
assertThat(response.getBody().error().message()).isEqualTo("Internal server error");
assertThat(response.getBody().error().message()).isEqualTo(ClientErrorMessages.OPAQUE);
assertThat(response.getBody().error().message()).doesNotContain(secret);
}
@@ -114,10 +117,10 @@ class GlobalExceptionHandlerTest {
assertThat(responses)
.extracting(response -> response.getBody().error().message())
.containsExactly(
"Authentication token is invalid",
"Authentication is required",
"Access is denied",
"Resource state changed; refresh and retry");
ClientErrorMessages.of(Category.AUTH),
ClientErrorMessages.of(Category.AUTH),
ClientErrorMessages.of(Category.AUTHZ),
ClientErrorMessages.of(Category.CONFLICT));
assertThat(responses)
.allSatisfy(
response -> {
@@ -135,7 +138,8 @@ class GlobalExceptionHandlerTest {
new PageValidationException("size", "SIZE_EXCEEDS_MAX", secret));
assertThat(page.getBody()).isNotNull();
assertThat(page.getBody().error().message()).isEqualTo("Pagination parameter is invalid");
assertThat(page.getBody().error().message())
.isEqualTo(ClientErrorMessages.of(Category.VALIDATION));
assertThat(page.getBody().error().details())
.isEqualTo(Map.of("field", "size", "code", "SIZE_EXCEEDS_MAX"));
assertThat(page.getBody().error().toString()).doesNotContain(secret);
@@ -155,8 +159,10 @@ class GlobalExceptionHandlerTest {
ResponseEntity<Envelope<Void>> response = handler.handleTypeMismatch(exception);
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().error().message()).isEqualTo("Parameter 'accountId' is invalid");
assertThat(response.getBody().error().details()).isEqualTo(Map.of("expectedType", "Long"));
assertThat(response.getBody().error().message())
.isEqualTo(ClientErrorMessages.of(Category.VALIDATION));
assertThat(response.getBody().error().details())
.isEqualTo(Map.of("parameter", "accountId", "expectedType", "Long"));
assertThat(response.getBody().error().toString()).doesNotContain(secret);
}
@@ -194,7 +200,7 @@ class GlobalExceptionHandlerTest {
Map.of(
"field", "attributes.passwords",
"code", "PATTERN",
"message", "Value has an invalid format"));
"message", "값의 형식이 올바르지 않습니다."));
assertThat(envelope.error().toString())
.doesNotContain(secret, "rejectedValue", "rejected interpolated value", "[7]");
}
@@ -224,7 +230,7 @@ class GlobalExceptionHandlerTest {
// then
assertThat(((Envelope<?>) response.getBody()).error().details())
.isEqualTo(
List.of(Map.of("field", "request", "code", "INVALID", "message", "Invalid value")));
List.of(Map.of("field", "request", "code", "INVALID", "message", "값이 올바르지 않습니다.")));
}
@Test
@@ -286,7 +292,7 @@ class GlobalExceptionHandlerTest {
Map.of(
"field", "attributes.value",
"code", "PATTERN",
"message", "Value has an invalid format"));
"message", "값의 형식이 올바르지 않습니다."));
assertThat(response.getBody().error().toString())
.doesNotContain(secret, "rejected interpolated value", "[3]");
}
@@ -306,7 +312,7 @@ class GlobalExceptionHandlerTest {
assertThat(response.getBody()).isInstanceOf(Envelope.class);
Envelope<?> envelope = (Envelope<?>) response.getBody();
assertThat(envelope.error().message()).isEqualTo("Requested route was not found");
assertThat(envelope.error().message()).isEqualTo(ClientErrorMessages.of(Category.NOT_FOUND));
assertThat(envelope.error().toString()).doesNotContain(secret);
}
@@ -316,7 +322,7 @@ class GlobalExceptionHandlerTest {
MDC.put("request_id", "req-xyz");
MDC.put("trace_id", "trace-xyz");
MDC.put("correlation_id", "corr-xyz");
ResponseEntity<Envelope<Void>> response = handler.handleMapping(new MappingException("x"));
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(new MappingException("x"));
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().meta().requestId()).isEqualTo("req-xyz");
assertThat(response.getBody().meta().traceId()).isEqualTo("trace-xyz");
@@ -336,7 +342,7 @@ class GlobalExceptionHandlerTest {
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().error().retryable()).isTrue();
assertThat(response.getBody().error().message()).isEqualTo("Internal server error");
assertThat(response.getBody().error().message()).isEqualTo(ClientErrorMessages.OPAQUE);
}
// feature-authentication-authorization-contract D5/§4: an authorization denial that
@@ -370,7 +376,7 @@ class GlobalExceptionHandlerTest {
new SQLException(
"duplicate key value violates unique constraint \"uq_worklog_title\"", "23505"));
ResponseEntity<Envelope<Void>> response = handler.handlePersistenceFailure(carrier);
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(carrier);
Envelope<Void> body = response.getBody();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
@@ -382,7 +388,7 @@ class GlobalExceptionHandlerTest {
// the safe message must not echo the SQLState, constraint name, or "unique constraint".
assertThat(body.error().message())
.as("D1/C7: client message is the fixed category-safe string")
.isEqualTo("Request conflicted with the current state, please retry");
.isEqualTo(ClientErrorMessages.of(Category.CONFLICT));
assertThat(body.error().details()).isNull();
}
@@ -403,7 +409,7 @@ class GlobalExceptionHandlerTest {
"persistence failure classified from SQLState=23505",
new SQLException(raw, "23505"));
handler.handlePersistenceFailure(carrier);
handler.handleCarrier(carrier);
assertThat(appender.list).hasSize(1);
ILoggingEvent event = appender.list.getFirst();
@@ -435,7 +441,7 @@ class GlobalExceptionHandlerTest {
"persistence failure classified from SQLState=08006",
new SQLException("connection refused", "08006"));
ResponseEntity<Envelope<Void>> response = handler.handlePersistenceFailure(carrier);
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(carrier);
Envelope<Void> body = response.getBody();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
@@ -444,7 +450,7 @@ class GlobalExceptionHandlerTest {
assertThat(body.error().category()).isEqualTo("TRANSIENT_DEPENDENCY");
assertThat(body.error().retryable()).isTrue();
assertThat(body.error().message())
.isEqualTo("Service temporarily unavailable, please retry later");
.isEqualTo(ClientErrorMessages.of(Category.TRANSIENT_DEPENDENCY));
}
@Test
@@ -455,13 +461,13 @@ class GlobalExceptionHandlerTest {
"persistence failure classified from SQLState=23502",
new SQLException("null value in column \"owner_id\"", "23502"));
ResponseEntity<Envelope<Void>> response = handler.handlePersistenceFailure(carrier);
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(carrier);
Envelope<Void> body = response.getBody();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
assertThat(body).isNotNull();
assertThat(body.error().category()).isEqualTo("DATA_INTEGRITY");
assertThat(body.error().message()).isEqualTo("Request violates a data constraint");
assertThat(body.error().message()).isEqualTo(ClientErrorMessages.OPAQUE);
}
// feature-business-rule-validation-contract C7 / D9 + persistence-failure-baseline
@@ -490,7 +496,7 @@ class GlobalExceptionHandlerTest {
// logically subsumed.
assertThat(body.error().message())
.as("C7/D9: client message must be the fixed safe string, never the raw DB message")
.isEqualTo("Internal server error");
.isEqualTo(ClientErrorMessages.OPAQUE);
assertThat(body.error().details())
.as("C7/D9: no raw object / body / SQL detail in error.details")
.isNull();
@@ -510,7 +516,7 @@ class GlobalExceptionHandlerTest {
"connect timed out after 3000 ms",
null);
ResponseEntity<Envelope<Void>> response = handler.handleDependencyFailure(ex);
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(ex);
Envelope<Void> body = response.getBody();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.GATEWAY_TIMEOUT);
@@ -520,7 +526,7 @@ class GlobalExceptionHandlerTest {
assertThat(body.error().category()).isEqualTo("TRANSIENT_DEPENDENCY");
assertThat(body.error().retryable()).isTrue();
assertThat(body.error().message())
.isEqualTo("Upstream service did not respond in time, please retry");
.isEqualTo(ClientErrorMessages.of(Category.TRANSIENT_DEPENDENCY));
// Retry-After header must be present (registry: 2 s)
assertThat(response.getHeaders().getFirst(ApiHeaders.RETRY_AFTER)).isEqualTo("2");
}
@@ -534,7 +540,7 @@ class GlobalExceptionHandlerTest {
"Connection refused to 10.0.0.1:8080",
null);
ResponseEntity<Envelope<Void>> response = handler.handleDependencyFailure(ex);
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(ex);
Envelope<Void> body = response.getBody();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
@@ -542,7 +548,8 @@ class GlobalExceptionHandlerTest {
assertThat(body.error().code()).isEqualTo("DEPENDENCY_CONNECT_FAILED");
assertThat(body.error().category()).isEqualTo("TRANSIENT_DEPENDENCY");
assertThat(body.error().retryable()).isTrue();
assertThat(body.error().message()).isEqualTo("Upstream service unreachable, please retry");
assertThat(body.error().message())
.isEqualTo(ClientErrorMessages.of(Category.TRANSIENT_DEPENDENCY));
assertThat(response.getHeaders().getFirst(ApiHeaders.RETRY_AFTER)).isEqualTo("2");
}
@@ -555,7 +562,7 @@ class GlobalExceptionHandlerTest {
"DNS resolution failed for notification-service.internal",
null);
ResponseEntity<Envelope<Void>> response = handler.handleDependencyFailure(ex);
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(ex);
Envelope<Void> body = response.getBody();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
@@ -563,7 +570,8 @@ class GlobalExceptionHandlerTest {
assertThat(body.error().code()).isEqualTo("DEPENDENCY_DNS_FAILED");
assertThat(body.error().category()).isEqualTo("TRANSIENT_DEPENDENCY");
assertThat(body.error().retryable()).isTrue();
assertThat(body.error().message()).isEqualTo("Upstream service unreachable, please retry");
assertThat(body.error().message())
.isEqualTo(ClientErrorMessages.of(Category.TRANSIENT_DEPENDENCY));
assertThat(response.getHeaders().getFirst(ApiHeaders.RETRY_AFTER)).isEqualTo("5");
}
@@ -576,7 +584,7 @@ class GlobalExceptionHandlerTest {
"upstream returned 422 Unprocessable Entity",
null);
ResponseEntity<Envelope<Void>> response = handler.handleDependencyFailure(ex);
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(ex);
Envelope<Void> body = response.getBody();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_GATEWAY);
@@ -584,7 +592,7 @@ class GlobalExceptionHandlerTest {
assertThat(body.error().code()).isEqualTo("DEPENDENCY_4XX_CLIENT");
assertThat(body.error().category()).isEqualTo("PERMANENT_DEPENDENCY");
assertThat(body.error().retryable()).isFalse();
assertThat(body.error().message()).isEqualTo("Upstream service rejected the request");
assertThat(body.error().message()).isEqualTo(ClientErrorMessages.OPAQUE);
// non-retryable → no Retry-After header
assertThat(response.getHeaders().getFirst(ApiHeaders.RETRY_AFTER)).isNull();
}
@@ -598,7 +606,7 @@ class GlobalExceptionHandlerTest {
"upstream returned HTTP 503 Service Unavailable",
null);
ResponseEntity<Envelope<Void>> response = handler.handleDependencyFailure(ex);
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(ex);
Envelope<Void> body = response.getBody();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_GATEWAY);
@@ -606,7 +614,8 @@ class GlobalExceptionHandlerTest {
assertThat(body.error().code()).isEqualTo("DEPENDENCY_5XX_SERVER");
assertThat(body.error().category()).isEqualTo("TRANSIENT_DEPENDENCY");
assertThat(body.error().retryable()).isTrue();
assertThat(body.error().message()).isEqualTo("Upstream service error, please retry");
assertThat(body.error().message())
.isEqualTo(ClientErrorMessages.of(Category.TRANSIENT_DEPENDENCY));
assertThat(response.getHeaders().getFirst(ApiHeaders.RETRY_AFTER)).isEqualTo("2");
}
@@ -619,7 +628,7 @@ class GlobalExceptionHandlerTest {
"circuit breaker OPEN for payment-service",
null);
ResponseEntity<Envelope<Void>> response = handler.handleDependencyFailure(ex);
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(ex);
Envelope<Void> body = response.getBody();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
@@ -628,7 +637,7 @@ class GlobalExceptionHandlerTest {
assertThat(body.error().category()).isEqualTo("TRANSIENT_DEPENDENCY");
assertThat(body.error().retryable()).isTrue();
assertThat(body.error().message())
.isEqualTo("Upstream service temporarily unavailable, please retry later");
.isEqualTo(ClientErrorMessages.of(Category.TRANSIENT_DEPENDENCY));
assertThat(response.getHeaders().getFirst(ApiHeaders.RETRY_AFTER)).isEqualTo("10");
}
@@ -644,7 +653,7 @@ class GlobalExceptionHandlerTest {
"status 500 from upstream UPSTREAM_DIAG",
null);
ResponseEntity<Envelope<Void>> response = handler.handleDependencyFailure(ex);
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(ex);
Envelope<Void> body = response.getBody();
assertThat(body).isNotNull();
@@ -4,6 +4,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.idempotency.IdempotencyInFlightException;
import dev.caskeleton.application.idempotency.IdempotencyRequestMismatchException;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import dev.caskeleton.shared.response.Envelope;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import org.junit.jupiter.api.Test;
@@ -16,13 +18,13 @@ class IdempotencyExceptionMappingTest {
private final GlobalExceptionHandler handler = new GlobalExceptionHandler(SpanErrorRecorder.NOOP);
@Test
void inFlightMapsToNonRetryable409ConflictWithFixedMessage() {
void inFlightMapsToNonRetryable409ConflictWithTheConflictMessage() {
// given
IdempotencyInFlightException inFlight =
IdempotencyInFlightException.forScopeDigest(SCOPE_DIAGNOSTIC);
// when
ResponseEntity<Envelope<Void>> response = handler.handleIdempotentInFlight(inFlight);
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(inFlight);
// then
assertThat(response)
@@ -37,17 +39,17 @@ class IdempotencyExceptionMappingTest {
"IDEMPOTENT_IN_FLIGHT",
"CONFLICT",
false,
"A previous identical request is still being processed, please poll for result");
ClientErrorMessages.of(Category.CONFLICT));
}
@Test
void mismatchMapsToNonRetryable422ValidationWithFixedMessage() {
void mismatchMapsToNonRetryable422ValidationWithTheValidationMessage() {
// given
IdempotencyRequestMismatchException mismatch =
IdempotencyRequestMismatchException.forScopeDigest(SCOPE_DIAGNOSTIC);
// when
ResponseEntity<Envelope<Void>> response = handler.handleIdempotentMismatch(mismatch);
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(mismatch);
// then
assertThat(response)
@@ -62,6 +64,6 @@ class IdempotencyExceptionMappingTest {
"IDEMPOTENT_REQUEST_MISMATCH",
"VALIDATION",
false,
"Idempotency key reused with different request body");
ClientErrorMessages.of(Category.VALIDATION));
}
}
@@ -8,6 +8,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
@@ -44,7 +46,7 @@ class NoResourceFoundErrorHandlingTest {
.andExpect(jsonPath("$.error.code").value("ROUTE_NOT_FOUND"))
.andExpect(jsonPath("$.error.category").value("NOT_FOUND"))
.andExpect(jsonPath("$.error.retryable").value(false))
.andExpect(jsonPath("$.error.message").value("Requested route was not found"))
.andExpect(jsonPath("$.error.message").value(ClientErrorMessages.of(Category.NOT_FOUND)))
.andExpect(content().string(not(containsString(secret))));
}
@@ -56,7 +56,7 @@ class SpanErrorRecorderHookTest {
"SQLState=23505",
new SQLException("unique key violation", "23505"));
handler.handlePersistenceFailure(ex);
handler.handleCarrier(ex);
assertThat(recorder.calls).hasSize(1);
assertThat(recorder.calls.get(0).error())
@@ -77,7 +77,7 @@ class SpanErrorRecorderHookTest {
new DependencyFailureException(
OperationalError.DEPENDENCY_TIMEOUT, "payment-service", "connect timed out", null);
handler.handleDependencyFailure(ex);
handler.handleCarrier(ex);
assertThat(recorder.calls).hasSize(1);
assertThat(recorder.calls.get(0).error()).isSameAs(ex);
@@ -24,6 +24,8 @@ import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
@@ -99,9 +101,36 @@ class TransportErrorHandlingTest {
.andExpect(jsonPath("$.error.details.code").value("SIZE_EXCEEDS_MAX"));
}
@Test
void missingRequiredHeaderIsAnEnvelopeNotAProblemDocument() throws Exception {
mvc.perform(post("/t/needs-header"))
.andExpect(status().isBadRequest())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.success").value(false))
.andExpect(jsonPath("$.error.code").value("BAD_PARAMETER"));
}
@Test
void missingRequiredQueryParameterIsAnEnvelopeNotAProblemDocument() throws Exception {
mvc.perform(get("/t/needs-param"))
.andExpect(status().isBadRequest())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.error.code").value("BAD_PARAMETER"));
}
@RestController
static class Probe {
@PostMapping("/t/needs-header")
Map<String, String> needsHeader(@RequestHeader("Idempotency-Key") String key) {
return Map.of("ok", key);
}
@GetMapping("/t/needs-param")
Map<String, String> needsParam(@RequestParam("q") String q) {
return Map.of("ok", q);
}
@GetMapping("/t/get-only")
Map<String, String> getOnly() {
return Map.of("ok", "ok");
+4 -2
View File
@@ -91,8 +91,10 @@ WebSocket is a **build-composition opt-in**, not a dormant feature inside the de
- STOMP `SUBSCRIBE` is allowed only for the configured broadcast destination.
- Authenticated `SEND` is allowed only below `/app/**`.
- Client `SEND` to `/topic/**` and other destinations is rejected.
- Every client-visible processing failure becomes the fixed
`WEBSOCKET_REQUEST_REJECTED` ERROR code with an empty payload.
- Every client-visible processing failure becomes an ERROR frame with an empty payload and the
fixed `message` `WEBSOCKET_REQUEST_REJECTED`. Its `error-code` header is the carried
`ApiErrorCode` when an `ApiErrorCarrier` is in the cause chain, `BAD_PARAMETER` for an
`IllegalArgumentException`, and `WEBSOCKET_REQUEST_REJECTED` otherwise.
## Event projection contract
+3 -1
View File
@@ -21,7 +21,9 @@
해석하지 않는다.
- SUBSCRIBE는 설정된 broadcast destination 하나만, SEND는 `/app/**`만 허용한다. 클라이언트가
`/topic/**`으로 직접 보내는 것은 거부한다.
- 처리 실패는 모두 고정 코드 `WEBSOCKET_REQUEST_REJECTED`와 빈 본문의 ERROR 프레임이 된다.
- 처리 실패는 모두 빈 본문의 ERROR 프레임이 되고 `message` 헤더는 고정값
`WEBSOCKET_REQUEST_REJECTED`다. `error-code` 헤더는 원인 사슬에 `ApiErrorCarrier`가 있으면 그
코드, `IllegalArgumentException`이면 `BAD_PARAMETER`, 나머지는 `WEBSOCKET_REQUEST_REJECTED`다.
- `LiveEventProjector<T>` bean이 정확히 하나 있는 `@DomainEvent` 타입만 broadcast한다. 도메인
객체를 그대로 직렬화하지 않고, projector가 만든 bounded `Map<String, String>`만 보낸다.
@@ -23,6 +23,7 @@ description = 'Inbound adapter: WebSocket (STOMP over SockJS channel + servlet h
dependencies {
implementation project(':domain-core')
implementation project(':shared-contract')
implementation 'org.springframework.boot:spring-boot-starter-websocket'
implementation 'org.springframework.boot:spring-boot-starter-validation'
@@ -1,31 +1,60 @@
package dev.caskeleton.adapter.inbound.websocket.stomp;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.OperationalError;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.socket.messaging.StompSubProtocolErrorHandler;
/** Replaces all client-visible STOMP failures with one fixed, payload-free error frame. */
/**
* Replaces all client-visible STOMP failures with one payload-free error frame.
*
* <p>The frame's {@code message} header is fixed, so no exception text can reach the client. Its
* {@code error-code} header is the stable code every other transport would send for the same
* failure: an {@link ApiErrorCarrier} anywhere in the cause chain (the broker wraps use-case
* failures in a {@code MessagingException}) reports its own code, an {@link
* IllegalArgumentException} reports {@code BAD_PARAMETER}, and everything else stays {@link
* #SAFE_ERROR_CODE}.
*/
final class SafeStompSubProtocolErrorHandler extends StompSubProtocolErrorHandler {
static final String SAFE_ERROR_CODE = "WEBSOCKET_REQUEST_REJECTED";
/** Bounds the cause walk: a cause chain can loop. */
private static final int MAX_CAUSE_DEPTH = 16;
@Override
public Message<byte[]> handleClientMessageProcessingError(
Message<byte[]> clientMessage, Throwable ex) {
return safeError();
return safeError(errorCodeOf(ex));
}
@Override
public Message<byte[]> handleErrorMessageToClient(Message<byte[]> errorMessage) {
return safeError();
return safeError(SAFE_ERROR_CODE);
}
private static Message<byte[]> safeError() {
private static String errorCodeOf(Throwable failure) {
int depth = 0;
for (Throwable cause = failure;
cause != null && depth++ < MAX_CAUSE_DEPTH;
cause = cause.getCause()) {
if (cause instanceof ApiErrorCarrier carrier) {
return carrier.errorCode().code();
}
if (cause instanceof IllegalArgumentException) {
return OperationalError.BAD_PARAMETER.code();
}
}
return SAFE_ERROR_CODE;
}
private static Message<byte[]> safeError(String errorCode) {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR);
accessor.setMessage(SAFE_ERROR_CODE);
accessor.setNativeHeader("error-code", SAFE_ERROR_CODE);
accessor.setNativeHeader("error-code", errorCode);
accessor.setLeaveMutable(true);
return MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders());
}
@@ -3,8 +3,11 @@ package dev.caskeleton.adapter.inbound.websocket.stomp;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.shared.error.MappingException;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
@@ -26,4 +29,32 @@ class SafeStompSubProtocolErrorHandlerTest {
assertThat(new String(result.getPayload(), UTF_8)).isEmpty();
assertThat(result.toString()).doesNotContain("SECRET_SENTINEL");
}
@Test
void aWrappedCarrierFailureReportsItsOwnCode() {
// given: the broker wraps a use-case failure before it reaches the error handler
Throwable failure =
new MessagingException(
"SECRET_SENTINEL", new MappingException("SECRET_SENTINEL mapping detail"));
// when
Message<byte[]> result = handler.handleClientMessageProcessingError(null, failure);
// then
StompHeaderAccessor accessor = StompHeaderAccessor.wrap(result);
assertThat(List.of(accessor.getFirstNativeHeader("error-code"), accessor.getMessage()))
.containsExactly("MAPPING_FAILED", SafeStompSubProtocolErrorHandler.SAFE_ERROR_CODE);
}
@Test
void anIllegalArgumentReportsBadParameter() {
// when
Message<byte[]> result =
handler.handleClientMessageProcessingError(
null, new IllegalArgumentException("SECRET_SENTINEL"));
// then
assertThat(StompHeaderAccessor.wrap(result).getFirstNativeHeader("error-code"))
.isEqualTo("BAD_PARAMETER");
}
}
@@ -110,6 +110,9 @@ dependencies {
// Declared rather than inherited: the `testkit` source set extended testImplementation, so the
// fixtures compiled against every test library this leaf declared without stating any of them
// (ADR-BUILD-001). Listing them makes the fixtures' own surface reviewable.
// The public error hierarchy (`api.error.JpaPersistenceException`) extends the shared
// `PersistenceFailureException`; the fixtures that throw it compile against that supertype.
testFixturesImplementation project(':shared-contract')
testFixturesImplementation 'jakarta.persistence:jakarta.persistence-api'
testFixturesImplementation 'org.hibernate.orm:hibernate-envers'
testFixturesImplementation 'org.flywaydb:flyway-core'
@@ -1,5 +1,8 @@
package dev.caskeleton.adapter.outbound.persistence.api.error;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.OperationalError;
import dev.caskeleton.shared.error.PersistenceFailureException;
import java.util.Objects;
/**
@@ -10,8 +13,13 @@ import java.util.Objects;
* values, entity ids, and PII out of every log line, error response, and metric derived from these
* exceptions. The provider exception is preserved as the {@linkplain #getCause() cause} for
* in-process classification and server-side diagnosis only.
*
* <p>It is a {@link PersistenceFailureException}: every inbound transport already maps that one
* shared carrier by its {@code DB_*} code (never by message), so a JPA failure reaches a client as
* the same classified code a SQLState-translated failure does, instead of three parallel
* persistence hierarchies being mapped separately — or not at all.
*/
public class JpaPersistenceException extends RuntimeException {
public class JpaPersistenceException extends PersistenceFailureException {
private static final long serialVersionUID = 1L;
@@ -20,8 +28,11 @@ public class JpaPersistenceException extends RuntimeException {
public JpaPersistenceException(
FailureCategory category, JpaFailureContext context, Throwable cause) {
super(describe(category, context), cause);
this.category = Objects.requireNonNull(category, "category");
super(
operationalErrorOf(Objects.requireNonNull(category, "category")),
describe(category, context),
cause);
this.category = category;
this.context = Objects.requireNonNull(context, "context");
}
@@ -29,6 +40,40 @@ public class JpaPersistenceException extends RuntimeException {
this(category, context, null);
}
/**
* The classified code, derived from {@link #category()} rather than read from the transient
* superclass field, so a deserialized failure still answers it.
*/
@Override
public ApiErrorCode errorCode() {
return operationalErrorOf(category);
}
/**
* The operational code a failure category is reported as.
*
* <p>A category with no specific code keeps the answer the web catch-all gave before this type
* was a carrier ({@code INTERNAL_ERROR}); classifying a schema mismatch or corrupt row as
* something the client could act on would be a guess.
*/
static OperationalError operationalErrorOf(FailureCategory category) {
return switch (category) {
case SERIALIZATION_FAILURE -> OperationalError.DB_SERIALIZATION_FAILURE;
case COMPLETION_UNKNOWN -> OperationalError.DB_COMPLETION_UNKNOWN;
case DEADLOCK -> OperationalError.DB_DEADLOCK;
case UNIQUE_CONSTRAINT -> OperationalError.DB_UNIQUE_VIOLATION;
case FOREIGN_KEY_CONSTRAINT -> OperationalError.DB_FK_VIOLATION;
case CHECK_CONSTRAINT -> OperationalError.DB_CHECK_VIOLATION;
case NOT_NULL_CONSTRAINT -> OperationalError.DB_NULL_VIOLATION;
case LOCK_NOT_AVAILABLE -> OperationalError.DB_LOCK_TIMEOUT;
case OPTIMISTIC_CONFLICT -> OperationalError.DB_OPTIMISTIC_CONFLICT;
case QUERY_TIMEOUT, TRANSACTION_TIMEOUT -> OperationalError.DB_QUERY_CANCELED;
case CONNECTION_UNAVAILABLE -> OperationalError.DB_UNAVAILABLE;
case SCHEMA_MISMATCH, DATA_CORRUPTION, ENTITY_NOT_FOUND, UNKNOWN ->
OperationalError.INTERNAL_ERROR;
};
}
/** The bounded metadata carried by this failure. */
public JpaFailureContext context() {
return context;
@@ -0,0 +1,58 @@
package dev.caskeleton.adapter.outbound.persistence.api.error;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName;
import dev.caskeleton.shared.error.OperationalError;
import dev.caskeleton.shared.error.PersistenceFailureException;
import java.time.Duration;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
/**
* A JPA failure is a {@link PersistenceFailureException}, so every inbound transport maps one
* persistence hierarchy by its {@code DB_*} code instead of masking it as an internal error.
*/
class JpaPersistenceExceptionCodeTest {
private static final JpaFailureContext CONTEXT =
JpaFailureContext.terminal(
new PersistenceOperationName("user.create"), "23505", 1, Duration.ZERO, null);
static Stream<Arguments> classifiedCategories() {
return Stream.of(
Arguments.of(
FailureCategory.SERIALIZATION_FAILURE, OperationalError.DB_SERIALIZATION_FAILURE),
Arguments.of(FailureCategory.COMPLETION_UNKNOWN, OperationalError.DB_COMPLETION_UNKNOWN),
Arguments.of(FailureCategory.DEADLOCK, OperationalError.DB_DEADLOCK),
Arguments.of(FailureCategory.UNIQUE_CONSTRAINT, OperationalError.DB_UNIQUE_VIOLATION),
Arguments.of(FailureCategory.FOREIGN_KEY_CONSTRAINT, OperationalError.DB_FK_VIOLATION),
Arguments.of(FailureCategory.CHECK_CONSTRAINT, OperationalError.DB_CHECK_VIOLATION),
Arguments.of(FailureCategory.NOT_NULL_CONSTRAINT, OperationalError.DB_NULL_VIOLATION),
Arguments.of(FailureCategory.LOCK_NOT_AVAILABLE, OperationalError.DB_LOCK_TIMEOUT),
Arguments.of(FailureCategory.OPTIMISTIC_CONFLICT, OperationalError.DB_OPTIMISTIC_CONFLICT),
Arguments.of(FailureCategory.QUERY_TIMEOUT, OperationalError.DB_QUERY_CANCELED),
Arguments.of(FailureCategory.TRANSACTION_TIMEOUT, OperationalError.DB_QUERY_CANCELED),
Arguments.of(FailureCategory.CONNECTION_UNAVAILABLE, OperationalError.DB_UNAVAILABLE),
Arguments.of(FailureCategory.SCHEMA_MISMATCH, OperationalError.INTERNAL_ERROR),
Arguments.of(FailureCategory.DATA_CORRUPTION, OperationalError.INTERNAL_ERROR),
Arguments.of(FailureCategory.ENTITY_NOT_FOUND, OperationalError.INTERNAL_ERROR),
Arguments.of(FailureCategory.UNKNOWN, OperationalError.INTERNAL_ERROR));
}
@ParameterizedTest
@MethodSource("classifiedCategories")
void aJpaFailureCarriesTheOperationalCodeOfItsCategory(
FailureCategory category, OperationalError expected) {
// when
Object failure = new JpaPersistenceException(category, CONTEXT);
// then
assertThat(failure)
.isInstanceOfSatisfying(
PersistenceFailureException.class,
carrier -> assertThat(carrier.errorCode()).isEqualTo(expected));
}
}
@@ -35,10 +35,9 @@ import org.yaml.snakeyaml.Yaml;
* envelope ("all locks generic 500" is the D5 forbidden state).
* </ul>
*
* <p>The optimistic-lock ({@code @Version}) case has <em>no dedicated code</em> yet — that registry
* gap is delegated to {@code feature-persistence-failure-baseline} (§Audit REGISTRY-GAP-1). This
* test pins the gap as a known-absent code so it surfaces as a documented delegation rather than a
* silent pass.
* <p>The optimistic-lock ({@code @Version}) case has its own code, {@code DB_OPTIMISTIC_CONFLICT}
* (§Audit REGISTRY-GAP-1, closed): a non-retryable conflict, because resending the same stale
* version cannot succeed.
*
* <p>The enum-side assertions use the on-classpath SSOT; the registry row loads its checked-in
* resource fail-closed.
@@ -53,6 +52,13 @@ class LockFailureClassificationContractTest {
private static final OperationalError NON_RETRYABLE_CONFLICT =
OperationalError.DB_UNIQUE_VIOLATION;
/**
* The optimistic-lock ({@code @Version}) conflict, reported by the JPA failure hierarchy
* (REGISTRY-GAP-1, closed by review-followup P15).
*/
private static final OperationalError OPTIMISTIC_CONFLICT =
OperationalError.DB_OPTIMISTIC_CONFLICT;
private static Map<String, Map<String, Object>> registryByCode;
@BeforeAll
@@ -132,20 +138,19 @@ class LockFailureClassificationContractTest {
});
}
// ---- §Audit REGISTRY-GAP-1: optimistic-lock dedicated code is delegated and absent ----
// ---- §Audit REGISTRY-GAP-1 closed: the optimistic-lock code is a non-retryable conflict ----
@Test
void optimisticLockHasNoDedicatedCodeYetDelegatedToPersistenceBaseline() {
boolean anyOptimisticCode =
Arrays.stream(OperationalError.values())
.map(OperationalError::code)
.anyMatch(code -> code.contains("OPTIMISTIC") || code.contains("VERSION"));
assertThat(anyOptimisticCode)
void anOptimisticLockConflictIsANonRetryableConflict() {
assertThat(
List.of(
OPTIMISTIC_CONFLICT.category(),
OPTIMISTIC_CONFLICT.httpStatus(),
OPTIMISTIC_CONFLICT.retryable()))
.as(
"optimistic @Version conflict has no dedicated code — "
+ "REGISTRY-GAP-1 delegated to feature-persistence-failure-baseline; "
+ "if one is added there, promote it into this policy table")
.isFalse();
"a stale @Version is a conflict the client resolves by re-reading, "
+ "not by resending the same request")
.containsExactly(Category.CONFLICT, 409, false);
}
// ---- required registry rows agree with the classified policy (fail-closed) ----
@@ -154,6 +159,7 @@ class LockFailureClassificationContractTest {
void registryRowsAgreeWithTheLockClassificationPolicy() {
RETRYABLE_LOCK_CONFLICTS.forEach(code -> assertRegistryRow(code, "CONFLICT", 409, true));
assertRegistryRow(NON_RETRYABLE_CONFLICT, "CONFLICT", 409, false);
assertRegistryRow(OPTIMISTIC_CONFLICT, "CONFLICT", 409, false);
}
private static void assertRegistryRow(
@@ -2,6 +2,8 @@ package dev.caskeleton.bootstrap.contract;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
@@ -72,6 +74,33 @@ class OperationalErrorRegistryContractTest {
.isEqualTo(expected));
}
@Test
void everyRegistryClientMessageIsTheSharedCategoryMessage() {
// given
Map<String, String> expected = new LinkedHashMap<>();
Map<String, String> actual = new LinkedHashMap<>();
// when
registryRows()
.forEach(
row -> {
String code = String.valueOf(row.get("code"));
expected.put(
code,
ClientErrorMessages.of(Category.valueOf(String.valueOf(row.get("category")))));
actual.put(code, String.valueOf(row.get("client_safe_message")));
});
// then
assertThat(actual).isNotEmpty().isEqualTo(expected);
}
@SuppressWarnings("unchecked")
private static List<Map<String, Object>> registryRows() {
Object loaded = new Yaml(new SafeConstructor(new LoaderOptions())).load(read(REGISTRY));
return (List<Map<String, Object>>) ((Map<String, Object>) loaded).get("errors");
}
private static Map<String, Contract> declaredInCode() {
Map<String, Contract> declared = new LinkedHashMap<>();
Matcher matcher = ENUM_ENTRY.matcher(read(SOURCE));
@@ -1,11 +1,15 @@
package dev.caskeleton.application.idempotency;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.OperationalError;
/**
* Raised when another attempt still holds the same {@link IdempotencyScopeDigest}. Framework-free,
* application-owned; the web adapter maps it to a {@code IDEMPOTENT_IN_FLIGHT} 409 (retryable=false
* application-owned; every transport maps it to a {@code IDEMPOTENT_IN_FLIGHT} 409 (retryable=false
* — the client polls). The message carries only the opaque scope digest, for logs.
*/
public class IdempotencyInFlightException extends RuntimeException {
public class IdempotencyInFlightException extends RuntimeException implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
@@ -24,4 +28,9 @@ public class IdempotencyInFlightException extends RuntimeException {
private IdempotencyInFlightException(String scopeDiagnostic) {
super("idempotent request still in flight: " + scopeDiagnostic);
}
@Override
public ApiErrorCode errorCode() {
return OperationalError.IDEMPOTENT_IN_FLIGHT;
}
}
@@ -1,11 +1,21 @@
package dev.caskeleton.application.idempotency;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.OperationalError;
/** Raised when request replay cannot safely decide whether an external effect already occurred. */
public final class IdempotencyRecoveryRequiredException extends RuntimeException {
public final class IdempotencyRecoveryRequiredException extends RuntimeException
implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
public IdempotencyRecoveryRequiredException(String message) {
super(message);
}
@Override
public ApiErrorCode errorCode() {
return OperationalError.IDEMPOTENCY_RECOVERY_REQUIRED;
}
}
@@ -1,12 +1,17 @@
package dev.caskeleton.application.idempotency;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.OperationalError;
/**
* Raised when an {@code Idempotency-Key} is reused with a different request body (same {@link
* IdempotencyScopeDigest}, different {@link RequestFingerprint}). Framework-free,
* application-owned; the web adapter maps it to a {@code IDEMPOTENT_REQUEST_MISMATCH} 422
* application-owned; every transport maps it to a {@code IDEMPOTENT_REQUEST_MISMATCH} 422
* (retryable=false). The message carries only the opaque scope digest, for logs.
*/
public class IdempotencyRequestMismatchException extends RuntimeException {
public class IdempotencyRequestMismatchException extends RuntimeException
implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
@@ -25,4 +30,9 @@ public class IdempotencyRequestMismatchException extends RuntimeException {
private IdempotencyRequestMismatchException(String scopeDiagnostic) {
super("idempotency key reused with a different request body: " + scopeDiagnostic);
}
@Override
public ApiErrorCode errorCode() {
return OperationalError.IDEMPOTENT_REQUEST_MISMATCH;
}
}
@@ -1,11 +1,21 @@
package dev.caskeleton.application.idempotency;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.OperationalError;
/** Fail-closed signal raised before an action when request-replay coordination is unavailable. */
public final class IdempotencyUnavailableException extends RuntimeException {
public final class IdempotencyUnavailableException extends RuntimeException
implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
public IdempotencyUnavailableException() {
super("idempotency coordination is unavailable");
}
@Override
public ApiErrorCode errorCode() {
return OperationalError.IDEMPOTENCY_UNAVAILABLE;
}
}
@@ -0,0 +1,37 @@
package dev.caskeleton.application.idempotency;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.OperationalError;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class IdempotencyFailureCodeTest {
static Stream<Arguments> failures() {
return Stream.of(
Arguments.of(
IdempotencyInFlightException.forScopeDigest("digest"),
OperationalError.IDEMPOTENT_IN_FLIGHT),
Arguments.of(
IdempotencyRequestMismatchException.forScopeDigest("digest"),
OperationalError.IDEMPOTENT_REQUEST_MISMATCH),
Arguments.of(
new IdempotencyUnavailableException(), OperationalError.IDEMPOTENCY_UNAVAILABLE),
Arguments.of(
new IdempotencyRecoveryRequiredException("outcome unknown"),
OperationalError.IDEMPOTENCY_RECOVERY_REQUIRED));
}
@ParameterizedTest
@MethodSource("failures")
void everyIdempotencyFailureCarriesItsOperationalCode(
RuntimeException failure, OperationalError expected) {
assertThat((Object) failure)
.isInstanceOfSatisfying(
ApiErrorCarrier.class, carrier -> assertThat(carrier.errorCode()).isEqualTo(expected));
}
}
@@ -2,7 +2,6 @@ package dev.caskeleton.application.fileserver.api.error;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.Category;
import java.util.Locale;
/**
* Stable Fileserver failure vocabulary shared by every transport adapter.
@@ -18,8 +17,10 @@ import java.util.Locale;
* servlet transport, the reactive transport and the Nginx delegation path cannot answer the same
* failure three different ways.
*
* <p>The URN is the {@code type} member of the emitted problem detail and has no counterpart in the
* shared contract, so it remains Fileserver-specific.
* <p>{@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).
*/
public enum FileserverErrorCode implements ApiErrorCode {
BAD_REQUEST(400, Category.VALIDATION, false),
@@ -54,8 +55,6 @@ public enum FileserverErrorCode implements ApiErrorCode {
TRANSFER_TIMEOUT(504, Category.TRANSIENT_DEPENDENCY, true),
STORAGE_FULL(507, Category.TRANSIENT_DEPENDENCY, false);
private static final String PROBLEM_TYPE_PREFIX = "urn:fileserver:problem:";
private final int httpStatus;
private final Category category;
private final boolean retryable;
@@ -93,9 +92,4 @@ public enum FileserverErrorCode implements ApiErrorCode {
public boolean retryable() {
return retryable;
}
/** Problem-detail {@code type} URN, for example {@code urn:fileserver:problem:file-not-found}. */
public String problemType() {
return PROBLEM_TYPE_PREFIX + name().toLowerCase(Locale.ROOT).replace('_', '-');
}
}
@@ -5,7 +5,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.api.FileState;
import dev.caskeleton.application.fileserver.api.UploadId;
import dev.caskeleton.shared.error.OperationalError;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.junit.jupiter.api.Test;
@@ -70,10 +73,30 @@ class FileserverExceptionTest {
@ParameterizedTest
@EnumSource(FileserverErrorCode.class)
void everyCodeMapsToADesignStatusAndAStableProblemUrn(FileserverErrorCode code) {
void everyCodeMapsToADesignStatus(FileserverErrorCode code) {
assertThat(DESIGN_STATUSES).contains(code.httpStatus());
assertThat(code.problemType()).startsWith("urn:fileserver:problem:");
assertThat(code.problemType()).doesNotContain("_");
}
@ParameterizedTest
@EnumSource(FileserverErrorCode.class)
void aCodeNamedLikeAnOperationalErrorMeansTheSameOnTheWire(FileserverErrorCode code) {
// given
List<Object> fileserverWire = List.of(code.category(), code.httpStatus(), code.retryable());
// when
List<List<Object>> operationalWiresWithTheSameName =
Arrays.stream(OperationalError.values())
.filter(operational -> operational.code().equals(code.code()))
.map(
operational ->
List.<Object>of(
operational.category(), operational.httpStatus(), operational.retryable()))
.toList();
// then
assertThat(operationalWiresWithTheSameName)
.as("a shared code name must not carry a second meaning")
.allMatch(fileserverWire::equals);
}
@Test
@@ -2,7 +2,6 @@ package dev.caskeleton.composition.fileserver;
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.problem.FileserverProblemFactory;
import dev.caskeleton.adapter.inbound.web.fileserver.security.FileserverRequestContextFactory;
import dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure.FileserverPlatformSettings;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@@ -19,12 +18,6 @@ class FileserverWebAssemblyConfiguration {
return new FileserverRequestContextFactory(properties.instanceId());
}
@Bean
@ConditionalOnMissingBean
FileserverProblemFactory fileserverProblemFactory() {
return new FileserverProblemFactory();
}
@Bean
@ConditionalOnMissingBean
RawUploadRequestMapper fileserverRawUploadRequestMapper(FileserverPlatformSettings properties) {

Some files were not shown because too many files have changed in this diff Show More