From 98c42fd0b3d9f03f0d46641b491fb8a615442e76 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 14:31:42 +0900 Subject: [PATCH 1/5] =?UTF-8?q?fix(notification)!:=20=EA=B0=99=EC=9D=80=20?= =?UTF-8?q?=ED=82=A4=C2=B7=EB=8B=A4=EB=A5=B8=20plan=EC=9D=98=20=EC=95=8C?= =?UTF-8?q?=EB=A6=BC=20=EC=A0=9C=EC=B6=9C=EC=9D=84=20422=20carrier?= =?UTF-8?q?=EB=A1=9C=20=EB=8B=B5=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NotificationSubmissionService는 이미 다른 plan에 쓴 idempotencyKey를 받으면 IdempotencyConflictException을 던진다. 그 예외는 NotificationException만 잇고 ApiErrorCarrier가 아니어서, controller에도 web-notification에도 받는 곳이 없다. web GlobalExceptionHandler가 500 INTERNAL_ERROR와 ERROR 로그, span 오류로 답한다. notification:submit 권한자가 잘못된 요청만으로 5xx 경보를 반복해 울리고, 클라이언트는 자기 잘못과 서버 장애를 가르지 못한다. docs/manual/06-errors.md는 클라이언트 탓이면 carrier, manual 05는 이 경우 코드를 IDEMPOTENCY_CONFLICT라고 약속했다. 이 예외만 ApiErrorCarrier를 구현한다. code는 새 기능 enum NotificationSubmissionErrorCode의 IDEMPOTENCY_CONFLICT(422, VALIDATION, retryable false)다. converge로 가는 길 셋(키를 찾은 제출, 동시 제출에서 insert에 진 제출, 중복 제거로 버린 제출을 저장하다 진 제출)이 같은 throw라 함께 바뀐다. service의 throw 자리와 descriptor(IDEMPOTENCY_CONFLICT, INVALID_PAYLOAD)는 그대로이고, 응답 category VALIDATION은 errorCode()에서만 나온다. 버린 안: executor의 IDEMPOTENT_REQUEST_MISMATCH 422를 다시 쓰기(manual 05의 알림 코드를 버리고 KEYED 헤더 전용 계약을 넓힌다), web-notification에만 처리기 두기(HTTP만 고쳐지고 다른 전송은 500으로 남는다), NotificationException 전체를 carrier로 만들기(서버 쪽 실패까지 4xx가 된다). 안 A는 review 허브가 project-docs README 7절 1번으로 고른 권하는 안이고 소유자가 정한 것이 아니다. 결정 색인 2.3절에 그렇게 적었다. 위험·한계: 공개 계약 변경이다. 500을 「같은 키 재사용」으로 읽던 클라이언트와 5xx만 세던 경보는 422를 새로 다뤄야 한다. 예외 타입은 그대로라 직접 잡던 코드는 그대로 동작한다. 알림 code 목록(NotificationFailureCode)과 템플릿 오류 code registry는 넓히지 않았다. 공개 타입이 하나 늘어 notification API surface 기준선이 377에서 378이 된다. 다른 NotificationException(검증, template 없음 등)의 HTTP 응답은 이 변경이 바꾸지 않는다. 기본 jar에는 알림 capability가 없어 이 경로가 없다. 검증: AcceptNotificationApplicationUseCaseTest의 표 둘이 진짜 Accept → Submit → service(동시 제출 두 길은 request 저장 fake의 새 missNextIdempotencyLookup, 버린 제출 길은 Submit부터)로 같은 키·다른 variables가 IdempotencyConflictException·message·carrier code(code, category, status, retryable)·저장 1행을, 같은 요청은 첫 receipt id를 단언한다. NotificationSubmissionControllerTest는 service와 같게 만든 예외를 실제 GlobalExceptionHandler로 보내 422·같은 error 본문·처리기 로그 0줄· span 오류 0을, carrier가 아닌 IllegalStateException은 500·ERROR 한 줄· span INTERNAL_ERROR를 단언한다. 노트북 감싸개 :application-notification:check, :adapter:inbound:web-notification:check, :adapter:outbound:notification:verifyNotificationApiSurface rc=0, check-docs.py·check-work-docs.py OK. BREAKING CHANGE: 알림 제출이 같은 idempotencyKey로 다른 plan을 받으면 500 INTERNAL_ERROR 대신 422 IDEMPOTENCY_CONFLICT(category VALIDATION, retryable false)로 답하고 서버 오류 로그를 남기지 않는다. IdempotencyConflictException이 ApiErrorCarrier를 구현한다. 옮기는 법은 docs/upgrade/2026-11-notification-idempotency-conflict.md 2.1절이다. Refs: REV-BE-0054 --- docs/manual/05-idempotency.md | 8 +- docs/notification/api-surface-snapshot.txt | 3 +- ...26-11-notification-idempotency-conflict.md | 37 ++++ docs/web/http-contract.md | 6 +- docs/work/reference/decisions.md | 1 + .../NotificationSubmissionController.java | 6 + .../SubmitNotificationHttpRequest.java | 4 +- .../NotificationSubmissionControllerTest.java | 119 ++++++++++++ .../error/IdempotencyConflictException.java | 23 ++- .../NotificationSubmissionErrorCode.java | 51 +++++ ...eptNotificationApplicationUseCaseTest.java | 175 ++++++++++++++++++ .../InMemoryNotificationRequestStore.java | 17 ++ 12 files changed, 442 insertions(+), 8 deletions(-) create mode 100644 docs/upgrade/2026-11-notification-idempotency-conflict.md create mode 100644 src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationSubmissionErrorCode.java diff --git a/docs/manual/05-idempotency.md b/docs/manual/05-idempotency.md index 62f3285c..8b4576f4 100644 --- a/docs/manual/05-idempotency.md +++ b/docs/manual/05-idempotency.md @@ -53,12 +53,16 @@ executor는 **응답을 다시 돌려주는 기록**이다: HTTP `Idempotency-Ke | 어디 | 키 | 같은 키·같은 요청 | 같은 키·다른 요청 | 수명 | | --- | --- | --- | --- | --- | | executor(KEYED 유스케이스) | `Idempotency-Key` 헤더의 scope digest | 저장된 응답 재생 | 422 `IDEMPOTENT_REQUEST_MISMATCH` | TTL | -| 알림 받기(`AcceptNotificationApplicationUseCase`) | 본문의 `idempotencyKey`. 없으면 알림 plan 지문 | 처음 만든 알림의 receipt | `IDEMPOTENCY_CONFLICT`(요청 지문 비교) | 알림 행과 같다 | +| 알림 받기(`AcceptNotificationApplicationUseCase`) | 본문의 `idempotencyKey`. 없으면 알림 plan 지문 | 처음 만든 알림의 receipt | 422 `IDEMPOTENCY_CONFLICT`(retryable=false). 본문이 아니라 plan 지문을 견준다 | 알림 행과 같다 | | durable operation 제출(`SubmitDurableOperationUseCase`) | 제출 scope(tenant·principal·operation 이름)와 payload 지문 | 처음 받은 operation | 지문이 키에 들어 있어 다른 키다. 새 operation | operation 보존 기간 | - 알림: 키는 tenant 안에서 같은 알림을 한 번만 만드는 업무 키다. 저장소의 유일 제약이 동시 제출을 막고, 진 쪽은 이긴 행을 읽어 같은 receipt로 수렴한다. 키를 주지 않은 호출자도 중복을 막도록 plan 지문으로 키를 만든다. executor로 옮기면 TTL - 뒤 같은 알림을 다시 만들고, 키 없는 호출은 중복을 막지 못한다. 저장한 키 값을 어떻게 다룰지(원본 저장)는 보안 검토 + 뒤 같은 알림을 다시 만들고, 키 없는 호출은 중복을 막지 못한다. +- 알림의 「같은 요청」은 같은 plan이다. 지문은 본문이 아니라 기본값(version·locale)을 채운 plan으로 만든다. 그래서 변수 + 순서나 생략한 version처럼 본문만 다르면 같은 receipt다. 같은 키로 다른 plan을 보내면 422 `IDEMPOTENCY_CONFLICT`다. 키를 + 먼저 찾았든, 동시 제출에서 저장에 졌든 같은 답이다. 이 예외는 `ApiErrorCarrier`라 모든 전송이 같은 code로 답하고, + 서버 오류 로그를 남기지 않는다. 다시 보내도 같은 답이니 새 알림이면 새 키를 쓴다. 저장한 키 값을 어떻게 다룰지(원본 저장)는 보안 검토 항목이다. - durable operation: 결정 15·26(서버가 id를 만들고 payload 지문으로 재제출을 판정)이 정한다. capability의 `KEYED`는 "같은 scope·같은 payload로 다시 보내면 같은 작업"이라는 뜻이고, 그 판정은 operation 저장소의 scope 유일성이 한다. diff --git a/docs/notification/api-surface-snapshot.txt b/docs/notification/api-surface-snapshot.txt index 9b274554..f1ecb1ce 100644 --- a/docs/notification/api-surface-snapshot.txt +++ b/docs/notification/api-surface-snapshot.txt @@ -2,7 +2,7 @@ # Every top-level public type under the platform packages. Growth is a reviewed change. # Update only after review with: # ./gradlew :adapter:outbound:notification:updateNotificationApiSurface -PapproveNotificationApiSurfaceChange -# types: 377 +# types: 378 dev.caskeleton.adapter.outbound.notification.NotificationConfig dev.caskeleton.adapter.outbound.notification.NotificationRoutesSettings dev.caskeleton.adapter.outbound.notification.core.FailOpenNotificationProvider @@ -174,6 +174,7 @@ dev.caskeleton.application.notification.platform.api.error.IdempotencyConflictEx dev.caskeleton.application.notification.platform.api.error.NotificationException dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor +dev.caskeleton.application.notification.platform.api.error.NotificationSubmissionErrorCode dev.caskeleton.application.notification.platform.api.error.NotificationValidationException dev.caskeleton.application.notification.platform.api.error.ProviderConfigurationException dev.caskeleton.application.notification.platform.api.error.ProviderPayloadLimitException diff --git a/docs/upgrade/2026-11-notification-idempotency-conflict.md b/docs/upgrade/2026-11-notification-idempotency-conflict.md new file mode 100644 index 00000000..233e22f2 --- /dev/null +++ b/docs/upgrade/2026-11-notification-idempotency-conflict.md @@ -0,0 +1,37 @@ +# 업그레이드 안내 — 2026-11 알림 제출의 같은 키·다른 요청 + +- 범위: 알림 제출(`POST /notifications`, `AcceptNotificationUseCase`·`SubmitNotificationUseCase`)이 이미 다른 알림에 + 쓴 `idempotencyKey`를 받았을 때의 응답을 바꾼 변경. 설정 키는 그대로다. 공개 타입이 하나 늘었다 + (`NotificationSubmissionErrorCode`). 기본 jar에는 이 경로가 없다. 알림 capability(`:composition:notification-platform`)를 + 실은 서비스만 해당한다. +- 근거: 2026-11-22 리뷰 발견 REV-BE-0054. 클라이언트 탓인 실패는 carrier로 답한다는 것은 `docs/manual/06-errors.md` + 「어떤 예외 타입으로 던지나」가, 이 경우의 코드 `IDEMPOTENCY_CONFLICT`는 `docs/manual/05-idempotency.md` + 「executor를 쓰지 않는 중복 판정 둘」이 이미 약속했다. status를 적은 문서는 없었다. + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 알림 capability를 켜고 `POST /notifications`나 +알림 제출 유스케이스를 부르는 서비스다. + +## 2. 바뀐 동작 + +### 2.1 2026-11-23 — 같은 키·다른 plan을 422로 (따라 할 일 있음) + +| # | 바뀐 것 | 전에는 | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | --- | --- | +| 1 | `IdempotencyConflictException`이 `ApiErrorCarrier`를 구현한다. code는 `NotificationSubmissionErrorCode.IDEMPOTENCY_CONFLICT`(422, category `VALIDATION`, retryable false)다. 공용 처리기(web `GlobalExceptionHandler`, GraphQL, gRPC, STOMP)가 모두 code `IDEMPOTENCY_CONFLICT`로 답한다. web은 422와 고정 문구의 error 본문이고 서버 오류 로그·span 오류를 남기지 않는다. 키를 먼저 찾은 제출, 동시 제출에서 저장에 진 제출, 중복 제거로 버린 제출을 저장하다 진 제출이 모두 같은 답이다. 견주는 것은 본문이 아니라 기본값을 채운 plan의 지문이다. 예외 타입·descriptor(`IDEMPOTENCY_CONFLICT`, `INVALID_PAYLOAD`)·메시지는 그대로다 | 예외가 carrier가 아니어서 공용 처리기가 500 `INTERNAL_ERROR`로 답하고 ERROR 로그와 span 오류를 남겼다. 5xx 경보가 울렸다 | 500을 「같은 키 재사용」으로 읽던 클라이언트·모니터링을 422 `IDEMPOTENCY_CONFLICT`로 바꾼다. 다시 보내지 않고, 새 알림이면 새 키를 만든다. 이 예외를 잡아 직접 응답을 만들던 서비스 코드는 그대로 둬도 된다. 공용 처리기에 맡겼다면 고칠 코드는 없다(응답이 422로 바뀐다) | 클라이언트가 422를 모르면 이 거절을 처리하지 못하고, 5xx만 세던 경보 규칙은 이 거절을 더 보지 않는다 | 알림 capability를 켠 서비스 | + +## 3. 바뀌지 않은 것 + +- 같은 키·같은 plan은 전처럼 처음 receipt를 다시 준다. 동시 제출에서 진 쪽도 같다. +- `NotificationSubmissionService`가 이 예외를 던지는 자리와 조건은 그대로다. +- 다른 `NotificationException`(검증, template 없음 등)의 응답은 이 변경이 바꾸지 않는다. +- 오류 code 목록(`NotificationFailureCode`)과 템플릿 오류 code registry(`docs/registries/error-codes.yaml`)는 그대로다. + 응답 code는 전송이 읽는 `NotificationSubmissionErrorCode`에 두었다. descriptor의 category(`INVALID_PAYLOAD`)와 응답 + category(`VALIDATION`)는 다른 어휘다. +- KEYED 유스케이스의 `Idempotency-Key` 헤더 불일치는 전처럼 422 `IDEMPOTENT_REQUEST_MISMATCH`다. 알림 제출 본문의 + `idempotencyKey`는 그 헤더가 아니다. + +## 4. 되돌리는 법 + +carrier 구현, `NotificationSubmissionErrorCode`, 문서와 API surface 기준선 행을 함께 revert하고, 이 문서에 되돌린 행을 더한다. diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index e74fb134..9b1686a9 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -14,7 +14,8 @@ 실행 전 거부와 결과 불명의 구분은 `IdempotencyExecutorTest`, lease 하한은 `IdempotencySettingsTest` - 헤더 규칙(3절): `WebMvcRequestIdFilterTest`, `CorsSecurityFilterIntegrationTest` - web 전용 코드(4절): `TransportErrorHandlingTest`, `IdempotencyKeyHeaderTest`, web-advanced - `WebAdvancedErrorMappingTest` + `WebAdvancedErrorMappingTest`, 알림 제출의 `IDEMPOTENCY_CONFLICT`는 web-notification + `NotificationSubmissionControllerTest` ## 1. Envelope 키 존재 규칙 @@ -190,7 +191,7 @@ CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의 ## 4. web 전용 오류 코드 `OperationalError`(`docs/registries/error-codes.yaml`) 밖의 코드다. HTTP 어댑터가 내는 코드와, 기능 leaf의 enum이 내고 -HTTP가 그대로 답하는 코드(`DELIVERY_ATTEMPT_NOT_FOUND`)가 있다. +HTTP가 그대로 답하는 코드(`DELIVERY_ATTEMPT_NOT_FOUND`, `IDEMPOTENCY_CONFLICT`)가 있다. | 코드 | status | category | `retryable` | `Retry-After` | 언제 | | --- | --- | --- | --- | --- | --- | @@ -200,6 +201,7 @@ HTTP가 그대로 답하는 코드(`DELIVERY_ATTEMPT_NOT_FOUND`)가 있다. | `RATE_LIMIT_INCOMPATIBLE` | 503 | `INTERNAL` | `false` | 없음 | rate-limit 제공자가 계약과 맞지 않음 | | `OPERATION_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | durable operation 조회(`DurableOperationController`)에서 그 operation이 없거나 다른 호출자의 것이다. 둘을 가르지 않는다 | | `DELIVERY_ATTEMPT_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | 알림 운영자 redrive(`RedriveDeliveryUseCase`)가 받은 attempt가 없거나 운영자 tenant 밖이다. 둘을 가르지 않는다. 코드는 `application-notification`의 `NotificationAdminErrorCode`라 모든 전송이 같은 코드로 답한다. 템플릿은 이 연산의 전송을 싣지 않는다(`docs/notification/operations.md`) | +| `IDEMPOTENCY_CONFLICT` | 422 | `VALIDATION` | `false` | 없음 | 알림 제출(`POST /notifications`)이 본문의 `idempotencyKey`를 이미 다른 알림에 쓴 키로 받았다. 견주는 것은 본문이 아니라 알림 plan 지문이다. 2절의 `Idempotency-Key` 헤더와는 다른 키라 `IDEMPOTENT_REQUEST_MISMATCH`가 아니다. 다시 보내지 않는다. 새 알림이면 새 키를 쓴다. 코드는 `application-notification`의 `NotificationSubmissionErrorCode`라 모든 전송이 같은 코드로 답한다(`docs/manual/05-idempotency.md` 「executor를 쓰지 않는 중복 판정 둘」) | - 컨트롤러 파라미터 제약 위반(`@RequestParam @Max(10)`)은 요청 본문 위반과 같은 `400 VALIDATION_FAILED`이고 `details`는 `[{field, code, message}]`다. 거절된 값은 싣지 않는다. diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index f7032c98..421c38e6 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -112,6 +112,7 @@ | Draft-12 offset 불일치 | problem 문서는 프로토콜 예외로 유지 | 소유자 | 결정 12 | | 알림 category 생략 | 거부(400), 판정은 유스케이스 | 소유자 | 결정 13 | | 알림 redrive의 없는·남의 attempt | 없는 attempt id와 운영자 tenant 밖의 attempt를 같은 404 carrier(`DeliveryAttemptNotFoundException`, code `DELIVERY_ATTEMPT_NOT_FOUND`) 하나로 답한다. 권한 거절(403)로 바꾸는 안과 문서만 500으로 고치는 안은 버렸다. 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다. 다른 운영자 연산의 tenant 거절은 그대로다 | 기본값(2026-11-22, review 허브가 고른 권하는 안, 자율 운영. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0039 정정(2026-11-22 12:51), `docs/upgrade/2026-11-notification-admin-redrive.md` 2.1절 | +| 알림 제출의 같은 키·다른 plan | 알림 제출이 이미 다른 plan에 쓴 `idempotencyKey`를 받으면 422 carrier(`IdempotencyConflictException`, code `IDEMPOTENCY_CONFLICT`, category `VALIDATION`, retryable false)로 답한다. code는 기능 enum `NotificationSubmissionErrorCode`에 둔다. executor의 `IDEMPOTENT_REQUEST_MISMATCH`를 다시 쓰는 안과 web-notification에만 처리기를 두는 안은 버렸다. `NotificationException` 전체를 carrier로 만들지 않는다(서버 쪽 실패까지 4xx가 된다). 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다 | 기본값(2026-11-22, review 허브가 고른 권하는 안, 자율 운영. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0054 요청(2026-11-22 12:58), `docs/upgrade/2026-11-notification-idempotency-conflict.md` 2.1절 | | 오류 코드 로그 레벨 | `error-codes.yaml`에 `log_level` 칸을 두지 않는다. 레벨은 실패 종류·경로가 정한다(`ServerFailureLog`, 보안 필터 `AuthErrorResponseWriter`). 칸이 다시 생기면 `OperationalErrorRegistryContractTest`가 실패한다. 보안 필터는 5xx(`AUTH_JWKS_UNAVAILABLE`·`INTERNAL_AUTH_MISCONFIGURATION`)를 ERROR, 4xx를 WARN으로 남긴다. 401 서명·issuer·audience 불일치는 WARN | 소유자 | 2026-11-06, `docs/design/2026-11-06-error-code-log-level-design.md` 10절 | | 감싼 carrier를 전송이 읽는 법 | web·GraphQL·STOMP·gRPC 네 전송 모두 원인 사슬의 첫 carrier를 본다. 감싼 carrier의 응답이 500 `INTERNAL_ERROR` 대신 그 carrier의 코드가 된다. 그보다 먼저 답하는 것은 아래 「GraphQL 판정 순서」(등록 매핑)와 「인자 변환 단계의 감싼 carrier」 두 행이다 | 소유자 | `1103` 18.4절(RR7-01-05), 2026-11-06 | | GraphQL 판정 순서 | 플랫폼 거부 → 실패 자신이 carrier → 등록된 application 매핑 → 원인 사슬의 첫 carrier → 거부된 인자(`IllegalArgumentException`, 인자 binder의 `BindException`) → 가림(`INTERNAL_ERROR`). 앱이 등록한 실패는 carrier를 원인으로 들어도 등록한 코드로 답한다(web에서 앱의 도메인 advice가 먼저 받는 것과 같다). 실패 자신이 carrier인 타입(예: `LockAcquisitionTimeoutException`)을 등록한 매핑은 쓰이지 않는다. 로그 줄은 어느 단계가 답하든 원인 사슬의 첫 carrier로 정한다 — 등록 매핑이 답해도 그 안의 서버 쪽 carrier 줄은 남는다 | 소유자(2026-11-07). 로그 줄도 소유자(2026-11-07, 기본값 확인) | `1103` 19.4절 ①(RR8-01-01), 2026-11-07 총괄 세션 전달 | diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java index 9bc663d0..99a2c352 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java @@ -33,6 +33,12 @@ import org.springframework.web.bind.annotation.RestController; *

Authenticated like every other non-public path, and authorized by {@code notification:submit} * on the use case rather than here. A transport that decided its own permissions would be a second * authorization model to keep in step with the first. + * + *

Repeating a submission with the same {@code idempotencyKey} answers the first receipt again + * when it makes the same notification plan. A different plan under that key is refused with {@code + * 422 IDEMPOTENCY_CONFLICT}, not retryable. The use case raises it as an {@code ApiErrorCarrier}, + * so the shared error handler answers it like any other client error; this controller catches + * nothing. */ @RestController @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/SubmitNotificationHttpRequest.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/SubmitNotificationHttpRequest.java index ce5cbcba..cd84bf89 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/SubmitNotificationHttpRequest.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/SubmitNotificationHttpRequest.java @@ -24,7 +24,9 @@ import java.util.Map; * @param templateVersion the version to pin; 1 when the caller omits it * @param locale the BCP 47 language tag to render in; the platform default when omitted * @param variables template variables, as JSON scalars, lists and objects - * @param idempotencyKey the caller's key; derived from the request when omitted + * @param idempotencyKey the caller's key, one notification per key within the tenant; derived from + * the request when omitted. Reusing it for a different notification plan is refused with {@code + * 422 IDEMPOTENCY_CONFLICT} * @param category the routing and reporting category; required — the application refuses a * submission without one (400) instead of guessing, since it decides marketing suppression */ diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java index 6cb97c21..81f42528 100644 --- a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java @@ -4,8 +4,19 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import 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 com.jayway.jsonpath.JsonPath; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; +import dev.caskeleton.application.notification.platform.api.error.FailureCategory; +import dev.caskeleton.application.notification.platform.api.error.IdempotencyConflictException; +import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; +import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor; import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationCommand; +import dev.caskeleton.shared.error.Category; +import dev.caskeleton.shared.error.ClientErrorMessages; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import java.util.ArrayList; import java.util.List; @@ -13,12 +24,23 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; class NotificationSubmissionControllerTest { + private static final String ANSWER_FIELDS = + "[status, success, error code, category, message, retryable, handler log levels, span error" + + " codes]"; + + private static final String KEYED_SUBMISSION = + "{\"recipientRef\":\"r-1\",\"channel\":\"EMAIL\",\"address\":\"a@example.com\"," + + "\"template\":\"welcome\",\"variables\":{\"amount\":\"1000\"}," + + "\"idempotencyKey\":\"order-1\",\"category\":\"TRANSACTIONAL\"}"; + private final List accepted = new ArrayList<>(); private final MockMvc mvc = @@ -82,4 +104,101 @@ class NotificationSubmissionControllerTest { .doesNotContain("%%%"); assertThat(accepted).isEmpty(); } + + /** + * A key the caller reused with a different request is the caller's mistake: 422 with the + * notification's own code, and nothing the error handler counts as a server failure — no log + * line, no span error. The exception is built exactly as the submission service raises it. + */ + @Test + void aKeyReusedWithADifferentRequestAnswers422AndRecordsNoServerFailure() throws Exception { + // given + IdempotencyConflictException conflict = + new IdempotencyConflictException( + NotificationFailureDescriptor.preDispatch( + NotificationFailureCode.IDEMPOTENCY_CONFLICT, FailureCategory.INVALID_PAYLOAD)); + + // when + List answer = answerWhenTheUseCaseThrows(conflict); + + // then + assertThat(answer) + .as(ANSWER_FIELDS) + .containsExactly( + 422, + false, + "IDEMPOTENCY_CONFLICT", + "VALIDATION", + ClientErrorMessages.of(Category.VALIDATION), + false, + List.of(), + List.of()); + } + + /** A failure that carries no code is still a server fault: 500, logged and recorded. */ + @Test + void aFailureCarryingNoCodeStillAnswers500AndIsRecordedAsAServerFailure() throws Exception { + // when + List answer = + answerWhenTheUseCaseThrows(new IllegalStateException("contact point store unreadable")); + + // then + assertThat(answer) + .as(ANSWER_FIELDS) + .containsExactly( + 500, + false, + "INTERNAL_ERROR", + "INTERNAL", + ClientErrorMessages.OPAQUE, + false, + List.of(Level.ERROR), + List.of("INTERNAL_ERROR")); + } + + /** + * Sends a keyed submission to a use case that fails with {@code failure}, through the real error + * handler, and reads what the caller and the handler's diagnostics saw. + */ + private static List answerWhenTheUseCaseThrows(RuntimeException failure) + throws Exception { + List spanErrorCodes = new ArrayList<>(); + MockMvc failing = + MockMvcBuilders.standaloneSetup( + new NotificationSubmissionController( + command -> { + throw failure; + })) + .setControllerAdvice( + new GlobalExceptionHandler((error, code) -> spanErrorCodes.add(code))) + .build(); + Logger handlerLogger = (Logger) LoggerFactory.getLogger(GlobalExceptionHandler.class); + ListAppender handlerLog = new ListAppender<>(); + handlerLog.start(); + handlerLogger.addAppender(handlerLog); + MockHttpServletResponse response; + try { + response = + failing + .perform( + post("/notifications") + .contentType(MediaType.APPLICATION_JSON) + .content(KEYED_SUBMISSION)) + .andReturn() + .getResponse(); + } finally { + handlerLogger.detachAppender(handlerLog); + handlerLog.stop(); + } + String body = response.getContentAsString(); + return List.of( + response.getStatus(), + JsonPath.read(body, "$.success"), + JsonPath.read(body, "$.error.code"), + JsonPath.read(body, "$.error.category"), + JsonPath.read(body, "$.error.message"), + JsonPath.read(body, "$.error.retryable"), + handlerLog.list.stream().map(ILoggingEvent::getLevel).toList(), + spanErrorCodes); + } } diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/IdempotencyConflictException.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/IdempotencyConflictException.java index d821e409..ab390560 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/IdempotencyConflictException.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/IdempotencyConflictException.java @@ -1,11 +1,30 @@ package dev.caskeleton.application.notification.platform.api.error; -/** Same idempotency key reused with a different request fingerprint. */ -public class IdempotencyConflictException extends NotificationException { +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + +/** + * Same idempotency key reused with a different request fingerprint. + * + *

The fingerprint is the notification plan's, not the request body's: two bodies that make the + * same plan converge on the first receipt, and only a different plan under the same key lands here. + * That is the caller's failure, not a server fault, so a transport answers {@link + * NotificationSubmissionErrorCode#IDEMPOTENCY_CONFLICT} (422) and logs no server failure. + * + *

The {@linkplain #descriptor() descriptor} keeps the closed notification registry ({@code + * IDEMPOTENCY_CONFLICT}, {@code INVALID_PAYLOAD}). The status and the client category on the wire + * come from {@link #errorCode()} alone. + */ +public class IdempotencyConflictException extends NotificationException implements ApiErrorCarrier { private static final long serialVersionUID = 1L; public IdempotencyConflictException(NotificationFailureDescriptor descriptor) { super(descriptor); } + + @Override + public ApiErrorCode errorCode() { + return NotificationSubmissionErrorCode.IDEMPOTENCY_CONFLICT; + } } diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationSubmissionErrorCode.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationSubmissionErrorCode.java new file mode 100644 index 00000000..bd61c0aa --- /dev/null +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationSubmissionErrorCode.java @@ -0,0 +1,51 @@ +package dev.caskeleton.application.notification.platform.api.error; + +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.Category; + +/** + * Codes a notification submission answers a transport with when the caller's request is at fault. + * + *

The closed {@link NotificationFailureCode} registry is the platform's own vocabulary — metric + * tags, ledger rows, audit — and carries no status. A transport answers with this code instead, + * read through {@link dev.caskeleton.shared.error.ApiErrorCarrier}, so every transport gives the + * same status without naming the feature. + */ +public enum NotificationSubmissionErrorCode implements ApiErrorCode { + /** + * The idempotency key was already used for a different notification. The stored plan fingerprint + * and this request's differ, so the caller sent a different notification under the same key. Not + * retryable: the same request gets the same answer, and a new notification needs a new key. + */ + IDEMPOTENCY_CONFLICT(422, Category.VALIDATION, false); + + private final int httpStatus; + private final Category category; + private final boolean retryable; + + NotificationSubmissionErrorCode(int httpStatus, Category category, boolean retryable) { + this.httpStatus = httpStatus; + this.category = category; + this.retryable = retryable; + } + + @Override + public String code() { + return name(); + } + + @Override + public Category category() { + return category; + } + + @Override + public int httpStatus() { + return httpStatus; + } + + @Override + public boolean retryable() { + return retryable; + } +} diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java index ac1d51f7..6b912774 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java @@ -3,14 +3,21 @@ package dev.caskeleton.application.notification.platform.dispatch; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.application.notification.platform.api.DeduplicationAction; +import dev.caskeleton.application.notification.platform.api.DeduplicationSpec; import dev.caskeleton.application.notification.platform.api.NotificationId; import dev.caskeleton.application.notification.platform.api.NotificationPlan; import dev.caskeleton.application.notification.platform.api.NotificationReceipt; import dev.caskeleton.application.notification.platform.api.NotificationVariable; import dev.caskeleton.application.notification.platform.api.RequestStatus; +import dev.caskeleton.application.notification.platform.api.error.IdempotencyConflictException; import dev.caskeleton.application.notification.platform.api.routing.Channel; +import dev.caskeleton.application.notification.platform.api.routing.ExplicitChannel; import dev.caskeleton.application.notification.platform.contact.ContactPointValue; import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryContactPointStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryRecipientQueue; import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationCommand; import dev.caskeleton.application.notification.platform.port.in.SubmitNotificationCommand; import dev.caskeleton.application.notification.platform.port.in.SubmitNotificationUseCase; @@ -18,7 +25,10 @@ import dev.caskeleton.application.notification.platform.security.AccessContext; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; import dev.caskeleton.application.notification.platform.security.ProtectedContactPoint; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.Category; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; @@ -29,6 +39,8 @@ import java.util.Map; import java.util.Optional; import java.util.UUID; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; class AcceptNotificationApplicationUseCaseTest { @@ -228,6 +240,169 @@ class AcceptNotificationApplicationUseCaseTest { .hasMessage("defaultLocale must name a language"); } + /** + * A key reused with a different request is refused with the notification's own client code, + * whichever of the three paths the second request takes to the stored one. Every transport reads + * that code from the cause chain, so a refusal without it answers as a server fault. Nothing is + * stored for the refused request. + */ + @ParameterizedTest + @EnumSource(KeyReuse.class) + void aKeyReusedWithADifferentRequestIsRefusedWithTheClientCodeOnEveryPath(KeyReuse path) { + // given + RealSubmission chain = new RealSubmission(); + path.send(chain, "1000"); + path.prepareSecond(chain); + + // when + Throwable refused = catchThrowable(() -> path.send(chain, "9999")); + + // then + assertThat( + List.of( + refused.getClass(), + String.valueOf(refused.getMessage()), + carriedCode(refused), + chain.requests.byId.size())) + .as( + "[exception, message, carried code (code, category, status, retryable), stored requests]") + .containsExactly( + IdempotencyConflictException.class, + "IDEMPOTENCY_CONFLICT", + List.of("IDEMPOTENCY_CONFLICT", Category.VALIDATION, 422, false), + 1); + } + + /** The same key with the same request still converges on the first receipt on every path. */ + @ParameterizedTest + @EnumSource(KeyReuse.class) + void aKeyReusedWithTheSameRequestConvergesOnTheFirstReceiptOnEveryPath(KeyReuse path) { + // given + RealSubmission chain = new RealSubmission(); + NotificationReceipt first = path.send(chain, "1000"); + path.prepareSecond(chain); + + // when + NotificationReceipt second = path.send(chain, "1000"); + + // then + assertThat(List.of(second.notificationId(), chain.requests.byId.size())) + .as("[receipt id, stored requests]") + .containsExactly(first.notificationId(), 1); + } + + /** The carrier's code as code, category, status and retryable; empty when none is carried. */ + private static List carriedCode(Throwable failure) { + return ApiErrorCarrier.firstIn(failure) + .map(carrier -> ((ApiErrorCarrier) carrier).errorCode()) + .>map( + code -> List.of(code.code(), code.category(), code.httpStatus(), code.retryable())) + .orElse(List.of()); + } + + /** + * The three places a second request with a stored key meets the first one in {@code + * NotificationSubmissionService}. + */ + enum KeyReuse { + /** The second acceptance finds the stored request by its key. */ + FOUND_BY_LOOKUP(false), + /** The second acceptance read before the first committed, and loses the insert of the key. */ + LOST_THE_INSERT(true), + /** + * The second submission read before the first committed, deduplication drops it, and storing + * the drop loses the key. An acceptance carries no deduplication, so this path starts at the + * submit use case an acceptance hands its plan to. + */ + LOST_THE_DROP_INSERT(true) { + @Override + NotificationReceipt send(RealSubmission chain, String amount) { + return chain.submit.handle( + new SubmitNotificationCommand( + PlatformFakes.plan( + "order-77", + Map.of("amount", amount), + new ExplicitChannel(Channel.EMAIL), + Optional.empty(), + Optional.of( + new DeduplicationSpec( + "order-77", Duration.ofMinutes(10), DeduplicationAction.DROP))))); + } + }; + + private final boolean secondMissesTheLookup; + + KeyReuse(boolean secondMissesTheLookup) { + this.secondMissesTheLookup = secondMissesTheLookup; + } + + /** Sets up how the second request meets the stored one. */ + void prepareSecond(RealSubmission chain) { + if (secondMissesTheLookup) { + chain.requests.missNextIdempotencyLookup(); + } + } + + /** Sends one request with the key {@code order-77}. */ + NotificationReceipt send(RealSubmission chain, String amount) { + return chain.accept.handle( + new AcceptNotificationCommand( + Optional.empty(), + "customer-42", + Channel.EMAIL, + "person@example.com", + "payment-receipt", + Optional.of(1L), + Optional.of(Locale.KOREAN), + Map.of("amount", new NotificationVariable.TextValue(amount)), + Optional.of("order-77"), + "billing")); + } + } + + /** + * Acceptance over the real submit use case and submission service, on the request store fake, so + * a refusal reaches the caller as the service raises it. + */ + static final class RealSubmission { + private final InMemoryNotificationRequestStore requests = + new InMemoryNotificationRequestStore(); + private final SubmitNotificationUseCase submit; + private final AcceptNotificationApplicationUseCase accept; + + RealSubmission() { + Clock clock = Clock.fixed(NOW, ZoneOffset.UTC); + DirectTransactionPort transactions = new DirectTransactionPort(); + PlatformFakes.SequentialIds ids = new PlatformFakes.SequentialIds(); + submit = + new SubmitNotificationApplicationUseCase( + new NotificationSubmissionService( + requests, + new InMemoryRecipientQueue(requests, clock), + new InMemoryDeliveryAttemptStore(requests), + PlatformFakes.templates(true), + PlatformFakes.fingerprints(), + new CanonicalNotificationPlanWriter(ids, PlatformFakes.routes(Channel.EMAIL)), + transactions, + PlatformFakes.tenant("tenant-a"), + PlatformFakes.deduplication(clock), + new PlatformFakes.RecordingMetrics(), + clock), + transactions); + accept = + new AcceptNotificationApplicationUseCase( + submit, + new InMemoryContactPointStore(clock), + protector(), + PlatformFakes.tenant("tenant-a"), + ids, + PlatformFakes.fingerprints(), + transactions, + clock, + DEFAULT_LOCALE); + } + } + private static AcceptNotificationCommand command(Map variables) { return new AcceptNotificationCommand( Optional.empty(), diff --git a/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java b/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java index a27a5c01..eb95d913 100644 --- a/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java +++ b/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java @@ -44,6 +44,8 @@ public final class InMemoryNotificationRequestStore implements NotificationReque private boolean failNextInsertAsDuplicate; + private boolean missNextIdempotencyLookup; + private BooleanSupplier transactionOpen; /** @@ -67,6 +69,17 @@ public final class InMemoryNotificationRequestStore implements NotificationReque this.failNextInsertAsDuplicate = true; } + /** + * Makes the next idempotency lookup find nothing, as it does for a submission that read before a + * concurrent one with the same key committed. + * + *

The key stays claimed, so the insert that follows loses to the stored row. That is the + * concurrent submission's whole path, which a lookup that sees the row would skip. + */ + public synchronized void missNextIdempotencyLookup() { + this.missNextIdempotencyLookup = true; + } + @Override public synchronized NotificationRequestInsertOutcome insert( NotificationRequestRecord request, List jobs) { @@ -91,6 +104,10 @@ public final class InMemoryNotificationRequestStore implements NotificationReque @Override public synchronized Optional findByIdempotency( TenantId tenantId, String idempotencyKey) { + if (missNextIdempotencyLookup) { + missNextIdempotencyLookup = false; + return Optional.empty(); + } return Optional.ofNullable(byIdempotency.get(key(tenantId, idempotencyKey))).map(byId::get); } -- 2.54.0 From 915ca2ca8b2c3ba4533c895f30781d03240f48a7 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 14:45:18 +0900 Subject: [PATCH 2/5] =?UTF-8?q?fix(notification):=20=EB=A9=B1=EB=93=B1=20?= =?UTF-8?q?=EC=B6=A9=EB=8F=8C=20=EC=95=88=EB=82=B4=EC=9D=98=20=EC=A0=84?= =?UTF-8?q?=EC=86=A1=EB=B3=84=20=EB=8B=B5=EC=9D=84=20=EB=B0=94=EB=A1=9C?= =?UTF-8?q?=EC=9E=A1=EA=B3=A0=20descriptor=EB=A5=BC=20=EA=B3=A0=EC=A0=95?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 98c42fd0b 리뷰(종류 B, 렌즈 넷)가 낸 Medium 1·Low 5와 manual 05의 문장 하나를 고친다. - upgrade 안내는 「이 예외를 잡던 코드는 그대로 둬도 된다」고 했다. GraphQL은 실패 자신이 carrier면 등록 매핑보다 먼저 답하므로, 이 예외나 상위 타입을 GraphQlExceptionResolver에 등록해 자기 code로 답하던 서비스는 그 매핑이 더 쓰이지 않는다(GraphQlWireErrorMapper.sharedCodeOf, 기존 aCarrierTheApplicationAlsoRegisteredIsAnsweredWithItsOwnCode). 할 일 칸에 그 경고와 감싸 던지는 법을 적고, 전송별 답(web 422, GraphQL code·category REQUEST, gRPC INVALID_ARGUMENT와 trailer)을 적는다. (Medium) - STOMP @MessageMapping 실패는 전처럼 frame이 없고 ERROR 로그만 사라진다. 「모든 전송이 같은 code·status」를 manual 05·http-contract·두 Javadoc에서 「실패를 답하는 전송(web·GraphQL·gRPC)이 같은 code」로 좁힌다. (Low) - 기본 locale은 배포 설정이라 그 값이 바뀐 뒤 locale 없는 재전송도 다른 plan이 되어 422다. 예외 Javadoc, manual 05, upgrade 3절에 적는다. (Low) - 응답 code는 고정인데 생성자가 아무 descriptor나 받았다. 생성자가 (IDEMPOTENCY_CONFLICT, INVALID_PAYLOAD) 밖을 IllegalStateException으로 거절한다. service의 throw는 그대로다. NotificationExceptionTest에 표 세 행을 더한다. (Low) - 다른 요청 표의 then이 아무것도 던지지 않으면 NPE로 끝났다. 값이 없으면 "nothing"을 넣어 목록 비교로 실패하게 한다. (Low) - 동시 제출 두 행이 그 길을 지났는지 시험이 보지 않아, fake의 조회 놓치기가 망가지면 :125로 돌아가 조용히 통과했다. fake가 놓친 조회 수 (missedIdempotencyLookups)를 세고 두 표가 행마다 단언한다. (Low) - 98c42fd0b가 manual 05 「알림」 항목 끝 문장(저장한 키 값의 보안 검토)을 새 항목 뒤로 밀어 붙였다. 제자리로 돌린다. - http-contract 시험 목록에 NotificationAdminRefusalHttpAnswerTest를 더한다 (리뷰가 짚은, 고친 줄 위의 빠진 이름). 위험·한계: 생성자 검사는 공개 계약을 좁힌다. 이 타입을 다른 descriptor로 만들던 파생 서비스 코드는 IllegalStateException(500)이 된다. upgrade 행에 적었다. 문서 수정의 전송별 답은 코드로 대조했고 GraphQL·gRPC·STOMP 실행은 하지 않았다. 검증: 노트북 감싸개 :application-notification:check, :adapter:inbound:web-notification:check, :adapter:outbound:notification:verifyNotificationApiSurface rc=0, check-docs.py·check-work-docs.py OK. 변이와 desktop 게이트는 PR 본문에 적는다. Refs: REV-BE-0054 --- docs/manual/05-idempotency.md | 11 +++--- ...26-11-notification-idempotency-conflict.md | 4 ++- docs/web/http-contract.md | 6 ++-- .../error/IdempotencyConflictException.java | 36 ++++++++++++++++--- .../NotificationSubmissionErrorCode.java | 5 +-- .../api/error/NotificationExceptionTest.java | 28 +++++++++++++++ ...eptNotificationApplicationUseCaseTest.java | 28 ++++++++++----- .../InMemoryNotificationRequestStore.java | 15 ++++++++ 8 files changed, 110 insertions(+), 23 deletions(-) diff --git a/docs/manual/05-idempotency.md b/docs/manual/05-idempotency.md index 8b4576f4..60bf4d6f 100644 --- a/docs/manual/05-idempotency.md +++ b/docs/manual/05-idempotency.md @@ -58,12 +58,15 @@ executor는 **응답을 다시 돌려주는 기록**이다: HTTP `Idempotency-Ke - 알림: 키는 tenant 안에서 같은 알림을 한 번만 만드는 업무 키다. 저장소의 유일 제약이 동시 제출을 막고, 진 쪽은 이긴 행을 읽어 같은 receipt로 수렴한다. 키를 주지 않은 호출자도 중복을 막도록 plan 지문으로 키를 만든다. executor로 옮기면 TTL - 뒤 같은 알림을 다시 만들고, 키 없는 호출은 중복을 막지 못한다. + 뒤 같은 알림을 다시 만들고, 키 없는 호출은 중복을 막지 못한다. 저장한 키 값을 어떻게 다룰지(원본 저장)는 보안 검토 + 항목이다. - 알림의 「같은 요청」은 같은 plan이다. 지문은 본문이 아니라 기본값(version·locale)을 채운 plan으로 만든다. 그래서 변수 순서나 생략한 version처럼 본문만 다르면 같은 receipt다. 같은 키로 다른 plan을 보내면 422 `IDEMPOTENCY_CONFLICT`다. 키를 - 먼저 찾았든, 동시 제출에서 저장에 졌든 같은 답이다. 이 예외는 `ApiErrorCarrier`라 모든 전송이 같은 code로 답하고, - 서버 오류 로그를 남기지 않는다. 다시 보내도 같은 답이니 새 알림이면 새 키를 쓴다. 저장한 키 값을 어떻게 다룰지(원본 저장)는 보안 검토 - 항목이다. + 먼저 찾았든, 동시 제출에서 저장에 졌든 같은 답이다. 이 예외는 `ApiErrorCarrier`라 실패를 답하는 전송(web·GraphQL·gRPC)이 + 같은 code로 답하고, 어느 전송도 서버 오류 로그를 남기지 않는다. STOMP 핸들러가 던진 실패는 전처럼 frame을 보내지 않는다. + 다시 보내도 같은 답이니 새 알림이면 새 키를 쓴다. +- 기본 locale은 배포 설정(`APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE`)이다. 그 값을 바꾼 뒤 locale 없이 같은 키로 다시 + 보내면 다른 plan이 되어 422다. 재전송이 설정 변경을 넘을 수 있는 호출자는 locale을 본문에 적는다. - durable operation: 결정 15·26(서버가 id를 만들고 payload 지문으로 재제출을 판정)이 정한다. capability의 `KEYED`는 "같은 scope·같은 payload로 다시 보내면 같은 작업"이라는 뜻이고, 그 판정은 operation 저장소의 scope 유일성이 한다. - 새 기능이 이 둘을 따라 할 일은 거의 없다. 클라이언트가 응답을 못 받아 다시 보내는 쓰기는 위 순서대로 executor를 쓴다. diff --git a/docs/upgrade/2026-11-notification-idempotency-conflict.md b/docs/upgrade/2026-11-notification-idempotency-conflict.md index 233e22f2..9ce82fd0 100644 --- a/docs/upgrade/2026-11-notification-idempotency-conflict.md +++ b/docs/upgrade/2026-11-notification-idempotency-conflict.md @@ -19,11 +19,13 @@ | # | 바뀐 것 | 전에는 | 할 일 | 안 하면 | 해당 서비스 | | --- | --- | --- | --- | --- | --- | -| 1 | `IdempotencyConflictException`이 `ApiErrorCarrier`를 구현한다. code는 `NotificationSubmissionErrorCode.IDEMPOTENCY_CONFLICT`(422, category `VALIDATION`, retryable false)다. 공용 처리기(web `GlobalExceptionHandler`, GraphQL, gRPC, STOMP)가 모두 code `IDEMPOTENCY_CONFLICT`로 답한다. web은 422와 고정 문구의 error 본문이고 서버 오류 로그·span 오류를 남기지 않는다. 키를 먼저 찾은 제출, 동시 제출에서 저장에 진 제출, 중복 제거로 버린 제출을 저장하다 진 제출이 모두 같은 답이다. 견주는 것은 본문이 아니라 기본값을 채운 plan의 지문이다. 예외 타입·descriptor(`IDEMPOTENCY_CONFLICT`, `INVALID_PAYLOAD`)·메시지는 그대로다 | 예외가 carrier가 아니어서 공용 처리기가 500 `INTERNAL_ERROR`로 답하고 ERROR 로그와 span 오류를 남겼다. 5xx 경보가 울렸다 | 500을 「같은 키 재사용」으로 읽던 클라이언트·모니터링을 422 `IDEMPOTENCY_CONFLICT`로 바꾼다. 다시 보내지 않고, 새 알림이면 새 키를 만든다. 이 예외를 잡아 직접 응답을 만들던 서비스 코드는 그대로 둬도 된다. 공용 처리기에 맡겼다면 고칠 코드는 없다(응답이 422로 바뀐다) | 클라이언트가 422를 모르면 이 거절을 처리하지 못하고, 5xx만 세던 경보 규칙은 이 거절을 더 보지 않는다 | 알림 capability를 켠 서비스 | +| 1 | `IdempotencyConflictException`이 `ApiErrorCarrier`를 구현한다. code는 `NotificationSubmissionErrorCode.IDEMPOTENCY_CONFLICT`(422, category `VALIDATION`, retryable false)다. 실패를 답하는 공용 처리기가 그 code로 답한다: web은 422와 고정 문구의 error 본문, GraphQL은 errors의 code `IDEMPOTENCY_CONFLICT`·category `REQUEST`, gRPC는 `INVALID_ARGUMENT`와 trailer `error-code: IDEMPOTENCY_CONFLICT`·`error-retryable: false`다. 어느 전송도 서버 오류 로그·span 오류를 남기지 않는다. STOMP `@MessageMapping`이 던진 실패는 전처럼 frame을 보내지 않고 ERROR 로그만 사라진다. 키를 먼저 찾은 제출, 동시 제출에서 저장에 진 제출, 중복 제거로 버린 제출을 저장하다 진 제출이 모두 같은 답이다. 견주는 것은 본문이 아니라 기본값을 채운 plan의 지문이다. 예외 타입과 메시지(`IDEMPOTENCY_CONFLICT`)는 그대로이고, 생성자는 descriptor(`IDEMPOTENCY_CONFLICT`, `INVALID_PAYLOAD`) 말고는 `IllegalStateException`으로 거절한다 | carrier가 아니어서 공용 처리기가 서버 오류로 다뤘다. web은 500 `INTERNAL_ERROR`와 ERROR 로그·span 오류, gRPC는 `INTERNAL`, GraphQL은 이 타입(또는 상위 타입)을 등록한 매핑이 없으면 `INTERNAL_ERROR`였다. STOMP는 frame 없이 ERROR 로그를 남겼다. 5xx 경보가 울렸다 | 500·`INTERNAL`을 「같은 키 재사용」으로 읽던 클라이언트·모니터링을 위 code로 바꾼다. 다시 보내지 않고, 새 알림이면 새 키를 만든다. GraphQL에 `GraphQlExceptionResolver`로 이 예외나 상위 타입(`NotificationException` 등)을 등록해 자기 code로 답하던 서비스는 그 매핑이 더 쓰이지 않는다(실패 자신이 carrier면 등록 매핑보다 먼저 답한다, `docs/work/reference/decisions.md` 2.3절). 자기 code가 필요하면 이 예외를 감싼 자기 예외로 던지고 그 타입을 등록한다. 이 타입을 다른 descriptor로 만들던 코드는 자기 예외 타입으로 바꾼다. web `@ExceptionHandler`와 이 예외를 직접 잡던 코드는 그대로 동작한다 | 클라이언트가 이 code를 모르면 이 거절을 처리하지 못하고, 5xx만 세던 경보 규칙은 이 거절을 더 보지 않는다. GraphQL의 등록 매핑에 기대던 클라이언트 분기는 code가 바뀌어 깨진다 | 알림 capability를 켠 서비스 | ## 3. 바뀌지 않은 것 - 같은 키·같은 plan은 전처럼 처음 receipt를 다시 준다. 동시 제출에서 진 쪽도 같다. +- plan 지문에는 기본 locale(`APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE`)이 들어간다. 그 값을 바꾼 뒤 locale 없이 같은 키로 다시 + 보내면 전에는 500, 이제는 422다. 재전송이 설정 변경을 넘을 수 있으면 locale을 본문에 적는다. - `NotificationSubmissionService`가 이 예외를 던지는 자리와 조건은 그대로다. - 다른 `NotificationException`(검증, template 없음 등)의 응답은 이 변경이 바꾸지 않는다. - 오류 code 목록(`NotificationFailureCode`)과 템플릿 오류 code registry(`docs/registries/error-codes.yaml`)는 그대로다. diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index 9b1686a9..8af6eb86 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -14,8 +14,8 @@ 실행 전 거부와 결과 불명의 구분은 `IdempotencyExecutorTest`, lease 하한은 `IdempotencySettingsTest` - 헤더 규칙(3절): `WebMvcRequestIdFilterTest`, `CorsSecurityFilterIntegrationTest` - web 전용 코드(4절): `TransportErrorHandlingTest`, `IdempotencyKeyHeaderTest`, web-advanced - `WebAdvancedErrorMappingTest`, 알림 제출의 `IDEMPOTENCY_CONFLICT`는 web-notification - `NotificationSubmissionControllerTest` + `WebAdvancedErrorMappingTest`, 알림 기능 코드는 web-notification의 `NotificationAdminRefusalHttpAnswerTest` + (`DELIVERY_ATTEMPT_NOT_FOUND`)와 `NotificationSubmissionControllerTest`(`IDEMPOTENCY_CONFLICT`) ## 1. Envelope 키 존재 규칙 @@ -201,7 +201,7 @@ HTTP가 그대로 답하는 코드(`DELIVERY_ATTEMPT_NOT_FOUND`, `IDEMPOTENCY_CO | `RATE_LIMIT_INCOMPATIBLE` | 503 | `INTERNAL` | `false` | 없음 | rate-limit 제공자가 계약과 맞지 않음 | | `OPERATION_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | durable operation 조회(`DurableOperationController`)에서 그 operation이 없거나 다른 호출자의 것이다. 둘을 가르지 않는다 | | `DELIVERY_ATTEMPT_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | 알림 운영자 redrive(`RedriveDeliveryUseCase`)가 받은 attempt가 없거나 운영자 tenant 밖이다. 둘을 가르지 않는다. 코드는 `application-notification`의 `NotificationAdminErrorCode`라 모든 전송이 같은 코드로 답한다. 템플릿은 이 연산의 전송을 싣지 않는다(`docs/notification/operations.md`) | -| `IDEMPOTENCY_CONFLICT` | 422 | `VALIDATION` | `false` | 없음 | 알림 제출(`POST /notifications`)이 본문의 `idempotencyKey`를 이미 다른 알림에 쓴 키로 받았다. 견주는 것은 본문이 아니라 알림 plan 지문이다. 2절의 `Idempotency-Key` 헤더와는 다른 키라 `IDEMPOTENT_REQUEST_MISMATCH`가 아니다. 다시 보내지 않는다. 새 알림이면 새 키를 쓴다. 코드는 `application-notification`의 `NotificationSubmissionErrorCode`라 모든 전송이 같은 코드로 답한다(`docs/manual/05-idempotency.md` 「executor를 쓰지 않는 중복 판정 둘」) | +| `IDEMPOTENCY_CONFLICT` | 422 | `VALIDATION` | `false` | 없음 | 알림 제출(`POST /notifications`)이 본문의 `idempotencyKey`를 이미 다른 알림에 쓴 키로 받았다. 견주는 것은 본문이 아니라 알림 plan 지문이다. 2절의 `Idempotency-Key` 헤더와는 다른 키라 `IDEMPOTENT_REQUEST_MISMATCH`가 아니다. 다시 보내지 않는다. 새 알림이면 새 키를 쓴다. 코드는 `application-notification`의 `NotificationSubmissionErrorCode`라 실패를 답하는 전송(web·GraphQL·gRPC)이 같은 코드로 답한다(`docs/manual/05-idempotency.md` 「executor를 쓰지 않는 중복 판정 둘」) | - 컨트롤러 파라미터 제약 위반(`@RequestParam @Max(10)`)은 요청 본문 위반과 같은 `400 VALIDATION_FAILED`이고 `details`는 `[{field, code, message}]`다. 거절된 값은 싣지 않는다. diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/IdempotencyConflictException.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/IdempotencyConflictException.java index ab390560..cfb67a35 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/IdempotencyConflictException.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/IdempotencyConflictException.java @@ -8,23 +8,49 @@ import dev.caskeleton.shared.error.ApiErrorCode; * *

