From b282b63d863cb1ed3c3ee136f01728675b05ed3a Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 21:14:43 +0900 Subject: [PATCH 1/5] =?UTF-8?q?fix(notification)!:=20=EC=9A=B4=EC=98=81?= =?UTF-8?q?=EC=9E=90=20=EC=97=B0=EC=82=B0=EC=9D=98=20=EA=B1=B0=EC=A0=88=20?= =?UTF-8?q?=EB=8B=A4=EC=84=AF=EC=9D=84=20=ED=81=B4=EB=9D=BC=EC=9D=B4?= =?UTF-8?q?=EC=96=B8=ED=8A=B8=20=EC=98=A4=EB=A5=98=20carrier=EB=A1=9C=20?= =?UTF-8?q?=EB=8B=B5=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 알림 운영자 연산 넷의 거절 예외 가운데 ApiErrorCarrier는 redrive의 DeliveryAttemptNotFoundException 하나뿐이다. 권한 부족 (AdminAccessDeniedException), suppression·reconcile의 tenant 밖 대상(같은 예외), 중복 위험 승인 없음(DuplicateRiskApprovalRequiredException), operation id 재사용과 진행 중(AdminOperationConflictException· AdminOperationInProgressException)은 carrier가 아니어서 web GlobalExceptionHandler가 500 INTERNAL_ERROR와 ERROR 로그·span 오류로 답한다. 운영자 실수가 서버 장애 경보를 울리고, 클라이언트는 5xx를 재시도해도 되는 것으로 읽는다. gRPC·GraphQL도 carrier만 읽어서 같다. docs/manual/06-errors.md와 07-authorization.md는 클라이언트 탓이면 carrier, 남의 것은 없는 것과 같은 404라고 약속했다. 다섯 예외가 ApiErrorCarrier를 구현하고, code는 NotificationAdminErrorCode에 더한 다섯이다: ADMIN_ACCESS_DENIED 403 AUTHZ, ADMIN_TARGET_NOT_FOUND 404 NOT_FOUND, DUPLICATE_RISK_APPROVAL_REQUIRED 409 CONFLICT, ADMIN_OPERATION_CONFLICT 422 VALIDATION, ADMIN_OPERATION_IN_PROGRESS 409 CONFLICT(retryable true). descriptor는 모두 그대로다. tenant 밖 대상은 권한 거절이 아니라 상태 없는 새 AdminTargetNotFoundException으로 던져 403과 다른 404로 답한다. AdminAuthorizationGuard.requireTenant는 그 거절이 authority를 싣지 않으므로 authority 인자를 뺐다. package-private 예외 둘은 공개하지 않는다. 요청 표와 다르게 한 곳: 표는 operation id 재사용을 409로 적었다. 같은 멱등 키·다른 요청은 상태 충돌이 아니라 422라는 manual 06 판단 표, executor 선례(IDEMPOTENT_IN_FLIGHT 409 retryable, IDEMPOTENT_REQUEST_MISMATCH 422), AdminOperationRequestFingerprint의 「operation id가 멱등 키」를 따라 422로 했다. 409로 바꾸려면 enum 한 줄과 시험 행·문서 표의 422를 바꾼다. 버린 안: 문서만 500으로 고치기(운영자 실수가 경보를 울리는 것이 그대로다), web 처리기에서 예외 이름으로 잡기(gRPC·GraphQL이 빠진다). 표의 답은 review 허브가 project-docs README 7절 1번으로 고른 권하는 안이고 소유자가 정한 것이 아니다. 결정 색인 2.3절에 그렇게 적었다. 위험·한계: 공개 계약 변경이다. 500을 거절로 읽던 운영자 화면과 5xx만 세던 경보는 새 code를 다뤄야 한다. GraphQL에서 이 예외나 상위 타입을 등록한 매핑은 더 쓰이지 않는다(실패 자신이 carrier면 먼저 답한다). STOMP는 frame 없이 ERROR 로그만 사라진다. ADMIN_OPERATION_IN_PROGRESS는 retryable true지만 web이 Retry-After를 싣지 않는다. 이 커밋에서 reconcile의 남의 tenant attempt는 ADMIN_TARGET_NOT_FOUND이고 없는 id는 전처럼 건너뛴다. 둘을 redrive와 같은 DELIVERY_ATTEMPT_NOT_FOUND로 맞추는 것은 다음 커밋이다. notification API surface 기준선이 378에서 379가 된다. 알림 code 목록과 템플릿 registry는 넓히지 않았다. 검증: NotificationAdminRefusalHttpAnswerTest의 거절 표가 다섯 거절을 실제 유스케이스와 GlobalExceptionHandler로 보내 status·code·category·고정 문구· retryable·Retry-After 없음·처리기 로그 0줄·span 오류 0을 단언한다. base 957cbc96에 이 시험을 얹은 desktop leaf --no-cache에서 다섯 행 모두 500 INTERNAL_ERROR·로그 1줄·span INTERNAL_ERROR로 실패하고 redrive 404 4행은 통과했다. NotificationAdminUseCasesTest·AdminAuthorizationGuardTest는 tenant 밖 대상이 ADMIN_TARGET_NOT_FOUND임을 단언한다. 노트북 감싸개 :application-notification:check, :adapter:inbound:web-notification:check, :adapter:outbound:notification:verifyNotificationApiSurface rc=0, check-docs.py·check-work-docs.py OK. BREAKING CHANGE: 알림 운영자 연산의 거절 다섯이 500 INTERNAL_ERROR 대신 403 ADMIN_ACCESS_DENIED, 404 ADMIN_TARGET_NOT_FOUND, 409 DUPLICATE_RISK_APPROVAL_REQUIRED, 422 ADMIN_OPERATION_CONFLICT, 409 ADMIN_OPERATION_IN_PROGRESS(retryable)로 답하고 서버 오류 로그를 남기지 않는다. suppression·reconcile의 tenant 밖 대상은 AdminAccessDeniedException 대신 AdminTargetNotFoundException이고, AdminAuthorizationGuard.requireTenant는 authority 인자를 받지 않는다. 옮기는 법은 docs/upgrade/2026-11-notification-admin-refusals.md 2.1절이다. Refs: REV-BE-0058 --- docs/notification/api-surface-snapshot.txt | 3 +- docs/notification/operations.md | 23 +- .../2026-11-notification-admin-redrive.md | 2 + .../2026-11-notification-admin-refusals.md | 56 +++ docs/web/http-contract.md | 10 +- docs/work/reference/decisions.md | 1 + ...otificationAdminRefusalHttpAnswerTest.java | 471 +++++++++++++++--- .../admin/AdminAccessDeniedException.java | 24 +- .../admin/AdminAuthorizationGuard.java | 19 +- .../AdminOperationConflictException.java | 18 +- .../AdminOperationInProgressException.java | 18 +- .../admin/AdminTargetNotFoundException.java | 38 ++ .../admin/ChangeSuppressionUseCase.java | 2 +- ...uplicateRiskApprovalRequiredException.java | 16 +- .../admin/NotificationAdminErrorCode.java | 42 +- .../admin/ReconcileDeliveriesUseCase.java | 5 +- .../admin/AdminAuthorizationGuardTest.java | 50 +- .../admin/NotificationAdminUseCasesTest.java | 24 +- 18 files changed, 692 insertions(+), 130 deletions(-) create mode 100644 docs/upgrade/2026-11-notification-admin-refusals.md create mode 100644 src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminTargetNotFoundException.java diff --git a/docs/notification/api-surface-snapshot.txt b/docs/notification/api-surface-snapshot.txt index f1ecb1ce..7c73b7bc 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: 378 +# types: 379 dev.caskeleton.adapter.outbound.notification.NotificationConfig dev.caskeleton.adapter.outbound.notification.NotificationRoutesSettings dev.caskeleton.adapter.outbound.notification.core.FailOpenNotificationProvider @@ -100,6 +100,7 @@ dev.caskeleton.application.notification.platform.admin.AdminAuthorizationGuard dev.caskeleton.application.notification.platform.admin.AdminOperationClaim dev.caskeleton.application.notification.platform.admin.AdminOperationResult dev.caskeleton.application.notification.platform.admin.AdminOperationStorePort +dev.caskeleton.application.notification.platform.admin.AdminTargetNotFoundException dev.caskeleton.application.notification.platform.admin.ChangeProviderStateCommand dev.caskeleton.application.notification.platform.admin.ChangeProviderStateUseCase dev.caskeleton.application.notification.platform.admin.ChangeSuppressionCommand diff --git a/docs/notification/operations.md b/docs/notification/operations.md index e9fb4a2c..3329862e 100644 --- a/docs/notification/operations.md +++ b/docs/notification/operations.md @@ -51,11 +51,24 @@ redrive는 `NotificationId`와 `RecipientDeliveryId`를 유지하고, 새 `Deliv - 확인은 두 겹이다. permission은 전송의 호출자가 이 연산을 부를 수 있는지다(`@RequiresPermission`). authority와 tenant 범위는 command의 `AdminActor`가 쥐고, 연산이 건드리는 delivery의 tenant와 대조한다. -- redrive가 받은 attempt id가 없거나 그 attempt가 운영자 tenant 밖이면 둘 다 `DeliveryAttemptNotFoundException`이다. - 이 예외는 `ApiErrorCarrier`라서 모든 전송이 code `DELIVERY_ATTEMPT_NOT_FOUND`(category `NOT_FOUND`, retryable false)로 - 답하고 서버 오류로 남기지 않는다. web은 404다. 운영자 입력이라 서버 오류가 아니고, 두 경우가 같은 답이라 다른 tenant에 그 id가 있는지도 - 알 수 없다. 예외의 descriptor는 알림 code 목록의 `VALIDATION_FAILED`라 응답 code와 다르다. reconcile은 묶음 안의 없는 - id를 건너뛴다. +- 거절은 모두 운영자 입력이라 서버 오류가 아니다. 거절 예외는 `ApiErrorCarrier`라서 실패를 답하는 전송(web·GraphQL·gRPC)이 + 아래 code(`NotificationAdminErrorCode`)로 답하고 서버 오류로 남기지 않는다. 예외의 descriptor는 알림 code 목록 값이라 + 응답 code와 다르다. 전송마다의 모양은 `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절이다. + + | 거절 | code | web | retryable | 운영자가 할 일 | + |---|---|---|---|---| + | authority가 없다. tenant 범위 운영자가 provider 상태를 바꾸려 했다 | `ADMIN_ACCESS_DENIED` | 403 | false | authority를 받거나 tenant 범위 없는 운영자에게 맡긴다 | + | redrive의 attempt id가 없거나 그 attempt가 운영자 tenant 밖이다 | `DELIVERY_ATTEMPT_NOT_FOUND` | 404 | false | id를 확인한다 | + | suppression·reconcile이 운영자 tenant 밖의 대상을 골랐다 | `ADMIN_TARGET_NOT_FOUND` | 404 | false | tenant를 확인한다 | + | 모호한 attempt를 중복 위험 승인 없이 redrive했다 | `DUPLICATE_RISK_APPROVAL_REQUIRED` | 409 | false | 중복 위험을 받아들이면 승인을 붙여 다시 보낸다 | + | operation id가 전에 다른 요청에 쓰였다 | `ADMIN_OPERATION_CONFLICT` | 422 | false | 새 operation id를 쓴다 | + | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다 | `ADMIN_OPERATION_IN_PROGRESS` | 409 | true | 기다렸다가 같은 id·같은 요청을 다시 보낸다. 끝났으면 저장된 결과가 온다 | + +- authority는 대상을 읽기 전에 본다. 그래서 403은 대상에 대해 아무것도 알려 주지 않는다. tenant 밖의 대상은 authority + 거절이 아니라 없는 대상과 같은 404다. redrive는 없는 attempt와 남의 tenant attempt가 같은 답이라 다른 tenant에 그 id가 + 있는지 알 수 없다. reconcile은 묶음 안의 없는 id를 건너뛴다. +- provider 호출 중에 프로세스가 멈춘 reconcile의 operation id는 claim이 끝나지 않아 계속 진행 중으로 답한다. 그 묶음은 새 + operation id로 보낸다. - 모든 연산은 운영자가 준 operation id로 멱등이다. 같은 id·같은 요청은 저장된 결과를 돌려주고, 같은 id·다른 요청은 충돌이다. 대상 확인(tenant·중복 위험)과 claim과 쓰기는 한 쓰기 트랜잭션에서 커밋한다. reconcile만 대상 확인을 읽기 트랜잭션에서 하고, provider 호출은 트랜잭션 밖에서 하며, claim과 결과를 따로 커밋한다. diff --git a/docs/upgrade/2026-11-notification-admin-redrive.md b/docs/upgrade/2026-11-notification-admin-redrive.md index 26251e16..a5216966 100644 --- a/docs/upgrade/2026-11-notification-admin-redrive.md +++ b/docs/upgrade/2026-11-notification-admin-redrive.md @@ -34,6 +34,8 @@ - `ReconcileDeliveriesUseCase`는 묶음 안의 없는 attempt id를 그대로 건너뛴다. - suppression·reconcile·provider 상태 연산은 남의 tenant 대상을 전처럼 `AdminAccessDeniedException`으로 거절한다. authority가 없을 때의 답도 네 연산 모두 그대로다. + - 2026-11-23에 이 줄은 낡았다. suppression·reconcile의 남의 tenant 대상과 네 연산의 authority 없음의 답은 + `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절이 대신한다. - 오류 code 목록(`NotificationFailureCode`)과 템플릿 오류 code registry(`docs/registries/error-codes.yaml`)는 그대로다. not-found 코드는 그 목록이 아니라 전송이 읽는 `NotificationAdminErrorCode`에 두었다. 새 예외의 descriptor는 있는 값(`VALIDATION_FAILED`, `INVALID_PAYLOAD`)이라 descriptor code와 응답 code가 다르다. diff --git a/docs/upgrade/2026-11-notification-admin-refusals.md b/docs/upgrade/2026-11-notification-admin-refusals.md new file mode 100644 index 00000000..ceb8a222 --- /dev/null +++ b/docs/upgrade/2026-11-notification-admin-refusals.md @@ -0,0 +1,56 @@ +# 업그레이드 안내 — 2026-11 알림 운영자 연산의 거절 + +- 범위: 알림 운영자 연산 넷(`RedriveDeliveryUseCase`·`ReconcileDeliveriesUseCase`·`ChangeSuppressionUseCase`· + `ChangeProviderStateUseCase`)이 운영자 입력을 거절할 때 전송이 내는 답을 바꾼 변경. 설정 키는 그대로다. 공개 타입이 + 하나 늘었고(`AdminTargetNotFoundException`), 공개 메서드 `AdminAuthorizationGuard.requireTenant`의 인자가 하나 줄었다. + 템플릿은 이 연산을 부르는 전송을 싣지 않는다. 알림 capability(`:composition:notification-platform`)를 싣고 이 연산에 + 전송(운영자 화면, admin endpoint)을 연 서비스만 해당한다. +- 근거: 2026-11-23 리뷰 발견 REV-BE-0058. 운영자 실수는 클라이언트 탓이라 carrier로 답하고, 남의 것은 없는 것과 같은 404로 + 답한다는 것은 `docs/manual/06-errors.md` 「판단: 어떤 예외 타입으로 던지나」와 `docs/manual/07-authorization.md` + 「객체 단위 권한」이 이미 약속했다. 거절마다 status를 고른 것은 review 허브의 권하는 안이고 소유자 결정이 아니다 + (`docs/work/reference/decisions.md` 2.3절). + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 알림 운영자 연산을 부르는 전송을 연 서비스다. + +## 2. 바뀐 동작 + +### 2.1 2026-11-23 — 거절 다섯을 클라이언트 오류로 (따라 할 일 있음) + +거절마다 답하는 code다. code는 `application-notification`의 `NotificationAdminErrorCode`다. + +| code | 거절 | 예외 | status | category | retryable | +| --- | --- | --- | --- | --- | --- | +| `ADMIN_ACCESS_DENIED` | 운영자에게 연산의 authority가 없다. 또는 tenant 범위 운영자가 provider 상태를 바꾸려 했다 | `AdminAccessDeniedException` | 403 | `AUTHZ` | false | +| `ADMIN_TARGET_NOT_FOUND` | suppression·reconcile이 운영자 tenant 밖의 대상을 골랐다 | `AdminTargetNotFoundException`(새 타입) | 404 | `NOT_FOUND` | false | +| `DUPLICATE_RISK_APPROVAL_REQUIRED` | 모호한 attempt의 redrive가 중복 위험 승인 없이 왔다 | `DuplicateRiskApprovalRequiredException` | 409 | `CONFLICT` | false | +| `ADMIN_OPERATION_CONFLICT` | operation id가 전에 다른 요청에 쓰였다 | 공개되지 않은 타입(`RuntimeException`) | 422 | `VALIDATION` | false | +| `ADMIN_OPERATION_IN_PROGRESS` | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다 | 공개되지 않은 타입(`RuntimeException`) | 409 | `CONFLICT` | true | + +| # | 바뀐 것 | 전에는 | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | --- | --- | +| 1 | 위 다섯 예외가 `ApiErrorCarrier`를 구현한다. 실패를 답하는 공용 처리기가 위 code로 답한다. web은 위 status와 error 본문(code·category·category별 고정 문구·retryable)이고, 서버 오류 로그와 span 오류를 남기지 않는다. `ADMIN_OPERATION_IN_PROGRESS`는 retryable true지만 `Retry-After` 헤더는 없다. GraphQL은 errors의 code가 위 code이고 category는 `AUTHORIZATION`(403)·`BUSINESS`(404·409)·`REQUEST`(422)다. 실패 자신이 carrier라서 등록 매핑보다 먼저 답한다. resolver observation은 전처럼 던진 예외를 오류로 센다(`graphql.outcome=ERROR`와 span 오류). gRPC는 `PERMISSION_DENIED`(403)·`NOT_FOUND`(404)·`ABORTED`(409)·`INVALID_ARGUMENT`(422)와 trailer `error-code`·`error-category`·`error-retryable`이고 서버 오류 로그를 남기지 않는다. STOMP `@MessageMapping`이 던진 실패는 전처럼 frame을 보내지 않고 ERROR 로그만 사라진다. 예외 타입·메시지·descriptor(알림 code 목록 값)는 그대로다 | carrier가 아니어서 공용 처리기가 서버 오류로 다뤘다. web은 500 `INTERNAL_ERROR`와 ERROR 로그·span 오류, gRPC는 `INTERNAL`, GraphQL은 이 타입(또는 상위 타입)을 등록한 매핑이 없으면 `INTERNAL_ERROR`였다. STOMP는 frame 없이 ERROR 로그를 남겼다. 운영자 실수가 5xx 경보를 울렸다 | 500·`INTERNAL`을 거절로 읽던 운영자 화면·모니터링을 위 code로 바꾼다. `ADMIN_OPERATION_IN_PROGRESS`만 같은 요청을 다시 보낸다(첫 요청이 끝났으면 저장된 결과가 온다). `ADMIN_OPERATION_CONFLICT`는 다시 보내지 않고 새 operation id를 쓴다. GraphQL에 `GraphQlExceptionResolver`로 이 예외나 상위 타입(`NotificationException`, `RuntimeException` 등)을 등록해 자기 code로 답하던 서비스는 그 매핑이 더 쓰이지 않는다(`docs/work/reference/decisions.md` 2.3절 「GraphQL 판정 순서」). 자기 code가 필요하면 이 예외를 감싼 자기 예외로 던지고 그 타입을 등록한다. web `@ExceptionHandler`와 이 예외를 직접 잡던 코드는 그대로 동작한다 | 운영자 화면이 이 code를 모르면 거절을 처리하지 못한다. 5xx만 세던 경보 규칙은 이 거절을 더 보지 않는다. GraphQL의 등록 매핑에 기대던 분기는 code가 바뀌어 깨진다 | 알림 운영자 연산 전송을 연 서비스 | +| 2 | suppression이 운영자 tenant 밖의 tenant를 고르면 `AdminTargetNotFoundException`이다. reconcile 묶음에 운영자 tenant 밖의 attempt가 있어도 같은 예외다. 이 예외는 상태를 싣지 않는다. 거절은 그 tenant의 어떤 것도 읽지 않아서, 답으로 그 tenant가 무엇을 가졌는지 알 수 없다 | `AdminAccessDeniedException`(`required()`는 `SUPPRESS` 또는 `RECONCILE`)이었다. 운영자에게 authority가 없을 때와 같은 예외였다 | 이 경우를 `AdminAccessDeniedException`으로 잡던 코드를 `AdminTargetNotFoundException`으로 바꾼다. `AdminAccessDeniedException`은 이제 authority가 없을 때와 tenant 범위 운영자의 provider 상태 변경에만 난다. 공용 처리기에 맡겼다면 고칠 코드는 없다(web 응답이 404로 바뀐다) | 그 catch가 이 예외를 놓쳐 공용 처리기로 간다. 서비스가 만든 거절 응답 대신 `ADMIN_TARGET_NOT_FOUND`(web은 404)가 나간다 | 알림 운영자 연산 전송을 연 서비스 | +| 3 | `AdminAuthorizationGuard.requireTenant(AdminActor, TenantId)`가 authority 인자를 받지 않는다. tenant 밖이면 `AdminTargetNotFoundException`을 던진다 | `requireTenant(AdminActor, TenantId, NotificationAdminAuthority)`가 그 authority를 실은 `AdminAccessDeniedException`을 던졌다 | 이 guard를 자기 연산에 쓰는 서비스는 셋째 인자를 지우고, 거절을 잡던 곳은 2행대로 바꾼다 | 컴파일이 실패한다 | 이 guard를 직접 부르는 서비스 | + +## 3. 바뀌지 않은 것 + +- redrive의 없는 attempt id와 남의 tenant attempt는 전처럼 404 `DELIVERY_ATTEMPT_NOT_FOUND`다 + (`docs/upgrade/2026-11-notification-admin-redrive.md` 2.1절). +- authority는 대상을 읽기 전에 본다. 그래서 403은 대상에 대해 아무것도 알려 주지 않는다. +- `ReconcileDeliveriesUseCase`는 묶음 안의 없는 attempt id를 전처럼 건너뛴다. +- 같은 operation id·같은 요청은 전처럼 저장된 결과를 돌려준다. +- carrier가 아닌 실패는 공용 처리기가 전처럼 500으로 답한다(web `GlobalExceptionHandler`). +- 오류 code 목록(`NotificationFailureCode`)과 템플릿 오류 code registry(`docs/registries/error-codes.yaml`)는 그대로다. + 응답 code는 전송이 읽는 `NotificationAdminErrorCode`에 두었다. 예외의 descriptor는 알림 code 목록 값이라 + descriptor code와 응답 code가 다르다. +- 같은 operation id를 다른 요청에 쓴 거절이 409가 아니라 422인 것은 같은 멱등 키·다른 요청을 422로 답하는 규칙을 + 따랐다(`docs/manual/06-errors.md` 「판단: 어떤 예외 타입으로 던지나」). operation id가 이 연산의 멱등 키다. + +## 4. 되돌리는 법 + +다섯 예외의 carrier 구현, `NotificationAdminErrorCode`의 다섯 행, `AdminTargetNotFoundException`, `requireTenant`의 인자, +문서와 API surface 기준선 행을 함께 revert하고, 이 문서에 되돌린 행을 더한다. operation id 재사용만 409로 바꾸려면 +`ADMIN_OPERATION_CONFLICT`를 `(409, Category.CONFLICT, false)`로 바꾸고, 시험 행과 이 문서·`docs/web/http-contract.md` +4절·`docs/notification/operations.md`의 422를 409로 고친다. diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index 8af6eb86..71eb27ae 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -15,7 +15,8 @@ - 헤더 규칙(3절): `WebMvcRequestIdFilterTest`, `CorsSecurityFilterIntegrationTest` - web 전용 코드(4절): `TransportErrorHandlingTest`, `IdempotencyKeyHeaderTest`, web-advanced `WebAdvancedErrorMappingTest`, 알림 기능 코드는 web-notification의 `NotificationAdminRefusalHttpAnswerTest` - (`DELIVERY_ATTEMPT_NOT_FOUND`)와 `NotificationSubmissionControllerTest`(`IDEMPOTENCY_CONFLICT`) + (운영자 연산 거절: `DELIVERY_ATTEMPT_NOT_FOUND`·`ADMIN_*`·`DUPLICATE_RISK_APPROVAL_REQUIRED`)와 + `NotificationSubmissionControllerTest`(`IDEMPOTENCY_CONFLICT`) ## 1. Envelope 키 존재 규칙 @@ -191,7 +192,7 @@ CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의 ## 4. web 전용 오류 코드 `OperationalError`(`docs/registries/error-codes.yaml`) 밖의 코드다. HTTP 어댑터가 내는 코드와, 기능 leaf의 enum이 내고 -HTTP가 그대로 답하는 코드(`DELIVERY_ATTEMPT_NOT_FOUND`, `IDEMPOTENCY_CONFLICT`)가 있다. +HTTP가 그대로 답하는 코드(알림 운영자 연산 거절, `IDEMPOTENCY_CONFLICT`)가 있다. | 코드 | status | category | `retryable` | `Retry-After` | 언제 | | --- | --- | --- | --- | --- | --- | @@ -201,6 +202,11 @@ 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`) | +| `ADMIN_ACCESS_DENIED` | 403 | `AUTHZ` | `false` | 없음 | 알림 운영자 연산에서 운영자에게 그 연산의 authority가 없거나, tenant 범위 운영자가 provider 상태를 바꾸려 했다. authority는 대상을 읽기 전에 보므로 대상에 대해 알려 주지 않는다. 코드는 `application-notification`의 `NotificationAdminErrorCode`다(아래 운영자 연산 행 모두 같다). 템플릿은 이 연산의 전송을 싣지 않는다(`docs/notification/operations.md`) | +| `ADMIN_TARGET_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | 알림 운영자 suppression·reconcile이 운영자 tenant 밖의 대상을 골랐다. 권한 거절(403)이 아니라 없는 대상과 같은 404라 그 tenant가 무엇을 가졌는지 알려 주지 않는다 | +| `DUPLICATE_RISK_APPROVAL_REQUIRED` | 409 | `CONFLICT` | `false` | 없음 | 이미 사용자에게 닿았을 수 있는 attempt의 redrive가 중복 위험 승인 없이 왔다. 같은 요청은 다시 거절된다. 승인을 붙여 보낸다 | +| `ADMIN_OPERATION_CONFLICT` | 422 | `VALIDATION` | `false` | 없음 | 알림 운영자 연산의 operation id(그 연산의 멱등 키)가 전에 다른 요청에 쓰였다. 같은 멱등 키·다른 요청이라 409가 아니다(`docs/manual/06-errors.md`). 새 operation id를 쓴다 | +| `ADMIN_OPERATION_IN_PROGRESS` | 409 | `CONFLICT` | `true` | 없음 | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다. 기다렸다가 같은 요청을 다시 보내면 끝난 결과가 온다. 2절의 `IDEMPOTENT_IN_FLIGHT`와 달리 `Retry-After`를 싣지 않는다 | | `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)`)은 요청 본문 위반과 같은 diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index 421c38e6..f69fe7f0 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -113,6 +113,7 @@ | 알림 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절 | +| 알림 운영자 연산의 거절 | 운영자 입력 거절 다섯을 carrier로 답한다. code는 기능 enum `NotificationAdminErrorCode`다: authority 없음 403 `ADMIN_ACCESS_DENIED`, suppression·reconcile의 tenant 밖 대상 404 `ADMIN_TARGET_NOT_FOUND`(권한 거절이 아니라 없는 대상과 같은 답), 중복 위험 승인 없음 409 `DUPLICATE_RISK_APPROVAL_REQUIRED`, operation id 재사용 422 `ADMIN_OPERATION_CONFLICT`, 같은 id 진행 중 409 `ADMIN_OPERATION_IN_PROGRESS`(retryable true, `Retry-After` 없음). 요청의 표는 재사용을 409로 적었지만, 같은 멱등 키·다른 요청은 422라는 `docs/manual/06-errors.md` 판단 표와 executor 선례(`IDEMPOTENT_REQUEST_MISMATCH`)를 따라 422로 했다. 문서만 500으로 고치는 안과 web 처리기에서 이름으로 잡는 안은 버렸다. 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다 | 기본값(2026-11-23, review 허브가 고른 권하는 안, 자율 운영. 422는 백엔드 개발자가 매뉴얼에 맞춘 것이고 review 판정을 받는다. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0058 요청(2026-11-23 09:40), `docs/upgrade/2026-11-notification-admin-refusals.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/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java index b5bec64b..c433a6ac 100644 --- a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java @@ -6,41 +6,74 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; +import com.jayway.jsonpath.Configuration; +import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; +import com.jayway.jsonpath.Option; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; import dev.caskeleton.application.notification.platform.admin.AdminActor; import dev.caskeleton.application.notification.platform.admin.AdminAuthorizationGuard; +import dev.caskeleton.application.notification.platform.admin.ChangeSuppressionCommand; +import dev.caskeleton.application.notification.platform.admin.ChangeSuppressionUseCase; import dev.caskeleton.application.notification.platform.admin.DuplicateRiskGuard; import dev.caskeleton.application.notification.platform.admin.NotificationAdminAuthority; import dev.caskeleton.application.notification.platform.admin.NotificationAdminErrorCode; +import dev.caskeleton.application.notification.platform.admin.ReconcileDeliveriesCommand; +import dev.caskeleton.application.notification.platform.admin.ReconcileDeliveriesUseCase; +import dev.caskeleton.application.notification.platform.admin.ReconcileRequest; import dev.caskeleton.application.notification.platform.admin.RedriveDeliveryCommand; import dev.caskeleton.application.notification.platform.admin.RedriveDeliveryUseCase; import dev.caskeleton.application.notification.platform.admin.RedriveRequest; +import dev.caskeleton.application.notification.platform.admin.SuppressionRequest; import dev.caskeleton.application.notification.platform.admin.testkit.InMemoryAdminOperationStore; import dev.caskeleton.application.notification.platform.api.ContactPointId; import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; import dev.caskeleton.application.notification.platform.api.TenantId; import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; +import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService; +import dev.caskeleton.application.notification.platform.callback.StandardDeliveryProjector; +import dev.caskeleton.application.notification.platform.callback.testkit.InMemoryProviderEventLedger; import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestRecord; import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort; +import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService; +import dev.caskeleton.application.notification.platform.dispatch.SuppressionSideEffect; +import dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint; +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.dispatch.testkit.NotificationRows; +import dev.caskeleton.application.notification.platform.dispatch.testkit.Sha256ProviderRequestIdHasher; +import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; import dev.caskeleton.application.notification.platform.observation.testkit.RecordingNotificationAudit; +import dev.caskeleton.application.notification.platform.policy.SuppressionReason; +import dev.caskeleton.application.notification.platform.policy.SuppressionScope; +import dev.caskeleton.application.notification.platform.policy.testkit.InMemorySuppressionStore; +import dev.caskeleton.application.notification.platform.provider.ReconciliationResult; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.ClientErrorMessages; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumSet; import java.util.List; +import java.util.Map; import java.util.Optional; -import java.util.Set; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.LoggerFactory; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.MockMvc; @@ -51,41 +84,78 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** - * What an HTTP caller sees when a notification operator's redrive names an attempt the operator - * cannot reach. + * What an HTTP caller sees when a notification operator operation refuses a request. * *

