fix(notification)!: 같은 키·다른 plan의 알림 제출을 422 carrier로 답한다 #104

Merged
donghyeon.kang merged 6 commits from fix/notification-idempotency-conflict-carrier into main 2026-11-23 11:38:29 +00:00
14 changed files with 568 additions and 8 deletions
+11 -1
View File
@@ -53,13 +53,23 @@ 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`라 실패를 답하는 전송(web·GraphQL·gRPC)이
같은 code로 답하고, 어느 전송도 서버 오류 로그를 남기지 않는다. STOMP 핸들러가 던진 실패는 전처럼 frame을 보내지 않는다.
다시 보내도 같은 답이니 새 알림이면 새 키를 쓴다.
- 기본 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를 쓴다.
+1
View File
@@ -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 -1
View File
@@ -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
@@ -0,0 +1,41 @@
# 업그레이드 안내 — 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)다. 실패를 답하는 공용 처리기가 그 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의 template(같은 id·version)이 없으면 멱등 조회 전에 전처럼 template 없음으로
거절되고, 키를 주지 않은 호출은 바뀐 plan에서 키를 다시 만들어 전처럼 두 번째 알림이 된다. 재전송이 설정 변경을 넘을 수
있으면 키와 locale을 본문에 적는다.
- `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하고, 이 문서에 되돌린 행을 더한다.
+4 -2
View File
@@ -14,7 +14,8 @@
실행 전 거부와 결과 불명의 구분은 `IdempotencyExecutorTest`, lease 하한은 `IdempotencySettingsTest`
- 헤더 규칙(3절): `WebMvcRequestIdFilterTest`, `CorsSecurityFilterIntegrationTest`
- web 전용 코드(4절): `TransportErrorHandlingTest`, `IdempotencyKeyHeaderTest`, web-advanced
`WebAdvancedErrorMappingTest`
`WebAdvancedErrorMappingTest`, 알림 기능 코드는 web-notification의 `NotificationAdminRefusalHttpAnswerTest`
(`DELIVERY_ATTEMPT_NOT_FOUND`)와 `NotificationSubmissionControllerTest`(`IDEMPOTENCY_CONFLICT`)
## 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`라 실패를 답하는 전송(web·GraphQL·gRPC)이 같은 코드로 답한다(`docs/manual/05-idempotency.md` 「executor를 쓰지 않는 중복 판정 둘」) |
- 컨트롤러 파라미터 제약 위반(`@RequestParam @Max(10)`)은 요청 본문 위반과 같은
`400 VALIDATION_FAILED`이고 `details`는 `[{field, code, message}]`다. 거절된 값은 싣지 않는다.
+1
View File
@@ -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 총괄 세션 전달 |
@@ -33,6 +33,12 @@ import org.springframework.web.bind.annotation.RestController;
* <p>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.
*
* <p>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)
@@ -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
*/
@@ -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<AcceptNotificationCommand> 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<Object> 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<Object> 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<Object> answerWhenTheUseCaseThrows(RuntimeException failure)
throws Exception {
List<String> 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<ILoggingEvent> 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.<Boolean>read(body, "$.success"),
JsonPath.<String>read(body, "$.error.code"),
JsonPath.<String>read(body, "$.error.category"),
JsonPath.<String>read(body, "$.error.message"),
JsonPath.<Boolean>read(body, "$.error.retryable"),
handlerLog.list.stream().map(ILoggingEvent::getLevel).toList(),
spanErrorCodes);
}
}
@@ -1,11 +1,56 @@
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.
*
* <p>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.
* 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.
*
* <p>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.
*
* <p>The {@linkplain #descriptor() descriptor} keeps the closed notification registry ({@code
* 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;
}
}
@@ -0,0 +1,52 @@
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.
*
* <p>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 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 {
/**
* 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;
}
}
@@ -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,36 @@ 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: 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)
.isInstanceOf(IllegalStateException.class)
.hasMessage(
"an idempotency conflict is described by IDEMPOTENCY_CONFLICT and INVALID_PAYLOAD");
}
@Test
void failureCodesComeFromAClosedRegistry() {
assertThatThrownBy(
@@ -3,14 +3,22 @@ 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.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;
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 +26,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 +40,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 +241,200 @@ 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(
Optional.ofNullable(refused).<Object>map(Throwable::getClass).orElse("nothing"),
Optional.ofNullable(refused).map(Throwable::getMessage).orElse("nothing"),
carriedCode(refused),
chain.requests.byId.size(),
chain.requests.missedIdempotencyLookups(),
lostInserts(chain)))
.as(
"[exception, message, carried code (code, category, status, retryable), stored"
+ " 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.lostInserts());
}
/** 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(),
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<NotificationAcceptance> 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. */
private static List<Object> carriedCode(Throwable failure) {
return ApiErrorCarrier.firstIn(failure)
.map(carrier -> ((ApiErrorCarrier) carrier).errorCode())
.<List<Object>>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, Optional.empty()),
/** The second acceptance read before the first committed, and loses the insert of the key. */
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, Optional.of(NotificationAcceptance.DROPPED_AS_DUPLICATE)) {
@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;
private final Optional<NotificationAcceptance> lostInsert;
KeyReuse(boolean secondMissesTheLookup, Optional<NotificationAcceptance> lostInsert) {
this.secondMissesTheLookup = secondMissesTheLookup;
this.lostInsert = lostInsert;
}
/** Sets up how the second request meets the stored one. */
void prepareSecond(RealSubmission chain) {
if (secondMissesTheLookup) {
chain.requests.missNextIdempotencyLookup();
}
}
/** How many lookups the store must have answered empty for the second request to take it. */
int missedLookups() {
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<NotificationAcceptance> lostInserts() {
return lostInsert.stream().toList();
}
/** 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<String, NotificationVariable> variables) {
return new AcceptNotificationCommand(
Optional.empty(),
@@ -42,8 +42,19 @@ public final class InMemoryNotificationRequestStore implements NotificationReque
/** Whether each status write ran inside the observed transaction, in call order. */
public final List<Boolean> 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<NotificationRequestRecord> lostInserts = new ArrayList<>();
private boolean failNextInsertAsDuplicate;
private boolean missNextIdempotencyLookup;
private int missedIdempotencyLookups;
private BooleanSupplier transactionOpen;
/**
@@ -67,6 +78,29 @@ 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.
*
* <p>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;
}
/**
* How many idempotency lookups {@link #missNextIdempotencyLookup()} answered with nothing.
*
* <p>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<RecipientDeliveryRecord> jobs) {
@@ -78,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);
@@ -91,6 +126,11 @@ public final class InMemoryNotificationRequestStore implements NotificationReque
@Override
public synchronized Optional<NotificationRequestRecord> findByIdempotency(
TenantId tenantId, String idempotencyKey) {
if (missNextIdempotencyLookup) {
missNextIdempotencyLookup = false;
missedIdempotencyLookups++;
return Optional.empty();
}
return Optional.ofNullable(byIdempotency.get(key(tenantId, idempotencyKey))).map(byId::get);
}