The fingerprint is the notification plan's, not the request body's: two bodies that make the * same plan converge on the first receipt, and only a different plan under the same key lands here. - * That is the caller's failure, not a server fault, so a transport answers {@link - * NotificationSubmissionErrorCode#IDEMPOTENCY_CONFLICT} (422) and logs no server failure. + * The plan is built after the defaults are filled in, and the default locale is a deployment + * setting, so a resend that names no locale after that setting changed is a different plan too. + * + *

The caller chose the key and the request, so this is answered as the caller's failure, not a + * server fault: {@link #errorCode()} is {@link + * NotificationSubmissionErrorCode#IDEMPOTENCY_CONFLICT} (422 on the web) and no transport logs it + * as a server failure. * *

The {@linkplain #descriptor() descriptor} keeps the closed notification registry ({@code - * IDEMPOTENCY_CONFLICT}, {@code INVALID_PAYLOAD}). The status and the client category on the wire - * come from {@link #errorCode()} alone. + * IDEMPOTENCY_CONFLICT}, {@code INVALID_PAYLOAD}); the client category on the wire comes from + * {@link #errorCode()} alone. The constructor refuses any other descriptor, because the code is + * fixed: a server-side failure raised as this type would be answered as a client mistake and logged + * nowhere. */ public class IdempotencyConflictException extends NotificationException implements ApiErrorCarrier { private static final long serialVersionUID = 1L; + /** + * Creates the exception. + * + * @param descriptor the conflict's descriptor: code {@code IDEMPOTENCY_CONFLICT}, category {@code + * INVALID_PAYLOAD} + * @throws IllegalStateException when the descriptor describes another failure + */ public IdempotencyConflictException(NotificationFailureDescriptor descriptor) { - super(descriptor); + super(requireConflict(descriptor)); } @Override public ApiErrorCode errorCode() { return NotificationSubmissionErrorCode.IDEMPOTENCY_CONFLICT; } + + private static NotificationFailureDescriptor requireConflict( + NotificationFailureDescriptor descriptor) { + if (!NotificationFailureCode.IDEMPOTENCY_CONFLICT.equals(descriptor.code()) + || descriptor.category() != FailureCategory.INVALID_PAYLOAD) { + // Not IllegalArgumentException: the web answers that as a client's 400, and a caller that + // built the wrong descriptor is a server-side mistake. + throw new IllegalStateException( + "an idempotency conflict is described by IDEMPOTENCY_CONFLICT and INVALID_PAYLOAD"); + } + return descriptor; + } } diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationSubmissionErrorCode.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationSubmissionErrorCode.java index bd61c0aa..29dddf4c 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationSubmissionErrorCode.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationSubmissionErrorCode.java @@ -8,8 +8,9 @@ import dev.caskeleton.shared.error.Category; * *

The closed {@link NotificationFailureCode} registry is the platform's own vocabulary — metric * tags, ledger rows, audit — and carries no status. A transport answers with this code instead, - * read through {@link dev.caskeleton.shared.error.ApiErrorCarrier}, so every transport gives the - * same status without naming the feature. + * read through {@link dev.caskeleton.shared.error.ApiErrorCarrier}, so every transport that answers + * a failure gives the same code without naming the feature, each in its own shape (the web's + * status, GraphQL's error category, gRPC's status). */ public enum NotificationSubmissionErrorCode implements ApiErrorCode { /** diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/api/error/NotificationExceptionTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/api/error/NotificationExceptionTest.java index e5f08b3d..d5b94a86 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/api/error/NotificationExceptionTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/api/error/NotificationExceptionTest.java @@ -2,12 +2,15 @@ package dev.caskeleton.application.notification.platform.api.error; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.notification.platform.api.ProviderId; import dev.caskeleton.application.notification.platform.api.routing.Channel; import java.time.Duration; import java.util.Optional; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; class NotificationExceptionTest { @@ -48,6 +51,31 @@ class NotificationExceptionTest { assertThat(exception.getMessage()).isEqualTo(NotificationFailureCode.NOTIFICATION_SUPPRESSED); } + /** + * The conflict's answer is fixed at 422, so the type refuses a descriptor of any other failure + * rather than answering it as a client mistake. The refusal is a server-side one. + */ + @ParameterizedTest + @CsvSource({ + "PROVIDER_UNAVAILABLE, TRANSIENT_PROVIDER", + "IDEMPOTENCY_CONFLICT, TRANSIENT_PROVIDER", + "VALIDATION_FAILED, INVALID_PAYLOAD" + }) + void anIdempotencyConflictRefusesTheDescriptorOfAnotherFailure( + String code, FailureCategory category) { + // given + NotificationFailureDescriptor other = NotificationFailureDescriptor.preDispatch(code, category); + + // when + Throwable refused = catchThrowable(() -> new IdempotencyConflictException(other)); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "an idempotency conflict is described by IDEMPOTENCY_CONFLICT and INVALID_PAYLOAD"); + } + @Test void failureCodesComeFromAClosedRegistry() { assertThatThrownBy( diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java index 6b912774..8438ee28 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java @@ -260,17 +260,20 @@ class AcceptNotificationApplicationUseCaseTest { // then assertThat( List.of( - refused.getClass(), - String.valueOf(refused.getMessage()), + Optional.ofNullable(refused).map(Throwable::getClass).orElse("nothing"), + Optional.ofNullable(refused).map(Throwable::getMessage).orElse("nothing"), carriedCode(refused), - chain.requests.byId.size())) + chain.requests.byId.size(), + chain.requests.missedIdempotencyLookups())) .as( - "[exception, message, carried code (code, category, status, retryable), stored requests]") + "[exception, message, carried code (code, category, status, retryable), stored" + + " requests, lookups missed on purpose]") .containsExactly( IdempotencyConflictException.class, "IDEMPOTENCY_CONFLICT", List.of("IDEMPOTENCY_CONFLICT", Category.VALIDATION, 422, false), - 1); + 1, + path.missedLookups()); } /** The same key with the same request still converges on the first receipt on every path. */ @@ -286,9 +289,13 @@ class AcceptNotificationApplicationUseCaseTest { NotificationReceipt second = path.send(chain, "1000"); // then - assertThat(List.of(second.notificationId(), chain.requests.byId.size())) - .as("[receipt id, stored requests]") - .containsExactly(first.notificationId(), 1); + assertThat( + List.of( + second.notificationId(), + chain.requests.byId.size(), + chain.requests.missedIdempotencyLookups())) + .as("[receipt id, stored requests, lookups missed on purpose]") + .containsExactly(first.notificationId(), 1, path.missedLookups()); } /** The carrier's code as code, category, status and retryable; empty when none is carried. */ @@ -343,6 +350,11 @@ class AcceptNotificationApplicationUseCaseTest { } } + /** How many lookups the store must have answered empty for the second request to take it. */ + int missedLookups() { + return secondMissesTheLookup ? 1 : 0; + } + /** Sends one request with the key {@code order-77}. */ NotificationReceipt send(RealSubmission chain, String amount) { return chain.accept.handle( diff --git a/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java b/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java index eb95d913..bae16bd7 100644 --- a/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java +++ b/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java @@ -46,6 +46,8 @@ public final class InMemoryNotificationRequestStore implements NotificationReque private boolean missNextIdempotencyLookup; + private int missedIdempotencyLookups; + private BooleanSupplier transactionOpen; /** @@ -80,6 +82,18 @@ public final class InMemoryNotificationRequestStore implements NotificationReque this.missNextIdempotencyLookup = true; } + /** + * How many idempotency lookups {@link #missNextIdempotencyLookup()} answered with nothing. + * + *

A test that means to take the concurrent path asserts this, so a miss that was never served + * fails it instead of letting the request find the stored row by its key. + * + * @return the number of lookups answered empty on purpose + */ + public synchronized int missedIdempotencyLookups() { + return missedIdempotencyLookups; + } + @Override public synchronized NotificationRequestInsertOutcome insert( NotificationRequestRecord request, List jobs) { @@ -106,6 +120,7 @@ public final class InMemoryNotificationRequestStore implements NotificationReque TenantId tenantId, String idempotencyKey) { if (missNextIdempotencyLookup) { missNextIdempotencyLookup = false; + missedIdempotencyLookups++; return Optional.empty(); } return Optional.ofNullable(byIdempotency.get(key(tenantId, idempotencyKey))).map(byId::get); -- 2.54.0 From 424288d8bd2c93a669099b42465393d5566d1b0c Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 15:01:42 +0900 Subject: [PATCH 3/5] =?UTF-8?q?fix(notification):=20=EB=B2=84=EB=A6=B0=20?= =?UTF-8?q?=EC=A0=9C=EC=B6=9C=20=EA=B2=BD=EB=A1=9C=EB=A5=BC=20=EC=8B=9C?= =?UTF-8?q?=ED=97=98=EC=9D=B4=20=EB=8B=A8=EC=96=B8=ED=95=98=EA=B3=A0=20?= =?UTF-8?q?=EB=A9=B1=EB=93=B1=20=EC=B6=A9=EB=8F=8C=20=EC=95=88=EB=82=B4?= =?UTF-8?q?=EC=9D=98=20=EC=A1=B0=EA=B1=B4=EC=9D=84=20=EC=A2=81=ED=9E=8C?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 915ca2ca8 확인 리뷰(종류 B, 렌즈 be-api-contract·be-testing·be-domain)가 낸 Low 넷을 고친다. - 다른 요청·같은 요청 표의 LOST_THE_DROP_INSERT 행은 조회를 놓쳤는지만 봤다. 준비가 바뀌어 중복 제거가 빠져도 일반 insert 길로 조용히 통과했다. request 저장 fake가 키에 진 insert를 lostInserts에 남기고, 두 표가 행마다 진 insert의 acceptance(없음·ACCEPTED· DROPPED_AS_DUPLICATE)를 단언한다. - upgrade 2.1절의 「어느 전송도 서버 오류 로그·span 오류를 남기지 않는다」는 GraphQL에서 틀렸다. resolver observation은 던진 예외를 그대로 오류로 센다(GraphQlResolverObservationConventionAdapter의 graphql.outcome=ERROR와 span 오류). 로그는 모든 전송, span은 web으로 좁힌다. - 「기본 locale을 바꾼 뒤 locale 없이 다시 보내면 422」는 조건이 빠졌다. template을 멱등 조회보다 먼저 찾으므로 새 locale의 template이 없으면 template 없음으로 거절되고, 키를 주지 않은 호출은 바뀐 plan에서 키를 다시 만들어 두 번째 알림이 된다. manual 05와 upgrade 3절에 두 조건을 적고, 권고를 「키와 locale을 본문에」로 넓힌다. - 915ca2ca8 제목에 `!`가 빠졌다. 생성자의 descriptor 거절은 파생 코드가 따라 고칠 변경이다(upgrade 2.1절 행에 있다). brief가 amend를 막으므로 이력은 두고 PR 제목(`!`)과 PR 본문의 BREAKING 줄에 적는다. 위험·한계: 시험 fake에 공개 필드가 하나 는다. GraphQL span 문장은 convention 코드와 의존 구성으로만 대조했고 GraphQL을 띄워 보지 않았다. locale 두 조건은 desktop 임시 시험으로 확인한다(결과는 PR 본문). 검증: 노트북 감싸개 :application-notification:spotlessApply·check rc=0, check-docs.py·check-work-docs.py OK. 변이와 desktop 게이트는 PR 본문에 적는다. Refs: REV-BE-0054 --- docs/manual/05-idempotency.md | 7 +++- ...26-11-notification-idempotency-conflict.md | 6 ++- ...eptNotificationApplicationUseCaseTest.java | 40 ++++++++++++++----- .../InMemoryNotificationRequestStore.java | 8 ++++ 4 files changed, 47 insertions(+), 14 deletions(-) diff --git a/docs/manual/05-idempotency.md b/docs/manual/05-idempotency.md index 60bf4d6f..3990800e 100644 --- a/docs/manual/05-idempotency.md +++ b/docs/manual/05-idempotency.md @@ -65,8 +65,11 @@ executor는 **응답을 다시 돌려주는 기록**이다: HTTP `Idempotency-Ke 먼저 찾았든, 동시 제출에서 저장에 졌든 같은 답이다. 이 예외는 `ApiErrorCarrier`라 실패를 답하는 전송(web·GraphQL·gRPC)이 같은 code로 답하고, 어느 전송도 서버 오류 로그를 남기지 않는다. STOMP 핸들러가 던진 실패는 전처럼 frame을 보내지 않는다. 다시 보내도 같은 답이니 새 알림이면 새 키를 쓴다. -- 기본 locale은 배포 설정(`APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE`)이다. 그 값을 바꾼 뒤 locale 없이 같은 키로 다시 - 보내면 다른 plan이 되어 422다. 재전송이 설정 변경을 넘을 수 있는 호출자는 locale을 본문에 적는다. +- 기본 locale은 배포 설정(`APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE`)이고 plan 지문에 들어간다. 그 값을 바꾼 뒤 locale + 없이 다시 보내면 첫 요청과 다른 plan이다. 키를 준 호출은 422다. 다만 template은 멱등 조회보다 먼저 찾으므로, 새 locale의 + template(같은 id·version)이 없으면 그 전에 template 없음으로 거절된다. 키를 주지 않은 호출은 바뀐 plan에서 키를 다시 + 만들어 두 번째 알림이 된다. 이 경우에는 키 없는 호출의 중복 막기(위 항목)가 지켜지지 않는다. 재전송이 설정 + 변경을 넘을 수 있는 호출자는 키와 locale을 본문에 적는다. - durable operation: 결정 15·26(서버가 id를 만들고 payload 지문으로 재제출을 판정)이 정한다. capability의 `KEYED`는 "같은 scope·같은 payload로 다시 보내면 같은 작업"이라는 뜻이고, 그 판정은 operation 저장소의 scope 유일성이 한다. - 새 기능이 이 둘을 따라 할 일은 거의 없다. 클라이언트가 응답을 못 받아 다시 보내는 쓰기는 위 순서대로 executor를 쓴다. diff --git a/docs/upgrade/2026-11-notification-idempotency-conflict.md b/docs/upgrade/2026-11-notification-idempotency-conflict.md index 9ce82fd0..1152aa3b 100644 --- a/docs/upgrade/2026-11-notification-idempotency-conflict.md +++ b/docs/upgrade/2026-11-notification-idempotency-conflict.md @@ -19,13 +19,15 @@ | # | 바뀐 것 | 전에는 | 할 일 | 안 하면 | 해당 서비스 | | --- | --- | --- | --- | --- | --- | -| 1 | `IdempotencyConflictException`이 `ApiErrorCarrier`를 구현한다. code는 `NotificationSubmissionErrorCode.IDEMPOTENCY_CONFLICT`(422, category `VALIDATION`, retryable false)다. 실패를 답하는 공용 처리기가 그 code로 답한다: web은 422와 고정 문구의 error 본문, GraphQL은 errors의 code `IDEMPOTENCY_CONFLICT`·category `REQUEST`, gRPC는 `INVALID_ARGUMENT`와 trailer `error-code: IDEMPOTENCY_CONFLICT`·`error-retryable: false`다. 어느 전송도 서버 오류 로그·span 오류를 남기지 않는다. STOMP `@MessageMapping`이 던진 실패는 전처럼 frame을 보내지 않고 ERROR 로그만 사라진다. 키를 먼저 찾은 제출, 동시 제출에서 저장에 진 제출, 중복 제거로 버린 제출을 저장하다 진 제출이 모두 같은 답이다. 견주는 것은 본문이 아니라 기본값을 채운 plan의 지문이다. 예외 타입과 메시지(`IDEMPOTENCY_CONFLICT`)는 그대로이고, 생성자는 descriptor(`IDEMPOTENCY_CONFLICT`, `INVALID_PAYLOAD`) 말고는 `IllegalStateException`으로 거절한다 | carrier가 아니어서 공용 처리기가 서버 오류로 다뤘다. web은 500 `INTERNAL_ERROR`와 ERROR 로그·span 오류, gRPC는 `INTERNAL`, GraphQL은 이 타입(또는 상위 타입)을 등록한 매핑이 없으면 `INTERNAL_ERROR`였다. STOMP는 frame 없이 ERROR 로그를 남겼다. 5xx 경보가 울렸다 | 500·`INTERNAL`을 「같은 키 재사용」으로 읽던 클라이언트·모니터링을 위 code로 바꾼다. 다시 보내지 않고, 새 알림이면 새 키를 만든다. GraphQL에 `GraphQlExceptionResolver`로 이 예외나 상위 타입(`NotificationException` 등)을 등록해 자기 code로 답하던 서비스는 그 매핑이 더 쓰이지 않는다(실패 자신이 carrier면 등록 매핑보다 먼저 답한다, `docs/work/reference/decisions.md` 2.3절). 자기 code가 필요하면 이 예외를 감싼 자기 예외로 던지고 그 타입을 등록한다. 이 타입을 다른 descriptor로 만들던 코드는 자기 예외 타입으로 바꾼다. web `@ExceptionHandler`와 이 예외를 직접 잡던 코드는 그대로 동작한다 | 클라이언트가 이 code를 모르면 이 거절을 처리하지 못하고, 5xx만 세던 경보 규칙은 이 거절을 더 보지 않는다. GraphQL의 등록 매핑에 기대던 클라이언트 분기는 code가 바뀌어 깨진다 | 알림 capability를 켠 서비스 | +| 1 | `IdempotencyConflictException`이 `ApiErrorCarrier`를 구현한다. code는 `NotificationSubmissionErrorCode.IDEMPOTENCY_CONFLICT`(422, category `VALIDATION`, retryable false)다. 실패를 답하는 공용 처리기가 그 code로 답한다: web은 422와 고정 문구의 error 본문, GraphQL은 errors의 code `IDEMPOTENCY_CONFLICT`·category `REQUEST`, gRPC는 `INVALID_ARGUMENT`와 trailer `error-code: IDEMPOTENCY_CONFLICT`·`error-retryable: false`다. 어느 전송도 서버 오류 로그를 남기지 않고, web은 span 오류도 남기지 않는다. GraphQL resolver observation은 전처럼 던진 예외를 오류로 센다(`graphql.outcome=ERROR`와 span 오류). STOMP `@MessageMapping`이 던진 실패는 전처럼 frame을 보내지 않고 ERROR 로그만 사라진다. 키를 먼저 찾은 제출, 동시 제출에서 저장에 진 제출, 중복 제거로 버린 제출을 저장하다 진 제출이 모두 같은 답이다. 견주는 것은 본문이 아니라 기본값을 채운 plan의 지문이다. 예외 타입과 메시지(`IDEMPOTENCY_CONFLICT`)는 그대로이고, 생성자는 descriptor(`IDEMPOTENCY_CONFLICT`, `INVALID_PAYLOAD`) 말고는 `IllegalStateException`으로 거절한다 | carrier가 아니어서 공용 처리기가 서버 오류로 다뤘다. web은 500 `INTERNAL_ERROR`와 ERROR 로그·span 오류, gRPC는 `INTERNAL`, GraphQL은 이 타입(또는 상위 타입)을 등록한 매핑이 없으면 `INTERNAL_ERROR`였다. STOMP는 frame 없이 ERROR 로그를 남겼다. 5xx 경보가 울렸다 | 500·`INTERNAL`을 「같은 키 재사용」으로 읽던 클라이언트·모니터링을 위 code로 바꾼다. 다시 보내지 않고, 새 알림이면 새 키를 만든다. GraphQL에 `GraphQlExceptionResolver`로 이 예외나 상위 타입(`NotificationException` 등)을 등록해 자기 code로 답하던 서비스는 그 매핑이 더 쓰이지 않는다(실패 자신이 carrier면 등록 매핑보다 먼저 답한다, `docs/work/reference/decisions.md` 2.3절). 자기 code가 필요하면 이 예외를 감싼 자기 예외로 던지고 그 타입을 등록한다. 이 타입을 다른 descriptor로 만들던 코드는 자기 예외 타입으로 바꾼다. web `@ExceptionHandler`와 이 예외를 직접 잡던 코드는 그대로 동작한다 | 클라이언트가 이 code를 모르면 이 거절을 처리하지 못하고, 5xx만 세던 경보 규칙은 이 거절을 더 보지 않는다. GraphQL의 등록 매핑에 기대던 클라이언트 분기는 code가 바뀌어 깨진다 | 알림 capability를 켠 서비스 | ## 3. 바뀌지 않은 것 - 같은 키·같은 plan은 전처럼 처음 receipt를 다시 준다. 동시 제출에서 진 쪽도 같다. - plan 지문에는 기본 locale(`APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE`)이 들어간다. 그 값을 바꾼 뒤 locale 없이 같은 키로 다시 - 보내면 전에는 500, 이제는 422다. 재전송이 설정 변경을 넘을 수 있으면 locale을 본문에 적는다. + 보내면 전에는 500, 이제는 422다. 다만 새 locale의 template(같은 id·version)이 없으면 멱등 조회 전에 전처럼 template 없음으로 + 거절되고, 키를 주지 않은 호출은 바뀐 plan에서 키를 다시 만들어 전처럼 두 번째 알림이 된다. 재전송이 설정 변경을 넘을 수 + 있으면 키와 locale을 본문에 적는다. - `NotificationSubmissionService`가 이 예외를 던지는 자리와 조건은 그대로다. - 다른 `NotificationException`(검증, template 없음 등)의 응답은 이 변경이 바꾸지 않는다. - 오류 code 목록(`NotificationFailureCode`)과 템플릿 오류 code registry(`docs/registries/error-codes.yaml`)는 그대로다. diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java index 8438ee28..1f390de5 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.notification.platform.api.DeduplicationAction; import dev.caskeleton.application.notification.platform.api.DeduplicationSpec; +import dev.caskeleton.application.notification.platform.api.NotificationAcceptance; import dev.caskeleton.application.notification.platform.api.NotificationId; import dev.caskeleton.application.notification.platform.api.NotificationPlan; import dev.caskeleton.application.notification.platform.api.NotificationReceipt; @@ -264,16 +265,18 @@ class AcceptNotificationApplicationUseCaseTest { Optional.ofNullable(refused).map(Throwable::getMessage).orElse("nothing"), carriedCode(refused), chain.requests.byId.size(), - chain.requests.missedIdempotencyLookups())) + chain.requests.missedIdempotencyLookups(), + lostInserts(chain))) .as( "[exception, message, carried code (code, category, status, retryable), stored" - + " requests, lookups missed on purpose]") + + " requests, lookups missed on purpose, inserts that lost the key]") .containsExactly( IdempotencyConflictException.class, "IDEMPOTENCY_CONFLICT", List.of("IDEMPOTENCY_CONFLICT", Category.VALIDATION, 422, false), 1, - path.missedLookups()); + path.missedLookups(), + path.lostInserts()); } /** The same key with the same request still converges on the first receipt on every path. */ @@ -293,9 +296,15 @@ class AcceptNotificationApplicationUseCaseTest { List.of( second.notificationId(), chain.requests.byId.size(), - chain.requests.missedIdempotencyLookups())) - .as("[receipt id, stored requests, lookups missed on purpose]") - .containsExactly(first.notificationId(), 1, path.missedLookups()); + chain.requests.missedIdempotencyLookups(), + lostInserts(chain))) + .as("[receipt id, stored requests, lookups missed on purpose, inserts that lost the key]") + .containsExactly(first.notificationId(), 1, path.missedLookups(), path.lostInserts()); + } + + /** What each insert that lost the key to the stored request would have stored. */ + private static List lostInserts(RealSubmission chain) { + return chain.requests.lostInserts.stream().map(NotificationRequestRecord::acceptance).toList(); } /** The carrier's code as code, category, status and retryable; empty when none is carried. */ @@ -313,15 +322,15 @@ class AcceptNotificationApplicationUseCaseTest { */ enum KeyReuse { /** The second acceptance finds the stored request by its key. */ - FOUND_BY_LOOKUP(false), + FOUND_BY_LOOKUP(false, Optional.empty()), /** The second acceptance read before the first committed, and loses the insert of the key. */ - LOST_THE_INSERT(true), + LOST_THE_INSERT(true, Optional.of(NotificationAcceptance.ACCEPTED)), /** * The second submission read before the first committed, deduplication drops it, and storing * the drop loses the key. An acceptance carries no deduplication, so this path starts at the * submit use case an acceptance hands its plan to. */ - LOST_THE_DROP_INSERT(true) { + LOST_THE_DROP_INSERT(true, Optional.of(NotificationAcceptance.DROPPED_AS_DUPLICATE)) { @Override NotificationReceipt send(RealSubmission chain, String amount) { return chain.submit.handle( @@ -339,8 +348,11 @@ class AcceptNotificationApplicationUseCaseTest { private final boolean secondMissesTheLookup; - KeyReuse(boolean secondMissesTheLookup) { + private final Optional lostInsert; + + KeyReuse(boolean secondMissesTheLookup, Optional lostInsert) { this.secondMissesTheLookup = secondMissesTheLookup; + this.lostInsert = lostInsert; } /** Sets up how the second request meets the stored one. */ @@ -355,6 +367,14 @@ class AcceptNotificationApplicationUseCaseTest { return secondMissesTheLookup ? 1 : 0; } + /** + * What the second request's losing insert would have stored: an accepted request, a dropped + * one, or nothing when the lookup found the stored request first. + */ + List lostInserts() { + return lostInsert.stream().toList(); + } + /** Sends one request with the key {@code order-77}. */ NotificationReceipt send(RealSubmission chain, String amount) { return chain.accept.handle( diff --git a/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java b/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java index bae16bd7..721f1185 100644 --- a/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java +++ b/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java @@ -42,6 +42,13 @@ public final class InMemoryNotificationRequestStore implements NotificationReque /** Whether each status write ran inside the observed transaction, in call order. */ public final List statusWritesInTransaction = new ArrayList<>(); + /** + * Every request whose insert lost its key to a stored request, in call order. A test that means + * to take a losing insert asserts which request lost, so a path that never reached the insert + * fails instead of passing on the lookup. + */ + public final List lostInserts = new ArrayList<>(); + private boolean failNextInsertAsDuplicate; private boolean missNextIdempotencyLookup; @@ -105,6 +112,7 @@ public final class InMemoryNotificationRequestStore implements NotificationReque throw new DuplicateIdempotencyKeyException( "idempotency key is claimed but its request cannot be read"); } + lostInserts.add(request); // Deliberately no recipient jobs on this path: the loser's jobs would attach a second set // to the winner's request. return NotificationRequestInsertOutcome.lost(winner); -- 2.54.0 From 40bd8b044692ca3506ffbb863eefe87304c8fe74 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 16:37:48 +0900 Subject: [PATCH 4/5] =?UTF-8?q?test(notification):=20=EC=83=9D=EC=84=B1?= =?UTF-8?q?=EC=9E=90=20=EA=B1=B0=EC=A0=88=20=EC=8B=9C=ED=97=98=EC=9D=B4=20?= =?UTF-8?q?=EB=A7=8C=EB=93=A0=20=EC=98=88=EC=99=B8=EB=A5=BC=20=EB=8D=98?= =?UTF-8?q?=EC=A0=B8=20SpotBugs=20=EA=B2=BD=EA=B3=A0=EB=A5=BC=20=EC=97=86?= =?UTF-8?q?=EC=95=A4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 915ca2ca8이 더한 NotificationExceptionTest의 생성자 거절 표는 catchThrowable 안에서 IdempotencyConflictException을 만들기만 하고 던지지 않는다. SpotBugs RV_EXCEPTION_NOT_THROWN(CORRECTNESS, rank 1)이 걸려 :prCheck의 :application-notification:spotbugsTest가 실패한다. leaf check에는 SpotBugs가 없어 앞선 검사가 놓쳤다. 람다 안에서 만든 예외를 던진다. 생성자가 거절하면 IllegalStateException이 먼저 나오고, 받아들이면 만든 충돌 예외가 던져져 isInstanceOf(IllegalStateException)가 실패하므로 시험의 뜻은 같다. 시험용 SpotBugs 제외 목록(config/spotbugs/exclude-test.xml)에 규칙을 더하는 안은 버렸다. 이 PR 범위 밖이고, 다른 시험에서 정말로 던지지 않은 예외를 가린다. 위험·한계: 시험 한 곳의 모양만 바뀐다. 생성자 검사를 빼는 변이와 기준 커밋 RED는 desktop에서 다시 돌린다(결과는 PR 본문). 검증: 고치기 전 노트북 감싸개 :application-notification:spotbugsTest rc=1(RV_EXCEPTION_NOT_THROWN, NotificationExceptionTest.java:70). 고친 뒤 --continue로 :application-notification:check·spotbugsMain·spotbugsTest· spotbugsTestFixtures, :adapter:inbound:web-notification:spotbugsMain· spotbugsTest rc=0. Fixes: 915ca2ca8b2c ("fix(notification): 멱등 충돌 안내의 전송별 답을 바로잡고 descriptor를 고정한다") Refs: REV-BE-0054 --- .../platform/api/error/NotificationExceptionTest.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/api/error/NotificationExceptionTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/api/error/NotificationExceptionTest.java index d5b94a86..777484fe 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/api/error/NotificationExceptionTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/api/error/NotificationExceptionTest.java @@ -66,8 +66,13 @@ class NotificationExceptionTest { // given NotificationFailureDescriptor other = NotificationFailureDescriptor.preDispatch(code, category); - // when - Throwable refused = catchThrowable(() -> new IdempotencyConflictException(other)); + // when: thrown, so a constructor that accepts the descriptor fails the test with the conflict + // itself instead of returning an exception nobody raised + Throwable refused = + catchThrowable( + () -> { + throw new IdempotencyConflictException(other); + }); // then assertThat(refused) -- 2.54.0 From f1d64d3848c809e7cec8ae429f2c19790275460d Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 17:47:14 +0900 Subject: [PATCH 5/5] =?UTF-8?q?docs(manual):=20=EA=B0=99=EC=9D=80=20?= =?UTF-8?q?=EB=A9=B1=EB=93=B1=20=ED=82=A4=C2=B7=EB=8B=A4=EB=A5=B8=20?= =?UTF-8?q?=EC=9A=94=EC=B2=AD=EC=9D=80=20409=EA=B0=80=20=EC=95=84=EB=8B=88?= =?UTF-8?q?=EB=9D=BC=20422=EB=9D=BC=EA=B3=A0=20=EC=98=A4=EB=A5=98=20?= =?UTF-8?q?=ED=8C=90=EB=8B=A8=20=ED=91=9C=EC=97=90=20=EC=A0=81=EB=8A=94?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 06장 「어떤 예외 타입으로 던지나」 표는 「상태 충돌(이미 있음, 버전 불일치) → 409」만 적고, 같은 멱등 키로 다른 요청을 보낸 경우를 따로 두지 않는다. 그래서 이 PR이 알림 제출의 그 경우를 422 `IDEMPOTENCY_CONFLICT`로 정한 것(05장)과 06장을 같이 읽으면 409로 읽힐 수 있다. review가 REV-BE-0054 추가 증거로 이 줄을 요청했다. 고른 방법: 표에 한 줄을 더한다. executor(`IDEMPOTENT_REQUEST_MISMATCH`)와 기능 유스케이스(알림 `IDEMPOTENCY_CONFLICT`) 모두 422이고, 상태 충돌이 아니라서 409가 아니라고 적는다. 05장의 표·설명은 그대로다. 위험·한계: 문서 한 줄이다. 이 문서를 읽는 시험은 없다 (`git grep -n 06-errors -- 'src/*.java'`는 scaffold 주석 한 줄뿐이다). 검증: 노트북 `python3 scripts/check-docs.py` OK, `python3 scripts/check-work-docs.py` OK, `scripts/verify.sh docs` rc=0. Refs: REV-BE-0054 --- docs/manual/06-errors.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/manual/06-errors.md b/docs/manual/06-errors.md index cf69867c..9838ee87 100644 --- a/docs/manual/06-errors.md +++ b/docs/manual/06-errors.md @@ -35,6 +35,7 @@ gRPC/GraphQL/WebSocket: 같은 ApiErrorCarrier를 자기 status 모양으로 | 도메인 불변식 위반 | domain `XInvariantException(Reason)` → 유스케이스가 `XRejectedException`으로 감쌈 | 400 기능 코드 | | 찾는 것이 없음 / 남의 것 | `XNotFoundException`(carrier) | 404. 남의 것도 404로 존재를 숨긴다(07장) | | 상태 충돌(이미 있음, 버전 불일치) | 기능 carrier(Category.CONFLICT, 409) | 409 | +| 같은 멱등 키로 다른 요청(05장) | executor는 `IDEMPOTENT_REQUEST_MISMATCH`, 기능 유스케이스는 기능 carrier(Category.VALIDATION, 예: 알림 `IDEMPOTENCY_CONFLICT`) | 422. 상태 충돌이 아니므로 409가 아니다 | | 요청 파라미터 형식 오류(경로 id 문법 등) | `IllegalArgumentException` | 400 `BAD_PARAMETER` | | 서버 조립·설정 오류, 있을 수 없는 상태 | `IllegalStateException` | 500, 로그 남음 | | DB·외부 의존 실패 | adapter가 shared-contract carrier(`PersistenceFailureException`, `DependencyFailureException`)로 | 분류표대로(04·05장) | -- 2.54.0