The template ships no operator endpoint. The probe controller below is the transport a service - * would write: it hands the command to the real use case over the notification fakes and lets the - * failure reach the real {@link GlobalExceptionHandler}. The use case's own table (both refusals, - * claims, audit) is {@code NotificationAdminUseCasesTest}; this one is the answer on the wire. + * would write: it hands the command to the real use cases over the notification fakes and lets the + * failure reach the real {@link GlobalExceptionHandler}. The use cases' own tables (claims, audit, + * provider calls) are {@code NotificationAdminUseCasesTest}; this one is the answer on the wire. + * + *

Every refusal here answers the operator's own input — a missing authority, a target out of + * reach, an unapproved duplicate risk, a reused or busy operation id — so none is answered or + * recorded as a server failure. */ class NotificationAdminRefusalHttpAnswerTest { private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-11-23T00:00:00Z"), ZoneOffset.UTC); + private static final TenantId TENANT_A = new TenantId("tenant-a"); + private static final TenantId TENANT_B = new TenantId("tenant-b"); private static final AdminActor TENANT_B_OPERATOR = new AdminActor( "operator-b", - Set.of(NotificationAdminAuthority.REDRIVE), - Optional.of(new TenantId("tenant-b"))); + EnumSet.of( + NotificationAdminAuthority.REDRIVE, + NotificationAdminAuthority.RECONCILE, + NotificationAdminAuthority.SUPPRESS), + Optional.of(TENANT_B)); private static final String UNKNOWN_ATTEMPT = "00000000-0000-7000-8000-000000000099"; + // A body without a field reads as null, so a success answer fails the comparison by its values. + private static final Configuration LENIENT_JSON = + Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS); + private static final String ANSWER_FIELDS = + "[status, success, error code, category, message, retryable, Retry-After, handler log lines," + + " span error codes]"; private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); private final InMemoryDeliveryAttemptStore attempts = new InMemoryDeliveryAttemptStore(requests); + private final InMemoryRecipientQueue recipients = new InMemoryRecipientQueue(requests, CLOCK); + private final InMemoryAdminOperationStore operations = new InMemoryAdminOperationStore(); private final RecordingNotificationAudit audit = new RecordingNotificationAudit(); + private final DirectTransactionPort transactions = new DirectTransactionPort(); private final List spanErrorCodes = new ArrayList<>(); + private final AtomicInteger providerCalls = new AtomicInteger(); + private ProviderCall duringProviderCall = () -> {}; + private AdminActor actor = TENANT_B_OPERATOR; private final MockMvc mvc = MockMvcBuilders.standaloneSetup( - new RedriveProbe( + new OperatorProbe( new RedriveDeliveryUseCase( new AdminAuthorizationGuard(), new DuplicateRiskGuard(), attempts, - new InMemoryRecipientQueue(requests, CLOCK), - new InMemoryAdminOperationStore(), + recipients, + operations, audit, - new DirectTransactionPort(), - CLOCK))) + transactions, + CLOCK), + new ReconcileDeliveriesUseCase( + new AdminAuthorizationGuard(), + attempts, + reconciliation(), + operations, + audit, + transactions, + CLOCK), + new ChangeSuppressionUseCase( + new AdminAuthorizationGuard(), + new InMemorySuppressionStore(), + operations, + audit, + transactions, + UUID::randomUUID, + CLOCK), + () -> actor)) .setControllerAdvice( new GlobalExceptionHandler((error, code) -> spanErrorCodes.add(code))) .build(); @@ -100,58 +170,192 @@ class NotificationAdminRefusalHttpAnswerTest { void anUnreachableRedriveAnswersOneNotFoundAndRecordsNoServerFailure( String target, boolean dryRun) throws Exception { // given - String attemptId = "foreign".equals(target) ? storedAttemptOfTenantA() : UNKNOWN_ATTEMPT; - Logger handlerLogger = (Logger) LoggerFactory.getLogger(GlobalExceptionHandler.class); - ListAppender handlerLog = new ListAppender<>(); - handlerLog.start(); - handlerLogger.addAppender(handlerLog); + String attemptId = "foreign".equals(target) ? storedAttemptOf(TENANT_A) : UNKNOWN_ATTEMPT; // when - MockHttpServletResponse response; - try { - response = - mvc.perform( - post("/operator/redrives/{attemptId}", attemptId) - .param("dryRun", String.valueOf(dryRun))) - .andReturn() - .getResponse(); - } finally { - handlerLogger.detachAppender(handlerLog); - handlerLog.stop(); - } + List answer = + answerRecordingServerFailures( + () -> redrive(attemptId, "op-rd-http", "provider outage", true, dryRun)); // then - String body = response.getContentAsString(); - assertThat( - 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"), - audit.events().size(), - handlerLog.list.size(), - spanErrorCodes)) - .as( - "[status, success, error code, category, message, retryable, audit events, handler" - + " log lines, span error codes]") + assertThat(List.of(answer, audit.events().size())) + .as("[%s, audit events]", ANSWER_FIELDS) + .containsExactly(notFound(NotificationAdminErrorCode.DELIVERY_ATTEMPT_NOT_FOUND.code()), 0); + } + + /** + * Each refusal answers its own status and code with the category's fixed message, and the handler + * records none as a server failure. A missing authority (403) and a target outside the operator's + * tenant (404) are different answers; only the busy operation id may be sent again. + */ + @ParameterizedTest(name = "{0}") + @MethodSource("refusals") + void eachOperatorRefusalAnswersItsOwnClientErrorAndRecordsNoServerFailure(Refusal refusal) + throws Exception { + // given + String ownAttempt = storedAttemptOf(TENANT_B); + + // when + List answer = answerRecordingServerFailures(() -> refusal.send(this, ownAttempt)); + + // then + assertThat(answer) + .as(ANSWER_FIELDS) .containsExactly( - 404, + refusal.status(), false, - "DELIVERY_ATTEMPT_NOT_FOUND", - "NOT_FOUND", - ClientErrorMessages.of(NotificationAdminErrorCode.DELIVERY_ATTEMPT_NOT_FOUND), - false, - 0, + refusal.code(), + refusal.category().name(), + ClientErrorMessages.of(refusal.category()), + refusal.retryable(), + null, 0, List.of()); } - /** Stores a FAILED delivery of tenant-a and its attempt, and returns the attempt id. */ - private String storedAttemptOfTenantA() { + private static Stream refusals() { + return Stream.of( + new Refusal( + "an operator without the authority", + (test, attempt) -> { + test.actor = + new AdminActor( + "operator-b", + EnumSet.complementOf(EnumSet.of(NotificationAdminAuthority.REDRIVE)), + Optional.of(TENANT_B)); + return test.redrive(attempt, "op-no-authority", "provider outage", true, false); + }, + 403, + "ADMIN_ACCESS_DENIED", + Category.AUTHZ, + false), + new Refusal( + "a suppression in another tenant", + (test, attempt) -> test.suppress(TENANT_A), + 404, + "ADMIN_TARGET_NOT_FOUND", + Category.NOT_FOUND, + false), + new Refusal( + "a redrive of an ambiguous attempt without the duplicate-risk approval", + (test, attempt) -> + test.redrive(attempt, "op-unapproved", "provider outage", false, false), + 409, + "DUPLICATE_RISK_APPROVAL_REQUIRED", + Category.CONFLICT, + false), + new Refusal( + "an operation id reused for another request", + (test, attempt) -> { + test.redrive(attempt, "op-reused", "provider outage", true, false); + return test.redrive(attempt, "op-reused", "another reason", true, false); + }, + 422, + "ADMIN_OPERATION_CONFLICT", + Category.VALIDATION, + false), + new Refusal( + "an operation id another caller still holds", + (test, attempt) -> test.reconcileAgainWhileItsProviderCallRuns(attempt), + 409, + "ADMIN_OPERATION_IN_PROGRESS", + Category.CONFLICT, + true)); + } + + /** The answer of a 404 with {@code code}, recorded as no server failure. */ + private static List notFound(String code) { + return Arrays.asList( + 404, + false, + code, + Category.NOT_FOUND.name(), + ClientErrorMessages.of(Category.NOT_FOUND), + false, + null, + 0, + List.of()); + } + + /** + * Sends a reconcile and, while its provider call runs — the operation id claimed, no result yet — + * sends the same request again, as a second operator would. Returns the second answer. + */ + private MockHttpServletResponse reconcileAgainWhileItsProviderCallRuns(String attemptId) + throws Exception { + AtomicReference second = new AtomicReference<>(); + duringProviderCall = () -> second.set(reconcile(List.of(attemptId), false, "op-held")); + reconcile(List.of(attemptId), false, "op-held"); + return second.get(); + } + + /** + * The wire answer of what {@code send} sent — status, the envelope's success and error fields, + * the {@code Retry-After} header — followed by what the handler recorded as a server failure: its + * log lines and span error codes. + */ + private List answerRecordingServerFailures(Request send) throws Exception { + Logger handlerLogger = (Logger) LoggerFactory.getLogger(GlobalExceptionHandler.class); + ListAppender handlerLog = new ListAppender<>(); + handlerLog.start(); + handlerLogger.addAppender(handlerLog); + MockHttpServletResponse response; + try { + response = send.send(); + } finally { + handlerLogger.detachAppender(handlerLog); + handlerLog.stop(); + } + DocumentContext body = JsonPath.using(LENIENT_JSON).parse(response.getContentAsString()); + return Arrays.asList( + response.getStatus(), + body.read("$.success"), + body.read("$.error.code"), + body.read("$.error.category"), + body.read("$.error.message"), + body.read("$.error.retryable"), + response.getHeader("Retry-After"), + handlerLog.list.size(), + List.copyOf(spanErrorCodes)); + } + + private MockHttpServletResponse redrive( + String attemptId, String operationId, String reason, boolean approve, boolean dryRun) + throws Exception { + return mvc.perform( + post("/operator/redrives/{attemptId}", attemptId) + .param("operationId", operationId) + .param("reason", reason) + .param("approveDuplicateRisk", String.valueOf(approve)) + .param("dryRun", String.valueOf(dryRun))) + .andReturn() + .getResponse(); + } + + private MockHttpServletResponse reconcile( + List attemptIds, boolean dryRun, String operationId) throws Exception { + return mvc.perform( + post("/operator/reconciliations") + .param("attemptId", attemptIds.toArray(String[]::new)) + .param("operationId", operationId) + .param("dryRun", String.valueOf(dryRun))) + .andReturn() + .getResponse(); + } + + private MockHttpServletResponse suppress(TenantId tenantId) throws Exception { + return mvc.perform(post("/operator/suppressions/{tenantId}", tenantId.value())) + .andReturn() + .getResponse(); + } + + /** + * Stores a FAILED delivery of {@code tenantId} and its attempt, ambiguous as a dispatching + * attempt is, and returns the attempt id. + */ + private String storedAttemptOf(TenantId tenantId) { NotificationRequestRecord request = - NotificationRows.request(new TenantId("tenant-a"), "idem-a", CLOCK.instant()); + NotificationRows.request(tenantId, "idem-" + tenantId.value(), CLOCK.instant()); RecipientDeliveryRecord job = NotificationRows.job( request, @@ -173,28 +377,167 @@ class NotificationAdminRefusalHttpAnswerTest { .toString(); } - /** The operator transport a service would write, as a tenant-b operator. */ + /** + * Reconciliation over the test's stores. Its provider answers every attempt unsupported, counts + * the calls, and runs {@link #duringProviderCall} inside each one. + */ + private ReconciliationService reconciliation() { + NotificationMetricsPort metrics = + new NotificationMetricsPort() { + @Override + public void increment(String metricName, Map tags) {} + + @Override + public void record(String metricName, Map tags, Duration value) {} + + @Override + public void gauge(String metricName, Map tags, double value) {} + }; + InMemoryProviderEventLedger ledger = + new InMemoryProviderEventLedger(attempts, new Sha256ProviderRequestIdHasher()); + return new ReconciliationService( + attempts, + recipients, + new ReconciliationGatewayPort() { + @Override + public boolean supports(ProviderProfileId profileId) { + return true; + } + + @Override + public ReconciliationResult reconcile(DeliveryAttemptSnapshot attempt) { + providerCalls.incrementAndGet(); + try { + duringProviderCall.run(); + } catch (Exception failure) { + throw new IllegalStateException("the request sent during the provider call", failure); + } + return new ReconciliationResult.Unsupported(); + } + }, + ledger, + new ProviderEventProjectionService( + ledger, + new StandardDeliveryProjector(), + attempts, + attempts, + new SuppressionSideEffect( + new InMemoryContactPointStore(CLOCK), + new InMemorySuppressionStore(), + UUID::randomUUID, + CLOCK), + transactions, + metrics), + audit, + metrics, + new SyntheticEventFingerprint(), + transactions, + CLOCK); + } + + /** A request this test sends. */ + @FunctionalInterface + private interface Request { + MockHttpServletResponse send() throws Exception; + } + + /** What the provider does while it is asked. */ + @FunctionalInterface + private interface ProviderCall { + void run() throws Exception; + } + + /** One refusal: how to send it, given an attempt of the operator's tenant, and its answer. */ + private record Refusal( + String name, Sender sender, int status, String code, Category category, boolean retryable) { + + MockHttpServletResponse send(NotificationAdminRefusalHttpAnswerTest test, String attemptId) + throws Exception { + return sender.send(test, attemptId); + } + + @Override + public String toString() { + return name; + } + } + + @FunctionalInterface + private interface Sender { + MockHttpServletResponse send(NotificationAdminRefusalHttpAnswerTest test, String attemptId) + throws Exception; + } + + /** The operator transport a service would write, acting as the test's current actor. */ @RestController - static final class RedriveProbe { + static final class OperatorProbe { private final RedriveDeliveryUseCase redrive; + private final ReconcileDeliveriesUseCase reconcile; + private final ChangeSuppressionUseCase suppression; + private final Supplier actor; - RedriveProbe(RedriveDeliveryUseCase redrive) { + OperatorProbe( + RedriveDeliveryUseCase redrive, + ReconcileDeliveriesUseCase reconcile, + ChangeSuppressionUseCase suppression, + Supplier actor) { this.redrive = redrive; + this.reconcile = reconcile; + this.suppression = suppression; + this.actor = actor; } @PostMapping("/operator/redrives/{attemptId}") - String redrive( - @PathVariable("attemptId") String attemptId, @RequestParam("dryRun") boolean dryRun) { + Map redrive( + @PathVariable("attemptId") String attemptId, + @RequestParam("operationId") String operationId, + @RequestParam("reason") String reason, + @RequestParam("approveDuplicateRisk") boolean approve, + @RequestParam("dryRun") boolean dryRun) { RedriveRequest request = new RedriveRequest( - "op-rd-http", + operationId, new DeliveryAttemptId(UUID.fromString(attemptId)), - "provider outage", - true, + reason, + approve, dryRun); - redrive.handle(new RedriveDeliveryCommand(request, TENANT_B_OPERATOR)); - return "redriven"; + return Map.of( + "affected", redrive.handle(new RedriveDeliveryCommand(request, actor.get())).affected()); + } + + @PostMapping("/operator/reconciliations") + Map reconcile( + @RequestParam("attemptId") List attemptIds, + @RequestParam("operationId") String operationId, + @RequestParam("dryRun") boolean dryRun) { + ReconcileRequest request = + new ReconcileRequest( + operationId, + attemptIds.stream().map(id -> new DeliveryAttemptId(UUID.fromString(id))).toList(), + "stuck attempt", + dryRun); + return Map.of( + "affected", + reconcile.handle(new ReconcileDeliveriesCommand(request, actor.get())).affected()); + } + + @PostMapping("/operator/suppressions/{tenantId}") + Map suppress(@PathVariable("tenantId") String tenantId) { + SuppressionRequest request = + new SuppressionRequest( + "op-s-http", + new TenantId(tenantId), + SuppressionScope.CONTACT_POINT, + SuppressionReason.ADMIN_BLOCK, + "c".repeat(64), + Optional.empty(), + false, + "reported abuse", + false); + return Map.of( + "affected", + suppression.handle(new ChangeSuppressionCommand(request, actor.get())).affected()); } } } diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAccessDeniedException.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAccessDeniedException.java index b2e34683..fea8003e 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAccessDeniedException.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAccessDeniedException.java @@ -4,16 +4,23 @@ import dev.caskeleton.application.notification.platform.api.error.FailureCategor import dev.caskeleton.application.notification.platform.api.error.NotificationException; import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; /** - * Raised when an operator action is refused: the actor lacks the authority, or the target is - * outside the actor's tenant scope. + * Raised when an operator action is refused for the actor: it lacks the authority the action + * exercises, or the action changes state every tenant shares and the actor is bound to one tenant. * - *

It does not hide whether a target exists. A reconcile skips an attempt id that does not exist - * and refuses another tenant's attempt with this exception, so the refusal tells that the id exists - * in another tenant. A redrive answers both with {@link DeliveryAttemptNotFoundException} instead. + *

The actor is the caller, so this is the caller's failure, not a server fault: a transport + * answers {@link NotificationAdminErrorCode#ADMIN_ACCESS_DENIED} (403) and logs no server failure. + * The authority is checked before any target is read, so the refusal says nothing about targets. A + * target outside the actor's tenant is a different answer, the one a missing target gets: {@link + * AdminTargetNotFoundException}, or {@link DeliveryAttemptNotFoundException} for an attempt. + * + *

The {@linkplain #descriptor() descriptor} keeps the closed notification registry ({@code + * VALIDATION_FAILED}, {@code AUTHORIZATION}); the code on the wire is {@link #errorCode()}. */ -public class AdminAccessDeniedException extends NotificationException { +public class AdminAccessDeniedException extends NotificationException implements ApiErrorCarrier { private static final long serialVersionUID = 1L; @@ -30,4 +37,9 @@ public class AdminAccessDeniedException extends NotificationException { public NotificationAdminAuthority required() { return required; } + + @Override + public ApiErrorCode errorCode() { + return NotificationAdminErrorCode.ADMIN_ACCESS_DENIED; + } } diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAuthorizationGuard.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAuthorizationGuard.java index 48060518..f506760f 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAuthorizationGuard.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAuthorizationGuard.java @@ -31,18 +31,17 @@ public final class AdminAuthorizationGuard { } /** - * Require that the actor may act on a tenant. + * Require that the actor may act on a tenant, or answer the tenant as a target that does not + * exist. * *

An actor with no tenant is a global operator; one bound to a tenant may only act inside it. - * - * @param authority the authority being exercised, which the refusal names; it used to name {@code - * SUPPRESS} whatever the operation was + * Another tenant is refused with {@link AdminTargetNotFoundException} (404), not as missing + * authority: the actor may hold the authority, and the answer must not tell what another tenant + * holds. */ - public void requireTenant( - AdminActor actor, TenantId tenantId, NotificationAdminAuthority authority) { - Objects.requireNonNull(authority, "authority"); + public void requireTenant(AdminActor actor, TenantId tenantId) { if (!mayActOn(actor, tenantId)) { - throw new AdminAccessDeniedException(authority); + throw new AdminTargetNotFoundException(); } } @@ -50,8 +49,8 @@ public final class AdminAuthorizationGuard { * Whether the actor's tenant scope covers a tenant: a global operator's covers every tenant, a * tenant-bound one's only its own. * - *

For an operation that answers a target outside the scope as it answers a target that does - * not exist, rather than with {@link #requireTenant}'s refusal. + *

For an operation that reads its target first and answers one outside the scope as it answers + * one that does not exist, with its own not-found exception. */ public boolean mayActOn(AdminActor actor, TenantId tenantId) { Objects.requireNonNull(actor, "actor"); diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationConflictException.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationConflictException.java index 390e34b2..f57f0bc2 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationConflictException.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationConflictException.java @@ -1,11 +1,25 @@ package dev.caskeleton.application.notification.platform.admin; -/** One admin operation id was reused for a different command. */ -final class AdminOperationConflictException extends RuntimeException { +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + +/** + * One admin operation id was reused for a different command. + * + *

The operation id is the operator's idempotency key, so this is the caller's mistake, not a + * server fault: a transport answers {@link NotificationAdminErrorCode#ADMIN_OPERATION_CONFLICT} + * (422) and logs no server failure. + */ +final class AdminOperationConflictException extends RuntimeException implements ApiErrorCarrier { private static final long serialVersionUID = 1L; AdminOperationConflictException(String operationId) { super("admin operation id was reused for a different command: " + operationId); } + + @Override + public ApiErrorCode errorCode() { + return NotificationAdminErrorCode.ADMIN_OPERATION_CONFLICT; + } } diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationInProgressException.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationInProgressException.java index 04949c64..4f393846 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationInProgressException.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationInProgressException.java @@ -1,11 +1,25 @@ package dev.caskeleton.application.notification.platform.admin; -/** The same admin operation id is currently held by another caller. */ -final class AdminOperationInProgressException extends RuntimeException { +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + +/** + * The same admin operation id is currently held by another caller. + * + *

Nothing is wrong with the request, it arrived while the first one runs: a transport answers + * {@link NotificationAdminErrorCode#ADMIN_OPERATION_IN_PROGRESS} (409, retryable) and logs no + * server failure. The same request sent again after the first finishes answers its stored result. + */ +final class AdminOperationInProgressException extends RuntimeException implements ApiErrorCarrier { private static final long serialVersionUID = 1L; AdminOperationInProgressException(String operationId) { super("admin operation is already in progress: " + operationId); } + + @Override + public ApiErrorCode errorCode() { + return NotificationAdminErrorCode.ADMIN_OPERATION_IN_PROGRESS; + } } diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminTargetNotFoundException.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminTargetNotFoundException.java new file mode 100644 index 00000000..c99189d8 --- /dev/null +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminTargetNotFoundException.java @@ -0,0 +1,38 @@ +package dev.caskeleton.application.notification.platform.admin; + +import dev.caskeleton.application.notification.platform.api.error.FailureCategory; +import dev.caskeleton.application.notification.platform.api.error.NotificationException; +import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; +import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + +/** + * Raised when an operator action names a tenant outside the actor's tenant scope, such as a + * tenant-bound operator adding or lifting a suppression of another tenant. + * + *

The tenant is the operator's input, so this is the caller's failure, not a server fault: a + * transport answers {@link NotificationAdminErrorCode#ADMIN_TARGET_NOT_FOUND} (404) and logs no + * server failure. The refusal reads nothing of the named tenant and holds no state of its own, so + * neither the answer nor the exception tells what that tenant holds, or that it exists. + * + *

The {@linkplain #descriptor() descriptor} keeps the closed notification registry, which has no + * not-found code ({@code VALIDATION_FAILED}, {@code INVALID_PAYLOAD}: the request names a target it + * may not use). The code on the wire is {@link #errorCode()}. + */ +public final class AdminTargetNotFoundException extends NotificationException + implements ApiErrorCarrier { + + private static final long serialVersionUID = 1L; + + public AdminTargetNotFoundException() { + super( + NotificationFailureDescriptor.preDispatch( + NotificationFailureCode.VALIDATION_FAILED, FailureCategory.INVALID_PAYLOAD)); + } + + @Override + public ApiErrorCode errorCode() { + return NotificationAdminErrorCode.ADMIN_TARGET_NOT_FOUND; + } +} diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ChangeSuppressionUseCase.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ChangeSuppressionUseCase.java index 4351472c..cbca93dd 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ChangeSuppressionUseCase.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ChangeSuppressionUseCase.java @@ -73,7 +73,7 @@ public class ChangeSuppressionUseCase SuppressionRequest request = change.request(); AdminActor actor = change.actor(); authorization.require(actor, NotificationAdminAuthority.SUPPRESS); - authorization.requireTenant(actor, request.tenantId(), NotificationAdminAuthority.SUPPRESS); + authorization.requireTenant(actor, request.tenantId()); if (request.dryRun()) { return new AdminOperationResult( diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/DuplicateRiskApprovalRequiredException.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/DuplicateRiskApprovalRequiredException.java index 10d615be..11f80edb 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/DuplicateRiskApprovalRequiredException.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/DuplicateRiskApprovalRequiredException.java @@ -4,13 +4,22 @@ import dev.caskeleton.application.notification.platform.api.error.FailureCategor import dev.caskeleton.application.notification.platform.api.error.NotificationException; import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; /** * Raised when an operator tries to redrive an ambiguous attempt without accepting the duplicate * risk. The platform cannot tell whether the first submission reached the user, so the decision has * to be recorded as a human one. + * + *

The request conflicts with the attempt's state, which the operator can resolve by approving: a + * transport answers {@link NotificationAdminErrorCode#DUPLICATE_RISK_APPROVAL_REQUIRED} (409) and + * logs no server failure. The {@linkplain #descriptor() descriptor} keeps the closed notification + * registry ({@code VALIDATION_FAILED}, {@code AMBIGUOUS_SUBMISSION}); the code on the wire is + * {@link #errorCode()}. */ -public class DuplicateRiskApprovalRequiredException extends NotificationException { +public class DuplicateRiskApprovalRequiredException extends NotificationException + implements ApiErrorCarrier { private static final long serialVersionUID = 1L; @@ -19,4 +28,9 @@ public class DuplicateRiskApprovalRequiredException extends NotificationExceptio NotificationFailureDescriptor.preDispatch( NotificationFailureCode.VALIDATION_FAILED, FailureCategory.AMBIGUOUS_SUBMISSION)); } + + @Override + public ApiErrorCode errorCode() { + return NotificationAdminErrorCode.DUPLICATE_RISK_APPROVAL_REQUIRED; + } } diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java index 66088c12..e6420ce5 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java @@ -6,17 +6,51 @@ import dev.caskeleton.shared.error.Category; /** * Codes the notification operator operations answer a transport with. * + *

Every refusal of an operator operation is the operator's own input — an authority they do not + * hold, a target out of their reach, an unapproved duplicate risk, a reused or busy operation id — + * so each is a client error, not a server fault. + * *

The closed {@code NotificationFailureCode} registry is the platform's own vocabulary — metric - * tags, ledger rows, audit — and has no not-found code. 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. + * tags, ledger rows, audit — and has no code for most of these. A transport answers with this code + * instead, read through {@link dev.caskeleton.shared.error.ApiErrorCarrier}, so each transport that + * answers a failure (web, GraphQL, gRPC) answers the same code without naming the feature. */ public enum NotificationAdminErrorCode implements ApiErrorCode { + /** + * The operator lacks the authority the operation exercises, or the operation changes state every + * tenant shares and the operator is bound to one tenant. + */ + ADMIN_ACCESS_DENIED(403, Category.AUTHZ, false), + + /** + * The operation named a tenant outside the operator's tenant scope. It is answered as a target + * that does not exist, so the answer does not tell what the other tenant holds. + */ + ADMIN_TARGET_NOT_FOUND(404, Category.NOT_FOUND, false), + /** * A redrive named an attempt the operator cannot act on: no attempt has that id, or it belongs to * a tenant outside the operator's scope. The two are one code so the answer does not tell which. */ - DELIVERY_ATTEMPT_NOT_FOUND(404, Category.NOT_FOUND, false); + DELIVERY_ATTEMPT_NOT_FOUND(404, Category.NOT_FOUND, false), + + /** + * A redrive of an attempt that may already have reached the user did not accept the duplicate + * risk. The same request is refused again; it succeeds only with the approval. + */ + DUPLICATE_RISK_APPROVAL_REQUIRED(409, Category.CONFLICT, false), + + /** + * The operation id was used before for a different request. Like a reused idempotency key, it is + * the caller's mistake rather than a state conflict, and sending it again fails again. + */ + ADMIN_OPERATION_CONFLICT(422, Category.VALIDATION, false), + + /** + * Another caller holds the same operation id for the same request and has not finished. Sending + * the same request again once it finishes answers its result. + */ + ADMIN_OPERATION_IN_PROGRESS(409, Category.CONFLICT, true); private final int httpStatus; private final Category category; diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java index aba76aca..e5d80b1d 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java @@ -85,10 +85,7 @@ public class ReconcileDeliveriesUseCase for (DeliveryAttemptId attemptId : request.attemptIds()) { attempts .snapshot(attemptId) - .ifPresent( - attempt -> - authorization.requireTenant( - actor, attempt.tenantId(), NotificationAdminAuthority.RECONCILE)); + .ifPresent(attempt -> authorization.requireTenant(actor, attempt.tenantId())); } return null; }); diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/AdminAuthorizationGuardTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/AdminAuthorizationGuardTest.java index 6192aa59..b776cb97 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/AdminAuthorizationGuardTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/AdminAuthorizationGuardTest.java @@ -1,7 +1,9 @@ package dev.caskeleton.application.notification.platform.admin; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.notification.platform.api.TenantId; import java.util.Optional; @@ -24,23 +26,29 @@ class AdminAuthorizationGuardTest { } @Test - void tenantScopedActorCannotCrossTenantBoundary() { - AdminActor actor = - new AdminActor( - "operator-1", - Set.of(NotificationAdminAuthority.SUPPRESS), - Optional.of(new TenantId("tenant-a"))); + void tenantScopedActorMayActInsideItsOwnTenant() { + AdminActor actor = tenantAOperator(); - assertThatCode( - () -> - guard.requireTenant( - actor, new TenantId("tenant-a"), NotificationAdminAuthority.SUPPRESS)) + assertThatCode(() -> guard.requireTenant(actor, new TenantId("tenant-a"))) .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - guard.requireTenant( - actor, new TenantId("tenant-b"), NotificationAdminAuthority.SUPPRESS)) - .isInstanceOf(AdminAccessDeniedException.class); + } + + /** Another tenant is answered as a target that does not exist, not as a missing authority. */ + @Test + void tenantScopedActorCannotCrossTenantBoundary() { + // given + AdminActor actor = tenantAOperator(); + + // when + Throwable failure = catchThrowable(() -> guard.requireTenant(actor, new TenantId("tenant-b"))); + + // then + assertThat(failure) + .isInstanceOfSatisfying( + AdminTargetNotFoundException.class, + notFound -> + assertThat(notFound.errorCode()) + .isEqualTo(NotificationAdminErrorCode.ADMIN_TARGET_NOT_FOUND)); } @Test @@ -49,10 +57,14 @@ class AdminAuthorizationGuardTest { new AdminActor( "global-operator", Set.of(NotificationAdminAuthority.SUPPRESS), Optional.empty()); - assertThatCode( - () -> - guard.requireTenant( - global, new TenantId("tenant-b"), NotificationAdminAuthority.SUPPRESS)) + assertThatCode(() -> guard.requireTenant(global, new TenantId("tenant-b"))) .doesNotThrowAnyException(); } + + private static AdminActor tenantAOperator() { + return new AdminActor( + "operator-1", + Set.of(NotificationAdminAuthority.SUPPRESS), + Optional.of(new TenantId("tenant-a"))); + } } diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java index a822d012..9dbea5f9 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java @@ -157,9 +157,10 @@ class NotificationAdminUseCasesTest { // then assertThat(failure) .isInstanceOfSatisfying( - AdminAccessDeniedException.class, - denied -> - assertThat(denied.required()).isEqualTo(NotificationAdminAuthority.RECONCILE)); + AdminTargetNotFoundException.class, + notFound -> + assertThat(notFound.errorCode()) + .isEqualTo(NotificationAdminErrorCode.ADMIN_TARGET_NOT_FOUND)); } @Test @@ -389,6 +390,10 @@ class NotificationAdminUseCasesTest { .containsExactly(call.authority(), 0)); } + /** + * Another tenant is answered as a target that does not exist, not as a missing authority: the + * operator holds {@code SUPPRESS}, and the answer must not tell what tenant-a holds. + */ @Test void aTenantScopedOperatorCannotSuppressAnotherTenantsContactPoint() { // given @@ -409,19 +414,20 @@ class NotificationAdminUseCasesTest { // then assertThat(failure) - .as("refused with AdminAccessDeniedException(SUPPRESS)") + .as("answered AdminTargetNotFoundException") .isInstanceOfSatisfying( - AdminAccessDeniedException.class, - denied -> + AdminTargetNotFoundException.class, + notFound -> assertThat( - List.of( - denied.required(), + List.of( + notFound.errorCode(), fixture .suppressions .activeFor(tenantA, "c".repeat(64), CLOCK.instant()) .size(), fixture.operations.claims)) - .containsExactly(NotificationAdminAuthority.SUPPRESS, 0, 0)); + .as("[code, active suppressions of tenant-a, claims]") + .containsExactly(NotificationAdminErrorCode.ADMIN_TARGET_NOT_FOUND, 0, 0)); } /** -- 2.54.0 From 00911cd1fbb3d433d77725bf891822bf3dee0af6 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 21:17:48 +0900 Subject: [PATCH 2/5] =?UTF-8?q?fix(notification)!:=20reconcile=20=EB=AC=B6?= =?UTF-8?q?=EC=9D=8C=EC=9D=98=20=EC=97=86=EB=8A=94=C2=B7=EB=82=A8=EC=9D=98?= =?UTF-8?q?=20attempt=EB=A5=BC=20404=20=ED=95=98=EB=82=98=EB=A1=9C=20?= =?UTF-8?q?=EA=B1=B0=EC=A0=88=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ReconcileDeliveriesUseCase는 id마다 snapshot(id).ifPresent(tenant 판정)로 본다. 없는 id는 아무 판정 없이 지나가 provider에 묻고 처리 수(affected)에 센다. dry run은 id 수를 그대로 답한다. 남의 tenant id는 묶음 전체를 거절한다. 그래서 tenant 범위 운영자가 id를 넣어 보는 것만으로 남의 tenant에 그 attempt가 있는지 알 수 있고, 감사 기록과 운영자 화면의 처리 수가 실제보다 크다. docs/manual/07-authorization.md는 남의 것을 없는 것과 같은 404로 답한다고 약속했고, redrive는 이미 그렇게 답한다. provider를 부르기 전 읽기 트랜잭션에서 id마다 snapshot(id).filter(mayActOn).isEmpty()이면 DeliveryAttemptNotFoundException을 던진다. 없는 id와 남의 tenant id가 redrive와 같은 404 DELIVERY_ATTEMPT_NOT_FOUND 하나로, 묶음 전체가 operation id claim과 audit 없이 거절된다. dry run도 같은 판정을 지난다. 통과한 묶음에는 없는 id가 없으니 처리 수는 묶음의 id 수와 같다. 직전 커밋에서 reconcile의 남의 tenant id가 받던 ADMIN_TARGET_NOT_FOUND는 suppression에만 남는다. 버린 안: 없는 id와 남의 id를 둘 다 건너뛰고 있는 것만 세기(「남의 id가 있으면 아무것도 안 바꾼다」가 깨지고 오타가 성공으로 보인다), 지금대로 두기(존재가 드러난다). 고른 안은 review 허브가 project-docs README 7절 1번으로 고른 권하는 안이고 소유자가 정한 것이 아니다. 결정 색인 2.3절에 적었다. 위험·한계: 공개 동작 변경이다. 보존 기간이 지나 지워진 attempt id를 섞은 묶음은 전에는 그 id를 건너뛰었지만 이제 묶음 전체가 거절된다. 답은 어느 id인지 알려 주지 않는다. 같은 id를 묶음에 두 번 넣으면 전처럼 두 번 묻고 두 번 센다(이 변경의 범위 밖). 묶음 상한 200과 redrive 규칙은 그대로다. 검증: NotificationAdminUseCasesTest의 표가 tenant 범위 운영자의 없는 id·남의 id와 전역 운영자의 없는 id를 각각 reconcile·dry run으로 보내 DeliveryAttemptNotFoundException·carrier code·결과 없음·provider 호출 0· claim 0·audit 0을, 다른 표가 있는 id만 든 묶음의 affected 2(dry run도)를 단언한다. NotificationAdminRefusalHttpAnswerTest는 같은 묶음을 web으로 보내 404 DELIVERY_ATTEMPT_NOT_FOUND·로그 0·span 오류 0·provider 호출 0·audit 0을 단언한다. base 957cbc96에 두 시험을 얹은 desktop leaf --no-cache에서 app은 없는 id 4행이 「affected 2」·provider 호출로, 남의 id 2행이 AdminAccessDeniedException으로 실패하고 처리 수 2행은 통과했다. web은 unknown 2행이 200, foreign 2행이 500으로 실패했다. 노트북 감싸개 :application-notification:check, :adapter:inbound:web-notification:check, :adapter:outbound:notification:verifyNotificationApiSurface rc=0, check-docs.py·check-work-docs.py OK. BREAKING CHANGE: reconcile 묶음에 없는 attempt id나 운영자 tenant 밖의 attempt가 하나라도 있으면 provider 호출 전에 묶음 전체를 404 DELIVERY_ATTEMPT_NOT_FOUND(DeliveryAttemptNotFoundException)로 거절한다. 전에는 없는 id를 건너뛰고 처리 수에 셌고, 남의 tenant attempt는 AdminAccessDeniedException이었다. 지워진 id를 섞어 보내던 도구는 그 id를 빼고 다시 보낸다. 옮기는 법은 docs/upgrade/2026-11-notification-admin-refusals.md 2.1절 4행이다. Refs: REV-BE-0059 --- docs/notification/operations.md | 11 +- .../2026-11-notification-admin-redrive.md | 4 +- .../2026-11-notification-admin-refusals.md | 19 +- docs/web/http-contract.md | 4 +- docs/work/reference/decisions.md | 5 +- ...otificationAdminRefusalHttpAnswerTest.java | 25 +++ .../admin/AdminAccessDeniedException.java | 3 +- .../DeliveryAttemptNotFoundException.java | 9 +- .../admin/NotificationAdminErrorCode.java | 5 +- .../admin/ReconcileDeliveriesUseCase.java | 20 +- .../admin/NotificationAdminUseCasesTest.java | 190 +++++++++++++++--- 11 files changed, 232 insertions(+), 63 deletions(-) diff --git a/docs/notification/operations.md b/docs/notification/operations.md index 3329862e..945c4532 100644 --- a/docs/notification/operations.md +++ b/docs/notification/operations.md @@ -58,15 +58,18 @@ redrive는 `NotificationId`와 `RecipientDeliveryId`를 유지하고, 새 `Deliv | 거절 | code | web | retryable | 운영자가 할 일 | |---|---|---|---|---| | authority가 없다. tenant 범위 운영자가 provider 상태를 바꾸려 했다 | `ADMIN_ACCESS_DENIED` | 403 | false | authority를 받거나 tenant 범위 없는 운영자에게 맡긴다 | - | redrive의 attempt id가 없거나 그 attempt가 운영자 tenant 밖이다 | `DELIVERY_ATTEMPT_NOT_FOUND` | 404 | false | id를 확인한다 | - | suppression·reconcile이 운영자 tenant 밖의 대상을 골랐다 | `ADMIN_TARGET_NOT_FOUND` | 404 | false | tenant를 확인한다 | + | redrive의 attempt id가 없거나 그 attempt가 운영자 tenant 밖이다. reconcile 묶음에 그런 id가 하나라도 있다 | `DELIVERY_ATTEMPT_NOT_FOUND` | 404 | false | id를 확인한다. reconcile은 묶음 전체가 거절되니 그 id를 빼고 다시 보낸다 | + | suppression이 운영자 tenant 밖의 tenant를 골랐다 | `ADMIN_TARGET_NOT_FOUND` | 404 | false | tenant를 확인한다 | | 모호한 attempt를 중복 위험 승인 없이 redrive했다 | `DUPLICATE_RISK_APPROVAL_REQUIRED` | 409 | false | 중복 위험을 받아들이면 승인을 붙여 다시 보낸다 | | operation id가 전에 다른 요청에 쓰였다 | `ADMIN_OPERATION_CONFLICT` | 422 | false | 새 operation id를 쓴다 | | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다 | `ADMIN_OPERATION_IN_PROGRESS` | 409 | true | 기다렸다가 같은 id·같은 요청을 다시 보낸다. 끝났으면 저장된 결과가 온다 | - authority는 대상을 읽기 전에 본다. 그래서 403은 대상에 대해 아무것도 알려 주지 않는다. tenant 밖의 대상은 authority - 거절이 아니라 없는 대상과 같은 404다. redrive는 없는 attempt와 남의 tenant attempt가 같은 답이라 다른 tenant에 그 id가 - 있는지 알 수 없다. reconcile은 묶음 안의 없는 id를 건너뛴다. + 거절이 아니라 없는 대상과 같은 404다. redrive와 reconcile은 없는 attempt와 남의 tenant attempt가 같은 답이라 다른 tenant에 + 그 id가 있는지 알 수 없다. +- reconcile은 provider를 부르기 전에 묶음의 id를 모두 본다. 하나라도 없거나 운영자 tenant 밖이면 묶음 전체를 거절하고 + 아무것도 묻지 않는다(dry run도 같다). 그래서 처리 수(`affected`)는 묶음의 id 수와 같다. 보존 기간이 지나 지워진 attempt + id가 섞인 묶음도 거절된다. - provider 호출 중에 프로세스가 멈춘 reconcile의 operation id는 claim이 끝나지 않아 계속 진행 중으로 답한다. 그 묶음은 새 operation id로 보낸다. - 모든 연산은 운영자가 준 operation id로 멱등이다. 같은 id·같은 요청은 저장된 결과를 돌려주고, 같은 id·다른 요청은 diff --git a/docs/upgrade/2026-11-notification-admin-redrive.md b/docs/upgrade/2026-11-notification-admin-redrive.md index a5216966..dd1e92be 100644 --- a/docs/upgrade/2026-11-notification-admin-redrive.md +++ b/docs/upgrade/2026-11-notification-admin-redrive.md @@ -34,8 +34,8 @@ - `ReconcileDeliveriesUseCase`는 묶음 안의 없는 attempt id를 그대로 건너뛴다. - suppression·reconcile·provider 상태 연산은 남의 tenant 대상을 전처럼 `AdminAccessDeniedException`으로 거절한다. authority가 없을 때의 답도 네 연산 모두 그대로다. - - 2026-11-23에 이 줄은 낡았다. suppression·reconcile의 남의 tenant 대상과 네 연산의 authority 없음의 답은 - `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절이 대신한다. +- 2026-11-23에 위 두 줄은 낡았다. reconcile의 없는 id와 남의 tenant attempt, suppression의 남의 tenant, 네 연산의 + authority 없음의 답은 `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절이 대신한다. - 오류 code 목록(`NotificationFailureCode`)과 템플릿 오류 code registry(`docs/registries/error-codes.yaml`)는 그대로다. not-found 코드는 그 목록이 아니라 전송이 읽는 `NotificationAdminErrorCode`에 두었다. 새 예외의 descriptor는 있는 값(`VALIDATION_FAILED`, `INVALID_PAYLOAD`)이라 descriptor code와 응답 code가 다르다. diff --git a/docs/upgrade/2026-11-notification-admin-refusals.md b/docs/upgrade/2026-11-notification-admin-refusals.md index ceb8a222..39f1b0f0 100644 --- a/docs/upgrade/2026-11-notification-admin-refusals.md +++ b/docs/upgrade/2026-11-notification-admin-refusals.md @@ -1,13 +1,15 @@ # 업그레이드 안내 — 2026-11 알림 운영자 연산의 거절 - 범위: 알림 운영자 연산 넷(`RedriveDeliveryUseCase`·`ReconcileDeliveriesUseCase`·`ChangeSuppressionUseCase`· - `ChangeProviderStateUseCase`)이 운영자 입력을 거절할 때 전송이 내는 답을 바꾼 변경. 설정 키는 그대로다. 공개 타입이 + `ChangeProviderStateUseCase`)이 운영자 입력을 거절할 때 전송이 내는 답과, reconcile이 없는 attempt id와 남의 tenant + attempt를 다루는 규칙을 바꾼 변경. 설정 키는 그대로다. 공개 타입이 하나 늘었고(`AdminTargetNotFoundException`), 공개 메서드 `AdminAuthorizationGuard.requireTenant`의 인자가 하나 줄었다. 템플릿은 이 연산을 부르는 전송을 싣지 않는다. 알림 capability(`:composition:notification-platform`)를 싣고 이 연산에 전송(운영자 화면, admin endpoint)을 연 서비스만 해당한다. -- 근거: 2026-11-23 리뷰 발견 REV-BE-0058. 운영자 실수는 클라이언트 탓이라 carrier로 답하고, 남의 것은 없는 것과 같은 404로 +- 근거: 2026-11-23 리뷰 발견 REV-BE-0058과 REV-BE-0059. 운영자 실수는 클라이언트 탓이라 carrier로 답하고, 남의 것은 없는 것과 같은 404로 답한다는 것은 `docs/manual/06-errors.md` 「판단: 어떤 예외 타입으로 던지나」와 `docs/manual/07-authorization.md` - 「객체 단위 권한」이 이미 약속했다. 거절마다 status를 고른 것은 review 허브의 권하는 안이고 소유자 결정이 아니다 + 「객체 단위 권한」이 이미 약속했다. 거절마다 status를 고른 것과 reconcile 묶음을 통째로 거절하는 것은 review 허브의 + 권하는 안이고 소유자 결정이 아니다 (`docs/work/reference/decisions.md` 2.3절). ## 1. 누가 읽나 @@ -16,14 +18,14 @@ ## 2. 바뀐 동작 -### 2.1 2026-11-23 — 거절 다섯을 클라이언트 오류로 (따라 할 일 있음) +### 2.1 2026-11-23 — 거절 다섯을 클라이언트 오류로, reconcile의 없는·남의 id를 404 하나로 (따라 할 일 있음) 거절마다 답하는 code다. code는 `application-notification`의 `NotificationAdminErrorCode`다. | code | 거절 | 예외 | status | category | retryable | | --- | --- | --- | --- | --- | --- | | `ADMIN_ACCESS_DENIED` | 운영자에게 연산의 authority가 없다. 또는 tenant 범위 운영자가 provider 상태를 바꾸려 했다 | `AdminAccessDeniedException` | 403 | `AUTHZ` | false | -| `ADMIN_TARGET_NOT_FOUND` | suppression·reconcile이 운영자 tenant 밖의 대상을 골랐다 | `AdminTargetNotFoundException`(새 타입) | 404 | `NOT_FOUND` | false | +| `ADMIN_TARGET_NOT_FOUND` | suppression이 운영자 tenant 밖의 tenant를 골랐다 | `AdminTargetNotFoundException`(새 타입) | 404 | `NOT_FOUND` | false | | `DUPLICATE_RISK_APPROVAL_REQUIRED` | 모호한 attempt의 redrive가 중복 위험 승인 없이 왔다 | `DuplicateRiskApprovalRequiredException` | 409 | `CONFLICT` | false | | `ADMIN_OPERATION_CONFLICT` | operation id가 전에 다른 요청에 쓰였다 | 공개되지 않은 타입(`RuntimeException`) | 422 | `VALIDATION` | false | | `ADMIN_OPERATION_IN_PROGRESS` | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다 | 공개되지 않은 타입(`RuntimeException`) | 409 | `CONFLICT` | true | @@ -31,15 +33,16 @@ | # | 바뀐 것 | 전에는 | 할 일 | 안 하면 | 해당 서비스 | | --- | --- | --- | --- | --- | --- | | 1 | 위 다섯 예외가 `ApiErrorCarrier`를 구현한다. 실패를 답하는 공용 처리기가 위 code로 답한다. web은 위 status와 error 본문(code·category·category별 고정 문구·retryable)이고, 서버 오류 로그와 span 오류를 남기지 않는다. `ADMIN_OPERATION_IN_PROGRESS`는 retryable true지만 `Retry-After` 헤더는 없다. GraphQL은 errors의 code가 위 code이고 category는 `AUTHORIZATION`(403)·`BUSINESS`(404·409)·`REQUEST`(422)다. 실패 자신이 carrier라서 등록 매핑보다 먼저 답한다. resolver observation은 전처럼 던진 예외를 오류로 센다(`graphql.outcome=ERROR`와 span 오류). gRPC는 `PERMISSION_DENIED`(403)·`NOT_FOUND`(404)·`ABORTED`(409)·`INVALID_ARGUMENT`(422)와 trailer `error-code`·`error-category`·`error-retryable`이고 서버 오류 로그를 남기지 않는다. STOMP `@MessageMapping`이 던진 실패는 전처럼 frame을 보내지 않고 ERROR 로그만 사라진다. 예외 타입·메시지·descriptor(알림 code 목록 값)는 그대로다 | carrier가 아니어서 공용 처리기가 서버 오류로 다뤘다. web은 500 `INTERNAL_ERROR`와 ERROR 로그·span 오류, gRPC는 `INTERNAL`, GraphQL은 이 타입(또는 상위 타입)을 등록한 매핑이 없으면 `INTERNAL_ERROR`였다. STOMP는 frame 없이 ERROR 로그를 남겼다. 운영자 실수가 5xx 경보를 울렸다 | 500·`INTERNAL`을 거절로 읽던 운영자 화면·모니터링을 위 code로 바꾼다. `ADMIN_OPERATION_IN_PROGRESS`만 같은 요청을 다시 보낸다(첫 요청이 끝났으면 저장된 결과가 온다). `ADMIN_OPERATION_CONFLICT`는 다시 보내지 않고 새 operation id를 쓴다. GraphQL에 `GraphQlExceptionResolver`로 이 예외나 상위 타입(`NotificationException`, `RuntimeException` 등)을 등록해 자기 code로 답하던 서비스는 그 매핑이 더 쓰이지 않는다(`docs/work/reference/decisions.md` 2.3절 「GraphQL 판정 순서」). 자기 code가 필요하면 이 예외를 감싼 자기 예외로 던지고 그 타입을 등록한다. web `@ExceptionHandler`와 이 예외를 직접 잡던 코드는 그대로 동작한다 | 운영자 화면이 이 code를 모르면 거절을 처리하지 못한다. 5xx만 세던 경보 규칙은 이 거절을 더 보지 않는다. GraphQL의 등록 매핑에 기대던 분기는 code가 바뀌어 깨진다 | 알림 운영자 연산 전송을 연 서비스 | -| 2 | suppression이 운영자 tenant 밖의 tenant를 고르면 `AdminTargetNotFoundException`이다. reconcile 묶음에 운영자 tenant 밖의 attempt가 있어도 같은 예외다. 이 예외는 상태를 싣지 않는다. 거절은 그 tenant의 어떤 것도 읽지 않아서, 답으로 그 tenant가 무엇을 가졌는지 알 수 없다 | `AdminAccessDeniedException`(`required()`는 `SUPPRESS` 또는 `RECONCILE`)이었다. 운영자에게 authority가 없을 때와 같은 예외였다 | 이 경우를 `AdminAccessDeniedException`으로 잡던 코드를 `AdminTargetNotFoundException`으로 바꾼다. `AdminAccessDeniedException`은 이제 authority가 없을 때와 tenant 범위 운영자의 provider 상태 변경에만 난다. 공용 처리기에 맡겼다면 고칠 코드는 없다(web 응답이 404로 바뀐다) | 그 catch가 이 예외를 놓쳐 공용 처리기로 간다. 서비스가 만든 거절 응답 대신 `ADMIN_TARGET_NOT_FOUND`(web은 404)가 나간다 | 알림 운영자 연산 전송을 연 서비스 | +| 2 | suppression이 운영자 tenant 밖의 tenant를 고르면 `AdminTargetNotFoundException`이다. 이 예외는 상태를 싣지 않는다. 거절은 그 tenant의 어떤 것도 읽지 않아서, 답으로 그 tenant가 무엇을 가졌는지 알 수 없다 | `AdminAccessDeniedException`(`required()`는 `SUPPRESS`)이었다. 운영자에게 authority가 없을 때와 같은 예외였다 | 이 경우를 `AdminAccessDeniedException`으로 잡던 코드를 `AdminTargetNotFoundException`으로 바꾼다. `AdminAccessDeniedException`은 이제 authority가 없을 때와 tenant 범위 운영자의 provider 상태 변경에만 난다. 공용 처리기에 맡겼다면 고칠 코드는 없다(web 응답이 404로 바뀐다) | 그 catch가 이 예외를 놓쳐 공용 처리기로 간다. 서비스가 만든 거절 응답 대신 `ADMIN_TARGET_NOT_FOUND`(web은 404)가 나간다 | 알림 운영자 연산 전송을 연 서비스 | | 3 | `AdminAuthorizationGuard.requireTenant(AdminActor, TenantId)`가 authority 인자를 받지 않는다. tenant 밖이면 `AdminTargetNotFoundException`을 던진다 | `requireTenant(AdminActor, TenantId, NotificationAdminAuthority)`가 그 authority를 실은 `AdminAccessDeniedException`을 던졌다 | 이 guard를 자기 연산에 쓰는 서비스는 셋째 인자를 지우고, 거절을 잡던 곳은 2행대로 바꾼다 | 컴파일이 실패한다 | 이 guard를 직접 부르는 서비스 | +| 4 | reconcile 묶음에 없는 attempt id나 운영자 tenant 밖의 attempt가 하나라도 있으면 provider를 부르기 전에 묶음 전체를 `DeliveryAttemptNotFoundException`(404 `DELIVERY_ATTEMPT_NOT_FOUND`, redrive와 같은 답)으로 거절한다. dry run도 같다. operation id를 claim하지 않고 audit도 남기지 않는다. 없는 id와 남의 tenant id가 같은 답이라 다른 tenant에 그 attempt가 있는지 알 수 없다. 통과한 묶음의 처리 수(`affected`)는 묶음의 id 수와 같다 | 없는 id는 건너뛰고도 처리 수에 셌다(dry run은 id 수를 그대로 답했다). 남의 tenant attempt는 `AdminAccessDeniedException(RECONCILE)`이라 web에서 500이었다. 그래서 tenant 범위 운영자가 id를 넣어 보는 것만으로 남의 tenant에 그 attempt가 있는지 알 수 있었다 | 보존 기간이 지나 지워진 attempt id를 섞어 보내던 운영자 도구는 그 id를 빼고 다시 보낸다. 답은 어느 id인지 알려 주지 않으니 묶음을 나눠 보내 찾는다. reconcile의 남의 tenant 거절을 `AdminAccessDeniedException`으로 잡던 코드는 `DeliveryAttemptNotFoundException`으로 바꾼다 | 지워진 id 하나가 묶음 전체를 막는다. 그 catch가 이 예외를 놓쳐 공용 처리기로 가고 `DELIVERY_ATTEMPT_NOT_FOUND`(web은 404)가 나간다 | 알림 운영자 연산 전송을 연 서비스 | ## 3. 바뀌지 않은 것 - redrive의 없는 attempt id와 남의 tenant attempt는 전처럼 404 `DELIVERY_ATTEMPT_NOT_FOUND`다 (`docs/upgrade/2026-11-notification-admin-redrive.md` 2.1절). - authority는 대상을 읽기 전에 본다. 그래서 403은 대상에 대해 아무것도 알려 주지 않는다. -- `ReconcileDeliveriesUseCase`는 묶음 안의 없는 attempt id를 전처럼 건너뛴다. +- reconcile 묶음에 같은 id를 두 번 넣으면 전처럼 provider에 두 번 묻고 두 번 센다. - 같은 operation id·같은 요청은 전처럼 저장된 결과를 돌려준다. - carrier가 아닌 실패는 공용 처리기가 전처럼 500으로 답한다(web `GlobalExceptionHandler`). - 오류 code 목록(`NotificationFailureCode`)과 템플릿 오류 code registry(`docs/registries/error-codes.yaml`)는 그대로다. @@ -51,6 +54,6 @@ ## 4. 되돌리는 법 다섯 예외의 carrier 구현, `NotificationAdminErrorCode`의 다섯 행, `AdminTargetNotFoundException`, `requireTenant`의 인자, -문서와 API surface 기준선 행을 함께 revert하고, 이 문서에 되돌린 행을 더한다. operation id 재사용만 409로 바꾸려면 +reconcile의 묶음 판정, 문서와 API surface 기준선 행을 함께 revert하고, 이 문서에 되돌린 행을 더한다. operation id 재사용만 409로 바꾸려면 `ADMIN_OPERATION_CONFLICT`를 `(409, Category.CONFLICT, false)`로 바꾸고, 시험 행과 이 문서·`docs/web/http-contract.md` 4절·`docs/notification/operations.md`의 422를 409로 고친다. diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index 71eb27ae..cfc62b4c 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -201,9 +201,9 @@ HTTP가 그대로 답하는 코드(알림 운영자 연산 거절, `IDEMPOTENCY_ | `RATE_LIMIT_UNAVAILABLE` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 있음 | rate-limit 저장소 응답 없음(`docs/web/runbook.md`) | | `RATE_LIMIT_INCOMPATIBLE` | 503 | `INTERNAL` | `false` | 없음 | rate-limit 제공자가 계약과 맞지 않음 | | `OPERATION_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | durable operation 조회(`DurableOperationController`)에서 그 operation이 없거나 다른 호출자의 것이다. 둘을 가르지 않는다 | -| `DELIVERY_ATTEMPT_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | 알림 운영자 redrive(`RedriveDeliveryUseCase`)가 받은 attempt가 없거나 운영자 tenant 밖이다. 둘을 가르지 않는다. 코드는 `application-notification`의 `NotificationAdminErrorCode`라 모든 전송이 같은 코드로 답한다. 템플릿은 이 연산의 전송을 싣지 않는다(`docs/notification/operations.md`) | +| `DELIVERY_ATTEMPT_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | 알림 운영자 redrive(`RedriveDeliveryUseCase`)가 받은 attempt나 reconcile(`ReconcileDeliveriesUseCase`) 묶음의 attempt 하나가 없거나 운영자 tenant 밖이다. 둘을 가르지 않는다. reconcile은 provider를 부르기 전에 묶음 전체를 거절한다. 코드는 `application-notification`의 `NotificationAdminErrorCode`라 실패를 답하는 전송(web·GraphQL·gRPC)이 같은 코드로 답한다. 템플릿은 이 연산의 전송을 싣지 않는다(`docs/notification/operations.md`) | | `ADMIN_ACCESS_DENIED` | 403 | `AUTHZ` | `false` | 없음 | 알림 운영자 연산에서 운영자에게 그 연산의 authority가 없거나, tenant 범위 운영자가 provider 상태를 바꾸려 했다. authority는 대상을 읽기 전에 보므로 대상에 대해 알려 주지 않는다. 코드는 `application-notification`의 `NotificationAdminErrorCode`다(아래 운영자 연산 행 모두 같다). 템플릿은 이 연산의 전송을 싣지 않는다(`docs/notification/operations.md`) | -| `ADMIN_TARGET_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | 알림 운영자 suppression·reconcile이 운영자 tenant 밖의 대상을 골랐다. 권한 거절(403)이 아니라 없는 대상과 같은 404라 그 tenant가 무엇을 가졌는지 알려 주지 않는다 | +| `ADMIN_TARGET_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | 알림 운영자 suppression이 운영자 tenant 밖의 tenant를 골랐다. 권한 거절(403)이 아니라 없는 대상과 같은 404라 그 tenant가 무엇을 가졌는지 알려 주지 않는다 | | `DUPLICATE_RISK_APPROVAL_REQUIRED` | 409 | `CONFLICT` | `false` | 없음 | 이미 사용자에게 닿았을 수 있는 attempt의 redrive가 중복 위험 승인 없이 왔다. 같은 요청은 다시 거절된다. 승인을 붙여 보낸다 | | `ADMIN_OPERATION_CONFLICT` | 422 | `VALIDATION` | `false` | 없음 | 알림 운영자 연산의 operation id(그 연산의 멱등 키)가 전에 다른 요청에 쓰였다. 같은 멱등 키·다른 요청이라 409가 아니다(`docs/manual/06-errors.md`). 새 operation id를 쓴다 | | `ADMIN_OPERATION_IN_PROGRESS` | 409 | `CONFLICT` | `true` | 없음 | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다. 기다렸다가 같은 요청을 다시 보내면 끝난 결과가 온다. 2절의 `IDEMPOTENT_IN_FLIGHT`와 달리 `Retry-After`를 싣지 않는다 | diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index f69fe7f0..23209c9f 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -111,9 +111,10 @@ | GraphQL DataLoader 키 실패 | 등록된 `ApiErrorCode`만 노출 | 소유자 | 결정 25 | | 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절 | +| 알림 redrive의 없는·남의 attempt | 없는 attempt id와 운영자 tenant 밖의 attempt를 같은 404 carrier(`DeliveryAttemptNotFoundException`, code `DELIVERY_ATTEMPT_NOT_FOUND`) 하나로 답한다. 권한 거절(403)로 바꾸는 안과 문서만 500으로 고치는 안은 버렸다. 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다. 다른 운영자 연산의 tenant 거절은 그대로다(2026-11-23에 아래 「알림 운영자 연산의 거절」·「알림 reconcile의 없는·남의 attempt」 행이 바꿨다) | 기본값(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절 | -| 알림 운영자 연산의 거절 | 운영자 입력 거절 다섯을 carrier로 답한다. code는 기능 enum `NotificationAdminErrorCode`다: authority 없음 403 `ADMIN_ACCESS_DENIED`, suppression·reconcile의 tenant 밖 대상 404 `ADMIN_TARGET_NOT_FOUND`(권한 거절이 아니라 없는 대상과 같은 답), 중복 위험 승인 없음 409 `DUPLICATE_RISK_APPROVAL_REQUIRED`, operation id 재사용 422 `ADMIN_OPERATION_CONFLICT`, 같은 id 진행 중 409 `ADMIN_OPERATION_IN_PROGRESS`(retryable true, `Retry-After` 없음). 요청의 표는 재사용을 409로 적었지만, 같은 멱등 키·다른 요청은 422라는 `docs/manual/06-errors.md` 판단 표와 executor 선례(`IDEMPOTENT_REQUEST_MISMATCH`)를 따라 422로 했다. 문서만 500으로 고치는 안과 web 처리기에서 이름으로 잡는 안은 버렸다. 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다 | 기본값(2026-11-23, review 허브가 고른 권하는 안, 자율 운영. 422는 백엔드 개발자가 매뉴얼에 맞춘 것이고 review 판정을 받는다. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0058 요청(2026-11-23 09:40), `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절 | +| 알림 운영자 연산의 거절 | 운영자 입력 거절 다섯을 carrier로 답한다. code는 기능 enum `NotificationAdminErrorCode`다: authority 없음 403 `ADMIN_ACCESS_DENIED`, suppression의 tenant 밖 대상 404 `ADMIN_TARGET_NOT_FOUND`(권한 거절이 아니라 없는 대상과 같은 답), 중복 위험 승인 없음 409 `DUPLICATE_RISK_APPROVAL_REQUIRED`, operation id 재사용 422 `ADMIN_OPERATION_CONFLICT`, 같은 id 진행 중 409 `ADMIN_OPERATION_IN_PROGRESS`(retryable true, `Retry-After` 없음). 요청의 표는 재사용을 409로 적었지만, 같은 멱등 키·다른 요청은 422라는 `docs/manual/06-errors.md` 판단 표와 executor 선례(`IDEMPOTENT_REQUEST_MISMATCH`)를 따라 422로 했다. 문서만 500으로 고치는 안과 web 처리기에서 이름으로 잡는 안은 버렸다. 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다 | 기본값(2026-11-23, review 허브가 고른 권하는 안, 자율 운영. 422는 백엔드 개발자가 매뉴얼에 맞춘 것이고 review 판정을 받는다. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0058 요청(2026-11-23 09:40), `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절 | +| 알림 reconcile의 없는·남의 attempt | reconcile 묶음에 없는 attempt id나 운영자 tenant 밖의 attempt가 하나라도 있으면 provider를 부르기 전에 묶음 전체를 redrive와 같은 404 carrier(`DeliveryAttemptNotFoundException`)로 거절한다. dry run도 같다. 처리 수는 묶음의 id 수다. 대가로 보존 기간이 지나 지워진 id가 섞인 묶음도 거절된다. 없는 id와 남의 id를 둘 다 건너뛰고 있는 것만 세는 안(「남의 id가 있으면 아무것도 안 바꾼다」가 깨지고 오타가 성공으로 보인다)과 지금대로 두는 안(존재가 드러난다)은 버렸다 | 기본값(2026-11-23, review 허브가 고른 권하는 안, 자율 운영. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0059 요청(2026-11-23 09:40), `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절 4행 | | 오류 코드 로그 레벨 | `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/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java index c433a6ac..6becbeba 100644 --- a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java @@ -183,6 +183,31 @@ class NotificationAdminRefusalHttpAnswerTest { .containsExactly(notFound(NotificationAdminErrorCode.DELIVERY_ATTEMPT_NOT_FOUND.code()), 0); } + /** + * One reconcile batch beside an attempt of the operator's own tenant names an id no attempt has, + * or an attempt of another tenant. Both refuse the whole batch with the answer a redrive gives, + * before any provider is asked, so the answer does not tell which ids exist elsewhere. + */ + @ParameterizedTest(name = "{0} attempt beside an own one, dryRun={1}") + @CsvSource({"unknown, false", "unknown, true", "foreign, false", "foreign, true"}) + void aReconcileNamingAnUnreachableAttemptAnswersOneNotFoundForTheWholeBatch( + String target, boolean dryRun) throws Exception { + // given + String ownAttempt = storedAttemptOf(TENANT_B); + String unreachable = "foreign".equals(target) ? storedAttemptOf(TENANT_A) : UNKNOWN_ATTEMPT; + + // when + List answer = + answerRecordingServerFailures( + () -> reconcile(List.of(ownAttempt, unreachable), dryRun, "op-rc-http")); + + // then + assertThat(List.of(answer, providerCalls.get(), audit.events().size())) + .as("[%s, provider calls, audit events]", ANSWER_FIELDS) + .containsExactly( + notFound(NotificationAdminErrorCode.DELIVERY_ATTEMPT_NOT_FOUND.code()), 0, 0); + } + /** * Each refusal answers its own status and code with the category's fixed message, and the handler * records none as a server failure. A missing authority (403) and a target outside the operator's diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAccessDeniedException.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAccessDeniedException.java index fea8003e..0b33a509 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAccessDeniedException.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAccessDeniedException.java @@ -15,7 +15,8 @@ import dev.caskeleton.shared.error.ApiErrorCode; * answers {@link NotificationAdminErrorCode#ADMIN_ACCESS_DENIED} (403) and logs no server failure. * The authority is checked before any target is read, so the refusal says nothing about targets. A * target outside the actor's tenant is a different answer, the one a missing target gets: {@link - * AdminTargetNotFoundException}, or {@link DeliveryAttemptNotFoundException} for an attempt. + * AdminTargetNotFoundException} for a suppression's tenant, {@link + * DeliveryAttemptNotFoundException} for an attempt a redrive or a reconcile batch names. * *

The {@linkplain #descriptor() descriptor} keeps the closed notification registry ({@code * VALIDATION_FAILED}, {@code AUTHORIZATION}); the code on the wire is {@link #errorCode()}. diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/DeliveryAttemptNotFoundException.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/DeliveryAttemptNotFoundException.java index 11678e0a..0a594bae 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/DeliveryAttemptNotFoundException.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/DeliveryAttemptNotFoundException.java @@ -8,10 +8,11 @@ import dev.caskeleton.shared.error.ApiErrorCarrier; import dev.caskeleton.shared.error.ApiErrorCode; /** - * Raised when a redrive names an attempt the operator cannot act on: no attempt has the id, or the - * attempt belongs to a tenant outside the operator's scope. Both raise this one exception with no - * state of its own, so neither the answer nor the exception tells a tenant-scoped operator which - * ids exist in other tenants. + * Raised when a redrive, or any id of a reconcile batch, names an attempt the operator cannot act + * on: no attempt has the id, or the attempt belongs to a tenant outside the operator's scope. Both + * raise this one exception with no state of its own, so neither the answer nor the exception tells + * a tenant-scoped operator which ids exist in other tenants. A reconcile batch is refused whole, + * before any provider is asked. * *

The id is the operator's input, so this is the caller's failure, not a server fault: a * transport answers {@link NotificationAdminErrorCode#DELIVERY_ATTEMPT_NOT_FOUND} (404) and logs no diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java index e6420ce5..8c277f58 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java @@ -29,8 +29,9 @@ public enum NotificationAdminErrorCode implements ApiErrorCode { ADMIN_TARGET_NOT_FOUND(404, Category.NOT_FOUND, false), /** - * A redrive named an attempt the operator cannot act on: no attempt has that id, or it belongs to - * a tenant outside the operator's scope. The two are one code so the answer does not tell which. + * A redrive or a reconcile batch named an attempt the operator cannot act on: no attempt has that + * id, or it belongs to a tenant outside the operator's scope. The two are one code so the answer + * does not tell which. */ DELIVERY_ATTEMPT_NOT_FOUND(404, Category.NOT_FOUND, false), diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java index e5d80b1d..db55bd83 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java @@ -21,9 +21,12 @@ import java.util.Optional; /** * Asks providers, on an operator's request, what happened to a bounded batch of attempts. * - *

Every attempt is checked against the operator's tenant scope before any is touched, so a batch - * with one foreign id changes none. An id with no attempt behind it is left to reconciliation, - * which does nothing with it. + *

Every attempt id is checked before any provider is asked. An id no attempt has and an attempt + * outside the operator's tenant scope get one answer for the whole batch, the one a redrive gives: + * {@link DeliveryAttemptNotFoundException}. A tenant-scoped operator cannot tell which ids exist in + * other tenants, a batch with one such id changes nothing and claims no operation id, and the + * result counts only attempts that were reconciled. The price: a batch that names an attempt + * already removed by retention is refused whole, and is sent again without that id. * *

The provider calls run with no transaction open: each one asks over the network, and inside a * write transaction it held a pooled connection for as long as the provider took, once per attempt. @@ -83,9 +86,14 @@ public class ReconcileDeliveriesUseCase transactions.inRead( () -> { for (DeliveryAttemptId attemptId : request.attemptIds()) { - attempts - .snapshot(attemptId) - .ifPresent(attempt -> authorization.requireTenant(actor, attempt.tenantId())); + boolean unreachable = + attempts + .snapshot(attemptId) + .filter(attempt -> authorization.mayActOn(actor, attempt.tenantId())) + .isEmpty(); + if (unreachable) { + throw new DeliveryAttemptNotFoundException(); + } } return null; }); diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java index 9dbea5f9..2ed1c57c 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java @@ -46,12 +46,14 @@ import java.util.List; import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; /** * The four operator-plane use cases, each its own entrypoint with its own permission (round9 review @@ -134,35 +136,6 @@ class NotificationAdminUseCasesTest { assertThat(fixture.runtime.calls).isZero(); } - @Test - void aTenantScopedOperatorCannotReconcileAnotherTenantsAttempt() { - // given - Fixture fixture = new Fixture(); - DeliveryAttemptSnapshot foreign = attemptOf(new TenantId("tenant-a")); - AttemptSnapshots.store( - fixture.requests, fixture.attempts, foreign, RecipientDeliveryState.DISPATCHING); - AdminActor tenantB = - new AdminActor( - "operator-b", - Set.of(NotificationAdminAuthority.RECONCILE), - Optional.of(new TenantId("tenant-b"))); - ReconcileRequest request = - new ReconcileRequest("op-r", List.of(foreign.attemptId()), "stuck attempt", false); - - // when - Throwable failure = - catchThrowable( - () -> fixture.reconcile.handle(new ReconcileDeliveriesCommand(request, tenantB))); - - // then - assertThat(failure) - .isInstanceOfSatisfying( - AdminTargetNotFoundException.class, - notFound -> - assertThat(notFound.errorCode()) - .isEqualTo(NotificationAdminErrorCode.ADMIN_TARGET_NOT_FOUND)); - } - @Test void aTenantScopedOperatorCannotChangeAGlobalProviderState() { // given @@ -233,6 +206,105 @@ class NotificationAdminUseCasesTest { .containsExactly(false); } + /** + * The attempt ids are the operator's input. A batch naming an id no attempt has, or an attempt + * outside the operator's tenant scope, is refused whole before any provider is asked, with the + * answer a redrive gives: a skipped id would be counted as reconciled, and a refusal for the + * foreign id alone would tell a tenant-scoped operator which ids exist in other tenants. + */ + @ParameterizedTest(name = "{0}") + @MethodSource("unreachableReconciles") + void aReconcileBatchNamingAnUnknownOrForeignAttemptIsNotFoundAndAsksNoProvider( + UnreachableReconcile reconcile) { + // given + AtomicInteger providerCalls = new AtomicInteger(); + Fixture fixture = new Fixture(countingProvider(providerCalls)); + DeliveryAttemptSnapshot own = attemptOf(new TenantId("tenant-b"), 2); + DeliveryAttemptSnapshot foreign = attemptOf(new TenantId("tenant-a")); + AttemptSnapshots.store( + fixture.requests, fixture.attempts, own, RecipientDeliveryState.DISPATCHING); + AttemptSnapshots.store( + fixture.requests, fixture.attempts, foreign, RecipientDeliveryState.DISPATCHING); + AdminActor operator = + new AdminActor( + "operator-b", Set.of(NotificationAdminAuthority.RECONCILE), reconcile.scope()); + ReconcileRequest request = + new ReconcileRequest( + "op-rc-unreachable", + List.of(own.attemptId(), reconcile.target(foreign)), + "stuck attempt", + reconcile.dryRun()); + AtomicReference answered = new AtomicReference<>(); + + // when + Throwable failure = + catchThrowable( + () -> + answered.set( + fixture.reconcile.handle(new ReconcileDeliveriesCommand(request, operator)))); + + // then + assertThat( + List.of( + failure == null ? "no failure" : failure.getClass(), + carrierCode(failure), + answered.get() == null ? "no result" : "affected " + answered.get().affected(), + providerCalls.get(), + fixture.operations.claims, + fixture.audit.events().size())) + .as("[failure, carrier code, result, provider calls, claims, audit events]") + .containsExactly( + DeliveryAttemptNotFoundException.class, + "DELIVERY_ATTEMPT_NOT_FOUND", + "no result", + 0, + 0, + 0); + } + + private static Stream unreachableReconciles() { + Optional tenantB = Optional.of(new TenantId("tenant-b")); + Optional global = Optional.empty(); + return Stream.of( + new UnreachableReconcile("tenant operator, unknown id, reconcile", tenantB, false, false), + new UnreachableReconcile("tenant operator, unknown id, dry run", tenantB, false, true), + new UnreachableReconcile("tenant operator, foreign id, reconcile", tenantB, true, false), + new UnreachableReconcile("tenant operator, foreign id, dry run", tenantB, true, true), + new UnreachableReconcile("global operator, unknown id, reconcile", global, false, false), + new UnreachableReconcile("global operator, unknown id, dry run", global, false, true)); + } + + /** A batch the operator may act on in full reports one affected attempt per id it named. */ + @ParameterizedTest(name = "dryRun={0}") + @ValueSource(booleans = {false, true}) + void aReconcileOfReachableAttemptsReportsEveryIdItNamed(boolean dryRun) { + // given + AtomicInteger providerCalls = new AtomicInteger(); + Fixture fixture = new Fixture(countingProvider(providerCalls)); + TenantId tenantB = new TenantId("tenant-b"); + DeliveryAttemptSnapshot first = attemptOf(tenantB); + DeliveryAttemptSnapshot second = attemptOf(tenantB, 2); + AttemptSnapshots.store( + fixture.requests, fixture.attempts, first, RecipientDeliveryState.DISPATCHING); + AttemptSnapshots.store( + fixture.requests, fixture.attempts, second, RecipientDeliveryState.DISPATCHING); + AdminActor operator = + new AdminActor( + "operator-b", Set.of(NotificationAdminAuthority.RECONCILE), Optional.of(tenantB)); + ReconcileRequest request = + new ReconcileRequest( + "op-rc-own", List.of(first.attemptId(), second.attemptId()), "stuck attempt", dryRun); + + // when + AdminOperationResult result = + fixture.reconcile.handle(new ReconcileDeliveriesCommand(request, operator)); + + // then + assertThat(List.of(result.affected(), providerCalls.get())) + .as("[affected, provider calls]") + .containsExactly(2, dryRun ? 0 : 2); + } + @Test void redriveReturnsTheDeliveryToTheQueueUnderItsClaim() { // given @@ -639,6 +711,47 @@ class NotificationAdminUseCasesTest { } } + /** + * A reconcile batch of the stored attempt of tenant-b and one the operator cannot reach: the + * operator's tenant scope, whether that one is the stored attempt of tenant-a or an id no attempt + * has, and whether it is a dry run. + */ + private record UnreachableReconcile( + String name, Optional scope, boolean foreign, boolean dryRun) { + + DeliveryAttemptId target(DeliveryAttemptSnapshot foreignAttempt) { + return foreign ? foreignAttempt.attemptId() : UNKNOWN_ATTEMPT; + } + + @Override + public String toString() { + return name; + } + } + + /** The code of the first carrier in {@code failure}'s cause chain, or {@code "no code"}. */ + private static String carrierCode(Throwable failure) { + return ApiErrorCarrier.firstIn(failure) + .map(carrier -> ((ApiErrorCarrier) carrier).errorCode().code()) + .orElse("no code"); + } + + /** A provider that supports every profile, answers unsupported, and counts its calls. */ + private static ReconciliationGatewayPort countingProvider(AtomicInteger calls) { + return new ReconciliationGatewayPort() { + @Override + public boolean supports(ProviderProfileId profileId) { + return true; + } + + @Override + public ReconciliationResult reconcile(DeliveryAttemptSnapshot attempt) { + calls.incrementAndGet(); + return new ReconciliationResult.Unsupported(); + } + }; + } + /** One operator use case, the authority it exercises, and how to call it as an actor. */ private record OperatorCall( String useCase, @@ -656,10 +769,19 @@ class NotificationAdminUseCasesTest { } private static DeliveryAttemptSnapshot attemptOf(TenantId tenantId) { + return attemptOf(tenantId, 1); + } + + /** + * An ambiguous attempt of {@code tenantId}. {@code serial} picks its ids — the attempt's ends in + * {@code 1}, the delivery's in {@code 2}, the notification's in {@code 3} + * — so two serials are two stored deliveries. + */ + private static DeliveryAttemptSnapshot attemptOf(TenantId tenantId, int serial) { return new DeliveryAttemptSnapshot( - new DeliveryAttemptId(UUID.fromString("00000000-0000-7000-8000-000000000011")), - new RecipientDeliveryId(UUID.fromString("00000000-0000-7000-8000-000000000012")), - new NotificationId(UUID.fromString("00000000-0000-7000-8000-000000000013")), + new DeliveryAttemptId(UUID.fromString(idOf(serial, 1))), + new RecipientDeliveryId(UUID.fromString(idOf(serial, 2))), + new NotificationId(UUID.fromString(idOf(serial, 3))), tenantId, 1, Channel.EMAIL, @@ -678,6 +800,10 @@ class NotificationAdminUseCasesTest { Optional.empty()); } + private static String idOf(int serial, int part) { + return String.format("00000000-0000-7000-8000-%012d", serial * 10 + part); + } + private static final class Fixture { private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); -- 2.54.0 From 228237301509f678db5251d4752ced76f5c85509 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 21:33:20 +0900 Subject: [PATCH 3/5] =?UTF-8?q?fix(notification)!:=20=EC=A7=84=ED=96=89=20?= =?UTF-8?q?=EC=A4=91=20=EA=B1=B0=EC=A0=88=EC=9D=84=20=EC=9E=AC=EC=8B=9C?= =?UTF-8?q?=EB=8F=84=20=EB=B6=88=EA=B0=80=EB=A1=9C=20=ED=95=98=EA=B3=A0=20?= =?UTF-8?q?reconcile=EC=9D=98=20=EA=B6=8C=ED=95=9C=20=EC=88=9C=EC=84=9C?= =?UTF-8?q?=EB=A5=BC=20=EA=B3=A0=EC=A0=95=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 첫 리뷰(종류 B, 리뷰어 셋)가 낸 Medium 둘과 Low를 고친다. ADMIN_OPERATION_IN_PROGRESS는 retryable true였다. 그런데 admin operation claim에는 만료가 없고(JpaAdminOperationStore는 CLAIMED를 계속 진행 중으로 답한다), reconcile은 claim을 먼저 커밋한 뒤 provider를 부른다. provider 호출 중에 프로세스가 멈추면 그 operation id는 영영 진행 중이고, retryable을 따라 자동으로 다시 보내는 클라이언트는 끝나지 않는다. docs/manual/06-errors.md는 시간이 지나면 성공할 수 있을 때만 true를 허용한다. claim에 lease를 더하는 것은 migration이 드는 범위 밖 일이라, retryable을 false로 하고 status 409와 code는 그대로 둔다. 다시 보내도 되는지는 code가 알린다. 문서는 「기다렸다가 같은 요청, 오래 가면 새 operation id」로 고쳤다. reconcile이 authority를 대상보다 먼저 보는지 지키는 시험이 없었다. 전에는 authority 없음과 남의 id가 같은 AdminAccessDeniedException이라 순서가 드러나지 않았지만, 이제 404와 403으로 갈려서 require를 루프 뒤로 옮기면 RECONCILE 없는 운영자가 id의 존재를 알 수 있다. redrive와 같은 시험을 reconcile에 더했다 (없는 id·남의 id 묶음 → AdminAccessDeniedException(RECONCILE), provider 호출 0, claim 0). Low: reconcile 클래스 주석의 처리 수 문장(물어본 id마다 하나), 읽기 블록 주석 (존재와 tenant 판정), 「모든 거절은 클라이언트 오류」를 표의 다섯으로 좁히고 provider 상태 연산의 받지 않은 변경·없는 profile은 아직 500이라고 적음, 끝난 operation id의 replay도 존재 판정을 먼저 지나 지워진 attempt가 있으면 404라는 것을 upgrade 4행에 적음, 422를 409로 되돌리는 곳 목록을 채움, redrive upgrade 3절의 「위 두 줄은 낡았다」를 낡은 부분으로 좁힘. 위험·한계: 직전 커밋(b282b63d8) 본문과 BREAKING CHANGE 꼬리말의 「409 ADMIN_OPERATION_IN_PROGRESS(retryable)」는 이 커밋으로 틀린 말이 된다. amend하지 않고 PR 본문에 정정으로 적는다. claim 만료가 없는 것 자체는 고치지 않았다(넘길 것). 검증: NotificationAdminRefusalHttpAnswerTest의 진행 중 행이 retryable false를, NotificationAdminUseCasesTest의 새 표 둘이 authority 거절을 단언한다. 노트북 감싸개 :application-notification:check, :adapter:inbound:web-notification:check, :adapter:outbound:notification:verifyNotificationApiSurface rc=0(app 시험 33, web 13, 실패 0), check-docs.py·check-work-docs.py OK. BREAKING CHANGE: 알림 운영자 연산의 ADMIN_OPERATION_IN_PROGRESS(409)는 retryable false다(직전 커밋은 true였다). 같은 operation id로 기다렸다가 다시 보내고, 오래 가면 새 operation id를 쓴다. Refs: REV-BE-0058, REV-BE-0059 --- docs/notification/operations.md | 11 +++-- .../2026-11-notification-admin-redrive.md | 6 ++- .../2026-11-notification-admin-refusals.md | 16 ++++--- docs/web/http-contract.md | 2 +- docs/work/reference/decisions.md | 2 +- ...otificationAdminRefusalHttpAnswerTest.java | 5 +- .../AdminOperationInProgressException.java | 5 +- .../admin/NotificationAdminErrorCode.java | 14 ++++-- .../admin/ReconcileDeliveriesUseCase.java | 7 +-- .../admin/NotificationAdminUseCasesTest.java | 46 +++++++++++++++++++ 10 files changed, 88 insertions(+), 26 deletions(-) diff --git a/docs/notification/operations.md b/docs/notification/operations.md index 945c4532..cf526540 100644 --- a/docs/notification/operations.md +++ b/docs/notification/operations.md @@ -51,9 +51,10 @@ redrive는 `NotificationId`와 `RecipientDeliveryId`를 유지하고, 새 `Deliv - 확인은 두 겹이다. permission은 전송의 호출자가 이 연산을 부를 수 있는지다(`@RequiresPermission`). authority와 tenant 범위는 command의 `AdminActor`가 쥐고, 연산이 건드리는 delivery의 tenant와 대조한다. -- 거절은 모두 운영자 입력이라 서버 오류가 아니다. 거절 예외는 `ApiErrorCarrier`라서 실패를 답하는 전송(web·GraphQL·gRPC)이 +- 아래 거절은 모두 운영자 입력이라 서버 오류가 아니다. 거절 예외는 `ApiErrorCarrier`라서 실패를 답하는 전송(web·GraphQL·gRPC)이 아래 code(`NotificationAdminErrorCode`)로 답하고 서버 오류로 남기지 않는다. 예외의 descriptor는 알림 code 목록 값이라 - 응답 code와 다르다. 전송마다의 모양은 `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절이다. + 응답 code와 다르다. 전송마다의 모양은 `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절이다. 이 표 밖의 거절 + (provider 상태 연산에서 runtime이 받아들이지 않은 변경, 없는 profile)은 아직 500과 ERROR 로그다. | 거절 | code | web | retryable | 운영자가 할 일 | |---|---|---|---|---| @@ -62,7 +63,7 @@ redrive는 `NotificationId`와 `RecipientDeliveryId`를 유지하고, 새 `Deliv | suppression이 운영자 tenant 밖의 tenant를 골랐다 | `ADMIN_TARGET_NOT_FOUND` | 404 | false | tenant를 확인한다 | | 모호한 attempt를 중복 위험 승인 없이 redrive했다 | `DUPLICATE_RISK_APPROVAL_REQUIRED` | 409 | false | 중복 위험을 받아들이면 승인을 붙여 다시 보낸다 | | operation id가 전에 다른 요청에 쓰였다 | `ADMIN_OPERATION_CONFLICT` | 422 | false | 새 operation id를 쓴다 | - | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다 | `ADMIN_OPERATION_IN_PROGRESS` | 409 | true | 기다렸다가 같은 id·같은 요청을 다시 보낸다. 끝났으면 저장된 결과가 온다 | + | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다 | `ADMIN_OPERATION_IN_PROGRESS` | 409 | false | 기다렸다가 같은 id·같은 요청을 다시 보낸다. 끝났으면 저장된 결과가 온다. 오래 가면 아래처럼 새 id를 쓴다 | - authority는 대상을 읽기 전에 본다. 그래서 403은 대상에 대해 아무것도 알려 주지 않는다. tenant 밖의 대상은 authority 거절이 아니라 없는 대상과 같은 404다. redrive와 reconcile은 없는 attempt와 남의 tenant attempt가 같은 답이라 다른 tenant에 @@ -70,8 +71,8 @@ redrive는 `NotificationId`와 `RecipientDeliveryId`를 유지하고, 새 `Deliv - reconcile은 provider를 부르기 전에 묶음의 id를 모두 본다. 하나라도 없거나 운영자 tenant 밖이면 묶음 전체를 거절하고 아무것도 묻지 않는다(dry run도 같다). 그래서 처리 수(`affected`)는 묶음의 id 수와 같다. 보존 기간이 지나 지워진 attempt id가 섞인 묶음도 거절된다. -- provider 호출 중에 프로세스가 멈춘 reconcile의 operation id는 claim이 끝나지 않아 계속 진행 중으로 답한다. 그 묶음은 새 - operation id로 보낸다. +- provider 호출 중에 프로세스가 멈춘 reconcile의 operation id는 claim이 끝나지 않아(claim에 만료가 없다) 계속 진행 중으로 + 답한다. 그 묶음은 새 operation id로 보낸다. 그래서 진행 중은 retryable이 false다. - 모든 연산은 운영자가 준 operation id로 멱등이다. 같은 id·같은 요청은 저장된 결과를 돌려주고, 같은 id·다른 요청은 충돌이다. 대상 확인(tenant·중복 위험)과 claim과 쓰기는 한 쓰기 트랜잭션에서 커밋한다. reconcile만 대상 확인을 읽기 트랜잭션에서 하고, provider 호출은 트랜잭션 밖에서 하며, claim과 결과를 따로 커밋한다. diff --git a/docs/upgrade/2026-11-notification-admin-redrive.md b/docs/upgrade/2026-11-notification-admin-redrive.md index dd1e92be..66ace525 100644 --- a/docs/upgrade/2026-11-notification-admin-redrive.md +++ b/docs/upgrade/2026-11-notification-admin-redrive.md @@ -34,8 +34,10 @@ - `ReconcileDeliveriesUseCase`는 묶음 안의 없는 attempt id를 그대로 건너뛴다. - suppression·reconcile·provider 상태 연산은 남의 tenant 대상을 전처럼 `AdminAccessDeniedException`으로 거절한다. authority가 없을 때의 답도 네 연산 모두 그대로다. -- 2026-11-23에 위 두 줄은 낡았다. reconcile의 없는 id와 남의 tenant attempt, suppression의 남의 tenant, 네 연산의 - authority 없음의 답은 `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절이 대신한다. +- 2026-11-23에 위 두 줄의 일부가 낡았다. reconcile의 없는 id와 남의 tenant attempt, suppression의 남의 tenant의 답과, + authority 없음의 응답(예외는 그대로 `AdminAccessDeniedException`, 이제 403)은 + `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절이 대신한다. provider 상태 연산이 tenant 범위 운영자를 + `AdminAccessDeniedException`으로 거절하는 것은 그대로다(이제 403). - 오류 code 목록(`NotificationFailureCode`)과 템플릿 오류 code registry(`docs/registries/error-codes.yaml`)는 그대로다. not-found 코드는 그 목록이 아니라 전송이 읽는 `NotificationAdminErrorCode`에 두었다. 새 예외의 descriptor는 있는 값(`VALIDATION_FAILED`, `INVALID_PAYLOAD`)이라 descriptor code와 응답 code가 다르다. diff --git a/docs/upgrade/2026-11-notification-admin-refusals.md b/docs/upgrade/2026-11-notification-admin-refusals.md index 39f1b0f0..e4efd1fb 100644 --- a/docs/upgrade/2026-11-notification-admin-refusals.md +++ b/docs/upgrade/2026-11-notification-admin-refusals.md @@ -28,14 +28,14 @@ | `ADMIN_TARGET_NOT_FOUND` | suppression이 운영자 tenant 밖의 tenant를 골랐다 | `AdminTargetNotFoundException`(새 타입) | 404 | `NOT_FOUND` | false | | `DUPLICATE_RISK_APPROVAL_REQUIRED` | 모호한 attempt의 redrive가 중복 위험 승인 없이 왔다 | `DuplicateRiskApprovalRequiredException` | 409 | `CONFLICT` | false | | `ADMIN_OPERATION_CONFLICT` | operation id가 전에 다른 요청에 쓰였다 | 공개되지 않은 타입(`RuntimeException`) | 422 | `VALIDATION` | false | -| `ADMIN_OPERATION_IN_PROGRESS` | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다 | 공개되지 않은 타입(`RuntimeException`) | 409 | `CONFLICT` | true | +| `ADMIN_OPERATION_IN_PROGRESS` | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다 | 공개되지 않은 타입(`RuntimeException`) | 409 | `CONFLICT` | false | | # | 바뀐 것 | 전에는 | 할 일 | 안 하면 | 해당 서비스 | | --- | --- | --- | --- | --- | --- | -| 1 | 위 다섯 예외가 `ApiErrorCarrier`를 구현한다. 실패를 답하는 공용 처리기가 위 code로 답한다. web은 위 status와 error 본문(code·category·category별 고정 문구·retryable)이고, 서버 오류 로그와 span 오류를 남기지 않는다. `ADMIN_OPERATION_IN_PROGRESS`는 retryable true지만 `Retry-After` 헤더는 없다. GraphQL은 errors의 code가 위 code이고 category는 `AUTHORIZATION`(403)·`BUSINESS`(404·409)·`REQUEST`(422)다. 실패 자신이 carrier라서 등록 매핑보다 먼저 답한다. resolver observation은 전처럼 던진 예외를 오류로 센다(`graphql.outcome=ERROR`와 span 오류). gRPC는 `PERMISSION_DENIED`(403)·`NOT_FOUND`(404)·`ABORTED`(409)·`INVALID_ARGUMENT`(422)와 trailer `error-code`·`error-category`·`error-retryable`이고 서버 오류 로그를 남기지 않는다. STOMP `@MessageMapping`이 던진 실패는 전처럼 frame을 보내지 않고 ERROR 로그만 사라진다. 예외 타입·메시지·descriptor(알림 code 목록 값)는 그대로다 | carrier가 아니어서 공용 처리기가 서버 오류로 다뤘다. web은 500 `INTERNAL_ERROR`와 ERROR 로그·span 오류, gRPC는 `INTERNAL`, GraphQL은 이 타입(또는 상위 타입)을 등록한 매핑이 없으면 `INTERNAL_ERROR`였다. STOMP는 frame 없이 ERROR 로그를 남겼다. 운영자 실수가 5xx 경보를 울렸다 | 500·`INTERNAL`을 거절로 읽던 운영자 화면·모니터링을 위 code로 바꾼다. `ADMIN_OPERATION_IN_PROGRESS`만 같은 요청을 다시 보낸다(첫 요청이 끝났으면 저장된 결과가 온다). `ADMIN_OPERATION_CONFLICT`는 다시 보내지 않고 새 operation id를 쓴다. GraphQL에 `GraphQlExceptionResolver`로 이 예외나 상위 타입(`NotificationException`, `RuntimeException` 등)을 등록해 자기 code로 답하던 서비스는 그 매핑이 더 쓰이지 않는다(`docs/work/reference/decisions.md` 2.3절 「GraphQL 판정 순서」). 자기 code가 필요하면 이 예외를 감싼 자기 예외로 던지고 그 타입을 등록한다. web `@ExceptionHandler`와 이 예외를 직접 잡던 코드는 그대로 동작한다 | 운영자 화면이 이 code를 모르면 거절을 처리하지 못한다. 5xx만 세던 경보 규칙은 이 거절을 더 보지 않는다. GraphQL의 등록 매핑에 기대던 분기는 code가 바뀌어 깨진다 | 알림 운영자 연산 전송을 연 서비스 | +| 1 | 위 다섯 예외가 `ApiErrorCarrier`를 구현한다. 실패를 답하는 공용 처리기가 위 code로 답한다. web은 위 status와 error 본문(code·category·category별 고정 문구·retryable)이고, 서버 오류 로그와 span 오류를 남기지 않는다. 다섯 모두 retryable false라 `Retry-After` 헤더도 없다. GraphQL은 errors의 code가 위 code이고 category는 `AUTHORIZATION`(403)·`BUSINESS`(404·409)·`REQUEST`(422)다. 실패 자신이 carrier라서 등록 매핑보다 먼저 답한다. resolver observation은 전처럼 던진 예외를 오류로 센다(`graphql.outcome=ERROR`와 span 오류). gRPC는 `PERMISSION_DENIED`(403)·`NOT_FOUND`(404)·`ABORTED`(409)·`INVALID_ARGUMENT`(422)와 trailer `error-code`·`error-category`·`error-retryable`이고 서버 오류 로그를 남기지 않는다. STOMP `@MessageMapping`이 던진 실패는 전처럼 frame을 보내지 않고 ERROR 로그만 사라진다. 예외 타입·메시지·descriptor(알림 code 목록 값)는 그대로다 | carrier가 아니어서 공용 처리기가 서버 오류로 다뤘다. web은 500 `INTERNAL_ERROR`와 ERROR 로그·span 오류, gRPC는 `INTERNAL`, GraphQL은 이 타입(또는 상위 타입)을 등록한 매핑이 없으면 `INTERNAL_ERROR`였다. STOMP는 frame 없이 ERROR 로그를 남겼다. 운영자 실수가 5xx 경보를 울렸다 | 500·`INTERNAL`을 거절로 읽던 운영자 화면·모니터링을 위 code로 바꾼다. `ADMIN_OPERATION_IN_PROGRESS`는 기다렸다가 같은 요청을 다시 보낸다(첫 요청이 끝났으면 저장된 결과가 온다). claim에 만료가 없어서 provider 호출 중에 프로세스가 멈춘 reconcile의 id는 끝나지 않는다. 그래서 retryable이 false이고, 오래 가면 새 operation id로 보낸다. retryable을 보고 자동으로 다시 보내는 공용 재시도는 이 code를 다시 보내지 않는다. `ADMIN_OPERATION_CONFLICT`는 다시 보내지 않고 새 operation id를 쓴다. GraphQL에 `GraphQlExceptionResolver`로 이 예외나 상위 타입(`NotificationException`, `RuntimeException` 등)을 등록해 자기 code로 답하던 서비스는 그 매핑이 더 쓰이지 않는다(`docs/work/reference/decisions.md` 2.3절 「GraphQL 판정 순서」). 자기 code가 필요하면 이 예외를 감싼 자기 예외로 던지고 그 타입을 등록한다. web `@ExceptionHandler`와 이 예외를 직접 잡던 코드는 그대로 동작한다 | 운영자 화면이 이 code를 모르면 거절을 처리하지 못한다. 5xx만 세던 경보 규칙은 이 거절을 더 보지 않는다. GraphQL의 등록 매핑에 기대던 분기는 code가 바뀌어 깨진다 | 알림 운영자 연산 전송을 연 서비스 | | 2 | suppression이 운영자 tenant 밖의 tenant를 고르면 `AdminTargetNotFoundException`이다. 이 예외는 상태를 싣지 않는다. 거절은 그 tenant의 어떤 것도 읽지 않아서, 답으로 그 tenant가 무엇을 가졌는지 알 수 없다 | `AdminAccessDeniedException`(`required()`는 `SUPPRESS`)이었다. 운영자에게 authority가 없을 때와 같은 예외였다 | 이 경우를 `AdminAccessDeniedException`으로 잡던 코드를 `AdminTargetNotFoundException`으로 바꾼다. `AdminAccessDeniedException`은 이제 authority가 없을 때와 tenant 범위 운영자의 provider 상태 변경에만 난다. 공용 처리기에 맡겼다면 고칠 코드는 없다(web 응답이 404로 바뀐다) | 그 catch가 이 예외를 놓쳐 공용 처리기로 간다. 서비스가 만든 거절 응답 대신 `ADMIN_TARGET_NOT_FOUND`(web은 404)가 나간다 | 알림 운영자 연산 전송을 연 서비스 | | 3 | `AdminAuthorizationGuard.requireTenant(AdminActor, TenantId)`가 authority 인자를 받지 않는다. tenant 밖이면 `AdminTargetNotFoundException`을 던진다 | `requireTenant(AdminActor, TenantId, NotificationAdminAuthority)`가 그 authority를 실은 `AdminAccessDeniedException`을 던졌다 | 이 guard를 자기 연산에 쓰는 서비스는 셋째 인자를 지우고, 거절을 잡던 곳은 2행대로 바꾼다 | 컴파일이 실패한다 | 이 guard를 직접 부르는 서비스 | -| 4 | reconcile 묶음에 없는 attempt id나 운영자 tenant 밖의 attempt가 하나라도 있으면 provider를 부르기 전에 묶음 전체를 `DeliveryAttemptNotFoundException`(404 `DELIVERY_ATTEMPT_NOT_FOUND`, redrive와 같은 답)으로 거절한다. dry run도 같다. operation id를 claim하지 않고 audit도 남기지 않는다. 없는 id와 남의 tenant id가 같은 답이라 다른 tenant에 그 attempt가 있는지 알 수 없다. 통과한 묶음의 처리 수(`affected`)는 묶음의 id 수와 같다 | 없는 id는 건너뛰고도 처리 수에 셌다(dry run은 id 수를 그대로 답했다). 남의 tenant attempt는 `AdminAccessDeniedException(RECONCILE)`이라 web에서 500이었다. 그래서 tenant 범위 운영자가 id를 넣어 보는 것만으로 남의 tenant에 그 attempt가 있는지 알 수 있었다 | 보존 기간이 지나 지워진 attempt id를 섞어 보내던 운영자 도구는 그 id를 빼고 다시 보낸다. 답은 어느 id인지 알려 주지 않으니 묶음을 나눠 보내 찾는다. reconcile의 남의 tenant 거절을 `AdminAccessDeniedException`으로 잡던 코드는 `DeliveryAttemptNotFoundException`으로 바꾼다 | 지워진 id 하나가 묶음 전체를 막는다. 그 catch가 이 예외를 놓쳐 공용 처리기로 가고 `DELIVERY_ATTEMPT_NOT_FOUND`(web은 404)가 나간다 | 알림 운영자 연산 전송을 연 서비스 | +| 4 | reconcile 묶음에 없는 attempt id나 운영자 tenant 밖의 attempt가 하나라도 있으면 provider를 부르기 전에 묶음 전체를 `DeliveryAttemptNotFoundException`(404 `DELIVERY_ATTEMPT_NOT_FOUND`, redrive와 같은 답)으로 거절한다. dry run도 같다. operation id를 claim하지 않고 audit도 남기지 않는다. 없는 id와 남의 tenant id가 같은 답이라 다른 tenant에 그 attempt가 있는지 알 수 없다. 통과한 묶음의 처리 수(`affected`)는 묶음의 id 수와 같다. 이 판정은 operation id claim보다 먼저라, 끝난 operation id를 다시 보내도(replay) 먼저 지난다. 그 사이 attempt가 지워졌으면 저장된 결과 대신 이 404다(redrive도 같다) | 없는 id는 건너뛰고도 처리 수에 셌다(dry run은 id 수를 그대로 답했다). 남의 tenant attempt는 `AdminAccessDeniedException(RECONCILE)`이라 web에서 500이었다. 그래서 tenant 범위 운영자가 id를 넣어 보는 것만으로 남의 tenant에 그 attempt가 있는지 알 수 있었다 | 보존 기간이 지나 지워진 attempt id를 섞어 보내던 운영자 도구는 그 id를 빼고 다시 보낸다. 답은 어느 id인지 알려 주지 않으니 묶음을 나눠 보내 찾는다. reconcile의 남의 tenant 거절을 `AdminAccessDeniedException`으로 잡던 코드는 `DeliveryAttemptNotFoundException`으로 바꾼다 | 지워진 id 하나가 묶음 전체를 막는다. 그 catch가 이 예외를 놓쳐 공용 처리기로 가고 `DELIVERY_ATTEMPT_NOT_FOUND`(web은 404)가 나간다 | 알림 운영자 연산 전송을 연 서비스 | ## 3. 바뀌지 않은 것 @@ -44,7 +44,9 @@ - authority는 대상을 읽기 전에 본다. 그래서 403은 대상에 대해 아무것도 알려 주지 않는다. - reconcile 묶음에 같은 id를 두 번 넣으면 전처럼 provider에 두 번 묻고 두 번 센다. - 같은 operation id·같은 요청은 전처럼 저장된 결과를 돌려준다. -- carrier가 아닌 실패는 공용 처리기가 전처럼 500으로 답한다(web `GlobalExceptionHandler`). +- carrier가 아닌 실패는 공용 처리기가 전처럼 500으로 답한다(web `GlobalExceptionHandler`). 운영자 연산에서도 위 다섯 밖의 + 거절은 그대로다. provider 상태 연산이 runtime이 받아들이지 않은 변경(`ProviderConfigurationException`)이나 없는 profile을 + 받으면 전처럼 500과 ERROR 로그다. - 오류 code 목록(`NotificationFailureCode`)과 템플릿 오류 code registry(`docs/registries/error-codes.yaml`)는 그대로다. 응답 code는 전송이 읽는 `NotificationAdminErrorCode`에 두었다. 예외의 descriptor는 알림 code 목록 값이라 descriptor code와 응답 code가 다르다. @@ -55,5 +57,7 @@ 다섯 예외의 carrier 구현, `NotificationAdminErrorCode`의 다섯 행, `AdminTargetNotFoundException`, `requireTenant`의 인자, reconcile의 묶음 판정, 문서와 API surface 기준선 행을 함께 revert하고, 이 문서에 되돌린 행을 더한다. operation id 재사용만 409로 바꾸려면 -`ADMIN_OPERATION_CONFLICT`를 `(409, Category.CONFLICT, false)`로 바꾸고, 시험 행과 이 문서·`docs/web/http-contract.md` -4절·`docs/notification/operations.md`의 422를 409로 고친다. +`ADMIN_OPERATION_CONFLICT`를 `(409, Category.CONFLICT, false)`로 바꾸고, 시험 행, 그 enum 상수와 +`AdminOperationConflictException`의 Javadoc, 이 문서·`docs/web/http-contract.md` 4절·`docs/notification/operations.md`· +`docs/work/reference/decisions.md` 2.3절의 422를 409로 고친다. 진행 중을 retryable true로 바꾸려면 claim에 만료가 먼저 +있어야 한다. diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index cfc62b4c..79b04239 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -206,7 +206,7 @@ HTTP가 그대로 답하는 코드(알림 운영자 연산 거절, `IDEMPOTENCY_ | `ADMIN_TARGET_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | 알림 운영자 suppression이 운영자 tenant 밖의 tenant를 골랐다. 권한 거절(403)이 아니라 없는 대상과 같은 404라 그 tenant가 무엇을 가졌는지 알려 주지 않는다 | | `DUPLICATE_RISK_APPROVAL_REQUIRED` | 409 | `CONFLICT` | `false` | 없음 | 이미 사용자에게 닿았을 수 있는 attempt의 redrive가 중복 위험 승인 없이 왔다. 같은 요청은 다시 거절된다. 승인을 붙여 보낸다 | | `ADMIN_OPERATION_CONFLICT` | 422 | `VALIDATION` | `false` | 없음 | 알림 운영자 연산의 operation id(그 연산의 멱등 키)가 전에 다른 요청에 쓰였다. 같은 멱등 키·다른 요청이라 409가 아니다(`docs/manual/06-errors.md`). 새 operation id를 쓴다 | -| `ADMIN_OPERATION_IN_PROGRESS` | 409 | `CONFLICT` | `true` | 없음 | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다. 기다렸다가 같은 요청을 다시 보내면 끝난 결과가 온다. 2절의 `IDEMPOTENT_IN_FLIGHT`와 달리 `Retry-After`를 싣지 않는다 | +| `ADMIN_OPERATION_IN_PROGRESS` | 409 | `CONFLICT` | `false` | 없음 | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다. 기다렸다가 같은 요청을 다시 보내면 끝난 결과가 온다. 다만 claim에 만료가 없어서 provider 호출 중에 프로세스가 멈춘 reconcile의 id는 끝나지 않는다. 그래서 2절의 `IDEMPOTENT_IN_FLIGHT`(lease가 끝나면 풀린다)와 달리 retryable이 `false`이고 `Retry-After`도 없다. 오래 가면 새 operation id를 쓴다 | | `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)`)은 요청 본문 위반과 같은 diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index 23209c9f..a6952936 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -113,7 +113,7 @@ | 알림 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-23에 아래 「알림 운영자 연산의 거절」·「알림 reconcile의 없는·남의 attempt」 행이 바꿨다) | 기본값(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절 | -| 알림 운영자 연산의 거절 | 운영자 입력 거절 다섯을 carrier로 답한다. code는 기능 enum `NotificationAdminErrorCode`다: authority 없음 403 `ADMIN_ACCESS_DENIED`, suppression의 tenant 밖 대상 404 `ADMIN_TARGET_NOT_FOUND`(권한 거절이 아니라 없는 대상과 같은 답), 중복 위험 승인 없음 409 `DUPLICATE_RISK_APPROVAL_REQUIRED`, operation id 재사용 422 `ADMIN_OPERATION_CONFLICT`, 같은 id 진행 중 409 `ADMIN_OPERATION_IN_PROGRESS`(retryable true, `Retry-After` 없음). 요청의 표는 재사용을 409로 적었지만, 같은 멱등 키·다른 요청은 422라는 `docs/manual/06-errors.md` 판단 표와 executor 선례(`IDEMPOTENT_REQUEST_MISMATCH`)를 따라 422로 했다. 문서만 500으로 고치는 안과 web 처리기에서 이름으로 잡는 안은 버렸다. 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다 | 기본값(2026-11-23, review 허브가 고른 권하는 안, 자율 운영. 422는 백엔드 개발자가 매뉴얼에 맞춘 것이고 review 판정을 받는다. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0058 요청(2026-11-23 09:40), `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절 | +| 알림 운영자 연산의 거절 | 운영자 입력 거절 다섯을 carrier로 답한다. code는 기능 enum `NotificationAdminErrorCode`다: authority 없음 403 `ADMIN_ACCESS_DENIED`, suppression의 tenant 밖 대상 404 `ADMIN_TARGET_NOT_FOUND`(권한 거절이 아니라 없는 대상과 같은 답), 중복 위험 승인 없음 409 `DUPLICATE_RISK_APPROVAL_REQUIRED`, operation id 재사용 422 `ADMIN_OPERATION_CONFLICT`, 같은 id 진행 중 409 `ADMIN_OPERATION_IN_PROGRESS`(retryable false, `Retry-After` 없음: claim에 만료가 없어 provider 호출 중 멈춘 reconcile의 id는 끝나지 않는다. 다시 보내도 되는지는 code가 알린다). 요청의 표는 재사용을 409로 적었지만, 같은 멱등 키·다른 요청은 422라는 `docs/manual/06-errors.md` 판단 표와 executor 선례(`IDEMPOTENT_REQUEST_MISMATCH`)를 따라 422로 했다. 문서만 500으로 고치는 안과 web 처리기에서 이름으로 잡는 안은 버렸다. 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다 | 기본값(2026-11-23, review 허브가 고른 권하는 안, 자율 운영. 422는 백엔드 개발자가 매뉴얼에 맞춘 것이고 review 판정을 받는다. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0058 요청(2026-11-23 09:40), `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절 | | 알림 reconcile의 없는·남의 attempt | reconcile 묶음에 없는 attempt id나 운영자 tenant 밖의 attempt가 하나라도 있으면 provider를 부르기 전에 묶음 전체를 redrive와 같은 404 carrier(`DeliveryAttemptNotFoundException`)로 거절한다. dry run도 같다. 처리 수는 묶음의 id 수다. 대가로 보존 기간이 지나 지워진 id가 섞인 묶음도 거절된다. 없는 id와 남의 id를 둘 다 건너뛰고 있는 것만 세는 안(「남의 id가 있으면 아무것도 안 바꾼다」가 깨지고 오타가 성공으로 보인다)과 지금대로 두는 안(존재가 드러난다)은 버렸다 | 기본값(2026-11-23, review 허브가 고른 권하는 안, 자율 운영. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0059 요청(2026-11-23 09:40), `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절 4행 | | 오류 코드 로그 레벨 | `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 | diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java index 6becbeba..9b65109a 100644 --- a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java @@ -211,7 +211,8 @@ class NotificationAdminRefusalHttpAnswerTest { /** * Each refusal answers its own status and code with the category's fixed message, and the handler * records none as a server failure. A missing authority (403) and a target outside the operator's - * tenant (404) are different answers; only the busy operation id may be sent again. + * tenant (404) are different answers. None is retryable: a busy operation id may never be + * released, so it is the code, not the flag, that tells an operator to send it again later. */ @ParameterizedTest(name = "{0}") @MethodSource("refusals") @@ -285,7 +286,7 @@ class NotificationAdminRefusalHttpAnswerTest { 409, "ADMIN_OPERATION_IN_PROGRESS", Category.CONFLICT, - true)); + false)); } /** The answer of a 404 with {@code code}, recorded as no server failure. */ diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationInProgressException.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationInProgressException.java index 4f393846..0c5add53 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationInProgressException.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationInProgressException.java @@ -7,8 +7,9 @@ import dev.caskeleton.shared.error.ApiErrorCode; * The same admin operation id is currently held by another caller. * *

Nothing is wrong with the request, it arrived while the first one runs: a transport answers - * {@link NotificationAdminErrorCode#ADMIN_OPERATION_IN_PROGRESS} (409, retryable) and logs no - * server failure. The same request sent again after the first finishes answers its stored result. + * {@link NotificationAdminErrorCode#ADMIN_OPERATION_IN_PROGRESS} (409) and logs no server failure. + * The same request sent again after the first finishes answers its stored result. The code is not + * retryable, because an id whose holder stopped stays held (see the code). */ final class AdminOperationInProgressException extends RuntimeException implements ApiErrorCarrier { diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java index 8c277f58..11cab6b2 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java @@ -6,9 +6,10 @@ import dev.caskeleton.shared.error.Category; /** * Codes the notification operator operations answer a transport with. * - *

Every refusal of an operator operation is the operator's own input — an authority they do not - * hold, a target out of their reach, an unapproved duplicate risk, a reused or busy operation id — - * so each is a client error, not a server fault. + *

Each refusal below is the operator's own input — an authority they do not hold, a target out + * of their reach, an unapproved duplicate risk, a reused or busy operation id — so each is a client + * error, not a server fault. A refusal with no code here, such as a provider state change the + * runtime does not accept, is still answered as a server failure. * *

The closed {@code NotificationFailureCode} registry is the platform's own vocabulary — metric * tags, ledger rows, audit — and has no code for most of these. A transport answers with this code @@ -50,8 +51,13 @@ public enum NotificationAdminErrorCode implements ApiErrorCode { /** * Another caller holds the same operation id for the same request and has not finished. Sending * the same request again once it finishes answers its result. + * + *

Not retryable: the claim has no expiry, so a reconcile whose process stopped during its + * provider calls holds its operation id for good, and a client retrying on its own would never + * stop. An operator sends the request again after a while, and under a new operation id if it + * stays busy. */ - ADMIN_OPERATION_IN_PROGRESS(409, Category.CONFLICT, true); + ADMIN_OPERATION_IN_PROGRESS(409, Category.CONFLICT, false); private final int httpStatus; private final Category category; diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java index db55bd83..bd945826 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java @@ -25,7 +25,7 @@ import java.util.Optional; * outside the operator's tenant scope get one answer for the whole batch, the one a redrive gives: * {@link DeliveryAttemptNotFoundException}. A tenant-scoped operator cannot tell which ids exist in * other tenants, a batch with one such id changes nothing and claims no operation id, and the - * result counts only attempts that were reconciled. The price: a batch that names an attempt + * result counts one per id a provider was asked about. The price: a batch that names an attempt * already removed by retention is refused whole, and is sent again without that id. * *

The provider calls run with no transaction open: each one asks over the network, and inside a @@ -81,8 +81,9 @@ public class ReconcileDeliveriesUseCase ReconcileRequest request = batch.request(); AdminActor actor = batch.actor(); authorization.require(actor, NotificationAdminAuthority.RECONCILE); - // Read in a read transaction of its own: the providers are asked with none open, so the tenant - // check cannot share the boundary the answers are recorded in. + // Read in a read transaction of its own: the providers are asked with none open, so the + // existence + // and tenant check cannot share the boundary the answers are recorded in. transactions.inRead( () -> { for (DeliveryAttemptId attemptId : request.attemptIds()) { diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java index 2ed1c57c..cc101f2c 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java @@ -274,6 +274,52 @@ class NotificationAdminUseCasesTest { new UnreachableReconcile("global operator, unknown id, dry run", global, false, true)); } + /** + * The authority is checked before any attempt of the batch is read: an operator without it is + * refused for that, whether the batch names an id no attempt has or another tenant's attempt, so + * the refusal does not tell which ids exist. + */ + @ParameterizedTest(name = "foreign attempt={0}") + @ValueSource(booleans = {false, true}) + void aReconcileWithoutTheAuthorityIsRefusedBeforeItsAttemptsAreLookedUp(boolean foreign) { + // given + AtomicInteger providerCalls = new AtomicInteger(); + Fixture fixture = new Fixture(countingProvider(providerCalls)); + DeliveryAttemptSnapshot foreignAttempt = attemptOf(new TenantId("tenant-a")); + AttemptSnapshots.store( + fixture.requests, fixture.attempts, foreignAttempt, RecipientDeliveryState.DISPATCHING); + AdminActor withoutReconcile = + new AdminActor( + "operator-b", + EnumSet.complementOf(EnumSet.of(NotificationAdminAuthority.RECONCILE)), + Optional.of(new TenantId("tenant-b"))); + ReconcileRequest request = + new ReconcileRequest( + "op-rc-no-authority", + List.of(foreign ? foreignAttempt.attemptId() : UNKNOWN_ATTEMPT), + "stuck attempt", + false); + + // when + Throwable failure = + catchThrowable( + () -> + fixture.reconcile.handle( + new ReconcileDeliveriesCommand(request, withoutReconcile))); + + // then + assertThat(failure) + .as("refused with AdminAccessDeniedException(RECONCILE), not answered as unreachable") + .isInstanceOfSatisfying( + AdminAccessDeniedException.class, + denied -> + assertThat( + List.of( + denied.required(), providerCalls.get(), fixture.operations.claims)) + .as("[required authority, provider calls, claims]") + .containsExactly(NotificationAdminAuthority.RECONCILE, 0, 0)); + } + /** A batch the operator may act on in full reports one affected attempt per id it named. */ @ParameterizedTest(name = "dryRun={0}") @ValueSource(booleans = {false, true}) -- 2.54.0 From f31e6941ac37f18e3adf988006674aa8db0cb76c Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 21:42:06 +0900 Subject: [PATCH 4/5] =?UTF-8?q?docs(notification):=20reconcile=20=EC=B2=98?= =?UTF-8?q?=EB=A6=AC=20=EC=88=98=EC=99=80=20=EC=A7=84=ED=96=89=20=EC=A4=91?= =?UTF-8?q?=20=EB=B9=84=EA=B5=90=20=EB=AC=B8=EC=9E=A5=EC=9D=84=20=EC=BD=94?= =?UTF-8?q?=EB=93=9C=EC=97=90=20=EB=A7=9E=EC=B6=98=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 확인 리뷰(종류 B, 리뷰어 하나)가 낸 Low를 고친다. 동작은 바꾸지 않는다. - ReconcileDeliveriesUseCase 클래스 주석이 처리 수를 「provider에 물어본 id마다 하나」라고 적었다. dry run은 provider에 묻지 않고 id 수를 답하고, 실제 실행도 provider가 지원하지 않아 묻지 않은 id까지 센다. 「묶음이 든 id마다 하나」로 고쳤다. NotificationAdminUseCasesTest의 aReconcileOfReachableAttemptsReportsEveryIdItNamed가 dry run에서 affected 2· provider 호출 0을 단언하는 그대로다. - 서식기가 접어 한 단어만 남은 읽기 블록 주석 줄을 다시 접었다. - upgrade 3절의 「위 다섯 밖의 거절은 그대로다」는 reconcile의 없는·남의 id (4행)와 어긋나 「2.1절이 다루지 않은 거절」로, 같은 id 두 번은 「두 번 묻고」가 아니라 「두 번 처리하고」로 고쳤다. - http-contract 4절이 IDEMPOTENT_IN_FLIGHT를 「lease가 끝나면 풀린다」고 적었다. 같은 문서 2절대로 Redis는 lease가 지나면 409 대신 500 IDEMPOTENCY_RECOVERY_REQUIRED라서 「lease가 지나면 409가 끝난다」로 고쳤다. 위험·한계: 직전 리뷰 반영 커밋(22823730) 본문의 「직전 커밋(b282b63d8)」은 두 커밋 앞을 가리키는 말이었다. amend하지 않고 PR 본문에 적는다. 검증: check-docs.py·check-work-docs.py OK, 서식은 노트북 감싸개 :application-notification:spotlessApply rc=0. 게이트는 이 head에서 돌린다. Refs: REV-BE-0058, REV-BE-0059 --- docs/upgrade/2026-11-notification-admin-refusals.md | 6 +++--- docs/web/http-contract.md | 2 +- .../platform/admin/ReconcileDeliveriesUseCase.java | 7 +++---- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/docs/upgrade/2026-11-notification-admin-refusals.md b/docs/upgrade/2026-11-notification-admin-refusals.md index e4efd1fb..b86865cc 100644 --- a/docs/upgrade/2026-11-notification-admin-refusals.md +++ b/docs/upgrade/2026-11-notification-admin-refusals.md @@ -42,10 +42,10 @@ - redrive의 없는 attempt id와 남의 tenant attempt는 전처럼 404 `DELIVERY_ATTEMPT_NOT_FOUND`다 (`docs/upgrade/2026-11-notification-admin-redrive.md` 2.1절). - authority는 대상을 읽기 전에 본다. 그래서 403은 대상에 대해 아무것도 알려 주지 않는다. -- reconcile 묶음에 같은 id를 두 번 넣으면 전처럼 provider에 두 번 묻고 두 번 센다. +- reconcile 묶음에 같은 id를 두 번 넣으면 전처럼 그 id를 두 번 처리하고 두 번 센다. - 같은 operation id·같은 요청은 전처럼 저장된 결과를 돌려준다. -- carrier가 아닌 실패는 공용 처리기가 전처럼 500으로 답한다(web `GlobalExceptionHandler`). 운영자 연산에서도 위 다섯 밖의 - 거절은 그대로다. provider 상태 연산이 runtime이 받아들이지 않은 변경(`ProviderConfigurationException`)이나 없는 profile을 +- carrier가 아닌 실패는 공용 처리기가 전처럼 500으로 답한다(web `GlobalExceptionHandler`). 운영자 연산에서도 2.1절이 다루지 + 않은 거절은 그대로다. provider 상태 연산이 runtime이 받아들이지 않은 변경(`ProviderConfigurationException`)이나 없는 profile을 받으면 전처럼 500과 ERROR 로그다. - 오류 code 목록(`NotificationFailureCode`)과 템플릿 오류 code registry(`docs/registries/error-codes.yaml`)는 그대로다. 응답 code는 전송이 읽는 `NotificationAdminErrorCode`에 두었다. 예외의 descriptor는 알림 code 목록 값이라 diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index 79b04239..73d541d1 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -206,7 +206,7 @@ HTTP가 그대로 답하는 코드(알림 운영자 연산 거절, `IDEMPOTENCY_ | `ADMIN_TARGET_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | 알림 운영자 suppression이 운영자 tenant 밖의 tenant를 골랐다. 권한 거절(403)이 아니라 없는 대상과 같은 404라 그 tenant가 무엇을 가졌는지 알려 주지 않는다 | | `DUPLICATE_RISK_APPROVAL_REQUIRED` | 409 | `CONFLICT` | `false` | 없음 | 이미 사용자에게 닿았을 수 있는 attempt의 redrive가 중복 위험 승인 없이 왔다. 같은 요청은 다시 거절된다. 승인을 붙여 보낸다 | | `ADMIN_OPERATION_CONFLICT` | 422 | `VALIDATION` | `false` | 없음 | 알림 운영자 연산의 operation id(그 연산의 멱등 키)가 전에 다른 요청에 쓰였다. 같은 멱등 키·다른 요청이라 409가 아니다(`docs/manual/06-errors.md`). 새 operation id를 쓴다 | -| `ADMIN_OPERATION_IN_PROGRESS` | 409 | `CONFLICT` | `false` | 없음 | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다. 기다렸다가 같은 요청을 다시 보내면 끝난 결과가 온다. 다만 claim에 만료가 없어서 provider 호출 중에 프로세스가 멈춘 reconcile의 id는 끝나지 않는다. 그래서 2절의 `IDEMPOTENT_IN_FLIGHT`(lease가 끝나면 풀린다)와 달리 retryable이 `false`이고 `Retry-After`도 없다. 오래 가면 새 operation id를 쓴다 | +| `ADMIN_OPERATION_IN_PROGRESS` | 409 | `CONFLICT` | `false` | 없음 | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다. 기다렸다가 같은 요청을 다시 보내면 끝난 결과가 온다. 다만 claim에 만료가 없어서 provider 호출 중에 프로세스가 멈춘 reconcile의 id는 끝나지 않는다. 그래서 2절의 `IDEMPOTENT_IN_FLIGHT`(lease가 지나면 409가 끝난다)와 달리 retryable이 `false`이고 `Retry-After`도 없다. 오래 가면 새 operation id를 쓴다 | | `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)`)은 요청 본문 위반과 같은 diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java index bd945826..f153c67c 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/ReconcileDeliveriesUseCase.java @@ -25,8 +25,8 @@ import java.util.Optional; * outside the operator's tenant scope get one answer for the whole batch, the one a redrive gives: * {@link DeliveryAttemptNotFoundException}. A tenant-scoped operator cannot tell which ids exist in * other tenants, a batch with one such id changes nothing and claims no operation id, and the - * result counts one per id a provider was asked about. The price: a batch that names an attempt - * already removed by retention is refused whole, and is sent again without that id. + * result counts one per id the batch names. The price: a batch that names an attempt already + * removed by retention is refused whole, and is sent again without that id. * *

The provider calls run with no transaction open: each one asks over the network, and inside a * write transaction it held a pooled connection for as long as the provider took, once per attempt. @@ -82,8 +82,7 @@ public class ReconcileDeliveriesUseCase AdminActor actor = batch.actor(); authorization.require(actor, NotificationAdminAuthority.RECONCILE); // Read in a read transaction of its own: the providers are asked with none open, so the - // existence - // and tenant check cannot share the boundary the answers are recorded in. + // existence and tenant check cannot share the boundary the answers are recorded in. transactions.inRead( () -> { for (DeliveryAttemptId attemptId : request.attemptIds()) { -- 2.54.0 From dfa4be20e6f695601f76fef9de8885d3cf8c22fa Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 22:18:35 +0900 Subject: [PATCH 5/5] =?UTF-8?q?docs(decisions):=20=EC=9A=B4=EC=98=81?= =?UTF-8?q?=EC=9E=90=20operation=20id=20=EC=9E=AC=EC=82=AC=EC=9A=A9=20422?= =?UTF-8?q?=EA=B0=80=20review=EC=97=90=EC=84=9C=20=ED=99=95=EC=A0=95?= =?UTF-8?q?=EB=90=90=EB=8B=A4=EA=B3=A0=20=EC=A0=81=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 결정 색인 2.3절 「알림 운영자 연산의 거절」 행은 operation id 재사용 422를 「review 판정을 받는다」고 적었다. review가 2026-11-23 21시대 메시지로 422를 확정했다(요청 표 09:40이 docs/manual/06-errors.md 판단 표보다 먼저 쓰여 표 쪽이 틀렸다고 봤다). 낡은 말을 확정으로 고친다. 동작은 바꾸지 않는다. 검증: check-docs.py·check-work-docs.py OK. Refs: REV-BE-0058 --- docs/work/reference/decisions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index a6952936..1e0e0330 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -113,7 +113,7 @@ | 알림 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-23에 아래 「알림 운영자 연산의 거절」·「알림 reconcile의 없는·남의 attempt」 행이 바꿨다) | 기본값(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절 | -| 알림 운영자 연산의 거절 | 운영자 입력 거절 다섯을 carrier로 답한다. code는 기능 enum `NotificationAdminErrorCode`다: authority 없음 403 `ADMIN_ACCESS_DENIED`, suppression의 tenant 밖 대상 404 `ADMIN_TARGET_NOT_FOUND`(권한 거절이 아니라 없는 대상과 같은 답), 중복 위험 승인 없음 409 `DUPLICATE_RISK_APPROVAL_REQUIRED`, operation id 재사용 422 `ADMIN_OPERATION_CONFLICT`, 같은 id 진행 중 409 `ADMIN_OPERATION_IN_PROGRESS`(retryable false, `Retry-After` 없음: claim에 만료가 없어 provider 호출 중 멈춘 reconcile의 id는 끝나지 않는다. 다시 보내도 되는지는 code가 알린다). 요청의 표는 재사용을 409로 적었지만, 같은 멱등 키·다른 요청은 422라는 `docs/manual/06-errors.md` 판단 표와 executor 선례(`IDEMPOTENT_REQUEST_MISMATCH`)를 따라 422로 했다. 문서만 500으로 고치는 안과 web 처리기에서 이름으로 잡는 안은 버렸다. 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다 | 기본값(2026-11-23, review 허브가 고른 권하는 안, 자율 운영. 422는 백엔드 개발자가 매뉴얼에 맞춘 것이고 review 판정을 받는다. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0058 요청(2026-11-23 09:40), `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절 | +| 알림 운영자 연산의 거절 | 운영자 입력 거절 다섯을 carrier로 답한다. code는 기능 enum `NotificationAdminErrorCode`다: authority 없음 403 `ADMIN_ACCESS_DENIED`, suppression의 tenant 밖 대상 404 `ADMIN_TARGET_NOT_FOUND`(권한 거절이 아니라 없는 대상과 같은 답), 중복 위험 승인 없음 409 `DUPLICATE_RISK_APPROVAL_REQUIRED`, operation id 재사용 422 `ADMIN_OPERATION_CONFLICT`, 같은 id 진행 중 409 `ADMIN_OPERATION_IN_PROGRESS`(retryable false, `Retry-After` 없음: claim에 만료가 없어 provider 호출 중 멈춘 reconcile의 id는 끝나지 않는다. 다시 보내도 되는지는 code가 알린다). 요청의 표는 재사용을 409로 적었지만, 같은 멱등 키·다른 요청은 422라는 `docs/manual/06-errors.md` 판단 표와 executor 선례(`IDEMPOTENT_REQUEST_MISMATCH`)를 따라 422로 했다. 문서만 500으로 고치는 안과 web 처리기에서 이름으로 잡는 안은 버렸다. 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다 | 기본값(2026-11-23, review 허브가 고른 권하는 안, 자율 운영. 422는 백엔드 개발자가 매뉴얼에 맞췄고 review가 2026-11-23에 확정했다(요청 표가 판단 표보다 먼저 쓰였다). 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0058 요청(2026-11-23 09:40), `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절 | | 알림 reconcile의 없는·남의 attempt | reconcile 묶음에 없는 attempt id나 운영자 tenant 밖의 attempt가 하나라도 있으면 provider를 부르기 전에 묶음 전체를 redrive와 같은 404 carrier(`DeliveryAttemptNotFoundException`)로 거절한다. dry run도 같다. 처리 수는 묶음의 id 수다. 대가로 보존 기간이 지나 지워진 id가 섞인 묶음도 거절된다. 없는 id와 남의 id를 둘 다 건너뛰고 있는 것만 세는 안(「남의 id가 있으면 아무것도 안 바꾼다」가 깨지고 오타가 성공으로 보인다)과 지금대로 두는 안(존재가 드러난다)은 버렸다 | 기본값(2026-11-23, review 허브가 고른 권하는 안, 자율 운영. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0059 요청(2026-11-23 09:40), `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절 4행 | | 오류 코드 로그 레벨 | `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 | -- 2.54.0