refactor(application)!: 시스템 쓰기와 운영자 연산을 유스케이스 계약 안으로 옮긴다
pr / done (pull_request) Canceled after 0s

시스템이 부르는 쓰기가 유스케이스 계약 밖에 있다. fileserver 정리·맞추기,
알림 claim·발송·lease 회복·맞추기·provider event replay는 capability도
트랜잭션 선언도 없는 서비스를 worker가 바로 부르고, 그 worker와 조립은
outbound adapter 안에 있다. 알림 운영자 연산 넷은 permission 없이 서비스
하나에 모여 있고 재시도 시각은 상수다. web stream bridge는 outbound가
구현한 replay 포트를 바로 읽는다. fileserver 관리 HTTP 기본값은
controller가 정한다.

고른 방법: 시스템 쓰기는 @SystemInvoked 유스케이스로 나누고 composition
worker 설정이 new로 만든다(bean 아님). 알림 worker와 fileserver 정리 조립은
composition으로 옮기고, 맞추기의 재시도·포기 시점은 유스케이스가 정한다.
운영자 연산은 platform.admin의 유스케이스 클래스 넷과 notification-admin:*
permission이다(port.in 인터페이스는 port.in과 admin의 cycle을 만들어 두지
않는다). replay 읽기는 조회 유스케이스 둘을 거치고 포트는
LiveEventReplayQueryPort로 이름을 바꾼다. 아키텍처 규칙 둘: 사용자 전송은
저장·id 포트를 쥐지 못하고, inbound는 application 서비스·coordinator를
interface로도 쥐지 못한다. 재시도 시각은 설정, 관리 기본값은 command
팩터리다. 재시도 시각의 규칙은 policy의 값 RetryTiming 하나가 갖고 설정은
그 값을 만든다. retry·routing 값들은 서버가 만드는 값이라 잘못된 값을
IllegalStateException으로 거절한다(manual 06). 모듈 기본값이 role notification-admin에 운영자 permission
넷을 준다(fileserver의 ROLE_FILE_ADMIN과 같다). 버린 대안: 서비스에
@UseCaseCapability만 달기(사용자와 시스템이 같은 진입점을 나눠 써서 권한
규칙이 막지 못한다), 운영자 서비스 삭제, 설정에서 policy를 만들어 버리며
검증하기(규칙이 바뀐 policy bean과 상관없이 남는다).

위험·한계: 공개 타입·생성자·bean 이름·아키텍처 규칙이 바뀐다. 파생
서비스가 할 일은 docs/upgrade/2026-11-round9-application.md 1~3·5·6행이다.
claim·fence 커밋 위에 쌓았다.

검증: PR 본문의 desktop 결과.

Refs: RR9-05-06, RR9-05-07, RR9-05-08, RR9-05-10, RR9-05-19
BREAKING CHANGE: NotificationAdminService·NotificationAdminApplicationService가 없어지고 운영자 연산은 platform.admin의 RedriveDeliveryUseCase 등이다(permission notification-admin:*). 알림 worker가 composition:notification-platform으로 옮기고 ReconciliationJobWorker·ProviderEventReplayWorker는 유스케이스가 됐다. MessagingReplayBridge 생성자가 조회 유스케이스를 받고 LiveEventReplayPort는 LiveEventReplayQueryPort다. 사용자 전송이 저장·id 포트나 application 서비스 interface를 쥐면 architectureTest가 실패한다. 운영자 요청 record 이름이 *Request로 바뀌고 DefaultNotificationRetryPolicy 생성자가 RetryTiming을 받는다. RetryBackoff·RetryBudget·RetryContext·RetryDecision.RetryAfter·RouteCandidate·RoutingContext·RoutingDecision·EligibilityResult가 잘못된 값에 IllegalStateException을 던진다.
This commit is contained in:
DongHyeonka
2026-11-13 16:37:03 +09:00
parent e60408e931
commit 2d274a6842
143 changed files with 4251 additions and 1383 deletions
+1 -1
View File
@@ -211,7 +211,7 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap
| cache 정책 카탈로그 (`WebCachePolicyCatalog`, `WebCachePolicy`, `WebVaryPolicy`, `WebCacheHeaders`)와 테스트 | `W/cache/` (W3-2에서 web-advanced로 옮긴 뒤 삭제) | `208077fd` | 한 기능에 한 세대: 운영은 `CacheControlFilter` |
| JSON mapper factory (`WebObjectMapperFactory`, `WebJsonProfile`, `BoundedJsonFactory`)와 테스트 | `W/json/` (W3-2에서 web-advanced로 옮긴 뒤 삭제) | `208077fd` | 한 기능에 한 세대: 운영은 Boot `JsonMapper` + `spring.jackson.*`. 스트리밍 encoder는 Boot `JsonMapper` bean을 받도록 변경 |
| OpenAPI customizer (`WebOpenApiCustomizer`, `WebOpenApiProfile`, `CursorSchemaContributor`)와 `WebOpenApiSnapshotTest` | `W/openapi/` 의 해당 3개 파일 (W3-2에서 web-advanced로 옮긴 뒤 삭제) | `208077fd` | 한 기능에 한 세대: 운영은 springdoc + `OpenApiContractConfig`. `CursorPage` 스키마는 이미 삭제된 커서 페이지네이션을 설명 |
| realtime 포트 (`ConnectionRegistryPort`, `DurableFanoutPort` 외 7개 타입)와 Redis 연결 레지스트리 (`RedisConnectionRegistryAdapter`) | `src/application-core/src/main/java/dev/caskeleton/application/realtime/`, `src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/` | `208077fd` | 소비자 0 (websocket 정리 후 호출자 없음, bean 없음). `LiveEventReplayPort` 계열은 유지 |
| realtime 포트 (`ConnectionRegistryPort`, `DurableFanoutPort` 외 7개 타입)와 Redis 연결 레지스트리 (`RedisConnectionRegistryAdapter`) | `src/application-core/src/main/java/dev/caskeleton/application/realtime/`, `src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/` | `208077fd` | 소비자 0 (websocket 정리 후 호출자 없음, bean 없음). `LiveEventReplayQueryPort` 계열은 유지 |
| graphql `advanced/**` 전체 (15개 패키지, 130개, ~5,600줄) + 테스트 | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/` | `208077fd` | 모든 진입점이 `GraphQlAdvancedModuleGuard`를 거치는데 그 플래그(`GraphQlAdvancedFeatureFlags`)를 바인딩하는 코드가 없다. Spring GraphQL/graphql-java SPI를 구현한 타입이 없어 SSE·RSocket·federation·incremental·GET·chaining은 이름만 있는 모델. `GraphQlReplaySource`·`GraphQlPersistedOperationAdminPort`는 구현체 없는 인터페이스, persisted 레지스트리가 기대는 `OperationalRecordStorePort`도 구현체 0. composition/incremental/bootstrap은 gate·등급 코드 |
| `backend.graphql.unsupported.*` 6개 키 (`GraphQlPlatformSettings.Unsupported`, `withUnsupportedCapability`, 검증기 분기) | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformSettings.java`, `GraphQlPlatformStartupValidator.java` | `208077fd` | 켜면 부팅 실패만 한다. 구현하지 않은 기능에는 설정 키를 두지 않는다(AGENTS 기준 3) |
| `backend.graphql.cursor.key-ids` (`GraphQlPlatformSettings.Cursor`, `withCursorKeyIds`) | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformSettings.java` | `208077fd` | 읽는 곳이 등록되지 않은 actuator 보고서뿐. 커서 서명은 라이브러리(`HmacGraphQlCursorCodec`)를 서비스가 직접 조립한다 |
+10 -3
View File
@@ -193,9 +193,16 @@ transport가 닿는 모든 연산은 `application.fileserver.port.in`의 메서
`BlockingTransferExecutor`가 요청의 context를 worker로 옮긴다(`BlockingTransferExecutorSecurityContextTest`).
이것이 없으면 인증한 append가 익명으로 거부됐다.
use case가 아닌 것은 어떤 transport도 부르지 않는 것이다. `CleanupService`와 `FileReconciliationService`는
호출자 신원이 없는 백그라운드 worker가 돌린다. 상태를 바꾸는 use case는 scheduler가 가질 수 없는 권한을
선언해야 한다. `FileserverUseCaseContractDeviationTest`가 그 목록을 고정한다.
백그라운드 worker가 하는 쓰기도 use case다. 다만 사용자 것과 따로다. `FileserverCleanupWorker`는 호출자 신원이 없는
scheduler 스레드에서 돌므로 `@SystemInvoked` use case 둘(`RunScheduledCleanupUseCase`,
`ReconcileRecoverableFilesUseCase`)을 `new`로 만들어 쥔다. bean이 아니어서 transport가 닿지 못한다. 운영자가 같은
cleanup을 돌리는 길은 `file:admin`을 선언한 `CleanupUploadsUseCase`다(2026-11-13).
use case가 아닌 것은 그 use case들이 쥔 협력 객체다. `CleanupService`(`DefaultCleanupService`),
`FileReconciliationService`(`DefaultFileReconciliationService`), `WriterLeaseCoordinator`다. 이 서비스들은
`composition:fileserver-platform`이 bean으로 조립한다. 권한 검사 없이 쓰는 bean이라, inbound adapter가 interface로라도
쥐면 `INBOUND_ADAPTERS_DEPEND_ON_PORTS_NOT_APPLICATION_SERVICES`가 빌드를 실패시킨다(2026-11-13부터 interface와
coordinator도 본다). `FileserverUseCaseContractDeviationTest`가 그 목록을 고정한다.
`FileserverErrorCode`의 HTTP 상태 어휘는 애플리케이션 계층에 남는다. 이 절이 예전에 든 이유 그대로다:
servlet transport와 Nginx 위임 경로가 같은 실패에 다른 상태로 답하면 안 된다.
+4 -3
View File
@@ -91,7 +91,7 @@ client가 같은 이름의 역할을 정의해도 이 서비스 권한이 되지
| 경로 | 어디에 두나 | 유스케이스는 누가 만드나 |
| --- | --- | --- |
| 조립 모듈의 스케줄러 | `composition:*` leaf. 예: outbox relay(`src/bootstrap/outbox-relay`) | 조립 모듈의 `@Bean` 메서드가 `new`로 만들어 스케줄러에 넘긴다 |
| 조립 모듈의 스케줄러 | `composition:*` leaf. 예: outbox relay(`src/bootstrap/outbox-relay`), 알림 worker(`NotificationWorkerConfiguration`), fileserver cleanup worker(`FileserverCleanupWorker`) | 조립 모듈의 `@Bean` 메서드가 `new`로 만들어 스케줄러에 넘긴다. worker 생성자가 받은 서비스로 만들어도 같다 |
| 메시지 handler | `adapter:inbound:messaging` leaf, 또는 서비스 leaf의 `..adapter.inbound.messaging..` 패키지 | handler 생성자가 port를 받아 `new`로 만든다. handler에 `@SystemCaller`. 작업 순서는 09장 「소비」 4단계 |
| 예약 작업 | 서비스 자기 leaf의 `..adapter.inbound.scheduler..` 패키지. 등록된 scheduler leaf는 없다 | 작업 클래스 생성자가 port를 받아 `new`로 만든다. 작업 클래스에 `@SystemCaller`. 모양은 메시지 handler와 같고, 깨우는 것이 `@Scheduled` 메서드다. `Runnable`·`ApplicationRunner` 같은 프로젝트 밖 타입을 구현하지 않는다. task scheduler에 직접 등록하면 그 자리에서 `job::run`을 넘긴다 |
@@ -105,6 +105,7 @@ client가 같은 이름의 역할을 정의해도 이 서비스 권한이 되지
| bean 금지 | `@SystemInvoked` 유스케이스가 bean이면 기동 실패. 호출자가 `new`로 만들어 혼자 들고 있는 것만 허용한다 | `src/bootstrap/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java` |
| 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스와 그 안에 중첩된 클래스만 예외. inbound 밖 사용자 전송과 중간 클래스를 거친 길은 아래 「전송 → 시스템 호출자 금지」가 잡는다 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) |
| controller 위치 | Spring controller는 `..adapter.inbound..`에만 둔다. 조립 루트나 조립 모듈에 둔 controller는 빌드 실패 | `CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS`(`AdapterBoundaryArchitectureTest`) |
| 감싼 서비스 금지 | inbound adapter가 application의 `*Service`·`*Orchestrator`·`*Coordinator`에 의존하면 빌드 실패. interface도 든다. 유스케이스를 구현한 타입은 빠진다. `@SystemInvoked` 유스케이스가 감싸는 서비스(fileserver `CleanupService`, 알림 `ReconciliationService` 등)는 bean이고 권한 검사 없이 쓰기 때문이다 | `INBOUND_ADAPTERS_DEPEND_ON_PORTS_NOT_APPLICATION_SERVICES`(`AdapterBoundaryArchitectureTest`) |
| 표시 검사 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·JAX-RS·GraphQL·STOMP mapping과 channel interceptor·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) |
| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`나, 그 클래스가 구현·상속하는 프로젝트 타입(작업의 인터페이스 등), 또는 `@SystemInvoked` 유스케이스 자신에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 타입에는 Spring Security의 요청 경로 확장점(`org.springframework.security.web`·`.config.annotation.web`·`.oauth2.server.resource`·`.oauth2.jwt` 패키지, `AuthenticationProvider`, `AuthorizationManager`)이 든다. 그래서 web 패키지 밖에 둔 JWT converter나 authorization manager도 사용자 전송이다. 사용자 전송 클래스는 넷이다. ① 사용자 전송 패키지에 있는 클래스. ② 설정(`@Configuration`·`@AutoConfiguration`) 클래스 자신이 요청 처리기 타입(함수형 `RouterFunction`·`HandlerFunction`, `@RestController`·`@RequestMapping`, servlet·`Filter`·`HandlerInterceptor`, `WebSocketHandler`, GraphQL `DataFetcher`·`RuntimeWiringConfigurer`, gRPC `BindableService`·`ServerInterceptor`, STOMP `ChannelInterceptor`·`ExecutorChannelInterceptor` 등)에 의존하는 것. 요청 처리 코드를 설정에 직접 쓴 경우와 등록만 한 경우가 모두 든다. 요청 처리기 타입을 구현·상속한 프로젝트 클래스(예: `ChannelInterceptor`를 구현한 interceptor)를 필드·생성자 인자·`new`로 쥔 설정도 든다. `registration.interceptors(frameCounter)`는 클래스 의존으로 `ChannelRegistration`만 남기므로 그 필드의 타입이 설정을 사용자 전송으로 만든다. channel interceptor를 구현한 설정은 프레임마다 자기 메서드가 돈다. interceptor를 `@Bean`으로 내놓는 설정은 route를 등록하는 설정과 같다. 함수형 route나 data fetcher를 람다로 쓰면 그 코드가 설정 클래스의 메서드로 컴파일되어 설정이 곧 endpoint다. 처리 코드를 다른 클래스에 두고 메서드 참조로 등록만 해도(`route().GET("/orders", orders::list)`) 설정은 route builder에 의존한다. 클래스 의존으로는 등록과 처리 코드를 가를 수 없어서 둘 다 사용자 전송으로 센다. ③ 설정 안에 중첩된 클래스 가운데 사용자 전송 타입에 의존하는 것. 중첩된 JAX-RS 자원·`@ServerEndpoint`, `configureClientInboundChannel`에서 등록하는 STOMP channel interceptor(익명 클래스여도, STOMP 헤더를 읽지 않아도)도 여기서 잡힌다. 설정용 타입(`WebMvcConfigurer`·`WebSocketConfigurer`·STOMP broker 설정과 그 registry, CORS 설정, `RequestMethod`)에만 의존하는 중첩 클래스는 설정의 일부로 본다. inbound channel의 thread 수만 정하는 설정도 설정용이다. ④ 그 밖의 클래스 가운데 사용자 전송 타입에 의존하는 것. 사용자 전송 패키지 밖에 둔 channel interceptor가 여기에 든다. 그래서 handler를 bean으로 등록하는 설정은 같은 클래스에서 `WebMvcConfigurer`(설정 필드를 읽는 익명 클래스여도)·CORS 설정·controller bean을 함께 만들어도 걸리지 않는다. 같은 클래스에 "지금 실행" route·data fetcher·interceptor를 쓰거나, route를 등록하거나, 안에 중첩한 endpoint가 작업을 부르면(설정의 메서드를 거쳐 불러도) 걸린다. route·data fetcher·interceptor 등록은 handler bean을 만드는 설정과 다른 설정에 둔다. 설정이 만드는 controller는 controller 자신이 검사받는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) |
| 프로젝트 밖 상위 타입 금지 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스(익명·지역 클래스와 예외 제외)는 프로젝트(`dev.caskeleton..`와 소유자의 별도 repo 라이브러리 `dev.cakit..`) 밖의 클래스·인터페이스를 상속·구현하지 않는다. `Runnable`은 누구나 의존하는 타입이라, endpoint가 작업을 `Runnable`로 주입받아도 위 규칙이 다른 사용과 구별하지 못하기 때문이다. 메시지 handler의 `MessageHandler<T>`(메시징 라이브러리 `dev.cakit.messaging`)는 프로젝트 타입으로 쳐서 된다. record·enum은 언어가 붙이는 상위 타입(`Record`, `Enum`과 `Enum`이 구현하는 `Comparable`·`Serializable`·`Constable`)만은 가져도 된다. 그래서 handler 안의 파싱 결과 record, 결과 enum, 독(poison) 메시지 예외, record로 쓴 handler는 통과하고, `Runnable`을 구현한 record는 걸린다 | `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`(같은 파일) |
@@ -165,7 +166,7 @@ web이 빠진 조립(gRPC 전용·배치 전용)에는 `@RequiresPermission`을
- 쓰기 = `@RequiresPermission` + non-final + bean + 역할 매핑.
- 시스템만 부르는 쓰기 = `@SystemInvoked` + bean 아님 + 사용자 전송에서 안 닿음. 부르는 쪽은 셋뿐이다:
조립 모듈의 스케줄러, `@SystemCaller` 메시지 handler, `@SystemCaller` 예약 작업. 사용자 전송은
`@SystemCaller`에도, 그 작업의 인터페이스에도 닿지 못한다. 타입 이름이 남지 않는 길(이름으로 찾기,
설정이 넘기는 함수)은 빌드가 못 보니 리뷰가 막는다.
`@SystemCaller`에도, 그 작업의 인터페이스에도, 유스케이스가 감싸는 서비스에도 닿지 못한다. 타입 이름이
남지 않는 길(이름으로 찾기, 설정이 넘기는 함수)은 빌드가 못 보니 리뷰가 막는다.
- 객체 판정은 유스케이스 안, 남의 것은 404.
- 역할은 자기 client 것만 읽는다.
+27 -11
View File
@@ -2,7 +2,7 @@
# Every top-level public type under the platform packages. Growth is a reviewed change.
# Update only after review with:
# ./gradlew :adapter:outbound:notification:updateNotificationApiSurface -PapproveNotificationApiSurfaceChange
# types: 359
# types: 375
dev.caskeleton.adapter.outbound.notification.NotificationConfig
dev.caskeleton.adapter.outbound.notification.NotificationRoutesSettings
dev.caskeleton.adapter.outbound.notification.core.FailOpenNotificationProvider
@@ -35,14 +35,10 @@ dev.caskeleton.adapter.outbound.notification.platform.dispatch.CapabilityReconci
dev.caskeleton.adapter.outbound.notification.platform.dispatch.ConfiguredProfileCatalog
dev.caskeleton.adapter.outbound.notification.platform.dispatch.JacksonRoutingPlanCodec
dev.caskeleton.adapter.outbound.notification.platform.dispatch.LoggingInboxSignalPublisher
dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationBackgroundWorkers
dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationDispatchProperties
dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationSchedulerWorker
dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderAttemptLimiter
dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderEventReplayWorker
dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderRuntime
dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderRuntimeRegistry
dev.caskeleton.adapter.outbound.notification.platform.dispatch.ReconciliationJobWorker
dev.caskeleton.adapter.outbound.notification.platform.dispatch.RegistryProviderDispatchGateway
dev.caskeleton.adapter.outbound.notification.platform.dispatch.RegistryProviderRuntimeControl
dev.caskeleton.adapter.outbound.notification.platform.dispatch.SingleTenantContext
@@ -104,16 +100,23 @@ 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.ChangeProviderStateCommand
dev.caskeleton.application.notification.platform.admin.ChangeProviderStateUseCase
dev.caskeleton.application.notification.platform.admin.ChangeSuppressionCommand
dev.caskeleton.application.notification.platform.admin.ChangeSuppressionUseCase
dev.caskeleton.application.notification.platform.admin.DuplicateRiskApprovalRequiredException
dev.caskeleton.application.notification.platform.admin.DuplicateRiskGuard
dev.caskeleton.application.notification.platform.admin.NotificationAdminApplicationService
dev.caskeleton.application.notification.platform.admin.NotificationAdminAuthority
dev.caskeleton.application.notification.platform.admin.NotificationAdminService
dev.caskeleton.application.notification.platform.admin.NotificationAdminPermissions
dev.caskeleton.application.notification.platform.admin.ProviderRuntimeControlPort
dev.caskeleton.application.notification.platform.admin.ReconcileCommand
dev.caskeleton.application.notification.platform.admin.RedriveCommand
dev.caskeleton.application.notification.platform.admin.SetProviderStateCommand
dev.caskeleton.application.notification.platform.admin.SuppressCommand
dev.caskeleton.application.notification.platform.admin.ProviderStateRequest
dev.caskeleton.application.notification.platform.admin.ReconcileDeliveriesCommand
dev.caskeleton.application.notification.platform.admin.ReconcileDeliveriesUseCase
dev.caskeleton.application.notification.platform.admin.ReconcileRequest
dev.caskeleton.application.notification.platform.admin.RedriveDeliveryCommand
dev.caskeleton.application.notification.platform.admin.RedriveDeliveryUseCase
dev.caskeleton.application.notification.platform.admin.RedriveRequest
dev.caskeleton.application.notification.platform.admin.SuppressionRequest
dev.caskeleton.application.notification.platform.api.CallbackIngestionResult
dev.caskeleton.application.notification.platform.api.CancelCommand
dev.caskeleton.application.notification.platform.api.CancelResult
@@ -198,6 +201,8 @@ dev.caskeleton.application.notification.platform.callback.ProviderEventRecord
dev.caskeleton.application.notification.platform.callback.ProviderEventRecordId
dev.caskeleton.application.notification.platform.callback.ProviderEventSource
dev.caskeleton.application.notification.platform.callback.ProviderRequestIdHash
dev.caskeleton.application.notification.platform.callback.ReplayProviderEventsCommand
dev.caskeleton.application.notification.platform.callback.ReplayProviderEventsUseCase
dev.caskeleton.application.notification.platform.callback.StandardDeliveryProjector
dev.caskeleton.application.notification.platform.callback.SuppressionFacts
dev.caskeleton.application.notification.platform.callback.VerifiedProviderEvent
@@ -218,11 +223,15 @@ dev.caskeleton.application.notification.platform.dispatch.AttachmentIntegrityGua
dev.caskeleton.application.notification.platform.dispatch.CancelNotificationApplicationUseCase
dev.caskeleton.application.notification.platform.dispatch.CanonicalNotificationPlanEncoder
dev.caskeleton.application.notification.platform.dispatch.CanonicalNotificationPlanWriter
dev.caskeleton.application.notification.platform.dispatch.ClaimDueDeliveriesCommand
dev.caskeleton.application.notification.platform.dispatch.ClaimDueDeliveriesUseCase
dev.caskeleton.application.notification.platform.dispatch.ContactPointRecord
dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort
dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFactory
dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptRecord
dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort
dev.caskeleton.application.notification.platform.dispatch.DispatchClaimedDeliveryCommand
dev.caskeleton.application.notification.platform.dispatch.DispatchClaimedDeliveryUseCase
dev.caskeleton.application.notification.platform.dispatch.DispatchGuardOutcome
dev.caskeleton.application.notification.platform.dispatch.DispatchOutcomeRecorder
dev.caskeleton.application.notification.platform.dispatch.DispatchPipeline
@@ -249,10 +258,14 @@ dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecor
dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort
dev.caskeleton.application.notification.platform.dispatch.RecipientLease
dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort
dev.caskeleton.application.notification.platform.dispatch.ReconcileOutstandingAttemptsCommand
dev.caskeleton.application.notification.platform.dispatch.ReconcileOutstandingAttemptsUseCase
dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort
dev.caskeleton.application.notification.platform.dispatch.ReconciliationJob
dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort
dev.caskeleton.application.notification.platform.dispatch.ReconciliationService
dev.caskeleton.application.notification.platform.dispatch.RecoverAbandonedDeliveriesCommand
dev.caskeleton.application.notification.platform.dispatch.RecoverAbandonedDeliveriesUseCase
dev.caskeleton.application.notification.platform.dispatch.ScheduleNotificationApplicationUseCase
dev.caskeleton.application.notification.platform.dispatch.SubmitNotificationApplicationUseCase
dev.caskeleton.application.notification.platform.dispatch.SuppressionSideEffect
@@ -274,6 +287,8 @@ dev.caskeleton.application.notification.platform.inbox.NotificationInbox
dev.caskeleton.application.notification.platform.inbox.NotificationInboxSignalPort
dev.caskeleton.application.notification.platform.observation.CardinalityGuard
dev.caskeleton.application.notification.platform.observation.IllegalMetricTagException
dev.caskeleton.application.notification.platform.observation.MeasureDispatchBacklogQuery
dev.caskeleton.application.notification.platform.observation.MeasureDispatchBacklogUseCase
dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent
dev.caskeleton.application.notification.platform.observation.NotificationAuditPort
dev.caskeleton.application.notification.platform.observation.NotificationMetricName
@@ -301,6 +316,7 @@ dev.caskeleton.application.notification.platform.policy.RetryBackoff
dev.caskeleton.application.notification.platform.policy.RetryBudget
dev.caskeleton.application.notification.platform.policy.RetryContext
dev.caskeleton.application.notification.platform.policy.RetryDecision
dev.caskeleton.application.notification.platform.policy.RetryTiming
dev.caskeleton.application.notification.platform.policy.RouteCandidate
dev.caskeleton.application.notification.platform.policy.RoutingContext
dev.caskeleton.application.notification.platform.policy.RoutingDecision
@@ -41,6 +41,18 @@ lease는 provider 호출 한 번이 delivery를 쥐는 시간보다 길어야
끝난 호출도 자기 결과를 기록한다(owner와 fence가 그대로다). 두 번째 worker가 다시 보내지는 않는다. claim은
`DISPATCHING`인 delivery를 가져가지 않는다.
## 재시도 시각
| 속성 | 환경 변수 | 기본값 | 범위 |
|---|---|---|---|
| `retry.backoff-base` | 없음 | `1s` | 양수. 첫 재시도의 상한이자 가장 짧은 대기 |
| `retry.backoff-max` | 없음 | `5m` | `backoff-base` 이상. provider의 `Retry-After`도 이 값을 넘지 못한다 |
| `retry.reconcile-delay` | 없음 | `1m` | 0 이상. 결과를 모르는 제출 뒤 provider에 처음 물어보기까지 |
대기는 `backoff-base`와 지수로 늘어난 상한 사이의 full jitter다. 세 값에는 env 자리표시자가 없다. 배포의 설정
파일(`application-{profile}.yml`)에서 바꾼다. 값은 provider의 호출 한도에 맞춰 정한다. 템플릿이 정할 일이 아니어서
상수가 아니라 설정이다(2026-11-13).
## 콜백
| 속성 | 환경 변수 | 기본값 | 범위 |
+25
View File
@@ -37,6 +37,31 @@ redrive는 `NotificationId`와 `RecipientDeliveryId`를 유지하고, 새 `Deliv
렌더링 digest를 다시 쓴다. 다른 내용을 보내는 것은 redrive가 아니라 새 알림이다. 모호한 attempt를 redrive하려면 중복
위험 승인을 명시해야 한다. 첫 제출이 사용자에게 닿았는지 플랫폼이 정말로 알 수 없기 때문이다.
## 운영자 연산
운영자 연산은 넷이고, 연산마다 유스케이스 하나다(`application.notification.platform.admin`의 클래스, command는 그 옆의
`*Command`). 조립은 `composition:notification-platform`의 `NotificationAdminConfiguration`이 bean으로 한다.
| 유스케이스 | 하는 일 | permission | 운영자 authority |
|---|---|---|---|
| `RedriveDeliveryUseCase` | delivery 하나를 다시 보낼 차례로 돌린다 | `notification-admin:redrive` | `REDRIVE` |
| `ReconcileDeliveriesUseCase` | attempt 묶음(200개까지)을 provider에 다시 묻는다 | `notification-admin:reconcile` | `RECONCILE` |
| `ChangeSuppressionUseCase` | 억제 항목 하나를 더하거나 푼다 | `notification-admin:suppress` | `SUPPRESS` |
| `ChangeProviderStateUseCase` | provider profile을 켜고 끄거나 drain한다 | `notification-admin:provider-control` | `PROVIDER_CONTROL`, tenant 범위 없는 운영자만 |
- 확인은 두 겹이다. permission은 전송의 호출자가 이 연산을 부를 수 있는지다(`@RequiresPermission`). authority와
tenant 범위는 command의 `AdminActor`가 쥐고, 연산이 건드리는 delivery의 tenant와 대조한다.
- 모든 연산은 운영자가 준 operation id로 멱등이다. 같은 id·같은 요청은 저장된 결과를 돌려주고, 같은 id·다른 요청은
충돌이다. 대상 확인(tenant·중복 위험)과 claim과 쓰기는 한 쓰기 트랜잭션에서 커밋한다. reconcile만 대상 확인을 읽기
트랜잭션에서 하고, provider 호출은 트랜잭션 밖에서 하며, claim과 결과를 따로 커밋한다.
- dry run은 보고만 하고 쓰지 않는다. redrive와 reconcile의 dry run은 대상을 읽기 트랜잭션에서 읽는다. suppression과 provider 상태의 dry run은 아무것도 읽지 않는다.
- 템플릿은 이 연산을 부르는 전송을 싣지 않는다. 운영자 화면이나 endpoint를 여는 서비스가 전송을 만든다.
- 모듈 기본값(`composition:notification-platform`의 `config/module-defaults/notification.yml`)이 role
`notification-admin`에 넷을 모두 준다(`app.authz.role-permissions`). 이 기본값의 정본은 그 파일이다. 운영자 role
이름이 다르면 배포의 설정 파일에서 `app.authz.role-permissions`에 그 role을 더한다. IdP가 `notification-admin` role을
다른 뜻으로 쓰면 배포의 설정 파일에서 `app.authz.role-permissions.notification-admin`에 그 role이 가질 permission 목록을
적는다. 출처마다 map 항목이 합쳐지고 같은 키는 배포의 값이 이긴다.
## actuator 표면
provider 런타임 상태와 세대, 큐 깊이와 나이, 콜백과 맞추기 상태. 주소와 자격 증명은 절대 싣지 않는다.
+4 -4
View File
@@ -215,7 +215,7 @@ source set에서 태그 `jpa-contract`로 `jpaPlatformContractTest` lane이 돌
| `IdempotencyStorePort` | `idempotency.testkit.IdempotencyStoreContract` | `InMemoryIdempotencyStore` | `RedisIdempotencyStoreContractTest`(command fake, `test`) · `LiveRedisIdempotencyStoreContractTest`(실 Redis, `redisTopologyTest` standalone·cluster) · `PostgreSqlIdempotencyStoreContractTest`(실 PostgreSQL, `jpaPlatformContractTest`) |
| `SecretSourcePort` | `secret.testkit.SecretSourceContract` | `InMemorySecretSource` | `EnvironmentSecretSourceContractTest` — support (`test`) |
| `OutboxAppendPort` | `outbox.testkit.OutboxAppendContract` | `InMemoryOutboxStore(DirectTransactionPort)` | `PostgreSqlOutboxAppendTransactionalIntegrationTest` (`postgresqlOutboxAppendTransactionalIntegrationTest`) |
| `LiveEventReplayPort` | `realtime.testkit.LiveEventReplayContract` | `InMemoryLiveEventReplay` | `JpaLiveEventReplayContractTest` (`jpaPlatformContractTest`) |
| `LiveEventReplayQueryPort` | `realtime.testkit.LiveEventReplayQueryContract` | `InMemoryLiveEventReplay` | `JpaLiveEventReplayContractTest` (`jpaPlatformContractTest`) |
| `AuthorizationPort` | `security.testkit.AuthorizationContract` | `InMemoryAuthorization` | `AuthorizationAdapterContractTest` — web (`test`) |
| `CorrelationIdPort` | `observability.testkit.CorrelationIdContract` | `FixedCorrelationId` | `MdcCorrelationIdPortAdapterContractTest` — web (`test`) |
| `CacheRegionPort` | `cache.testkit.CacheRegionContract` | `InMemoryCacheRegion` | `RedisCacheRegionContractTest`(`test`) · `LiveRedisCacheRegionContractTest`(`redisTopologyTest`) |
@@ -299,9 +299,9 @@ PostgreSQL 쪽에만 있던 테스트를 계약으로 옮긴 것이다. `Reconci
`PostgreSqlAdminOperationStoreContractTest`에만 남겼다. 처음 적용할 때 fake와 실제가 다르게 답한 경우는
없었다. 유스케이스 테스트의 대역은 `PlatformFakes.RequestStore`·deduplication 람다·
`AdminOperationExecutorTest.FakeStore`를 이 fake들로 바꿨다. 아직 테스트 안에 남은 대역: admin
`NotificationAdminApplicationServiceTest.RecordingOperations`·`UnusedSuppressionStore`, reconciliation job
`ReconciliationJobWorkerTest`(notification adapter)의 stub — 호출 횟수를 세거나 "부르지 않는다"를 확인하는
용도라 fake로 바꾸면 단언을 다시 써야 한다.
`NotificationAdminUseCasesTest.RecordingOperations`, reconciliation job
`ReconcileOutstandingAttemptsUseCaseTest`(application-notification)의 stub — 호출 횟수를 세거나 "부르지 않는다"를
확인하는 용도라 fake로 바꾸면 단언을 다시 써야 한다.
notification 계약 여덟 개(recipient lease·recipient delivery·attempt·resolver·projection·ledger·side
effect·contact point, 2026-11-03 r3-J)로 9.2의 "다음 단계"가 끝났다. fake는 JPA 구현의 묶음을 따른다:
+26 -7
View File
@@ -1,22 +1,41 @@
# 업그레이드 안내 — 2026-11 application 구조와 작은 정리
- 범위: durable operation 제출이 id를 유스케이스에서 만들고 tenant를 타입으로 받게 한 변경, 쓰지 않던 공개 타입 일곱의
삭제, 그 밖의 작은 정리. 공개 타입과 생성자가 바뀐 곳이 있다. 아래 표가 그 목록이다.
- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 application 작은 것(B15b) 발견
- 범위: 시스템이 부르는 쓰기를 `@SystemInvoked` 유스케이스로 나누고, 알림 worker와 fileserver 정리 서비스 조립을
composition으로 옮기고, 알림 운영자 연산을 유스케이스 넷으로 나누고, replay 읽기와 durable operation 제출을 유스케이스로
거치게 한 변경. 쓰지 않던 공개 타입 일곱을 지웠다. 공개 타입과 생성자가 바뀐 곳이 있다. 아래 표가 그 목록이다.
- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 application 구조(B15a)와 작은 것(B15b) 발견
## 1. 누가 읽나
이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 durable operation을 직접 제출·조회하는
서비스와 아래 표의 지운 타입을 쓴 서비스다.
이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 알림 운영자 연산이나 알림 worker bean을
직접 쓴 서비스, `MessagingReplayBridge`로 stream을 다시 보내는 서비스, durable operation을 직접 제출하는 서비스,
사용자 전송(web·GraphQL·gRPC·WebSocket) 클래스에서 저장 포트를 직접 쥐는 서비스다.
## 2. 할 일
| # | 할 일 | 안 하면 | 해당 서비스 |
| --- | --- | --- | --- |
| 1 | `OperationCommand`에서 operation id 인자를 지우고, tenant를 `Optional<TenantId>`(`application.tenant.TenantId`)로 넘긴다. `GetDurableOperationQuery`·`CancelDurableOperationCommand`의 tenant도 같다. `SubmitDurableOperationUseCase`는 생성자에 `DurableOperationIdFactory`를 받아 id를 직접 만든다. `DurableOperationController`는 id factory를 받지 않는다 | 컴파일이 실패한다 | durable operation을 직접 제출·조회하거나 그 use case를 조립한 서비스 |
| 2 | 쓰는 곳이 없던 공개 타입 일곱을 지웠다: `application.transaction.ReadConsistency`, `FileserverSpans`, 알림의 `ProviderEventId`·`NotificationExpiredException`·`BatchNotificationProviderAdapter`·`CollapseCapability`·`ProviderCollapseMapping` | 그 타입을 쓴 코드는 컴파일이 실패한다. 템플릿 안에는 쓰는 곳이 없었다 | 그 타입을 쓴 서비스 |
| 1 | `NotificationAdminService`·`NotificationAdminApplicationService`가 없어졌다. 운영자 연산은 `platform.admin`의 유스케이스 클래스 `RedriveDeliveryUseCase`·`ReconcileDeliveriesUseCase`·`ChangeSuppressionUseCase`·`ChangeProviderStateUseCase`를 주입받아 `handle(new …Command(request, actor))`로 부른다(command도 `platform.admin`). 운영자 요청 record의 이름이 바뀌었다: `RedriveCommand`→`RedriveRequest`, `ReconcileCommand`→`ReconcileRequest`, `SuppressCommand`→`SuppressionRequest`, `SetProviderStateCommand`→`ProviderStateRequest`. `adminAuthorizationGuard`·`duplicateRiskGuard` bean은 없어졌다(유스케이스 설정이 `new`로 만든다). 모듈 기본값이 role `notification-admin`에 permission 넷(`notification-admin:redrive`·`notification-admin:reconcile`·`notification-admin:suppress`·`notification-admin:provider-control`)을 준다. 운영자 role 이름이 다르면 `app.authz.role-permissions`에 직접 대응시킨다 | 컴파일이 실패한다. 두 guard bean을 주입받던 정의는 기동이 실패한다(`NoSuchBeanDefinitionException`). 운영자가 `notification-admin` role도 대응시킨 role도 없으면 운영자 호출이 403이다 | 알림 운영자 연산을 쓴 서비스 |
| 2 | 알림 worker가 `adapter:outbound:notification`에서 `composition:notification-platform`으로 옮겼다. `NotificationBackgroundWorkers`는 `dev.caskeleton.composition.notification`의 공개 타입이고, 생성자는 서비스 대신 유스케이스를 받는다(lease 회복·replay·맞추기). 발송 scheduler(`NotificationSchedulerWorker`)는 그 패키지 안의 타입이 됐다. claim·발송·backlog 측정 유스케이스로 돌고, 바꿔 끼우는 bean이 아니다. `ReconciliationJobWorker`·`ProviderEventReplayWorker`는 application의 `@SystemInvoked` 유스케이스(`ReconcileOutstandingAttemptsUseCase(jobs, reconciler, tx, clock, deliveryLease, batchSize, maxAdditionalAttempts)`·`ReplayProviderEventsUseCase(projection, batchSize)`)가 됐다. `reconciliationJobWorker`·`notificationProviderEventReplayWorker` bean을 덮어쓰던 서비스는 `notificationBackgroundWorkers` bean을 덮어쓴다 | 옛 import와 생성자가 컴파일되지 않는다. 옛 bean 이름으로 덮어쓴 정의는 더는 쓰이지 않는다 | 알림 worker를 직접 조립하거나 덮어쓴 서비스 |
| 3 | `MessagingReplayBridge`는 생성자에서 조회 유스케이스 둘을 받는다: `new MessagingReplayBridge<>(window, replay, decoder)`. 두 유스케이스는 서비스의 조립 설정(자기 `composition` 설정이나 bootstrap 설정, web 설정이 아니다)에서 bean으로 만든다: `@Bean GetReplayWindowUseCase(LiveEventReplayQueryPort port, TransactionPort tx)`, `@Bean ReplayLiveEventsUseCase(...)`. 템플릿은 bridge를 조립하지 않으므로 이 bean도 만들지 않는다. `LiveEventReplayPort`는 `LiveEventReplayQueryPort`로, testFixtures의 `LiveEventReplayContract`는 `LiveEventReplayQueryContract`로 이름이 바뀌었다 | 컴파일이 실패한다. web 설정에서 port를 쥐고 유스케이스를 만들면 5행 규칙에 걸린다 | stream replay를 쓰는 서비스 |
| 4 | `OperationCommand`에서 operation id 인자를 지우고, tenant를 `Optional<TenantId>`(`application.tenant.TenantId`)로 넘긴다. `GetDurableOperationQuery`·`CancelDurableOperationCommand`의 tenant도 같다. `SubmitDurableOperationUseCase`는 생성자에 `DurableOperationIdFactory`를 받아 id를 직접 만든다. `DurableOperationController`는 id factory를 받지 않는다 | 컴파일이 실패한다 | durable operation을 직접 제출·조회하거나 그 use case를 조립한 서비스 |
| 5 | 사용자 전송 패키지(시스템이 부르는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`를 뺀 모든 `..adapter.inbound..`)의 클래스가 `*Repository`·`*StorePort`·`*QueryPort`·`*IdFactory`·`*IdGeneratorPort`·`*IdentifierPort`를 직접 쥐면 새 아키텍처 규칙 `USER_TRANSPORTS_DO_NOT_HOLD_PERSISTENCE_OR_ID_PORTS`가 빌드를 실패시킨다. 또 inbound 클래스가 application의 `*Service`·`*Orchestrator`·`*Coordinator`를 interface로 쥐어도 `INBOUND_ADAPTERS_DEPEND_ON_PORTS_NOT_APPLICATION_SERVICES`가 실패시킨다(전에는 구체 클래스만 봤다). 읽기·쓰기는 유스케이스를 거친다 | `architectureTest`가 실패한다 | 사용자 전송에서 포트나 서비스를 직접 쓴 서비스 |
| 6 | `DefaultNotificationRetryPolicy`를 직접 만들던 코드는 `new DefaultNotificationRetryPolicy(timing, jitter)`로 바꾼다. `timing`은 새 값 `RetryTiming(backoff, reconcileDelay)`이고 배포 설정의 값은 `NotificationPlatformSettings.retry().timing()`이다(기본값은 `RetryTiming.DEFAULT`). `RetryBackoff`·`RetryBudget`·`RetryContext`·`RetryDecision.RetryAfter`·`RouteCandidate`·`RoutingContext`·`RoutingDecision`·`EligibilityResult`의 생성자와 `RetryBackoff.delay`(attempt 번호 1 미만)는 잘못된 값에 `IllegalStateException`을 던진다(전에는 `IllegalArgumentException`). 새 값 `RetryTiming`도 같다 | 컴파일이 실패한다. IAE를 잡던 코드는 그 예외를 놓친다 | 알림 retry policy를 직접 만들거나, route planner·plan codec·eligibility policy를 직접 구현하거나, `RoutingDecision`을 직접 만드는 서비스 |
| 7 | 쓰는 곳이 없던 공개 타입 일곱을 지웠다: `application.transaction.ReadConsistency`, `FileserverSpans`, 알림의 `ProviderEventId`·`NotificationExpiredException`·`BatchNotificationProviderAdapter`·`CollapseCapability`·`ProviderCollapseMapping` | 그 타입을 쓴 코드는 컴파일이 실패한다. 템플릿 안에는 쓰는 곳이 없었다 | 그 타입을 쓴 서비스 |
## 3. 바뀐 동작 (따라 할 일 없음)
- 알림 재시도 시각이 설정이다: `app.notification.platform.retry.backoff-base`(1s)·`backoff-max`(5m)·`reconcile-delay`(1m).
기본값은 전의 상수와 같고 코드(`RetryTiming.DEFAULT`)에만 있다. module-defaults에는 주석 예시만 있다. 값이 틀리면
(`backoff-base` 0 이하, `backoff-max`가 base보다 짧음, `reconcile-delay` 음수) 기동이 실패한다.
- fileserver cleanup worker와 알림 worker는 `@SystemInvoked` 유스케이스를 거쳐 쓴다(manual 07 「시스템이 부르는 쓰기」).
알림 worker의 lease claim과 reconciliation job 기록은 이제 쓰기 트랜잭션 안에서, scheduler의 backlog 측정과 replay의
ledger 읽기는 읽기 트랜잭션 안에서 돈다. provider에는 여전히 트랜잭션 없이 묻는다.
- 운영자 redrive는 대상 attempt를 claim·쓰기와 같은 쓰기 트랜잭션에서 읽는다(dry run은 읽기 트랜잭션). 운영자
reconcile의 tenant 확인은 읽기 트랜잭션에서 한다. 전에는 트랜잭션 밖에서 읽었다.
- fileserver 정리·맞추기 서비스(`CleanupService`·`FileReconciliationService`)는 `composition:fileserver-platform`이 조립한다.
bean 이름과 타입은 그대로다.
- fileserver 관리 HTTP의 기본값(orphan 정리 dry run과 1 GiB·`ORPHAN_APPLY`, cleanup 100개·1 GiB, 목록 100개)은 application
command의 `requested(...)`가 채운다. 응답은 같다.
- `GetDurableOperationUseCase`·`PublishPendingOutboxEventsUseCase`가 final이 아니다.
- 알림 받기의 `idempotencyKey`가 `IdempotencyExecutor`와 다른 이유는 manual 05 「executor를 쓰지 않는 중복 판정 둘」에 있다.
@@ -20,6 +20,8 @@ dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
implementation project(':adapter:inbound:web')
implementation project(':application-core')
// DirectTransactionPort, the read boundary the replay bridge's query use cases open.
testImplementation testFixtures(project(':application-core'))
implementation project(':shared-contract')
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
@@ -1,8 +1,11 @@
package dev.caskeleton.adapter.inbound.web.advanced.stream.replay;
import dev.caskeleton.adapter.inbound.web.advanced.stream.StreamSequence;
import dev.caskeleton.application.realtime.LiveEventReplayPort;
import dev.caskeleton.application.realtime.GetReplayWindowQuery;
import dev.caskeleton.application.realtime.GetReplayWindowUseCase;
import dev.caskeleton.application.realtime.ReplayCursorUnavailableException;
import dev.caskeleton.application.realtime.ReplayLiveEventsQuery;
import dev.caskeleton.application.realtime.ReplayLiveEventsUseCase;
import dev.caskeleton.application.realtime.ReplayWindow;
import java.util.List;
import java.util.Objects;
@@ -12,9 +15,11 @@ import java.util.function.Function;
* {@link WebStreamReplaySource} over the application's durable event log.
*
* <p>The web module stores no history, and this is what that decision looks like in code: the
* bridge holds a port and a decoder and nothing else. A copy here would have its own retention, its
* own eviction and its own opinion about ordering, and the two would diverge silently because both
* would look plausible.
* bridge holds the two read use cases over the event log and a decoder, and nothing else. It reads
* through them rather than through {@code LiveEventReplayQueryPort}: every read a transport makes
* goes through a query use case, which declares its capability and opens the read boundary (round9
* review 2026-11-12, RR9-05-10). A copy here would have its own retention, its own eviction and its
* own opinion about ordering, and the two would diverge silently because both would look plausible.
*
* <p>An expired cursor becomes {@link ReplayCursorExpiredException} rather than an empty replay.
* Serving from the oldest available position would deliver contiguous positions with a hole in the
@@ -28,14 +33,18 @@ public final class MessagingReplayBridge<T> implements WebStreamReplaySource<T>
/** How many events one replay call loads. The port caps this again on its own side. */
public static final int PAGE_SIZE = 200;
private final LiveEventReplayPort replay;
private final GetReplayWindowUseCase window;
private final ReplayLiveEventsUseCase replay;
private final Function<String, T> decoder;
/**
* @param replay the durable history
* @param window what a stream still holds
* @param replay the events after a position
* @param decoder turns a stored payload into the item the stream carries
*/
public MessagingReplayBridge(LiveEventReplayPort replay, Function<String, T> decoder) {
public MessagingReplayBridge(
GetReplayWindowUseCase window, ReplayLiveEventsUseCase replay, Function<String, T> decoder) {
this.window = Objects.requireNonNull(window, "window");
this.replay = Objects.requireNonNull(replay, "replay");
this.decoder = Objects.requireNonNull(decoder, "decoder");
}
@@ -65,7 +74,9 @@ public final class MessagingReplayBridge<T> implements WebStreamReplaySource<T>
throw new ReplayCursorExpiredException(cursor);
}
try {
return replay.replayAfter(position.streamId(), position.value(), PAGE_SIZE).stream()
return replay
.handle(new ReplayLiveEventsQuery(position.streamId(), position.value(), PAGE_SIZE))
.stream()
.map(
event ->
new Replayed<>(
@@ -91,7 +102,7 @@ public final class MessagingReplayBridge<T> implements WebStreamReplaySource<T>
private java.util.Optional<ReplayWindow> window(Position position) {
try {
return java.util.Optional.of(replay.window(position.streamId()));
return java.util.Optional.of(window.handle(new GetReplayWindowQuery(position.streamId())));
} catch (RuntimeException unavailable) {
// Empty means "no answer", not "no history". The caller turns that into a resnapshot, which
// is expensive and correct; treating it as a readable empty window would say the opposite.
@@ -4,10 +4,14 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.adapter.inbound.web.advanced.stream.StreamSequence;
import dev.caskeleton.application.realtime.LiveEventReplayPort;
import dev.caskeleton.application.realtime.GetReplayWindowUseCase;
import dev.caskeleton.application.realtime.LiveEventReplayQueryPort;
import dev.caskeleton.application.realtime.ReplayCursorUnavailableException;
import dev.caskeleton.application.realtime.ReplayLiveEventsUseCase;
import dev.caskeleton.application.realtime.ReplayWindow;
import dev.caskeleton.application.realtime.ReplayedEvent;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@@ -30,10 +34,16 @@ class MessagingReplayBridgeTest {
private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z");
private static MessagingReplayBridge<String> bridge(LiveEventReplayPort port) {
return new MessagingReplayBridge<>(port, payload -> payload);
private static MessagingReplayBridge<String> bridge(LiveEventReplayQueryPort port) {
return new MessagingReplayBridge<>(
new GetReplayWindowUseCase(port, PASS_THROUGH),
new ReplayLiveEventsUseCase(port, PASS_THROUGH),
payload -> payload);
}
/** The storage and its read boundary are the JPA adapter's to test; this runs the read inline. */
private static final TransactionPort PASS_THROUGH = new DirectTransactionPort();
@Test
@DisplayName("a cursor carries both the stream and the position")
void cursorCarriesStreamAndPosition() {
@@ -149,7 +159,7 @@ class MessagingReplayBridgeTest {
}
/** A replay port over a fixed window and a fixed event list. */
private static final class StubPort implements LiveEventReplayPort {
private static final class StubPort implements LiveEventReplayQueryPort {
private final long earliest;
private final long latest;
@@ -180,7 +190,7 @@ class MessagingReplayBridgeTest {
}
/** A replay port that is down. */
private static final class FailingPort implements LiveEventReplayPort {
private static final class FailingPort implements LiveEventReplayQueryPort {
@Override
public ReplayWindow window(String streamId) {
@@ -29,6 +29,7 @@ import dev.caskeleton.application.fileserver.port.in.ReverifyFileCommand;
import dev.caskeleton.application.fileserver.port.in.ReverifyFileUseCase;
import jakarta.validation.Valid;
import java.util.List;
import java.util.Optional;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@@ -57,8 +58,6 @@ import org.springframework.web.bind.annotation.RestController;
havingValue = "true")
public class FileserverAdminController {
private static final int DEFAULT_PAGE = 100;
private final GetStorageHealthUseCase storageHealth;
private final GetRuntimeCapabilitiesUseCase capabilities;
private final ListOrphansUseCase orphans;
@@ -105,8 +104,9 @@ public class FileserverAdminController {
}
@GetMapping(path = "/internal/fileserver/orphans", produces = MediaType.APPLICATION_JSON_VALUE)
public List<OrphanObject> orphans(@RequestParam(name = "limit", defaultValue = "100") int limit) {
return orphans.handle(new ListOrphansQuery(limit, contextFactory.current()));
public List<OrphanObject> orphans(@RequestParam(name = "limit", required = false) Integer limit) {
return orphans.handle(
ListOrphansQuery.requested(Optional.ofNullable(limit), contextFactory.current()));
}
@PostMapping(
@@ -141,40 +141,36 @@ public class FileserverAdminController {
path = "/internal/fileserver/uploads/incomplete",
produces = MediaType.APPLICATION_JSON_VALUE)
public List<IncompleteUploadView> incompleteUploads(
@RequestParam(name = "limit", defaultValue = "100") int limit) {
@RequestParam(name = "limit", required = false) Integer limit) {
return incompleteUploads.handle(
new ListIncompleteUploadsQuery(limit, contextFactory.current()));
ListIncompleteUploadsQuery.requested(Optional.ofNullable(limit), contextFactory.current()));
}
@PostMapping(
path = "/internal/fileserver/uploads:cleanup",
produces = MediaType.APPLICATION_JSON_VALUE)
public CleanupBatchResult cleanupUploads(
@RequestParam(name = "maxItems", defaultValue = "100") int maxItems,
@RequestParam(name = "maxBytes", defaultValue = "1073741824") long maxBytes) {
@RequestParam(name = "maxItems", required = false) Integer maxItems,
@RequestParam(name = "maxBytes", required = false) Long maxBytes) {
return cleanupUploads.handle(
new CleanupUploadsCommand(maxItems, maxBytes, contextFactory.current()));
CleanupUploadsCommand.requested(
Optional.ofNullable(maxItems),
Optional.ofNullable(maxBytes),
contextFactory.current()));
}
/**
* Reads the wire request conservatively.
*
* <p>Every absent field resolves to the safe value: a dry run, the default page, and no
* fingerprints. Nothing here can be omitted into a destructive default.
* Reads the wire request: absent fields stay absent, and the command applies the use case's safe
* defaults ({@link OrphanReconcileCommand#requested}).
*/
private static OrphanReconcileCommand toCommand(
OrphanReconcileHttpRequest request, RequestContext context) {
boolean dryRun = request.dryRun() == null || request.dryRun();
int limit = request.limit() == null ? DEFAULT_PAGE : request.limit();
if (dryRun) {
return OrphanReconcileCommand.dryRun(limit, context);
}
return new OrphanReconcileCommand(
false,
limit,
request.maxBytes() == null ? 1L << 30 : request.maxBytes(),
request.expectedFingerprints() == null ? List.of() : request.expectedFingerprints(),
request.reasonCode() == null ? "ORPHAN_APPLY" : request.reasonCode(),
return OrphanReconcileCommand.requested(
Optional.ofNullable(request.dryRun()),
Optional.ofNullable(request.limit()),
Optional.ofNullable(request.maxBytes()),
Optional.ofNullable(request.expectedFingerprints()),
Optional.ofNullable(request.reasonCode()),
context);
}
}
@@ -42,8 +42,7 @@ import org.springframework.core.env.Environment;
FileserverStorageGatewayConfiguration.class,
FileserverStorageOperationsConfiguration.class,
FileserverVerificationConfiguration.class,
FileserverSecurityConfiguration.class,
FileserverMaintenanceServiceConfiguration.class
FileserverSecurityConfiguration.class
})
public class FileserverCapabilityAutoConfiguration {
@@ -2,8 +2,6 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure;
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationDispatchProperties;
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderRuntimeRegistry;
import dev.caskeleton.application.notification.platform.admin.AdminAuthorizationGuard;
import dev.caskeleton.application.notification.platform.admin.DuplicateRiskGuard;
import dev.caskeleton.application.notification.platform.admin.ProviderRuntimeControlPort;
import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger;
import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService;
@@ -41,11 +39,11 @@ import org.springframework.context.annotation.Configuration;
matchIfMissing = true)
class NotificationPlatformDispatchConfig {
/**
* The operator plane, and the narrow port it reaches runtimes through.
* The narrow port the operator plane reaches provider runtimes through.
*
* <p>Neither had a bean. The admin service existed in the outbound adapter, fully written, doing
* authorization and transaction orchestration, and nothing constructed it — so every operator
* capability the platform documented was unreachable.
* <p>The operator use cases themselves, and the authority and duplicate-risk guards they hold,
* are assembled in {@code composition:notification-platform}: who may perform an operator action
* is a decision about the product, not about speaking a provider protocol.
*
* @param runtimes the provider runtime registry
* @return the control port
@@ -56,26 +54,6 @@ class NotificationPlatformDispatchConfig {
.RegistryProviderRuntimeControl(runtimes);
}
/**
* Operator authority, tenant scope and duplicate-risk approval.
*
* @return the guard
*/
@Bean
public AdminAuthorizationGuard adminAuthorizationGuard() {
return new AdminAuthorizationGuard();
}
/**
* The approval an ambiguous redrive requires.
*
* @return the guard
*/
@Bean
public DuplicateRiskGuard duplicateRiskGuard() {
return new DuplicateRiskGuard();
}
/** Pre-provider guard chain. */
@Bean
public DispatchPipeline dispatchPipeline(
@@ -13,12 +13,10 @@ import dev.caskeleton.application.notification.platform.policy.JitterSource;
import dev.caskeleton.application.notification.platform.policy.NotificationEligibilityPolicy;
import dev.caskeleton.application.notification.platform.policy.NotificationRetryPolicy;
import dev.caskeleton.application.notification.platform.policy.PreferenceStorePort;
import dev.caskeleton.application.notification.platform.policy.RetryBackoff;
import dev.caskeleton.application.notification.platform.policy.RoutingDecisionEngine;
import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.util.Optional;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
@@ -83,13 +81,18 @@ class NotificationPlatformPolicyConfig {
.orElseGet(NotificationEligibilityPolicy::permitAll));
}
/** Evidence-aware retry policy. */
/**
* Evidence-aware retry policy, timed by {@code app.notification.platform.retry}.
*
* @param settings the bound platform settings
* @return the policy
*/
@Bean
@ConditionalOnMissingBean
public NotificationRetryPolicy notificationRetryPolicy() {
public NotificationRetryPolicy notificationRetryPolicy(NotificationPlatformSettings settings) {
SecureRandom random = new SecureRandom();
JitterSource jitter = bound -> bound <= 1 ? 0 : Math.floorMod(random.nextLong(), bound);
return new DefaultNotificationRetryPolicy(RetryBackoff.DEFAULT, jitter, Duration.ofMinutes(1));
return new DefaultNotificationRetryPolicy(settings.retry().timing(), jitter);
}
/** Stable routing engine. */
@@ -32,7 +32,6 @@ import org.springframework.context.annotation.Import;
NotificationPlatformProviderConfig.class,
NotificationPlatformPolicyConfig.class,
NotificationPlatformDispatchConfig.class,
NotificationPlatformWorkerConfig.class,
NotificationCallbackProviderConfig.class,
NotificationSesProviderConfig.class,
// The SMTP provider family. It carries its own narrower condition — a relay must be configured —
@@ -1,5 +1,7 @@
package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure;
import dev.caskeleton.application.notification.platform.policy.RetryBackoff;
import dev.caskeleton.application.notification.platform.policy.RetryTiming;
import java.net.URI;
import java.time.Duration;
import java.util.List;
@@ -22,6 +24,7 @@ public record NotificationPlatformSettings(
Dispatch dispatch,
Callbacks callbacks,
ServingThresholds servingThresholds,
Retry retry,
Map<String, Provider> providers) {
@ConstructorBinding
@@ -34,6 +37,7 @@ public record NotificationPlatformSettings(
callbacks = callbacks == null ? Callbacks.defaults() : callbacks;
servingThresholds =
servingThresholds == null ? ServingThresholds.defaults() : servingThresholds;
retry = retry == null ? Retry.defaults() : retry;
providers = providers == null ? Map.of() : Map.copyOf(providers);
boolean callbacksEnabled = callbacks.enabled();
providers.forEach((id, provider) -> provider.validate(id, callbacksEnabled));
@@ -51,6 +55,68 @@ public record NotificationPlatformSettings(
this(enabled, mode, dispatch, callbacks, ServingThresholds.defaults(), providers);
}
/** The settings without a retry block: the shipped retry timing. */
public NotificationPlatformSettings(
boolean enabled,
NotificationPlatformMode mode,
Dispatch dispatch,
Callbacks callbacks,
ServingThresholds servingThresholds,
Map<String, Provider> providers) {
this(enabled, mode, dispatch, callbacks, servingThresholds, Retry.defaults(), providers);
}
/**
* How long a failed delivery waits before its next attempt, and how long an ambiguous one waits
* before the provider is asked what happened.
*
* <p>Settings rather than constants in the policy's assembly: how fast to retry a provider is a
* deployment's call, made against that provider's own rate limits (round9 review 2026-11-12,
* RR9-05-08).
*
* @param backoffBase the first retry's ceiling and the shortest delay
* @param backoffMax the longest delay, a provider's {@code Retry-After} included
* @param reconcileDelay how long after an ambiguous submission reconciliation first asks
*/
public record Retry(Duration backoffBase, Duration backoffMax, Duration reconcileDelay) {
/**
* Binds the block; a key left out takes the shipped value. The defaults and the rules are the
* retry policy's own {@link RetryTiming}: this builds one, which refuses what is not a timing,
* so neither the defaults nor the rules have a second home here.
*/
@ConstructorBinding
public Retry {
backoffBase = backoffBase == null ? RetryTiming.DEFAULT.backoff().base() : backoffBase;
backoffMax = backoffMax == null ? RetryTiming.DEFAULT.backoff().max() : backoffMax;
reconcileDelay =
reconcileDelay == null ? RetryTiming.DEFAULT.reconcileDelay() : reconcileDelay;
timing(backoffBase, backoffMax, reconcileDelay);
}
/**
* The shipped timing.
*
* @return the defaults
*/
public static Retry defaults() {
return new Retry(null, null, null);
}
/**
* The timing the retry policy uses.
*
* @return the timing of these settings
*/
public RetryTiming timing() {
return timing(backoffBase, backoffMax, reconcileDelay);
}
private static RetryTiming timing(Duration base, Duration max, Duration reconcileDelay) {
return new RetryTiming(new RetryBackoff(base, max), reconcileDelay);
}
}
/** Dispatch runtime bounds. */
public record Dispatch(
int claimBatchSize,
@@ -1,175 +0,0 @@
package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure;
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationBackgroundWorkers;
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationDispatchProperties;
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationSchedulerWorker;
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderEventReplayWorker;
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ReconciliationJobWorker;
import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger;
import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService;
import dev.caskeleton.application.notification.platform.dispatch.LeaseRecoveryService;
import dev.caskeleton.application.notification.platform.dispatch.NotificationDispatchService;
import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService;
import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort;
import dev.caskeleton.application.notification.platform.observation.NotificationServingStatePort;
import java.util.UUID;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Background workers and their lifecycle.
*
* <p>Everything that runs on a schedule rather than on a request. They are grouped so that a
* deployment reading its own configuration can see, in one place, what this process starts.
*
* <p>Split out of one 690-line composition class holding 42 beans. A configuration that assembles
* codecs, security, templates, policy, providers and workers at once has no boundary a reader can
* use: every change to any of them is a change to the same file, and nothing states which beans
* belong together (NTF-022).
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(
prefix = "app.notification.platform",
name = "enabled",
havingValue = "true",
matchIfMissing = true)
class NotificationPlatformWorkerConfig {
/*
* Queue worker. Started by the application lifecycle, stopped on shutdown.
*
* <p>The owner carries a per-process nonce, not just a configured name. Every instance used to
* call itself {@code notification-worker-1}, so a restarted process and the one it replaced were
* the same owner as far as the database was concerned — and a stale process's release could clear
* the lease its successor was working under. The nonce makes each incarnation distinguishable;
* the lease fence handles the rest.
*/
/**
* Asks providers what happened to attempts whose outcome is unknown.
*
* @param jobs the outstanding questions
* @param reconciliation the reconciliation service
* @param clock the clock
* @param properties the dispatch bounds
* @return the worker
*/
@Bean
@ConditionalOnMissingBean
public ReconciliationJobWorker reconciliationJobWorker(
ReconciliationJobStorePort jobs,
ReconciliationService reconciliation,
java.time.Clock clock,
NotificationDispatchProperties properties) {
return new ReconciliationJobWorker(
jobs,
reconciliation::reconcile,
clock,
properties.leaseDuration(),
// The claim lease reuses the delivery lease rather than adding a setting. One pass asks
// up to claimBatchSize providers in turn, so a pass slower than the lease lets another
// instance re-ask its remaining jobs; the claim fence keeps those answers recorded once.
properties.leaseDuration(),
properties.claimBatchSize(),
properties.maxAdditionalAttempts() + 1);
}
/**
* Projects provider events that were stored and never applied.
*
* @param ledger the stored events
* @param projection the projection service
* @param properties the dispatch bounds
* @return the replay worker
*/
@Bean
@ConditionalOnMissingBean
public ProviderEventReplayWorker notificationProviderEventReplayWorker(
ProviderEventLedger ledger,
ProviderEventProjectionService projection,
NotificationDispatchProperties properties) {
return new ProviderEventReplayWorker(ledger, projection, properties.claimBatchSize());
}
/**
* Everything that starts a thread, and therefore everything {@code INGEST_ONLY} must not have.
*
* <p>A nested configuration rather than a condition on each bean. Both beans below used to sit on
* the parent, which carried the capability switch alone, and both call {@code start()} in the
* factory method — so a deployment in {@code INGEST_ONLY}, the mode whose whole purpose is to
* accept and store without delivering, started the dispatch scheduler, the lease recovery pass,
* the provider-event replay worker and the reconciliation job. It accepted requests and then
* tried to deliver them, which is the mode not existing.
*
* <p>Structural because a per-bean condition is one a future bean can forget, and the cost of
* forgetting here is not a stray bean — it is a process delivering notifications that an operator
* put into a drain. A configuration that is not loaded cannot be forgotten.
*
* <p>{@code matchIfMissing = true} because {@code SERVING} is the shipped default: an absent mode
* must still deliver, or a missing property becomes a silent drain.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(
prefix = "app.notification.platform",
name = "mode",
havingValue = "SERVING",
matchIfMissing = true)
public static class ServingWorkerConfig {
/**
* Schedules the recovery and replay passes, and stops them on shutdown.
*
* @param recovery the recovery service
* @param replay the replay worker
* @param reconciliation the reconciliation worker
* @param properties the dispatch bounds
* @return the started background workers
*/
@Bean(destroyMethod = "close")
@ConditionalOnMissingBean
public NotificationBackgroundWorkers notificationBackgroundWorkers(
LeaseRecoveryService recovery,
ProviderEventReplayWorker replay,
ReconciliationJobWorker reconciliation,
NotificationDispatchProperties properties) {
NotificationBackgroundWorkers workers =
new NotificationBackgroundWorkers(
recovery,
replay,
reconciliation,
properties.leaseDuration(),
properties.shutdownGrace());
workers.start();
return workers;
}
/**
* The dispatch scheduler.
*
* @param leases the recipient lease store
* @param dispatcher the dispatch service
* @param metrics the metrics port
* @param properties the dispatch bounds
* @param servingState the serving-state port
* @return the started scheduler worker
*/
@Bean(destroyMethod = "close")
public NotificationSchedulerWorker notificationSchedulerWorker(
RecipientLeaseStorePort leases,
NotificationDispatchService dispatcher,
NotificationMetricsPort metrics,
NotificationDispatchProperties properties,
NotificationServingStatePort servingState) {
String owner = "notification-worker-1:" + UUID.randomUUID();
NotificationSchedulerWorker worker =
new NotificationSchedulerWorker(
leases, dispatcher, metrics, properties, servingState, owner);
worker.start();
return worker;
}
}
}
@@ -1,144 +0,0 @@
package dev.caskeleton.adapter.outbound.notification.platform.dispatch;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJob;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort;
import dev.caskeleton.application.notification.platform.provider.ReconciliationResult;
import java.time.Clock;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
/**
* Asks the provider what happened to attempts whose outcome is unknown.
*
* <p>Reconciliation only ever ran when a lease expired and recovery walked past an incomplete
* attempt. An ambiguous submission whose worker exited cleanly — the common case, because a worker
* that records AMBIGUOUS and then finishes its shift has not crashed — was never asked about again.
* The delivery sat {@code RECONCILIATION_REQUIRED} indefinitely, which reads as a queue that
* stopped rather than as an outcome nobody knows.
*
* <p>An unsupported provider is not retried in a loop. Without a status-query capability the answer
* will not change, so the job is completed and the attempt stays visibly ambiguous for an operator
* — a busy loop against a capability that does not exist is how a background worker burns a
* connection pool while achieving nothing.
*
* <p>Every instance runs this worker, so the claim is a lease: the jobs a pass takes are this
* instance's until {@code claimLease} has passed, and no transaction is held while the provider is
* asked. A pass that outlives its lease may find a job taken over by another instance; the store
* then ignores this pass's write for it, so the job is asked about twice but recorded once.
*/
public final class ReconciliationJobWorker {
private final ReconciliationJobStorePort jobs;
private final Function<
dev.caskeleton.application.notification.platform.api.DeliveryAttemptId,
ReconciliationResult>
reconciler;
private final Clock clock;
private final Duration retryBackoff;
private final Duration claimLease;
private final int batchSize;
private final int maxAttempts;
/**
* Creates the worker.
*
* @param jobs the outstanding questions
* @param reconciler asks one attempt's provider
* @param clock the clock
* @param retryBackoff how long to wait before asking again
* @param claimLease how long one pass owns the jobs it claimed; must cover the whole pass
* @param batchSize how many jobs one pass handles
* @param maxAttempts how many times one job may ask before it is left to an operator
*/
public ReconciliationJobWorker(
ReconciliationJobStorePort jobs,
Function<
dev.caskeleton.application.notification.platform.api.DeliveryAttemptId,
ReconciliationResult>
reconciler,
Clock clock,
Duration retryBackoff,
Duration claimLease,
int batchSize,
int maxAttempts) {
this.jobs = Objects.requireNonNull(jobs, "jobs");
this.reconciler = Objects.requireNonNull(reconciler, "reconciler");
this.clock = Objects.requireNonNull(clock, "clock");
this.retryBackoff = Objects.requireNonNull(retryBackoff, "retryBackoff");
if (retryBackoff.isNegative() || retryBackoff.isZero()) {
throw new IllegalArgumentException("retryBackoff must be positive and finite");
}
this.claimLease = Objects.requireNonNull(claimLease, "claimLease");
if (claimLease.isNegative() || claimLease.isZero()) {
throw new IllegalArgumentException("claimLease must be positive");
}
if (batchSize < 1) {
throw new IllegalArgumentException("batchSize");
}
if (maxAttempts < 1) {
throw new IllegalArgumentException("maxAttempts");
}
this.batchSize = batchSize;
this.maxAttempts = maxAttempts;
}
/**
* Runs one pass.
*
* @return how many jobs reached a terminal decision
*/
public int reconcileOnce() {
List<ReconciliationJob> due = jobs.claimDue(batchSize, clock.instant(), claimLease);
int settled = 0;
for (ReconciliationJob job : due) {
// One job's failure is not the pass's: a provider that is refusing connections would
// otherwise stop every other provider's jobs behind it.
try {
if (handle(job)) {
settled++;
}
} catch (RuntimeException failure) {
jobs.reschedule(
job, failure.getClass().getSimpleName(), clock.instant().plus(retryBackoff));
}
}
return settled;
}
private boolean handle(ReconciliationJob job) {
if (job.attempts() >= maxAttempts) {
// Asked enough times. Completing the job leaves the attempt ambiguous and visible rather
// than asking forever; an outcome that has not arrived after this many tries is an
// operator's decision, not a scheduler's.
jobs.reschedule(job, "MAX_ATTEMPTS", clock.instant().plus(retryBackoff));
jobs.complete(job);
return true;
}
ReconciliationResult result = reconciler.apply(job.attemptId());
return switch (result) {
case ReconciliationResult.Confirmed ignored -> {
jobs.complete(job);
yield true;
}
case ReconciliationResult.Unsupported ignored -> {
// The capability does not exist; asking again cannot change that.
jobs.complete(job);
yield true;
}
case ReconciliationResult.StillUnknown stillUnknown -> {
jobs.reschedule(job, "STILL_UNKNOWN", stillUnknown.nextCheckAt());
yield false;
}
case ReconciliationResult.Failed failed -> {
if (failed.retryable()) {
jobs.reschedule(job, failed.code(), clock.instant().plus(retryBackoff));
yield false;
}
jobs.complete(job);
yield true;
}
};
}
}
@@ -5,13 +5,17 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmContactPointProtector;
import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationTemplateEngine;
import dev.caskeleton.adapter.outbound.notification.platform.template.PlaceholderTemplateEngine;
import dev.caskeleton.application.notification.platform.admin.NotificationAdminService;
import dev.caskeleton.application.notification.platform.admin.ChangeProviderStateUseCase;
import dev.caskeleton.application.notification.platform.admin.ChangeSuppressionUseCase;
import dev.caskeleton.application.notification.platform.admin.ReconcileDeliveriesUseCase;
import dev.caskeleton.application.notification.platform.admin.RedriveDeliveryUseCase;
import dev.caskeleton.application.notification.platform.security.ContactPointProtector;
import dev.caskeleton.application.notification.platform.security.SecretKeyMaterial;
import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider;
import dev.caskeleton.application.notification.platform.security.SecretPurpose;
import dev.caskeleton.application.notification.platform.template.TemplateVariableValidator;
import java.util.Arrays;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
@@ -112,8 +116,22 @@ class NotificationPlatformCoreConfigurationTest {
}
@Test
void adminOperationsAreAbsentByDefaultRatherThanPresentAndUnguarded() {
enabled().run(context -> assertThat(context).doesNotHaveBean(NotificationAdminService.class));
void theAdapterAssemblesNoOperatorUseCase() {
enabled()
.run(
context ->
assertThat(
Stream.of(
RedriveDeliveryUseCase.class,
ReconcileDeliveriesUseCase.class,
ChangeSuppressionUseCase.class,
ChangeProviderStateUseCase.class)
.filter(type -> context.getBeanNamesForType(type).length > 0)
.toList())
.as(
"who may perform an operator action is the composition's to assemble, "
+ "behind each use case's permission")
.isEmpty());
}
@Test
@@ -66,13 +66,14 @@ class NotificationPlatformImportCoverageTest {
assertThat(imports).isNotNull();
assertThat(Arrays.stream(imports.value()).map(Class::getSimpleName).toList())
.as("codec, provider, policy, dispatch and worker are the capability's working parts")
.as(
"codec, provider, policy and dispatch are the capability's working parts; the workers"
+ " are the composition's")
.contains(
"NotificationPlatformCodecConfig",
"NotificationPlatformProviderConfig",
"NotificationSesProviderConfig",
"NotificationPlatformPolicyConfig",
"NotificationPlatformDispatchConfig",
"NotificationPlatformWorkerConfig");
"NotificationPlatformDispatchConfig");
}
}
@@ -172,6 +172,105 @@ class NotificationPlatformSettingsTest {
.hasMessageContaining("lease-duration");
}
@Test
@DisplayName("retry 블록이 없으면 backoff 1s~5m, reconcile 1분으로 묶인다")
void anAbsentRetryBlockBindsTheShippedTiming() {
// when
NotificationPlatformSettings settings =
bind(Map.of("app.notification.platform.enabled", "true"));
// then
assertThat(settings.retry())
.extracting(
NotificationPlatformSettings.Retry::backoffBase,
NotificationPlatformSettings.Retry::backoffMax,
NotificationPlatformSettings.Retry::reconcileDelay)
.containsExactly(Duration.ofSeconds(1), Duration.ofMinutes(5), Duration.ofMinutes(1));
}
@Test
@DisplayName("retry 블록에 reconcile-delay만 있으면 backoff는 1s~5m 기본값으로 묶인다")
void aPartialRetryBlockKeepsTheShippedBackoff() {
// when
NotificationPlatformSettings settings =
bind(
Map.of(
"app.notification.platform.enabled", "true",
"app.notification.platform.retry.reconcile-delay", "30s"));
// then
assertThat(settings.retry())
.extracting(
NotificationPlatformSettings.Retry::backoffBase,
NotificationPlatformSettings.Retry::backoffMax,
NotificationPlatformSettings.Retry::reconcileDelay)
.containsExactly(Duration.ofSeconds(1), Duration.ofMinutes(5), Duration.ofSeconds(30));
}
@Test
void theRetryTimingBindsFromTheDeploymentsSettings() {
// given
Map<String, String> properties =
Map.of(
"app.notification.platform.enabled", "true",
"app.notification.platform.retry.backoff-base", "2s",
"app.notification.platform.retry.backoff-max", "10m",
"app.notification.platform.retry.reconcile-delay", "30s");
// when
NotificationPlatformSettings settings = bind(properties);
// then
assertThat(settings.retry())
.isEqualTo(
new NotificationPlatformSettings.Retry(
Duration.ofSeconds(2), Duration.ofMinutes(10), Duration.ofSeconds(30)));
}
@Test
@DisplayName("backoff 상한 30s가 하한 1m보다 짧으면 기동이 retry 블록 이름과 그 이유로 실패한다")
void aBackoffCeilingBelowItsBaseFailsStartup() {
// when
Throwable failure =
catchThrowable(
() ->
bind(
Map.of(
"app.notification.platform.enabled", "true",
"app.notification.platform.retry.backoff-base", "1m",
"app.notification.platform.retry.backoff-max", "30s")));
// then
assertThat(failure)
.as("the policy's own timing refuses it; the binder names the block a deployer fixes")
.isInstanceOf(BindException.class)
.hasMessageContaining("'app.notification.platform.retry'")
.rootCause()
.isInstanceOf(IllegalStateException.class)
.hasMessage("the backoff max (PT30S) must not be shorter than its base (PT1M)");
}
@Test
@DisplayName("결과를 모르는 제출 뒤 기다림이 -1s면 기동이 retry 블록 이름과 그 이유로 실패한다")
void aNegativeReconcileDelayFailsStartup() {
// when
Throwable failure =
catchThrowable(
() ->
bind(
Map.of(
"app.notification.platform.enabled", "true",
"app.notification.platform.retry.reconcile-delay", "-1s")));
// then
assertThat(failure)
.isInstanceOf(BindException.class)
.hasMessageContaining("'app.notification.platform.retry'")
.rootCause()
.isInstanceOf(IllegalStateException.class)
.hasMessage("the reconcile delay must not be negative, was PT-1S");
}
@Test
void defaultsAreUsableAndConservative() {
var defaults = NotificationPlatformSettings.Dispatch.defaults();
@@ -1,99 +0,0 @@
package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
/**
* {@code INGEST_ONLY} starts no dispatch, recovery or reconciliation thread (NTF-INT-003).
*
* <p>The worker configuration carried the master switch and nothing else, and both of its worker
* beans called {@code start()} in the factory method. So a deployment in {@code INGEST_ONLY} — the
* mode whose entire purpose is to accept and store without delivering — started the dispatch
* scheduler, the lease recovery pass, the provider-event replay worker and the reconciliation job.
* It accepted requests and then tried to deliver them, which is the mode not existing.
*
* <p>The gate is structural rather than a condition repeated per bean: the two started beans live
* in a nested configuration the parent imports only in {@code SERVING}. A condition on each bean is
* one a future bean can forget; a configuration that is not loaded cannot be forgotten.
*
* <p>Asserted on the bean methods' own conditions rather than by booting the platform,
* deliberately. A full notification context needs a database, provider credentials and a secrets
* resolver, and the capability has no JPA persistence wired at all yet (Section D) — a test that
* could not run would be no gate. What this checks is the structural fact that decides the thread
* behaviour; the live thread count is asserted by the {@code local-notification-ingest} Compose
* lane, which is where a running thread can actually be counted.
*/
class NotificationWorkerLifecycleTest {
/** The bean methods that start something, and therefore may not exist outside SERVING. */
private static final List<String> THREAD_STARTING_BEANS =
List.of("notificationBackgroundWorkers", "notificationSchedulerWorker");
@Test
@DisplayName("every thread-starting worker bean sits behind the SERVING mode")
void everyThreadStartingBeanIsServingOnly() {
for (String beanMethod : THREAD_STARTING_BEANS) {
Class<?> declaring = declaringConfigurationOf(beanMethod);
ConditionalOnProperty condition = declaring.getAnnotation(ConditionalOnProperty.class);
assertThat(condition)
.as(
"%s starts a thread; the configuration declaring it must carry the mode condition, or "
+ "INGEST_ONLY delivers",
beanMethod)
.isNotNull();
assertThat(condition.prefix()).isEqualTo("app.notification.platform");
assertThat(condition.name()).containsExactly("mode");
assertThat(condition.havingValue()).isEqualTo("SERVING");
assertThat(condition.matchIfMissing())
.as(
"SERVING is the shipped default, so an absent mode must still deliver; making this "
+ "false would turn a missing property into a silent drain")
.isTrue();
}
}
@Test
@DisplayName("the ingest-side beans are not behind the SERVING mode")
void theIngestSideStaysAvailableInBothModes() {
List<String> servingOnly =
Arrays.stream(NotificationPlatformWorkerConfig.class.getDeclaredMethods())
.filter(method -> method.isAnnotationPresent(Bean.class))
.map(Method::getName)
.sorted()
.toList();
assertThat(servingOnly)
.as(
"what stays on the parent is what INGEST_ONLY still needs; a bean moved into the "
+ "SERVING child by accident would stop an ingest-only deployment from accepting")
.doesNotContainAnyElementsOf(THREAD_STARTING_BEANS)
.isNotEmpty();
}
private static Class<?> declaringConfigurationOf(String beanMethod) {
for (Class<?> candidate : NotificationPlatformWorkerConfig.class.getDeclaredClasses()) {
boolean declares =
Arrays.stream(candidate.getDeclaredMethods())
.anyMatch(
method ->
method.getName().equals(beanMethod)
&& method.isAnnotationPresent(Bean.class));
if (declares) {
return candidate;
}
}
throw new AssertionError(
beanMethod
+ " is declared by no nested configuration of NotificationPlatformWorkerConfig; a "
+ "thread-starting bean on the parent runs in every mode");
}
}
@@ -132,14 +132,6 @@ dependencies {
// The application-owned store contracts the notification adapters are held to, the same ones
// the in-memory fakes pass (review 04-14).
postgresqlIntegrationTestImplementation testFixtures(project(':application-notification'))
// The provider-event replay worker lives in the notification adapter and only fails against a
// real JPA stack with no caller transaction, so its real-DB test runs here beside the
// notification stores. Test scope only, like the Fileserver edge. Non-transitive: the worker
// needs only application-notification, which this lane already has, and the adapter's
// mail/Thymeleaf/actuator graph has no business on a database lane.
postgresqlIntegrationTestImplementation(project(':adapter:outbound:notification')) {
transitive = false
}
postgresqlIntegrationTestImplementation testFixtures(project(':application-core'))
postgresqlIntegrationTestImplementation 'org.testcontainers:testcontainers-postgresql'
postgresqlIntegrationTestImplementation 'org.testcontainers:testcontainers-junit-jupiter'
@@ -2,7 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.liveevent;
import dev.caskeleton.adapter.outbound.persistence.liveevent.entity.LiveEventEntity;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.realtime.LiveEventReplayPort;
import dev.caskeleton.application.realtime.LiveEventReplayQueryPort;
import dev.caskeleton.application.realtime.ReplayCursorUnavailableException;
import dev.caskeleton.application.realtime.ReplayWindow;
import dev.caskeleton.application.realtime.ReplayedEvent;
@@ -21,7 +21,7 @@ import org.springframework.jdbc.core.JdbcOperations;
* <p>Durable history lives here rather than in a transport adapter for one reason: a second copy
* would have its own retention, its own eviction and its own opinion about ordering, and the two
* would diverge silently because both would look plausible. The web and websocket modules reach it
* through {@link LiveEventReplayPort} and hold nothing.
* through {@link LiveEventReplayQueryPort} and hold nothing.
*
* <p>Positions are assigned per stream and are never reused, including after a sweep. Reusing a
* swept position would give two different events the same address, and a client holding the older
@@ -33,7 +33,7 @@ import org.springframework.jdbc.core.JdbcOperations;
* The counter update and event insert share this method's transaction, so a failed event insert
* also rolls the allocation back.
*/
public final class JpaLiveEventReplay implements LiveEventReplayPort {
public final class JpaLiveEventReplay implements LiveEventReplayQueryPort {
/** The most one replay call will load, whatever the caller asks for. */
public static final int MAX_REPLAY_LIMIT = 500;
@@ -5,8 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.liveevent.entity.LiveEventEntity;
import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport;
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction;
import dev.caskeleton.application.realtime.LiveEventReplayPort;
import dev.caskeleton.application.realtime.testkit.LiveEventReplayContract;
import dev.caskeleton.application.realtime.LiveEventReplayQueryPort;
import dev.caskeleton.application.realtime.testkit.LiveEventReplayQueryContract;
import dev.caskeleton.application.transaction.TransactionPort;
import jakarta.persistence.EntityManagerFactory;
import java.io.IOException;
@@ -45,7 +45,7 @@ import org.springframework.transaction.PlatformTransactionManager;
* allocates through the position counter rather than reusing a swept position.
*/
@Tag("jpa-contract")
class JpaLiveEventReplayContractTest extends LiveEventReplayContract {
class JpaLiveEventReplayContractTest extends LiveEventReplayQueryContract {
private static final Duration RETENTION = Duration.ofHours(1);
@@ -88,7 +88,7 @@ class JpaLiveEventReplayContractTest extends LiveEventReplayContract {
}
@Override
protected LiveEventReplayPort replay() {
protected LiveEventReplayQueryPort replay() {
return adapter();
}
@@ -3,7 +3,6 @@ package dev.caskeleton.adapter.outbound.persistence.readiness;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderEventReplayWorker;
import dev.caskeleton.adapter.outbound.persistence.notification.NotificationTestCodecs;
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaDeliveryAttemptStore;
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationRequestStore;
@@ -41,6 +40,8 @@ import dev.caskeleton.application.notification.platform.callback.ProjectionResul
import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService;
import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector;
import dev.caskeleton.application.notification.platform.callback.ProviderEventRecord;
import dev.caskeleton.application.notification.platform.callback.ReplayProviderEventsCommand;
import dev.caskeleton.application.notification.platform.callback.ReplayProviderEventsUseCase;
import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFactory;
import dev.caskeleton.application.notification.platform.dispatch.LeaseRecoveryService;
import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestRecord;
@@ -322,7 +323,7 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest {
UUID event = insertPendingEvent(null, requestHash);
// when
replay().replayOnce();
replay().handle(new ReplayProviderEventsCommand());
// then
assertThat(eventRow(event)).containsExactly(attempt.toString(), "APPLIED", null);
@@ -336,7 +337,7 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest {
UUID event = insertPendingEvent(attempt, null);
// when
replay().replayOnce();
replay().handle(new ReplayProviderEventsCommand());
// then
assertThat(eventRow(event))
@@ -381,8 +382,8 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest {
10);
}
private ProviderEventReplayWorker replay() {
return new ProviderEventReplayWorker(ledger, projection, 10);
private ReplayProviderEventsUseCase replay() {
return new ReplayProviderEventsUseCase(projection, 10);
}
private JpaRecipientDeliveryStore deliveries(RecipientDeliveryJpaRepository recipients) {
@@ -33,10 +33,10 @@ public final class JpaAdminOperationStore implements AdminOperationStorePort {
@Override
public dev.caskeleton.application.notification.platform.admin.AdminOperationClaim claim(
String operationId, String commandFingerprint, AdminActor actor, String action) {
String operationId, String requestFingerprint, AdminActor actor, String action) {
CallerTransaction.require("admin operation claim");
Objects.requireNonNull(operationId, "operationId");
Objects.requireNonNull(commandFingerprint, "commandFingerprint");
Objects.requireNonNull(requestFingerprint, "requestFingerprint");
Objects.requireNonNull(actor, "actor");
Objects.requireNonNull(action, "action");
@@ -46,7 +46,7 @@ public final class JpaAdminOperationStore implements AdminOperationStorePort {
operationId,
action,
actor.actorRef(),
commandFingerprint,
requestFingerprint,
clock.instant());
if (claimed == 1) {
return dev.caskeleton.application.notification.platform.admin.AdminOperationClaim.claimed();
@@ -61,7 +61,7 @@ public final class JpaAdminOperationStore implements AdminOperationStorePort {
}
String phase = String.valueOf(existing.get(0)[0]);
String fingerprint = existing.get(0)[1] == null ? null : String.valueOf(existing.get(0)[1]);
if (fingerprint != null && !fingerprint.equals(commandFingerprint)) {
if (fingerprint != null && !fingerprint.equals(requestFingerprint)) {
// The same id, a different command. Returning the earlier result would execute neither.
return dev.caskeleton.application.notification.platform.admin.AdminOperationClaim.conflict();
}
@@ -39,9 +39,10 @@ public final class JpaRecipientLeaseStore implements RecipientLeaseStorePort {
}
/**
* The one write here without {@code CallerTransaction.require}: the scheduler claims before any
* use case runs, and the claim is a single CTE statement that selects, locks and fences its rows
* by itself — there is no second write it has to be atomic with.
* The one write here without {@code CallerTransaction.require}: the claim is a single CTE
* statement that selects, locks and fences its rows by itself — there is no second write it has
* to be atomic with. {@code ClaimDueDeliveriesUseCase} opens a write transaction around it
* anyway, as every use case that writes does.
*/
@Override
public List<RecipientLease> claim(String workerId, int limit, Duration leaseDuration) {
+2 -1
View File
@@ -73,11 +73,12 @@ architectureTest)가 강제한다. 나머지는 리뷰 규칙이고, 리뷰가
|---|---|---|---|
| 유스케이스(inbound 포트 구현) | `<Verb><Noun>UseCase`, ArchUnit이 강제 | 기능의 `application` 패키지 | `*ApplicationUseCase`(application-fileserver, application-notification), `*Service`(notification, fileserver) |
| command·query record | `*Command` / `*Query` | 그 유스케이스 옆 | — |
| 요청 값 record: command가 담는 호출자 요청 내용(호출자가 누구인지는 뺀 값), 또는 포트 인자 묶음 | `*Request` | 그것을 담는 command나 받는 포트 옆 | `CreateUploadRequest`·`FinalizeUploadRequest`(application-fileserver `upload`, command는 `port.in`), `VerificationRequest`(application-fileserver `api.security`, 포트는 `upload`), application-objectstorage의 `request` 패키지(포트는 `port`, leaf가 값 타입 패키지로 정했다) |
| aggregate 영속(aggregate 전체를 저장하고 돌려준다) | `<Aggregate>Repository` | aggregate의 **domain** 패키지, 도메인이 가진다 | — |
| 애플리케이션이 가진 기술 저장소(outbox, 멱등성, operation 행) | `<Thing>StorePort` | application 패키지 | `*WritePort`(옛 onboarding fixture, 지움) |
| aggregate가 아니라 projection을 돌려주는 읽기 모델 | `<Thing>QueryPort` | application 패키지. projection만 돌려준다(ArchUnit) | — |
| 그 밖의 outbound 포트 | `<Capability>Port` | application 패키지 | — |
| 서버가 정하는 id 생성 | `<Aggregate>IdFactory extends IdFactory<<Aggregate>Id>` | domain 패키지. id record는 `implements ResourceId<Self>` | `DurableOperationIdFactory`(durable operation id는 aggregate의 resource id가 아니라 `IdFactory`를 따르지 않는다) |
| 서버가 정하는 id 생성 | `<Aggregate>IdFactory extends IdFactory<<Aggregate>Id>` | domain 패키지. id record는 `implements ResourceId<Self>` | `DurableOperationIdFactory`(durable operation id는 aggregate의 resource id가 아니라 `IdFactory`를 따르지 않는다), `NotificationIdGeneratorPort`(application-notification), `UploadIdentifierPort`(application-fileserver). 셋 다 사용자 전송이 쥐면 `USER_TRANSPORTS_DO_NOT_HOLD_PERSISTENCE_OR_ID_PORTS`가 막는다 |
| 설정 바인딩 | `*Settings`(운영) 또는 `*Policy`(인가·도메인 정책), ArchUnit이 강제 | 그것을 바인딩하는 leaf | — |
| Throwable | `*Exception`, ArchUnit이 강제 | — | — |
| 포트의 계약 시험 키트 | 포트 소유자의 testFixtures에 둔 추상 `<Port>Contract`. fake의 시험과 각 어댑터의 시험이 상속한다 | testFixtures | 값 타입 시험의 이름이 한때 `*ContractTest`였다. 지금은 `*ValueTypesTest`다 |
@@ -0,0 +1,16 @@
package dev.caskeleton.application.realtime;
import dev.caskeleton.application.query.Query;
import java.util.Objects;
/**
* A reconnecting client's stream, asked what it still holds.
*
* @param streamId which stream
*/
public record GetReplayWindowQuery(String streamId) implements Query {
public GetReplayWindowQuery {
Objects.requireNonNull(streamId, "streamId");
}
}
@@ -0,0 +1,41 @@
package dev.caskeleton.application.realtime;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.QueryUseCase;
import java.util.Objects;
/**
* What a stream still holds, so a transport can tell "your cursor is too old" from "nothing new".
*
* <p>Every read goes through a query use case: a transport adapter that held {@link
* LiveEventReplayQueryPort} itself read the event log with no capability declared and no read
* boundary (round9 review 2026-11-12, RR9-05-10).
*/
@UseCaseCapability(
transactionMode = TransactionMode.READ_ONLY,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.READ_REPOSITORY)
public class GetReplayWindowUseCase implements QueryUseCase<GetReplayWindowQuery, ReplayWindow> {
private final LiveEventReplayQueryPort replay;
private final TransactionPort transactions;
/**
* @param replay the retained event history
* @param transactions opens the read transaction
*/
public GetReplayWindowUseCase(LiveEventReplayQueryPort replay, TransactionPort transactions) {
this.replay = Objects.requireNonNull(replay, "replay");
this.transactions = Objects.requireNonNull(transactions, "transactions");
}
@Override
public ReplayWindow handle(GetReplayWindowQuery query) {
Objects.requireNonNull(query, "query");
return transactions.inRead(() -> replay.window(query.streamId()));
}
}
@@ -5,15 +5,18 @@ import java.util.List;
/**
* Retained event history, for a client that reconnects and wants to continue.
*
* <p>The history lives wherever the messaging platform keeps it, and this port is the only way a
* transport adapter reaches it. That boundary is the point: a web or websocket module that kept its
* own copy would have its own retention, its own eviction and its own opinion about ordering, and
* the two would diverge silently because both would look plausible.
* <p>The history lives wherever the messaging platform keeps it, and this port is the only way to
* it — through {@code GetReplayWindowUseCase} and {@code ReplayLiveEventsUseCase}, never from a
* transport directly. A read model that returns projections, so a {@code *QueryPort}: named {@code
* LiveEventReplayPort} until 2026-11-13, when a web bridge that held it read the log with no use
* case in between (round9 review 2026-11-12, RR9-05-10). That boundary is the point: a web or
* websocket module that kept its own copy would have its own retention, its own eviction and its
* own opinion about ordering, and the two would diverge silently because both would look plausible.
*
* <p>{@link #window} exists so a caller can distinguish "your cursor is too old" from "there is
* nothing new", which {@link #replayAfter} returning an empty list cannot.
*/
public interface LiveEventReplayPort {
public interface LiveEventReplayQueryPort {
/** What the stream still holds. */
ReplayWindow window(String streamId);
@@ -0,0 +1,22 @@
package dev.caskeleton.application.realtime;
import dev.caskeleton.application.query.Query;
import java.util.Objects;
/**
* A reconnecting client's request for what it missed.
*
* @param streamId which stream
* @param afterPosition the last position the client already has; 0 for the beginning
* @param limit the most events to return
*/
public record ReplayLiveEventsQuery(String streamId, long afterPosition, int limit)
implements Query {
public ReplayLiveEventsQuery {
Objects.requireNonNull(streamId, "streamId");
if (afterPosition < 0 || limit < 1) {
throw new IllegalArgumentException("afterPosition must be >= 0 and limit >= 1");
}
}
}
@@ -0,0 +1,45 @@
package dev.caskeleton.application.realtime;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.QueryUseCase;
import java.util.List;
import java.util.Objects;
/**
* The events a reconnecting client missed, a bounded page at a time.
*
* @see GetReplayWindowUseCase
*/
@UseCaseCapability(
transactionMode = TransactionMode.READ_ONLY,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.READ_REPOSITORY)
public class ReplayLiveEventsUseCase
implements QueryUseCase<ReplayLiveEventsQuery, List<ReplayedEvent>> {
private final LiveEventReplayQueryPort replay;
private final TransactionPort transactions;
/**
* @param replay the retained event history
* @param transactions opens the read transaction
*/
public ReplayLiveEventsUseCase(LiveEventReplayQueryPort replay, TransactionPort transactions) {
this.replay = Objects.requireNonNull(replay, "replay");
this.transactions = Objects.requireNonNull(transactions, "transactions");
}
/**
* @throws ReplayCursorUnavailableException when the position is older than what is retained
*/
@Override
public List<ReplayedEvent> handle(ReplayLiveEventsQuery query) {
Objects.requireNonNull(query, "query");
return transactions.inRead(
() -> replay.replayAfter(query.streamId(), query.afterPosition(), query.limit()));
}
}
@@ -1,17 +1,17 @@
package dev.caskeleton.application.realtime.testkit;
import dev.caskeleton.application.realtime.LiveEventReplayPort;
import dev.caskeleton.application.realtime.LiveEventReplayQueryPort;
import java.time.Duration;
/** The in-memory history keeps the replay contract the transport tests run over. */
class InMemoryLiveEventReplayContractTest extends LiveEventReplayContract {
class InMemoryLiveEventReplayContractTest extends LiveEventReplayQueryContract {
private static final Duration RETENTION = Duration.ofHours(1);
private final InMemoryLiveEventReplay replay = new InMemoryLiveEventReplay(clock(), RETENTION);
@Override
protected LiveEventReplayPort replay() {
protected LiveEventReplayQueryPort replay() {
return replay;
}
@@ -1,6 +1,6 @@
package dev.caskeleton.application.realtime.testkit;
import dev.caskeleton.application.realtime.LiveEventReplayPort;
import dev.caskeleton.application.realtime.LiveEventReplayQueryPort;
import dev.caskeleton.application.realtime.ReplayCursorUnavailableException;
import dev.caskeleton.application.realtime.ReplayWindow;
import dev.caskeleton.application.realtime.ReplayedEvent;
@@ -15,15 +15,15 @@ import java.util.Objects;
import java.util.Optional;
/**
* In-memory {@link LiveEventReplayPort} with the rules of the JPA history: positions per stream
* from 1 and never reused, an event replayable until {@code appendedAt + retention} on the given
* clock, a cursor older than what is retained refused with {@link
* ReplayCursorUnavailableException}. {@link LiveEventReplayContract} holds it and the JPA store to
* the same cases.
* In-memory {@link LiveEventReplayQueryPort} with the rules of the JPA history: positions per
* stream from 1 and never reused, an event replayable until {@code appendedAt + retention} on the
* given clock, a cursor older than what is retained refused with {@link
* ReplayCursorUnavailableException}. {@link LiveEventReplayQueryContract} holds it and the JPA
* store to the same cases.
*
* <p>Single-threaded: one instance per test.
*/
public final class InMemoryLiveEventReplay implements LiveEventReplayPort {
public final class InMemoryLiveEventReplay implements LiveEventReplayQueryPort {
private record Stored(ReplayedEvent event, Instant retainedUntil) {}
@@ -3,7 +3,7 @@ package dev.caskeleton.application.realtime.testkit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.realtime.LiveEventReplayPort;
import dev.caskeleton.application.realtime.LiveEventReplayQueryPort;
import dev.caskeleton.application.realtime.ReplayCursorUnavailableException;
import dev.caskeleton.application.realtime.ReplayWindow;
import dev.caskeleton.application.realtime.ReplayedEvent;
@@ -18,14 +18,14 @@ import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* What every {@link LiveEventReplayPort} promises a reconnecting client, run against the in-memory
* fake and the JPA history on real PostgreSQL.
* What every {@link LiveEventReplayQueryPort} promises a reconnecting client, run against the
* in-memory fake and the JPA history on real PostgreSQL.
*
* <p>Writing history is not on the port (a transport reads it and never writes it), so each
* implementation supplies its own {@link #append}. Retention is measured on {@link #clock()}, which
* the implementation is built with and the contract moves.
*/
public abstract class LiveEventReplayContract {
public abstract class LiveEventReplayQueryContract {
private final ContractClock clock = new ContractClock(Instant.parse("2026-11-03T00:00:00Z"));
@@ -43,7 +43,7 @@ public abstract class LiveEventReplayContract {
*
* @return the port
*/
protected abstract LiveEventReplayPort replay();
protected abstract LiveEventReplayQueryPort replay();
/**
* Appends an event the way the store's writer does.
@@ -0,0 +1,18 @@
package dev.caskeleton.application.fileserver.cleanup;
import dev.caskeleton.application.command.Command;
/**
* The bounds of one unattended cleanup batch.
*
* @param maxItems most queued items the batch claims
* @param maxBytes most bytes the batch reclaims before it stops starting items
*/
public record RunScheduledCleanupCommand(int maxItems, long maxBytes) implements Command {
public RunScheduledCleanupCommand {
if (maxItems < 1 || maxBytes < 1) {
throw new IllegalStateException("cleanup batch bounds must be positive");
}
}
}
@@ -0,0 +1,48 @@
package dev.caskeleton.application.fileserver.cleanup;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.security.SystemInvoked;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.util.Objects;
/**
* One unattended cleanup batch: reclaim what the queue holds, within the batch bounds.
*
* <p>The same work an operator starts with {@code CleanupUploadsUseCase}, which declares {@code
* file:admin}. A write both a user and the system start is two use cases: this one is the
* scheduler's, on a thread with no {@code Authentication}, so it carries no permission and no user
* transport may reach it.
*
* <p>{@code RepositoryAccess.NONE}: the batch is {@link CleanupService}'s, which opens a boundary
* per claimed item. One around the whole batch would hold a connection across every deletion.
*
* <p><b>Not a bean.</b> The Fileserver composition's cleanup worker constructs it and keeps it.
*/
@SystemInvoked(
reason =
"the Fileserver cleanup worker runs it on the scheduler thread, which has no"
+ " Authentication; an operator's run is CleanupUploadsUseCase with file:admin")
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.NONE,
// The cleanup service deletes staged and orphaned objects in the object store.
externalOutboundAllowed = true)
public class RunScheduledCleanupUseCase
implements CommandUseCase<RunScheduledCleanupCommand, CleanupBatchResult> {
private final CleanupService cleanup;
public RunScheduledCleanupUseCase(CleanupService cleanup) {
this.cleanup = Objects.requireNonNull(cleanup, "cleanup");
}
@Override
public CleanupBatchResult handle(RunScheduledCleanupCommand command) {
Objects.requireNonNull(command, "command");
return cleanup.runBatch(command.maxItems(), command.maxBytes());
}
}
@@ -3,6 +3,7 @@ package dev.caskeleton.application.fileserver.port.in;
import dev.caskeleton.application.command.Command;
import dev.caskeleton.application.fileserver.api.security.RequestContext;
import java.util.Objects;
import java.util.Optional;
/**
* Run one cleanup batch.
@@ -14,7 +15,28 @@ import java.util.Objects;
public record CleanupUploadsCommand(int maxItems, long maxBytes, RequestContext context)
implements Command {
/** How many queued items a request that names no bound processes. */
public static final int DEFAULT_MAX_ITEMS = 100;
/** The byte budget of a request that names none: 1 GiB. */
public static final long DEFAULT_MAX_BYTES = 1L << 30;
public CleanupUploadsCommand {
Objects.requireNonNull(context, "context");
}
/**
* The batch a request asks for, with absent bounds at the use case's defaults rather than at
* whatever a transport chose (round9 review 2026-11-12, RR9-05-19).
*
* @param maxItems absent means {@link #DEFAULT_MAX_ITEMS}
* @param maxBytes absent means {@link #DEFAULT_MAX_BYTES}
* @param context the operator
* @return the command
*/
public static CleanupUploadsCommand requested(
Optional<Integer> maxItems, Optional<Long> maxBytes, RequestContext context) {
return new CleanupUploadsCommand(
maxItems.orElse(DEFAULT_MAX_ITEMS), maxBytes.orElse(DEFAULT_MAX_BYTES), context);
}
}
@@ -3,6 +3,7 @@ package dev.caskeleton.application.fileserver.port.in;
import dev.caskeleton.application.fileserver.api.security.RequestContext;
import dev.caskeleton.application.query.Query;
import java.util.Objects;
import java.util.Optional;
/**
* List incomplete uploads.
@@ -12,7 +13,16 @@ import java.util.Objects;
*/
public record ListIncompleteUploadsQuery(int limit, RequestContext context) implements Query {
/** How many a request that names no limit lists. */
public static final int DEFAULT_LIMIT = 100;
public ListIncompleteUploadsQuery {
Objects.requireNonNull(context, "context");
}
/** The query a request asks for; an absent limit is {@link #DEFAULT_LIMIT}. */
public static ListIncompleteUploadsQuery requested(
Optional<Integer> limit, RequestContext context) {
return new ListIncompleteUploadsQuery(limit.orElse(DEFAULT_LIMIT), context);
}
}
@@ -3,6 +3,7 @@ package dev.caskeleton.application.fileserver.port.in;
import dev.caskeleton.application.fileserver.api.security.RequestContext;
import dev.caskeleton.application.query.Query;
import java.util.Objects;
import java.util.Optional;
/**
* List orphaned objects.
@@ -12,7 +13,15 @@ import java.util.Objects;
*/
public record ListOrphansQuery(int limit, RequestContext context) implements Query {
/** How many a request that names no limit lists. */
public static final int DEFAULT_LIMIT = 100;
public ListOrphansQuery {
Objects.requireNonNull(context, "context");
}
/** The query a request asks for; an absent limit is {@link #DEFAULT_LIMIT}. */
public static ListOrphansQuery requested(Optional<Integer> limit, RequestContext context) {
return new ListOrphansQuery(limit.orElse(DEFAULT_LIMIT), context);
}
}
@@ -4,6 +4,7 @@ import dev.caskeleton.application.command.Command;
import dev.caskeleton.application.fileserver.api.security.RequestContext;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* Request to reconcile orphaned physical objects.
@@ -45,9 +46,55 @@ public record OrphanReconcileCommand(
expectedFingerprints = List.copyOf(expectedFingerprints);
}
/** How many candidates a request that names no limit considers. */
public static final int DEFAULT_LIMIT = 100;
/** The byte budget of an apply that names none: 1 GiB. */
public static final long DEFAULT_APPLY_MAX_BYTES = 1L << 30;
/** The audit reason of an apply that names none. */
public static final String DEFAULT_APPLY_REASON = "ORPHAN_APPLY";
/** Bounded dry run, the default and the only shape a caller can reach without opting in. */
public static OrphanReconcileCommand dryRun(int limit, RequestContext context) {
return new OrphanReconcileCommand(
true, limit, Long.MAX_VALUE, List.of(), "ORPHAN_SCAN", context);
}
/**
* The command a request asks for, with every absent field at its safe value: a dry run, the
* default page, no fingerprints.
*
* <p>The defaults are the use case's, not the transport's, so every transport that offers the
* operation reaches the same ones; they used to be written into the HTTP controller (round9
* review 2026-11-12, RR9-05-19). Nothing here can be omitted into a destructive default: an apply
* still has to name its fingerprints.
*
* @param dryRun list only; absent means true
* @param limit the most candidates; absent means {@link #DEFAULT_LIMIT}
* @param maxBytes an apply's byte budget; absent means {@link #DEFAULT_APPLY_MAX_BYTES}
* @param expectedFingerprints the objects an apply may remove; absent means none
* @param reasonCode an apply's audit reason; absent means {@link #DEFAULT_APPLY_REASON}
* @param context the operator
* @return the command
*/
public static OrphanReconcileCommand requested(
Optional<Boolean> dryRun,
Optional<Integer> limit,
Optional<Long> maxBytes,
Optional<List<String>> expectedFingerprints,
Optional<String> reasonCode,
RequestContext context) {
int page = limit.orElse(DEFAULT_LIMIT);
if (dryRun.orElse(true)) {
return dryRun(page, context);
}
return new OrphanReconcileCommand(
false,
page,
maxBytes.orElse(DEFAULT_APPLY_MAX_BYTES),
expectedFingerprints.orElse(List.of()),
reasonCode.orElse(DEFAULT_APPLY_REASON),
context);
}
}
@@ -0,0 +1,17 @@
package dev.caskeleton.application.fileserver.recovery;
import dev.caskeleton.application.command.Command;
/**
* The bound of one unattended reconciliation pass.
*
* @param limit most open recovery items the pass settles
*/
public record ReconcileRecoverableFilesCommand(int limit) implements Command {
public ReconcileRecoverableFilesCommand {
if (limit < 1) {
throw new IllegalStateException("reconciliation limit must be positive");
}
}
}
@@ -0,0 +1,48 @@
package dev.caskeleton.application.fileserver.recovery;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.security.SystemInvoked;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.util.List;
import java.util.Objects;
/**
* One unattended reconciliation pass: settle the files an ambiguous publish or an unconfirmed
* commit left open, a bounded number at a time.
*
* <p>The scheduler's, on a thread with no {@code Authentication}, so it carries no permission and
* no user transport may reach it.
*
* <p>{@code RepositoryAccess.NONE}: each file is {@link FileReconciliationService}'s to settle, in
* a boundary of its own around each write.
*
* <p><b>Not a bean.</b> The Fileserver composition's cleanup worker constructs it and keeps it.
*/
@SystemInvoked(
reason =
"the Fileserver cleanup worker runs it on the scheduler thread, which has no"
+ " Authentication")
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.NONE,
// The reconciliation service reads the object store to decide each file.
externalOutboundAllowed = true)
public class ReconcileRecoverableFilesUseCase
implements CommandUseCase<ReconcileRecoverableFilesCommand, List<ReconciliationResult>> {
private final FileReconciliationService reconciliation;
public ReconcileRecoverableFilesUseCase(FileReconciliationService reconciliation) {
this.reconciliation = Objects.requireNonNull(reconciliation, "reconciliation");
}
@Override
public List<ReconciliationResult> handle(ReconcileRecoverableFilesCommand command) {
Objects.requireNonNull(command, "command");
return reconciliation.reconcileRecoverable(command.limit());
}
}
@@ -0,0 +1,60 @@
package dev.caskeleton.application.fileserver.cleanup;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.security.SystemInvoked;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* The scheduler's cleanup run is a use case of its own, apart from the operator's (round9 review
* 2026-11-12, RR9-05-06).
*/
class RunScheduledCleanupUseCaseTest {
@Test
@DisplayName("예약 cleanup은 command의 항목·byte 상한으로 batch 하나를 돌린다")
void aScheduledRunReclaimsOneBatchWithinTheCommandsBounds() {
// given
List<List<Long>> batches = new ArrayList<>();
RunScheduledCleanupUseCase useCase =
new RunScheduledCleanupUseCase(
(maxItems, maxBytes) -> {
batches.add(List.of((long) maxItems, maxBytes));
return CleanupBatchResult.empty();
});
// when
useCase.handle(new RunScheduledCleanupCommand(25, 4_096));
// then
assertThat(batches).containsExactly(List.of(25L, 4_096L));
}
@Test
@DisplayName("시스템만 부르는 쓰기라 권한을 선언하지 않고 @SystemInvoked로 그 이유를 적는다")
void itIsMarkedAsTheSystemsAndDeclaresNoPermission() {
assertThat(
List.of(
RunScheduledCleanupUseCase.class.isAnnotationPresent(SystemInvoked.class),
RunScheduledCleanupUseCase.class.isAnnotationPresent(RequiresPermission.class)))
.containsExactly(true, false);
}
@Test
@DisplayName("상한이 0인 batch는 만들 수 없다")
void aBatchWithNoRoomIsRefused() {
// when
Throwable refused = catchThrowable(() -> new RunScheduledCleanupCommand(0, 4_096));
// then
assertThat(refused)
.as("the worker's settings build the batch, so a bad bound is the assembly's fault")
.isInstanceOf(IllegalStateException.class)
.hasMessage("cleanup batch bounds must be positive");
}
}
@@ -0,0 +1,116 @@
package dev.caskeleton.application.fileserver.port.in;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.fileserver.api.security.FileAccessSubject;
import dev.caskeleton.application.fileserver.api.security.RequestContext;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* What an operator's admin request means when it leaves a field out.
*
* <p>The defaults are the use case's, not the transport's: the controller used to fill them in
* itself, so a second transport would have had to copy them (round9 review 2026-11-12, RR9-05-19).
*/
class AdminRequestDefaultsTest {
private static final RequestContext OPERATOR =
new RequestContext(FileAccessSubject.of("operator-1", Set.of("admin")), "trace-1", "node-a");
@Test
@DisplayName("값을 하나도 주지 않은 orphan 정리 요청은 dry run이고 아무것도 지우지 않는다")
void anOrphanRequestWithNothingSetIsADryRun() {
// when
OrphanReconcileCommand command =
OrphanReconcileCommand.requested(
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
OPERATOR);
// then
assertThat(command)
.extracting(
OrphanReconcileCommand::dryRun,
OrphanReconcileCommand::limit,
OrphanReconcileCommand::expectedFingerprints)
.containsExactly(true, OrphanReconcileCommand.DEFAULT_LIMIT, List.of());
}
@Test
@DisplayName("apply 요청은 byte 상한 1GiB와 기본 이유 코드를 받는다")
void anApplyRequestGetsTheDefaultByteCeilingAndReason() {
// when
OrphanReconcileCommand command =
OrphanReconcileCommand.requested(
Optional.of(false),
Optional.empty(),
Optional.empty(),
Optional.of(List.of("f".repeat(64))),
Optional.empty(),
OPERATOR);
// then
assertThat(command)
.extracting(
OrphanReconcileCommand::dryRun,
OrphanReconcileCommand::maxBytes,
OrphanReconcileCommand::reasonCode)
.containsExactly(false, 1L << 30, "ORPHAN_APPLY");
}
@Test
@DisplayName("지울 fingerprint를 대지 않은 apply 요청은 거절한다")
void anApplyRequestThatNamesNoFingerprintIsRefused() {
// when
Throwable refused =
catchThrowable(
() ->
OrphanReconcileCommand.requested(
Optional.of(false),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
OPERATOR));
// then
assertThat(refused)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("an apply must name the fingerprints it intends to remove");
}
@Test
@DisplayName("cleanup 요청은 항목 100개·1GiB 상한을 기본으로 받는다")
void aCleanupRequestGetsTheDefaultBatchBounds() {
// when
CleanupUploadsCommand command =
CleanupUploadsCommand.requested(Optional.empty(), Optional.empty(), OPERATOR);
// then
assertThat(command)
.extracting(CleanupUploadsCommand::maxItems, CleanupUploadsCommand::maxBytes)
.containsExactly(100, 1L << 30);
}
@Test
@DisplayName("목록 조회는 쪽 크기 100을 기본으로 받고, 준 값은 그대로 쓴다")
void listingsDefaultToAPageOfOneHundredAndKeepAGivenLimit() {
// when
List<Integer> limits =
List.of(
ListOrphansQuery.requested(Optional.empty(), OPERATOR).limit(),
ListIncompleteUploadsQuery.requested(Optional.empty(), OPERATOR).limit(),
ListOrphansQuery.requested(Optional.of(7), OPERATOR).limit());
// then
assertThat(limits).containsExactly(100, 100, 7);
}
}
@@ -0,0 +1,68 @@
package dev.caskeleton.application.fileserver.recovery;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.security.SystemInvoked;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* The scheduler's reconciliation pass is a {@code @SystemInvoked} use case (round9 review
* 2026-11-12, RR9-05-06).
*/
class ReconcileRecoverableFilesUseCaseTest {
@Test
@DisplayName("예약 reconcile은 command의 상한만큼 열린 복구 항목을 정리한다")
void aScheduledPassSettlesAsManyOpenItemsAsTheCommandAllows() {
// given
List<Integer> limits = new ArrayList<>();
ReconcileRecoverableFilesUseCase useCase =
new ReconcileRecoverableFilesUseCase(
new FileReconciliationService() {
@Override
public ReconciliationResult reconcile(FileId fileId) {
throw new UnsupportedOperationException("the pass reconciles in batches only");
}
@Override
public List<ReconciliationResult> reconcileRecoverable(int limit) {
limits.add(limit);
return List.of();
}
});
// when
useCase.handle(new ReconcileRecoverableFilesCommand(40));
// then
assertThat(limits).containsExactly(40);
}
@Test
void itIsMarkedAsTheSystemsAndDeclaresNoPermission() {
assertThat(
List.of(
ReconcileRecoverableFilesUseCase.class.isAnnotationPresent(SystemInvoked.class),
ReconcileRecoverableFilesUseCase.class.isAnnotationPresent(
RequiresPermission.class)))
.containsExactly(true, false);
}
@Test
@DisplayName("상한이 0인 pass는 만들 수 없고, 조립의 잘못으로 실패한다")
void aPassWithNoRoomIsRefused() {
// when
Throwable refused = catchThrowable(() -> new ReconcileRecoverableFilesCommand(0));
// then
assertThat(refused)
.isInstanceOf(IllegalStateException.class)
.hasMessage("reconciliation limit must be positive");
}
}
+2
View File
@@ -20,6 +20,8 @@
- framework 의존이 없다(`ca.java-library`). Spring·JPA·HTTP 타입을 쓰지 않는다. 허용 의존은 registry의 `application-core`·`shared-contract`뿐이다.
- 전송 DTO(HTTP 요청·응답 record)를 여기에 두지 않는다. 전송 모양은 `adapter:inbound:web-notification`의 것이다.
- 발송 판정(마케팅 억제, category 필수)은 여기서 한다. 전송이나 설정에서 기본값을 골라 넣지 않는다.
- 시스템이 부르는 쓰기는 `@SystemInvoked` 유스케이스다: 발송 claim·발송(`ClaimDueDeliveriesUseCase`·`DispatchClaimedDeliveryUseCase`), lease 회복, provider 결과 맞추기, provider event 다시 투영. `composition:notification-platform`의 worker가 `new`로 만들어 쥐고, bean으로 두지 않는다. 그 유스케이스가 감싸는 서비스(`LeaseRecoveryService`·`ReconciliationService` 등)는 bean이지만 inbound가 쥐면 빌드가 실패한다(`INBOUND_ADAPTERS_DEPEND_ON_PORTS_NOT_APPLICATION_SERVICES`). 언제 다시 묻고 언제 포기하는지는 이 유스케이스가 정한다. worker는 스레드와 일정만 가진다.
- 운영자 연산(redrive·reconcile·suppress·provider 상태)은 연산마다 `platform.admin`의 유스케이스 클래스이고(`RedriveDeliveryUseCase` 등, command는 그 옆), `notification-admin:*` permission을 선언한다. `platform.port.in`에 두지 않는다: command가 `AdminActor` 같은 운영자 어휘를 실어 `port.in`과 `admin`이 서로를 보게 된다. 운영자 authority와 tenant 범위는 command의 `AdminActor`로 한 번 더 본다.
- 공개 타입이 늘면 `docs/notification/api-surface-snapshot.txt`가 바뀐다(`adapter:outbound:notification`의 `verifyNotificationApiSurface`가 이 leaf까지 본다).
## 테스트
@@ -18,31 +18,30 @@ final class AdminOperationExecutor {
}
/**
* Claims an idempotent operator action before any side effect.
* Claims an idempotent operator action before any side effect, inside the caller's write
* transaction.
*
* <p>The claim and the operation run inside one write transaction. PostgreSQL's unique claim row
* serializes a concurrent caller on the operation id; the loser observes the committed result
* instead of reaching the side effect.
* <p>The use case opens that transaction and calls this in it, so the claim and the operation
* commit or roll back together: the boundary is the use case's to declare, and the architecture
* rule that matches a capability to its {@code TransactionPort} call reads it there. PostgreSQL's
* unique claim row serializes a concurrent caller on the operation id; the loser observes the
* committed result instead of reaching the side effect.
*/
AdminOperationResult execute(
AdminOperationResult runClaimed(
String operationId,
String commandFingerprint,
String requestFingerprint,
AdminActor actor,
String action,
Supplier<AdminOperationResult> operation) {
Objects.requireNonNull(operation, "operation");
return transactions.inWrite(
() -> {
AdminOperationClaim claim =
operations.claim(operationId, commandFingerprint, actor, action);
return claim.mayProceed() ? operation.get() : withoutRunning(claim, operationId);
});
AdminOperationClaim claim = operations.claim(operationId, requestFingerprint, actor, action);
return claim.mayProceed() ? operation.get() : withoutRunning(claim, operationId);
}
/**
* Claims the operation id in its own transaction and runs the operation with none open.
*
* <p>For an operation that calls a provider over the network. Inside {@link #execute} the call
* <p>For an operation that calls a provider over the network. Inside {@link #runClaimed} the call
* held a write transaction — and a pooled connection — for as long as the provider took, once per
* attempt in the batch. The operation opens its own boundaries for what it writes, including
* saving its result, which completes the claim.
@@ -53,14 +52,14 @@ final class AdminOperationExecutor {
*/
AdminOperationResult executeOutsideTransaction(
String operationId,
String commandFingerprint,
String requestFingerprint,
AdminActor actor,
String action,
Supplier<AdminOperationResult> operation) {
Objects.requireNonNull(operation, "operation");
AdminOperationClaim claim =
transactions.inWrite(
() -> operations.claim(operationId, commandFingerprint, actor, action));
() -> operations.claim(operationId, requestFingerprint, actor, action));
if (!claim.mayProceed()) {
return withoutRunning(claim, operationId);
}
@@ -4,55 +4,55 @@ import dev.caskeleton.shared.digest.Sha256;
import java.util.Objects;
/**
* Stable SHA-256 identity of an operator command, excluding the operation id itself.
* Stable SHA-256 identity of an operator request, excluding the operation id itself.
*
* <p>The operation id is the idempotency key. The fingerprint answers the separate question:
* whether a repeated key names the same command. Every field is length-framed so user supplied
* whether a repeated key names the same request. Every field is length-framed so user supplied
* reason text cannot imitate a field boundary.
*/
final class AdminOperationCommandFingerprint {
final class AdminOperationRequestFingerprint {
String of(RedriveCommand command) {
Objects.requireNonNull(command, "command");
String of(RedriveRequest request) {
Objects.requireNonNull(request, "request");
StringBuilder canonical = action("REDRIVE");
field(canonical, "attemptId", command.attemptId().value().toString());
field(canonical, "reason", command.reason());
field(canonical, "approveDuplicateRisk", Boolean.toString(command.approveDuplicateRisk()));
field(canonical, "attemptId", request.attemptId().value().toString());
field(canonical, "reason", request.reason());
field(canonical, "approveDuplicateRisk", Boolean.toString(request.approveDuplicateRisk()));
return digest(canonical);
}
String of(ReconcileCommand command) {
Objects.requireNonNull(command, "command");
String of(ReconcileRequest request) {
Objects.requireNonNull(request, "request");
StringBuilder canonical = action("RECONCILE");
command.attemptIds().stream()
request.attemptIds().stream()
.map(id -> id.value().toString())
.sorted()
.forEach(value -> field(canonical, "attemptId", value));
field(canonical, "reason", command.reason());
field(canonical, "reason", request.reason());
return digest(canonical);
}
String of(SuppressCommand command) {
Objects.requireNonNull(command, "command");
StringBuilder canonical = action(command.remove() ? "SUPPRESS_REMOVE" : "SUPPRESS_ADD");
field(canonical, "tenantId", command.tenantId().value());
field(canonical, "scope", command.scope().name());
field(canonical, "reason", command.reason().name());
field(canonical, "targetFingerprint", command.targetFingerprint());
String of(SuppressionRequest request) {
Objects.requireNonNull(request, "request");
StringBuilder canonical = action(request.remove() ? "SUPPRESS_REMOVE" : "SUPPRESS_ADD");
field(canonical, "tenantId", request.tenantId().value());
field(canonical, "scope", request.scope().name());
field(canonical, "reason", request.reason().name());
field(canonical, "targetFingerprint", request.targetFingerprint());
field(
canonical,
"expiresAt",
command.expiresAt().map(value -> Long.toString(value.toEpochMilli())).orElse("-"));
field(canonical, "reasonText", command.reasonText());
request.expiresAt().map(value -> Long.toString(value.toEpochMilli())).orElse("-"));
field(canonical, "reasonText", request.reasonText());
return digest(canonical);
}
String of(SetProviderStateCommand command) {
Objects.requireNonNull(command, "command");
String of(ProviderStateRequest request) {
Objects.requireNonNull(request, "request");
StringBuilder canonical = action("PROVIDER_STATE");
field(canonical, "profileId", command.profileId().value());
field(canonical, "desiredState", command.desiredState().name());
field(canonical, "reason", command.reason());
field(canonical, "profileId", request.profileId().value());
field(canonical, "desiredState", request.desiredState().name());
field(canonical, "reason", request.reason());
return digest(canonical);
}
@@ -19,15 +19,17 @@ public interface AdminOperationStorePort {
* was checked but never held, so it prevented a repeat and not a race. A destructive operation
* run twice concurrently is the exact failure the id exists to stop.
*
* <p>The fingerprint is part of the claim: the same id with a different command is not a replay,
* it is a conflict, and answering it with the earlier result would silently execute neither.
* <p>The fingerprint is part of the claim: the same id with a different request is not a replay,
* it is a conflict, and answering it with the earlier result would silently execute neither. It
* digests the operator's request and leaves the actor out; the store keeps it in the column V8
* named {@code command_fingerprint}.
*
* @param operationId the caller's idempotency key
* @param commandFingerprint a digest of the command this id was presented with
* @param requestFingerprint a digest of the request this id was presented with
* @param actor who is asking
* @param action what they are asking for
* @return whether this caller may proceed, and what the earlier one did if not
*/
AdminOperationClaim claim(
String operationId, String commandFingerprint, AdminActor actor, String action);
String operationId, String requestFingerprint, AdminActor actor, String action);
}
@@ -0,0 +1,22 @@
package dev.caskeleton.application.notification.platform.admin;
import dev.caskeleton.application.command.Command;
import java.util.Objects;
/**
* An operator's change to one provider profile's runtime state.
*
* <p>The request and the operator are apart because the operation id's fingerprint covers the
* request only: the same operator retrying the same request replays it.
*
* @param request what to do
* @param actor who asks, with the operator authorities and tenant scope the transport resolved
*/
public record ChangeProviderStateCommand(ProviderStateRequest request, AdminActor actor)
implements Command {
public ChangeProviderStateCommand {
Objects.requireNonNull(request, "request");
Objects.requireNonNull(actor, "actor");
}
}
@@ -0,0 +1,130 @@
package dev.caskeleton.application.notification.platform.admin;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.notification.platform.api.error.FailureCategory;
import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode;
import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor;
import dev.caskeleton.application.notification.platform.api.error.ProviderConfigurationException;
import dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent;
import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort;
import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/**
* Enables, disables or drains a provider profile as an operator.
*
* <p>A provider profile is shared by every tenant, so only an operator with no tenant scope may
* change it. The operation id is claimed before the runtime is asked, in the same transaction.
*/
@RequiresPermission(NotificationAdminPermissions.PROVIDER_CONTROL)
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.WRITE_REPOSITORY,
// The provider runtime and the audit port are the notification adapter's.
externalOutboundAllowed = true,
crossTenantAdmin = true)
// Not final: @RequiresPermission is applied through a CGLIB proxy.
public class ChangeProviderStateUseCase
implements CommandUseCase<ChangeProviderStateCommand, AdminOperationResult> {
private static final String ACTION = "ADMIN_PROVIDER_STATE";
private final AdminAuthorizationGuard authorization;
private final ProviderRuntimeControlPort runtimes;
private final AdminOperationStorePort operations;
private final AdminOperationExecutor operationExecutor;
private final AdminOperationRequestFingerprint requestFingerprints =
new AdminOperationRequestFingerprint();
private final NotificationAuditPort audit;
private final TransactionPort transactions;
private final Clock clock;
public ChangeProviderStateUseCase(
AdminAuthorizationGuard authorization,
ProviderRuntimeControlPort runtimes,
AdminOperationStorePort operations,
NotificationAuditPort audit,
TransactionPort transactions,
Clock clock) {
this.authorization = Objects.requireNonNull(authorization, "authorization");
this.runtimes = Objects.requireNonNull(runtimes, "runtimes");
this.operations = Objects.requireNonNull(operations, "operations");
this.transactions = Objects.requireNonNull(transactions, "transactions");
this.operationExecutor = new AdminOperationExecutor(this.operations, this.transactions);
this.audit = Objects.requireNonNull(audit, "audit");
this.clock = Objects.requireNonNull(clock, "clock");
}
@Override
public AdminOperationResult handle(ChangeProviderStateCommand change) {
Objects.requireNonNull(change, "change");
ProviderStateRequest request = change.request();
AdminActor actor = change.actor();
authorization.require(actor, NotificationAdminAuthority.PROVIDER_CONTROL);
authorization.requireGlobal(actor, NotificationAdminAuthority.PROVIDER_CONTROL);
if (request.dryRun()) {
return new AdminOperationResult(
request.operationId(),
true,
1,
Optional.empty(),
Optional.empty(),
Optional.empty(),
List.of("DRY_RUN"));
}
return transactions.inWrite(
() ->
operationExecutor.runClaimed(
request.operationId(),
requestFingerprints.of(request),
actor,
ACTION,
() -> change(request, actor)));
}
private AdminOperationResult change(ProviderStateRequest request, AdminActor actor) {
boolean applied =
runtimes.setState(request.profileId(), request.desiredState(), request.reason());
if (!applied) {
// The transition was refused — an authentication failure is not cleared by declaring the
// provider healthy, and a healthy runtime is not degraded on request. Recording success for a
// state change that did not happen tells an operator the provider is serving when it is not.
throw new ProviderConfigurationException(
NotificationFailureDescriptor.preDispatch(
NotificationFailureCode.PROVIDER_CONFIGURATION_INVALID,
FailureCategory.AUTHORIZATION));
}
AdminOperationResult result =
new AdminOperationResult(
request.operationId(),
false,
1,
Optional.empty(),
Optional.empty(),
Optional.empty(),
List.of(request.reason()));
audit.record(
new NotificationAuditEvent(
ACTION,
actor.actorRef(),
Optional.of(request.reason()),
Optional.of(request.operationId()),
clock.instant(),
Map.of(
"providerProfile", request.profileId().value(),
"status", request.desiredState().name())));
return operations.save(result, actor, ACTION);
}
}
@@ -0,0 +1,22 @@
package dev.caskeleton.application.notification.platform.admin;
import dev.caskeleton.application.command.Command;
import java.util.Objects;
/**
* An operator's change to one suppression entry.
*
* <p>The request and the operator are apart because the operation id's fingerprint covers the
* request only: the same operator retrying the same request replays it.
*
* @param request what to do
* @param actor who asks, with the operator authorities and tenant scope the transport resolved
*/
public record ChangeSuppressionCommand(SuppressionRequest request, AdminActor actor)
implements Command {
public ChangeSuppressionCommand {
Objects.requireNonNull(request, "request");
Objects.requireNonNull(actor, "actor");
}
}
@@ -0,0 +1,149 @@
package dev.caskeleton.application.notification.platform.admin;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort;
import dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent;
import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort;
import dev.caskeleton.application.notification.platform.policy.SuppressionEntry;
import dev.caskeleton.application.notification.platform.policy.SuppressionId;
import dev.caskeleton.application.notification.platform.policy.SuppressionSource;
import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort;
import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/**
* Adds or lifts a suppression entry as an operator.
*
* <p>Lifting is by fingerprint match rather than by id, because an operator lifting a suppression
* knows the target, not the row identifier the platform assigned.
*/
@RequiresPermission(NotificationAdminPermissions.SUPPRESS)
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.WRITE_REPOSITORY,
// The audit port and the id generator are the notification adapter's.
externalOutboundAllowed = true,
crossTenantAdmin = true)
// Not final: @RequiresPermission is applied through a CGLIB proxy.
public class ChangeSuppressionUseCase
implements CommandUseCase<ChangeSuppressionCommand, AdminOperationResult> {
private final AdminAuthorizationGuard authorization;
private final SuppressionStorePort suppressions;
private final AdminOperationStorePort operations;
private final AdminOperationExecutor operationExecutor;
private final AdminOperationRequestFingerprint requestFingerprints =
new AdminOperationRequestFingerprint();
private final NotificationAuditPort audit;
private final TransactionPort transactions;
private final NotificationIdGeneratorPort ids;
private final Clock clock;
public ChangeSuppressionUseCase(
AdminAuthorizationGuard authorization,
SuppressionStorePort suppressions,
AdminOperationStorePort operations,
NotificationAuditPort audit,
TransactionPort transactions,
NotificationIdGeneratorPort ids,
Clock clock) {
this.authorization = Objects.requireNonNull(authorization, "authorization");
this.suppressions = Objects.requireNonNull(suppressions, "suppressions");
this.operations = Objects.requireNonNull(operations, "operations");
this.transactions = Objects.requireNonNull(transactions, "transactions");
this.operationExecutor = new AdminOperationExecutor(this.operations, this.transactions);
this.audit = Objects.requireNonNull(audit, "audit");
this.ids = Objects.requireNonNull(ids, "ids");
this.clock = Objects.requireNonNull(clock, "clock");
}
@Override
public AdminOperationResult handle(ChangeSuppressionCommand change) {
Objects.requireNonNull(change, "change");
SuppressionRequest request = change.request();
AdminActor actor = change.actor();
authorization.require(actor, NotificationAdminAuthority.SUPPRESS);
authorization.requireTenant(actor, request.tenantId(), NotificationAdminAuthority.SUPPRESS);
if (request.dryRun()) {
return new AdminOperationResult(
request.operationId(),
true,
1,
Optional.empty(),
Optional.empty(),
Optional.empty(),
List.of("DRY_RUN"));
}
String action = request.remove() ? "ADMIN_SUPPRESS_REMOVE" : "ADMIN_SUPPRESS_ADD";
return transactions.inWrite(
() ->
operationExecutor.runClaimed(
request.operationId(),
requestFingerprints.of(request),
actor,
action,
() -> change(request, actor, action)));
}
private AdminOperationResult change(SuppressionRequest request, AdminActor actor, String action) {
int affected = request.remove() ? lift(request) : add(request);
AdminOperationResult result =
new AdminOperationResult(
request.operationId(),
false,
affected,
Optional.empty(),
Optional.empty(),
Optional.empty(),
List.of(request.reasonText()));
audit.record(
new NotificationAuditEvent(
request.remove() ? "ADMIN_SUPPRESSION_REMOVED" : "ADMIN_SUPPRESSION_ADDED",
actor.actorRef(),
Optional.of(request.reason().name()),
Optional.of(request.operationId()),
clock.instant(),
Map.of()));
return operations.save(result, actor, action);
}
private int lift(SuppressionRequest request) {
long lifted =
suppressions
.activeFor(request.tenantId(), request.targetFingerprint(), clock.instant())
.stream()
.map(entry -> suppressions.remove(request.tenantId(), entry.id()))
.filter(Optional::isPresent)
.count();
return lifted > 0 ? 1 : 0;
}
private int add(SuppressionRequest request) {
suppressions.upsert(
new SuppressionEntry(
// ids.nextId(), not UUID.randomUUID(): a random v4 id is unordered, so the suppression
// table's index degrades the way the platform's UUIDv7 policy exists to prevent.
new SuppressionId(ids.nextId()),
request.tenantId(),
request.scope(),
request.reason(),
request.targetFingerprint(),
Optional.empty(),
clock.instant(),
request.expiresAt(),
SuppressionSource.ADMIN));
return 1;
}
}
@@ -1,362 +0,0 @@
package dev.caskeleton.application.notification.platform.admin;
import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId;
import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState;
import dev.caskeleton.application.notification.platform.api.error.FailureCategory;
import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode;
import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor;
import dev.caskeleton.application.notification.platform.api.error.ProviderConfigurationException;
import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot;
import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort;
import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService;
import dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent;
import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort;
import dev.caskeleton.application.notification.platform.policy.SuppressionEntry;
import dev.caskeleton.application.notification.platform.policy.SuppressionId;
import dev.caskeleton.application.notification.platform.policy.SuppressionSource;
import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort;
import dev.caskeleton.application.notification.platform.provider.ProviderRuntimeState;
import dev.caskeleton.application.transaction.TransactionPort;
import java.time.Clock;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/**
* N4 operator plane.
*
* <p>It lived in the outbound notification adapter, where it performed operator authorization,
* tenant scoping, duplicate-risk approval, idempotency and transaction orchestration — every one of
* them a decision about what the product allows, in the layer whose job is speaking provider
* protocols. What remains out there is {@link ProviderRuntimeControlPort}: two operations that turn
* an application request into a runtime transition.
*
* <p>Four properties hold for every operation: a separate authority, an idempotent operation id, a
* recorded reason, and an audit row. The idempotency matters more than it looks — an operator
* retrying a redrive after a timeout must not send the message twice, which is exactly the failure
* the operation is trying to repair.
*
* <p>A dry run reads and reports but writes nothing, so an operator can see the blast radius of a
* bulk action before committing to it.
*/
public final class NotificationAdminApplicationService implements NotificationAdminService {
private final AdminAuthorizationGuard authorization;
private final DuplicateRiskGuard duplicateRiskGuard;
private final DeliveryAttemptStorePort attempts;
private final RecipientDeliveryStorePort recipients;
private final ReconciliationService reconciliation;
private final SuppressionStorePort suppressions;
private final ProviderRuntimeControlPort runtimes;
private final AdminOperationStorePort operations;
private final AdminOperationExecutor operationExecutor;
private final AdminOperationCommandFingerprint commandFingerprints;
private final TransactionPort transactions;
private final NotificationAuditPort audit;
private final dev.caskeleton.application.notification.platform.dispatch
.NotificationIdGeneratorPort
ids;
private final Clock clock;
public NotificationAdminApplicationService(
AdminAuthorizationGuard authorization,
DuplicateRiskGuard duplicateRiskGuard,
DeliveryAttemptStorePort attempts,
RecipientDeliveryStorePort recipients,
ReconciliationService reconciliation,
SuppressionStorePort suppressions,
ProviderRuntimeControlPort runtimes,
AdminOperationStorePort operations,
NotificationAuditPort audit,
TransactionPort transactions,
dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort ids,
Clock clock) {
this.authorization = Objects.requireNonNull(authorization, "authorization");
this.duplicateRiskGuard = Objects.requireNonNull(duplicateRiskGuard, "duplicateRiskGuard");
this.attempts = Objects.requireNonNull(attempts, "attempts");
this.recipients = Objects.requireNonNull(recipients, "recipients");
this.reconciliation = Objects.requireNonNull(reconciliation, "reconciliation");
this.suppressions = Objects.requireNonNull(suppressions, "suppressions");
this.runtimes = Objects.requireNonNull(runtimes, "runtimes");
this.operations = Objects.requireNonNull(operations, "operations");
this.transactions = Objects.requireNonNull(transactions, "transactions");
this.operationExecutor = new AdminOperationExecutor(this.operations, this.transactions);
this.commandFingerprints = new AdminOperationCommandFingerprint();
this.audit = Objects.requireNonNull(audit, "audit");
this.ids = Objects.requireNonNull(ids, "ids");
this.clock = Objects.requireNonNull(clock, "clock");
}
@Override
public AdminOperationResult redrive(RedriveCommand command, AdminActor actor) {
Objects.requireNonNull(command, "command");
authorization.require(actor, NotificationAdminAuthority.REDRIVE);
DeliveryAttemptSnapshot original =
attempts
.snapshot(command.attemptId())
.orElseThrow(() -> new IllegalStateException("delivery attempt is not available"));
authorization.requireTenant(actor, original.tenantId(), NotificationAdminAuthority.REDRIVE);
duplicateRiskGuard.verify(original, command.approveDuplicateRisk());
if (command.dryRun()) {
return new AdminOperationResult(
command.operationId(),
true,
1,
Optional.of(original.notificationId()),
Optional.of(original.recipientDeliveryId()),
Optional.empty(),
List.of("DRY_RUN"));
}
return operationExecutor.execute(
command.operationId(),
commandFingerprints.of(command),
actor,
"ADMIN_REDRIVE",
() -> {
// The logical identities are preserved and only the attempt is new, so the history stays
// one story rather than becoming two unrelated notifications.
recipients.transition(
original.recipientDeliveryId(),
RecipientDeliveryState.READY_TO_DISPATCH,
Optional.of(clock.instant()));
AdminOperationResult result =
new AdminOperationResult(
command.operationId(),
false,
1,
Optional.of(original.notificationId()),
Optional.of(original.recipientDeliveryId()),
Optional.empty(),
List.of(command.reason()));
audit.record(
new NotificationAuditEvent(
"ADMIN_REDRIVE",
actor.actorRef(),
Optional.of(command.reason()),
Optional.of(command.operationId()),
clock.instant(),
Map.of(
"provider", original.providerId().value(),
"channel", original.channel().name())));
return operations.save(result, actor, "ADMIN_REDRIVE");
});
}
@Override
public AdminOperationResult reconcile(ReconcileCommand command, AdminActor actor) {
Objects.requireNonNull(command, "command");
authorization.require(actor, NotificationAdminAuthority.RECONCILE);
// Every attempt is checked 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.
for (DeliveryAttemptId attemptId : command.attemptIds()) {
attempts
.snapshot(attemptId)
.ifPresent(
attempt ->
authorization.requireTenant(
actor, attempt.tenantId(), NotificationAdminAuthority.RECONCILE));
}
if (command.dryRun()) {
return new AdminOperationResult(
command.operationId(),
true,
command.attemptIds().size(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
List.of("DRY_RUN"));
}
// Outside a transaction: each reconcile asks a provider over the network and opens its own
// boundaries for what it writes.
return operationExecutor.executeOutsideTransaction(
command.operationId(),
commandFingerprints.of(command),
actor,
"ADMIN_RECONCILE",
() -> {
List<String> reasons = new ArrayList<>();
int reconciled = 0;
for (DeliveryAttemptId attemptId : command.attemptIds()) {
reconciliation.reconcile(attemptId);
reconciled++;
}
reasons.add(command.reason());
AdminOperationResult result =
new AdminOperationResult(
command.operationId(),
false,
reconciled,
Optional.empty(),
Optional.empty(),
Optional.empty(),
List.copyOf(reasons));
return transactions.inWrite(
() -> {
audit.record(
new NotificationAuditEvent(
"ADMIN_RECONCILE",
actor.actorRef(),
Optional.of(command.reason()),
Optional.of(command.operationId()),
clock.instant(),
Map.of()));
return operations.save(result, actor, "ADMIN_RECONCILE");
});
});
}
@Override
public AdminOperationResult suppress(SuppressCommand command, AdminActor actor) {
Objects.requireNonNull(command, "command");
authorization.require(actor, NotificationAdminAuthority.SUPPRESS);
authorization.requireTenant(actor, command.tenantId(), NotificationAdminAuthority.SUPPRESS);
if (command.dryRun()) {
return new AdminOperationResult(
command.operationId(),
true,
1,
Optional.empty(),
Optional.empty(),
Optional.empty(),
List.of("DRY_RUN"));
}
String action = command.remove() ? "ADMIN_SUPPRESS_REMOVE" : "ADMIN_SUPPRESS_ADD";
return operationExecutor.execute(
command.operationId(),
commandFingerprints.of(command),
actor,
action,
() -> {
int affected;
if (command.remove()) {
// Removal is by fingerprint match rather than by id, because an operator lifting a
// suppression knows the target, not the row identifier the platform assigned.
affected =
suppressions
.activeFor(
command.tenantId(), command.targetFingerprint(), clock.instant())
.stream()
.map(entry -> suppressions.remove(command.tenantId(), entry.id()))
.filter(Optional::isPresent)
.count()
> 0
? 1
: 0;
} else {
suppressions.upsert(
new SuppressionEntry(
// ids.nextId(), not UUID.randomUUID(). The identifier contract requires the
// generator port, and while this class lived in the outbound adapter the rule
// that says so did not apply to it — a random v4 id here is unordered, so the
// suppression table's index degrades the way the platform's own UUIDv7 policy
// exists to prevent.
new SuppressionId(ids.nextId()),
command.tenantId(),
command.scope(),
command.reason(),
command.targetFingerprint(),
Optional.empty(),
clock.instant(),
command.expiresAt(),
SuppressionSource.ADMIN));
affected = 1;
}
AdminOperationResult result =
new AdminOperationResult(
command.operationId(),
false,
affected,
Optional.empty(),
Optional.empty(),
Optional.empty(),
List.of(command.reasonText()));
audit.record(
new NotificationAuditEvent(
command.remove() ? "ADMIN_SUPPRESSION_REMOVED" : "ADMIN_SUPPRESSION_ADDED",
actor.actorRef(),
Optional.of(command.reason().name()),
Optional.of(command.operationId()),
clock.instant(),
Map.of()));
return operations.save(result, actor, action);
});
}
@Override
public AdminOperationResult setProviderState(SetProviderStateCommand command, AdminActor actor) {
Objects.requireNonNull(command, "command");
authorization.require(actor, NotificationAdminAuthority.PROVIDER_CONTROL);
authorization.requireGlobal(actor, NotificationAdminAuthority.PROVIDER_CONTROL);
if (command.dryRun()) {
return new AdminOperationResult(
command.operationId(),
true,
1,
Optional.empty(),
Optional.empty(),
Optional.empty(),
List.of("DRY_RUN"));
}
return operationExecutor.execute(
command.operationId(),
commandFingerprints.of(command),
actor,
"ADMIN_PROVIDER_STATE",
() -> {
boolean applied =
runtimes.setState(command.profileId(), command.desiredState(), command.reason());
if (!applied) {
// The transition was refused — an authentication failure is not cleared by declaring
// the provider healthy, and a healthy runtime is not degraded on request. Recording
// success for a state change that did not happen tells an operator the provider is
// serving when it is not.
throw new ProviderConfigurationException(
NotificationFailureDescriptor.preDispatch(
NotificationFailureCode.PROVIDER_CONFIGURATION_INVALID,
FailureCategory.AUTHORIZATION));
}
AdminOperationResult result =
new AdminOperationResult(
command.operationId(),
false,
1,
Optional.empty(),
Optional.empty(),
Optional.empty(),
List.of(command.reason()));
audit.record(
new NotificationAuditEvent(
"ADMIN_PROVIDER_STATE",
actor.actorRef(),
Optional.of(command.reason()),
Optional.of(command.operationId()),
clock.instant(),
Map.of(
"providerProfile", command.profileId().value(),
"status", command.desiredState().name())));
return operations.save(result, actor, "ADMIN_PROVIDER_STATE");
});
}
/** Current state of a provider runtime, for the health endpoint. */
public ProviderRuntimeState providerState(
dev.caskeleton.application.notification.platform.api.ProviderProfileId profileId) {
return runtimes.state(profileId);
}
}
@@ -0,0 +1,27 @@
package dev.caskeleton.application.notification.platform.admin;
/**
* The permissions the four operator-plane use cases declare.
*
* <p>One per operation, like the {@link NotificationAdminAuthority} the operator also has to hold:
* the permission is what the transport's caller may invoke at all, the authority and tenant scope
* on the {@code AdminActor} are what the operation then checks against the delivery it touches.
* Which roles hold them by default is the notification module defaults' to say, not this type's:
* {@code docs/notification/operations.md} 「운영자 연산」.
*/
public final class NotificationAdminPermissions {
/** Re-run one delivery. */
public static final String REDRIVE = "notification-admin:redrive";
/** Ask providers about a batch of attempts. */
public static final String RECONCILE = "notification-admin:reconcile";
/** Add or lift a suppression entry. */
public static final String SUPPRESS = "notification-admin:suppress";
/** Change a provider profile's runtime state. */
public static final String PROVIDER_CONTROL = "notification-admin:provider-control";
private NotificationAdminPermissions() {}
}
@@ -1,22 +0,0 @@
package dev.caskeleton.application.notification.platform.admin;
/**
* N4 operator plane.
*
* <p>Every operation requires a separate authority, an idempotent operation id, a reason and an
* audit record. It is deliberately not reachable from the application-facing APIs.
*/
public interface NotificationAdminService {
/** Re-run a delivery while preserving its logical identity. */
AdminOperationResult redrive(RedriveCommand command, AdminActor actor);
/** Force reconciliation of a bounded batch. */
AdminOperationResult reconcile(ReconcileCommand command, AdminActor actor);
/** Add or remove a suppression entry. */
AdminOperationResult suppress(SuppressCommand command, AdminActor actor);
/** Change a provider runtime state. */
AdminOperationResult setProviderState(SetProviderStateCommand command, AdminActor actor);
}
@@ -5,14 +5,14 @@ import dev.caskeleton.application.notification.platform.provider.ProviderRuntime
import java.util.Objects;
/** Enable, disable or drain a provider profile. */
public record SetProviderStateCommand(
public record ProviderStateRequest(
String operationId,
ProviderProfileId profileId,
ProviderRuntimeState desiredState,
String reason,
boolean dryRun) {
public SetProviderStateCommand {
public ProviderStateRequest {
Objects.requireNonNull(operationId, "operationId");
Objects.requireNonNull(profileId, "profileId");
Objects.requireNonNull(desiredState, "desiredState");
@@ -0,0 +1,22 @@
package dev.caskeleton.application.notification.platform.admin;
import dev.caskeleton.application.command.Command;
import java.util.Objects;
/**
* An operator's reconciliation of a bounded batch of attempts.
*
* <p>The request and the operator are apart because the operation id's fingerprint covers the
* request only: the same operator retrying the same request replays it.
*
* @param request what to do
* @param actor who asks, with the operator authorities and tenant scope the transport resolved
*/
public record ReconcileDeliveriesCommand(ReconcileRequest request, AdminActor actor)
implements Command {
public ReconcileDeliveriesCommand {
Objects.requireNonNull(request, "request");
Objects.requireNonNull(actor, "actor");
}
}
@@ -0,0 +1,143 @@
package dev.caskeleton.application.notification.platform.admin;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId;
import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService;
import dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent;
import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort;
import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/**
* Asks providers, on an operator's request, what happened to a bounded batch of attempts.
*
* <p>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.
*
* <p>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.
* The operation id is claimed in its own transaction first, and the audit row and result are
* written in one at the end.
*/
@RequiresPermission(NotificationAdminPermissions.RECONCILE)
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.WRITE_REPOSITORY,
externalOutboundAllowed = true,
crossTenantAdmin = true)
// Not final: @RequiresPermission is applied through a CGLIB proxy.
public class ReconcileDeliveriesUseCase
implements CommandUseCase<ReconcileDeliveriesCommand, AdminOperationResult> {
private static final String ACTION = "ADMIN_RECONCILE";
private final AdminAuthorizationGuard authorization;
private final DeliveryAttemptStorePort attempts;
private final ReconciliationService reconciliation;
private final AdminOperationStorePort operations;
private final AdminOperationExecutor operationExecutor;
private final AdminOperationRequestFingerprint requestFingerprints =
new AdminOperationRequestFingerprint();
private final NotificationAuditPort audit;
private final TransactionPort transactions;
private final Clock clock;
public ReconcileDeliveriesUseCase(
AdminAuthorizationGuard authorization,
DeliveryAttemptStorePort attempts,
ReconciliationService reconciliation,
AdminOperationStorePort operations,
NotificationAuditPort audit,
TransactionPort transactions,
Clock clock) {
this.authorization = Objects.requireNonNull(authorization, "authorization");
this.attempts = Objects.requireNonNull(attempts, "attempts");
this.reconciliation = Objects.requireNonNull(reconciliation, "reconciliation");
this.operations = Objects.requireNonNull(operations, "operations");
this.transactions = Objects.requireNonNull(transactions, "transactions");
this.operationExecutor = new AdminOperationExecutor(this.operations, this.transactions);
this.audit = Objects.requireNonNull(audit, "audit");
this.clock = Objects.requireNonNull(clock, "clock");
}
@Override
public AdminOperationResult handle(ReconcileDeliveriesCommand batch) {
Objects.requireNonNull(batch, "batch");
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.
transactions.inRead(
() -> {
for (DeliveryAttemptId attemptId : request.attemptIds()) {
attempts
.snapshot(attemptId)
.ifPresent(
attempt ->
authorization.requireTenant(
actor, attempt.tenantId(), NotificationAdminAuthority.RECONCILE));
}
return null;
});
if (request.dryRun()) {
return new AdminOperationResult(
request.operationId(),
true,
request.attemptIds().size(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
List.of("DRY_RUN"));
}
return operationExecutor.executeOutsideTransaction(
request.operationId(),
requestFingerprints.of(request),
actor,
ACTION,
() -> reconcile(request, actor));
}
private AdminOperationResult reconcile(ReconcileRequest request, AdminActor actor) {
int reconciled = 0;
for (DeliveryAttemptId attemptId : request.attemptIds()) {
reconciliation.reconcile(attemptId);
reconciled++;
}
AdminOperationResult result =
new AdminOperationResult(
request.operationId(),
false,
reconciled,
Optional.empty(),
Optional.empty(),
Optional.empty(),
List.of(request.reason()));
return transactions.inWrite(
() -> {
audit.record(
new NotificationAuditEvent(
ACTION,
actor.actorRef(),
Optional.of(request.reason()),
Optional.of(request.operationId()),
clock.instant(),
Map.of()));
return operations.save(result, actor, ACTION);
});
}
}
@@ -5,12 +5,12 @@ import java.util.List;
import java.util.Objects;
/** Operator-triggered reconciliation over a bounded batch of attempts. */
public record ReconcileCommand(
public record ReconcileRequest(
String operationId, List<DeliveryAttemptId> attemptIds, String reason, boolean dryRun) {
public static final int MAX_BATCH = 200;
public ReconcileCommand {
public ReconcileRequest {
Objects.requireNonNull(operationId, "operationId");
attemptIds = List.copyOf(Objects.requireNonNull(attemptIds, "attemptIds"));
Objects.requireNonNull(reason, "reason");
@@ -0,0 +1,21 @@
package dev.caskeleton.application.notification.platform.admin;
import dev.caskeleton.application.command.Command;
import java.util.Objects;
/**
* An operator's redrive of one delivery attempt.
*
* <p>The request and the operator are apart because the operation id's fingerprint covers the
* request only: the same operator retrying the same request replays it.
*
* @param request what to do
* @param actor who asks, with the operator authorities and tenant scope the transport resolved
*/
public record RedriveDeliveryCommand(RedriveRequest request, AdminActor actor) implements Command {
public RedriveDeliveryCommand {
Objects.requireNonNull(request, "request");
Objects.requireNonNull(actor, "actor");
}
}
@@ -0,0 +1,149 @@
package dev.caskeleton.application.notification.platform.admin;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState;
import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot;
import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort;
import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort;
import dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent;
import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort;
import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/**
* Re-runs one delivery while preserving its logical identity.
*
* <p>The logical identities are kept and only the next attempt is new, so the history stays one
* story rather than becoming two unrelated notifications. An operator retrying after a timeout must
* not send the message twice — exactly the failure a redrive is trying to repair — so the operation
* id is claimed before the delivery is touched, in the same transaction.
*
* <p>A dry run reads and reports but writes nothing.
*/
@RequiresPermission(NotificationAdminPermissions.REDRIVE)
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.WRITE_REPOSITORY,
// The audit port is the notification adapter's.
externalOutboundAllowed = true,
crossTenantAdmin = true)
// Not final: @RequiresPermission is applied through a CGLIB proxy.
public class RedriveDeliveryUseCase
implements CommandUseCase<RedriveDeliveryCommand, AdminOperationResult> {
private static final String ACTION = "ADMIN_REDRIVE";
private final AdminAuthorizationGuard authorization;
private final DuplicateRiskGuard duplicateRiskGuard;
private final DeliveryAttemptStorePort attempts;
private final RecipientDeliveryStorePort recipients;
private final AdminOperationStorePort operations;
private final AdminOperationExecutor operationExecutor;
private final AdminOperationRequestFingerprint requestFingerprints =
new AdminOperationRequestFingerprint();
private final NotificationAuditPort audit;
private final TransactionPort transactions;
private final Clock clock;
public RedriveDeliveryUseCase(
AdminAuthorizationGuard authorization,
DuplicateRiskGuard duplicateRiskGuard,
DeliveryAttemptStorePort attempts,
RecipientDeliveryStorePort recipients,
AdminOperationStorePort operations,
NotificationAuditPort audit,
TransactionPort transactions,
Clock clock) {
this.authorization = Objects.requireNonNull(authorization, "authorization");
this.duplicateRiskGuard = Objects.requireNonNull(duplicateRiskGuard, "duplicateRiskGuard");
this.attempts = Objects.requireNonNull(attempts, "attempts");
this.recipients = Objects.requireNonNull(recipients, "recipients");
this.operations = Objects.requireNonNull(operations, "operations");
this.transactions = Objects.requireNonNull(transactions, "transactions");
this.operationExecutor = new AdminOperationExecutor(this.operations, this.transactions);
this.audit = Objects.requireNonNull(audit, "audit");
this.clock = Objects.requireNonNull(clock, "clock");
}
@Override
public AdminOperationResult handle(RedriveDeliveryCommand delivery) {
Objects.requireNonNull(delivery, "delivery");
RedriveRequest request = delivery.request();
AdminActor actor = delivery.actor();
authorization.require(actor, NotificationAdminAuthority.REDRIVE);
if (request.dryRun()) {
DeliveryAttemptSnapshot original = transactions.inRead(() -> checkedOriginal(request, actor));
return new AdminOperationResult(
request.operationId(),
true,
1,
Optional.of(original.notificationId()),
Optional.of(original.recipientDeliveryId()),
Optional.empty(),
List.of("DRY_RUN"));
}
// The checks read the attempt in the transaction that claims the operation and writes, so the
// attempt they approved is the one redriven.
return transactions.inWrite(
() -> {
DeliveryAttemptSnapshot original = checkedOriginal(request, actor);
return operationExecutor.runClaimed(
request.operationId(),
requestFingerprints.of(request),
actor,
ACTION,
() -> redrive(request, actor, original));
});
}
private DeliveryAttemptSnapshot checkedOriginal(RedriveRequest request, AdminActor actor) {
DeliveryAttemptSnapshot original =
attempts
.snapshot(request.attemptId())
.orElseThrow(() -> new IllegalStateException("delivery attempt is not available"));
authorization.requireTenant(actor, original.tenantId(), NotificationAdminAuthority.REDRIVE);
duplicateRiskGuard.verify(original, request.approveDuplicateRisk());
return original;
}
private AdminOperationResult redrive(
RedriveRequest request, AdminActor actor, DeliveryAttemptSnapshot original) {
recipients.transition(
original.recipientDeliveryId(),
RecipientDeliveryState.READY_TO_DISPATCH,
Optional.of(clock.instant()));
AdminOperationResult result =
new AdminOperationResult(
request.operationId(),
false,
1,
Optional.of(original.notificationId()),
Optional.of(original.recipientDeliveryId()),
Optional.empty(),
List.of(request.reason()));
audit.record(
new NotificationAuditEvent(
ACTION,
actor.actorRef(),
Optional.of(request.reason()),
Optional.of(request.operationId()),
clock.instant(),
Map.of(
"provider", original.providerId().value(),
"channel", original.channel().name())));
return operations.save(result, actor, ACTION);
}
}
@@ -9,14 +9,14 @@ import java.util.Objects;
* <p>A redrive reuses the pinned template version and rendered digest: it re-executes the original
* notification rather than sending a new, possibly different message under an old identity.
*/
public record RedriveCommand(
public record RedriveRequest(
String operationId,
DeliveryAttemptId attemptId,
String reason,
boolean approveDuplicateRisk,
boolean dryRun) {
public RedriveCommand {
public RedriveRequest {
Objects.requireNonNull(operationId, "operationId");
Objects.requireNonNull(attemptId, "attemptId");
Objects.requireNonNull(reason, "reason");
@@ -8,7 +8,7 @@ import java.util.Objects;
import java.util.Optional;
/** Add or remove a suppression entry as an operator. */
public record SuppressCommand(
public record SuppressionRequest(
String operationId,
TenantId tenantId,
SuppressionScope scope,
@@ -19,7 +19,7 @@ public record SuppressCommand(
String reasonText,
boolean dryRun) {
public SuppressCommand {
public SuppressionRequest {
Objects.requireNonNull(operationId, "operationId");
Objects.requireNonNull(tenantId, "tenantId");
Objects.requireNonNull(scope, "scope");
@@ -3,6 +3,7 @@ package dev.caskeleton.application.notification.platform.callback;
import dev.caskeleton.application.notification.platform.observation.NotificationMetricName;
import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort;
import dev.caskeleton.application.transaction.TransactionPort;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
@@ -72,6 +73,26 @@ public final class ProviderEventProjectionService {
transactions.inWrite(() -> ledger.markFailed(event.id(), reasonCode));
}
/**
* Stored events that are not matched to an attempt yet, read in a read transaction of its own.
*
* @param limit the most events to return
* @return the oldest unmatched events
*/
public List<ProviderEventRecord> unmatched(int limit) {
return transactions.inRead(() -> ledger.unmatched(limit));
}
/**
* Stored events whose projection has not run or failed, read in a read transaction of its own.
*
* @param limit the most events to return
* @return the oldest events awaiting projection
*/
public List<ProviderEventRecord> pendingProjection(int limit) {
return transactions.inRead(() -> ledger.pendingProjection(limit));
}
private Optional<ProjectionResult> projectInTransaction(ProviderEventRecord event) {
Optional<DeliveryAttemptSnapshot> attempt = resolve(event);
if (attempt.isEmpty()) {
@@ -0,0 +1,6 @@
package dev.caskeleton.application.notification.platform.callback;
import dev.caskeleton.application.command.Command;
/** One replay pass over the stored, unprojected provider events; its bound is the use case's. */
public record ReplayProviderEventsCommand() implements Command {}
@@ -1,8 +1,11 @@
package dev.caskeleton.adapter.outbound.notification.platform.dispatch;
package dev.caskeleton.application.notification.platform.callback;
import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger;
import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService;
import dev.caskeleton.application.notification.platform.callback.ProviderEventRecord;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.security.SystemInvoked;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.util.List;
import java.util.Objects;
@@ -19,26 +22,41 @@ import java.util.Objects;
* ingestion path deliberately stores such an event as {@code PENDING} rather than dropping it. With
* nothing replaying it, "we will match it later" was true only in the comment: the delivery stayed
* unconfirmed forever and the callback that would have confirmed it sat in a table.
*
* <p>A use case, not a worker of the notification adapter, which it used to be (round9 review
* 2026-11-12, RR9-05-06, RR9-05-08). It holds no transaction and touches no repository itself:
* {@link ProviderEventProjectionService} reads each list in a read transaction and projects, or
* marks failed, each event in a write transaction of its own, so one event's failure does not roll
* back the others.
*
* <p><b>Not a bean.</b> The notification composition's background workers construct it and keep it.
*/
public final class ProviderEventReplayWorker {
@SystemInvoked(
reason =
"the notification background workers run it on their scheduler thread, which has no"
+ " Authentication")
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.IDEMPOTENT,
// Every read and write is the projection service's, each in a boundary of that service's.
repositoryAccess = RepositoryAccess.NONE)
public class ReplayProviderEventsUseCase
implements CommandUseCase<ReplayProviderEventsCommand, Integer> {
private final ProviderEventLedger ledger;
private final ProviderEventProjectionService projection;
private final int batchSize;
/**
* Creates the replay worker.
* Creates the use case.
*
* @param ledger the stored events
* @param projection the projection the events feed
* @param projection reads the stored events and projects them
* @param batchSize how many events one pass handles
* @throws IllegalStateException if the batch size is not positive, which is the assembly's fault
*/
public ProviderEventReplayWorker(
ProviderEventLedger ledger, ProviderEventProjectionService projection, int batchSize) {
this.ledger = Objects.requireNonNull(ledger, "ledger");
public ReplayProviderEventsUseCase(ProviderEventProjectionService projection, int batchSize) {
this.projection = Objects.requireNonNull(projection, "projection");
if (batchSize < 1) {
throw new IllegalArgumentException("batchSize");
throw new IllegalStateException("batchSize must be positive");
}
this.batchSize = batchSize;
}
@@ -52,10 +70,12 @@ public final class ProviderEventReplayWorker {
*
* @return how many events projected successfully
*/
public int replayOnce() {
@Override
public Integer handle(ReplayProviderEventsCommand command) {
Objects.requireNonNull(command, "command");
int projected = 0;
projected += replay(ledger.unmatched(batchSize));
projected += replay(ledger.pendingProjection(batchSize));
projected += replay(projection.unmatched(batchSize));
projected += replay(projection.pendingProjection(batchSize));
return projected;
}
@@ -69,8 +89,8 @@ public final class ProviderEventReplayWorker {
projected++;
}
} catch (RuntimeException failure) {
// Through the projection service, which opens the transaction: this worker has none, and
// marking the event is a modifying query that throws without one.
// Through the projection service, which opens the transaction: this use case holds none
// here, and marking the event is a modifying query that throws without one.
projection.markFailed(event, failure.getClass().getSimpleName());
}
}
@@ -0,0 +1,24 @@
package dev.caskeleton.application.notification.platform.dispatch;
import dev.caskeleton.application.command.Command;
import java.time.Duration;
import java.util.Objects;
/**
* One claim of due deliveries for a scheduler worker.
*
* @param workerId the claiming worker, including its process incarnation
* @param limit the most deliveries to claim; only as many as can start now
* @param leaseDuration how long the claimed deliveries are the worker's
*/
public record ClaimDueDeliveriesCommand(String workerId, int limit, Duration leaseDuration)
implements Command {
public ClaimDueDeliveriesCommand {
Objects.requireNonNull(workerId, "workerId");
Objects.requireNonNull(leaseDuration, "leaseDuration");
if (limit < 1) {
throw new IllegalStateException("limit must be positive");
}
}
}
@@ -0,0 +1,47 @@
package dev.caskeleton.application.notification.platform.dispatch;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.security.SystemInvoked;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.util.List;
import java.util.Objects;
/**
* Claims the deliveries that are due, each under a fresh lease and fence.
*
* <p>The first of the scheduler's two steps; {@link DispatchClaimedDeliveryUseCase} is the second,
* once per claimed delivery. The worker that drives them owns only threads and concurrency permits:
* what is claimed, and under which lease, is decided here (round9 review 2026-11-12, RR9-05-06).
*
* <p><b>Not a bean.</b> The notification composition's scheduler worker constructs it and keeps it.
*/
@SystemInvoked(
reason =
"the notification scheduler worker claims on its polling thread, which has no"
+ " Authentication")
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.NOT_IDEMPOTENT,
repositoryAccess = RepositoryAccess.WRITE_REPOSITORY)
public class ClaimDueDeliveriesUseCase
implements CommandUseCase<ClaimDueDeliveriesCommand, List<RecipientLease>> {
private final RecipientLeaseStorePort leases;
private final TransactionPort transactions;
public ClaimDueDeliveriesUseCase(RecipientLeaseStorePort leases, TransactionPort transactions) {
this.leases = Objects.requireNonNull(leases, "leases");
this.transactions = Objects.requireNonNull(transactions, "transactions");
}
@Override
public List<RecipientLease> handle(ClaimDueDeliveriesCommand command) {
Objects.requireNonNull(command, "command");
return transactions.inWrite(
() -> leases.claim(command.workerId(), command.limit(), command.leaseDuration()));
}
}
@@ -0,0 +1,16 @@
package dev.caskeleton.application.notification.platform.dispatch;
import dev.caskeleton.application.command.Command;
import java.util.Objects;
/**
* One claimed delivery to send.
*
* @param lease the claim the delivery is held under
*/
public record DispatchClaimedDeliveryCommand(RecipientLease lease) implements Command {
public DispatchClaimedDeliveryCommand {
Objects.requireNonNull(lease, "lease");
}
}
@@ -0,0 +1,46 @@
package dev.caskeleton.application.notification.platform.dispatch;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.security.SystemInvoked;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.util.Objects;
/**
* Sends one claimed delivery, under its lease.
*
* <p>{@code RepositoryAccess.NONE}: the delivery is {@link NotificationDispatchService}'s, which
* commits the attempt row before the provider call and records the outcome after it, each in a
* boundary of its own. One around the whole dispatch would hold a connection across the provider
* call.
*
* <p><b>Not a bean.</b> The notification composition's scheduler worker constructs it and keeps it.
*/
@SystemInvoked(
reason =
"the notification scheduler worker dispatches on its executor threads, which have no"
+ " Authentication")
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.NOT_IDEMPOTENT,
repositoryAccess = RepositoryAccess.NONE,
// The dispatch reaches the provider.
externalOutboundAllowed = true)
public class DispatchClaimedDeliveryUseCase
implements CommandUseCase<DispatchClaimedDeliveryCommand, Void> {
private final NotificationDispatchService dispatcher;
public DispatchClaimedDeliveryUseCase(NotificationDispatchService dispatcher) {
this.dispatcher = Objects.requireNonNull(dispatcher, "dispatcher");
}
@Override
public Void handle(DispatchClaimedDeliveryCommand command) {
Objects.requireNonNull(command, "command");
dispatcher.dispatch(command.lease());
return null;
}
}
@@ -0,0 +1,6 @@
package dev.caskeleton.application.notification.platform.dispatch;
import dev.caskeleton.application.command.Command;
/** One reconciliation pass over the due jobs; its bounds are the use case's. */
public record ReconcileOutstandingAttemptsCommand() implements Command {}
@@ -0,0 +1,185 @@
package dev.caskeleton.application.notification.platform.dispatch;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId;
import dev.caskeleton.application.notification.platform.provider.ReconciliationResult;
import dev.caskeleton.application.security.SystemInvoked;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
/**
* Asks the provider what happened to attempts whose outcome is unknown.
*
* <p>Reconciliation only ever ran when a lease expired and recovery walked past an incomplete
* attempt. An ambiguous submission whose worker exited cleanly — the common case, because a worker
* that records AMBIGUOUS and then finishes its shift has not crashed — was never asked about again.
* The delivery sat {@code RECONCILIATION_REQUIRED} indefinitely, which reads as a queue that
* stopped rather than as an outcome nobody knows.
*
* <p>An unsupported provider is not retried in a loop. Without a status-query capability the answer
* will not change, so the job is completed and the attempt stays visibly ambiguous for an operator
* — a busy loop against a capability that does not exist is how a background worker burns a
* connection pool while achieving nothing.
*
* <p>Every instance runs this worker, so the claim is a lease: the jobs a pass takes are this
* instance's until {@code claimLease} has passed, and no transaction is held while the provider is
* asked. A pass that outlives its lease may find a job taken over by another instance; the store
* then ignores this pass's write for it, so the job is asked about twice but recorded once.
*
* <p>A use case, not a worker of the notification adapter, which it used to be: when to ask again,
* when to give up and what each answer means are the platform's decisions, and the adapter's job is
* speaking provider protocols. The store writes each run in a write transaction of their own; the
* provider is asked with none open (round9 review 2026-11-12, RR9-05-06, RR9-05-08).
*
* <p><b>Not a bean.</b> The notification composition's background workers construct it and keep it.
*/
@SystemInvoked(
reason =
"the notification background workers run it on their scheduler thread, which has no"
+ " Authentication; an operator's run is ReconcileDeliveriesUseCase")
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.WRITE_REPOSITORY,
// Each job asks a provider what happened.
externalOutboundAllowed = true)
public class ReconcileOutstandingAttemptsUseCase
implements CommandUseCase<ReconcileOutstandingAttemptsCommand, Integer> {
private final ReconciliationJobStorePort jobs;
private final Function<DeliveryAttemptId, ReconciliationResult> reconciler;
private final TransactionPort transactions;
private final Clock clock;
private final Duration retryBackoff;
private final Duration claimLease;
private final int batchSize;
private final int maxAttempts;
/**
* Creates the use case.
*
* <p>The timing is derived here rather than in the assembly, because when to ask again and when
* to give up are this use case's decisions. A failed or crashed question waits one delivery lease
* before it is asked again. The claim lease reuses the delivery lease rather than adding a
* setting: one pass asks up to {@code batchSize} providers in turn, so a pass slower than the
* lease lets another instance re-ask its remaining jobs, and the claim fence keeps those answers
* recorded once. A job may ask once plus the delivery's additional attempts, the same budget a
* delivery has for being sent.
*
* @param jobs the outstanding questions
* @param reconciler asks one attempt's provider; it opens its own boundaries for what it writes
* @param transactions opens the write transaction around each job-store write
* @param clock the clock
* @param deliveryLease the delivery lease: the retry delay and how long one pass owns its jobs
* @param batchSize how many jobs one pass handles
* @param maxAdditionalAttempts how many more times a job may ask after its first question
* @throws IllegalStateException if a bound is not positive, which is the assembly's fault
*/
public ReconcileOutstandingAttemptsUseCase(
ReconciliationJobStorePort jobs,
Function<DeliveryAttemptId, ReconciliationResult> reconciler,
TransactionPort transactions,
Clock clock,
Duration deliveryLease,
int batchSize,
int maxAdditionalAttempts) {
this.jobs = Objects.requireNonNull(jobs, "jobs");
this.reconciler = Objects.requireNonNull(reconciler, "reconciler");
this.transactions = Objects.requireNonNull(transactions, "transactions");
this.clock = Objects.requireNonNull(clock, "clock");
Objects.requireNonNull(deliveryLease, "deliveryLease");
if (deliveryLease.isNegative() || deliveryLease.isZero()) {
throw new IllegalStateException("deliveryLease must be positive");
}
if (batchSize < 1) {
throw new IllegalStateException("batchSize must be positive");
}
if (maxAdditionalAttempts < 0) {
throw new IllegalStateException("maxAdditionalAttempts must not be negative");
}
this.retryBackoff = deliveryLease;
this.claimLease = deliveryLease;
this.batchSize = batchSize;
this.maxAttempts = maxAdditionalAttempts + 1;
}
/**
* Runs one pass.
*
* @return how many jobs reached a terminal decision
*/
@Override
public Integer handle(ReconcileOutstandingAttemptsCommand command) {
Objects.requireNonNull(command, "command");
List<ReconciliationJob> due =
transactions.inWrite(() -> jobs.claimDue(batchSize, clock.instant(), claimLease));
int settled = 0;
for (ReconciliationJob job : due) {
// One job's failure is not the pass's: a provider that is refusing connections would
// otherwise stop every other provider's jobs behind it.
try {
if (handle(job)) {
settled++;
}
} catch (RuntimeException failure) {
reschedule(job, failure.getClass().getSimpleName(), clock.instant().plus(retryBackoff));
}
}
return settled;
}
private boolean handle(ReconciliationJob job) {
if (job.attempts() >= maxAttempts) {
// Asked enough times. Completing the job leaves the attempt ambiguous and visible rather
// than asking forever; an outcome that has not arrived after this many tries is an
// operator's decision, not a scheduler's.
transactions.inWrite(
() -> {
jobs.reschedule(job, "MAX_ATTEMPTS", clock.instant().plus(retryBackoff));
jobs.complete(job);
});
return true;
}
ReconciliationResult result = reconciler.apply(job.attemptId());
return switch (result) {
case ReconciliationResult.Confirmed ignored -> {
complete(job);
yield true;
}
case ReconciliationResult.Unsupported ignored -> {
// The capability does not exist; asking again cannot change that.
complete(job);
yield true;
}
case ReconciliationResult.StillUnknown stillUnknown -> {
reschedule(job, "STILL_UNKNOWN", stillUnknown.nextCheckAt());
yield false;
}
case ReconciliationResult.Failed failed -> {
if (failed.retryable()) {
reschedule(job, failed.code(), clock.instant().plus(retryBackoff));
yield false;
}
complete(job);
yield true;
}
};
}
private void complete(ReconciliationJob job) {
transactions.inWrite(() -> jobs.complete(job));
}
private void reschedule(ReconciliationJob job, String result, Instant nextCheckAt) {
transactions.inWrite(() -> jobs.reschedule(job, result, nextCheckAt));
}
}
@@ -0,0 +1,6 @@
package dev.caskeleton.application.notification.platform.dispatch;
import dev.caskeleton.application.command.Command;
/** One lease-recovery pass; its bounds are the recovery service's. */
public record RecoverAbandonedDeliveriesCommand() implements Command {}
@@ -0,0 +1,47 @@
package dev.caskeleton.application.notification.platform.dispatch;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.security.SystemInvoked;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.util.Objects;
/**
* Returns deliveries a dead worker left dispatching to the queue, or to reconciliation when an
* attempt may have reached the provider.
*
* <p>{@code RepositoryAccess.NONE}: the pass is {@link LeaseRecoveryService}'s, which opens a
* boundary per delivery it settles and none around the provider question.
*
* <p><b>Not a bean.</b> The notification composition's background workers construct it and keep it.
*/
@SystemInvoked(
reason =
"the notification background workers run it on their scheduler thread, which has no"
+ " Authentication")
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.NONE,
// Recovery may ask a provider what happened to an attempt.
externalOutboundAllowed = true)
public class RecoverAbandonedDeliveriesUseCase
implements CommandUseCase<RecoverAbandonedDeliveriesCommand, Integer> {
private final LeaseRecoveryService recovery;
public RecoverAbandonedDeliveriesUseCase(LeaseRecoveryService recovery) {
this.recovery = Objects.requireNonNull(recovery, "recovery");
}
/**
* @return how many deliveries the pass settled
*/
@Override
public Integer handle(RecoverAbandonedDeliveriesCommand command) {
Objects.requireNonNull(command, "command");
return recovery.recoverOnce();
}
}
@@ -0,0 +1,6 @@
package dev.caskeleton.application.notification.platform.observation;
import dev.caskeleton.application.query.Query;
/** Asks how many deliveries are due and not yet sent; it has no parameters. */
public record MeasureDispatchBacklogQuery() implements Query {}
@@ -0,0 +1,52 @@
package dev.caskeleton.application.notification.platform.observation;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.QueryUseCase;
import java.util.Objects;
/**
* Measures the dispatch backlog the scheduler publishes as its queue-depth gauge on every poll.
*
* <p>The depth alone, one statement in a read transaction of its own: the full serving snapshot is
* several statements and is the health endpoint's. The scheduler read the serving-state port
* directly, with no use case and no read boundary in between (round9 review 2026-11-12, application
* structure). The notification composition constructs it for the scheduler; nothing else needs it.
*/
@UseCaseCapability(
transactionMode = TransactionMode.READ_ONLY,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.READ_REPOSITORY)
public class MeasureDispatchBacklogUseCase
implements QueryUseCase<MeasureDispatchBacklogQuery, Long> {
private final NotificationServingStatePort servingState;
private final TransactionPort transactions;
/**
* Creates the use case.
*
* @param servingState the serving-state read model
* @param transactions opens the read transaction around the measurement
*/
public MeasureDispatchBacklogUseCase(
NotificationServingStatePort servingState, TransactionPort transactions) {
this.servingState = Objects.requireNonNull(servingState, "servingState");
this.transactions = Objects.requireNonNull(transactions, "transactions");
}
/**
* Measures the backlog.
*
* @param query the measurement request
* @return how many deliveries are due and not yet sent
*/
@Override
public Long handle(MeasureDispatchBacklogQuery query) {
Objects.requireNonNull(query, "query");
return transactions.inRead(servingState::backlogDepth);
}
}
@@ -19,14 +19,15 @@ public final class DefaultNotificationRetryPolicy implements NotificationRetryPo
private final JitterSource jitter;
private final Duration reconcileDelay;
public DefaultNotificationRetryPolicy(
RetryBackoff backoff, JitterSource jitter, Duration reconcileDelay) {
this.backoff = Objects.requireNonNull(backoff, "backoff");
/**
* @param timing the backoff and the reconcile delay, already checked by {@link RetryTiming}
* @param jitter the randomness the backoff draws from
*/
public DefaultNotificationRetryPolicy(RetryTiming timing, JitterSource jitter) {
Objects.requireNonNull(timing, "timing");
this.backoff = timing.backoff();
this.jitter = Objects.requireNonNull(jitter, "jitter");
this.reconcileDelay = Objects.requireNonNull(reconcileDelay, "reconcileDelay");
if (reconcileDelay.isNegative()) {
throw new IllegalArgumentException("reconcileDelay");
}
this.reconcileDelay = timing.reconcileDelay();
}
@Override
@@ -9,7 +9,7 @@ public record EligibilityResult(boolean allowed, List<String> reasonCodes) {
public EligibilityResult {
reasonCodes = List.copyOf(Objects.requireNonNull(reasonCodes, "reasonCodes"));
if (!allowed && reasonCodes.isEmpty()) {
throw new IllegalArgumentException("a block must carry at least one reason code");
throw new IllegalStateException("a block must carry at least one reason code");
}
}
@@ -30,10 +30,11 @@ public record RetryBackoff(Duration base, Duration max) {
Objects.requireNonNull(base, "base");
Objects.requireNonNull(max, "max");
if (base.isNegative() || base.isZero()) {
throw new IllegalArgumentException("base");
throw new IllegalStateException("the backoff base must be positive, was " + base);
}
if (max.compareTo(base) < 0) {
throw new IllegalArgumentException("max must not be smaller than base");
throw new IllegalStateException(
"the backoff max (" + max + ") must not be shorter than its base (" + base + ")");
}
}
@@ -42,7 +43,7 @@ public record RetryBackoff(Duration base, Duration max) {
Objects.requireNonNull(retryAfter, "retryAfter");
Objects.requireNonNull(jitter, "jitter");
if (attemptNumber < 1) {
throw new IllegalArgumentException("attemptNumber");
throw new IllegalStateException("attemptNumber must be >= 1, was " + attemptNumber);
}
Duration jittered = new Backoff(base, max).fullJitter(attemptNumber, asRandom(jitter));
Duration computed = jittered.compareTo(base) < 0 ? base : jittered;
@@ -10,7 +10,8 @@ public record RetryBudget(int maxAdditionalAttempts, int consumed) {
public RetryBudget {
if (maxAdditionalAttempts < 0 || consumed < 0) {
throw new IllegalArgumentException("budget values must not be negative");
throw new IllegalStateException(
"budget values must not be negative, were " + maxAdditionalAttempts + " and " + consumed);
}
}
@@ -47,7 +47,7 @@ public record RetryContext(
Objects.requireNonNull(estimatedDispatchDuration, "estimatedDispatchDuration");
Objects.requireNonNull(now, "now");
if (attemptNumber < 1) {
throw new IllegalArgumentException("attemptNumber");
throw new IllegalStateException("attemptNumber must be >= 1, was " + attemptNumber);
}
}
@@ -12,7 +12,7 @@ public sealed interface RetryDecision {
public RetryAfter {
Objects.requireNonNull(delay, "delay");
if (delay.isNegative()) {
throw new IllegalArgumentException("delay");
throw new IllegalStateException("delay must not be negative, was " + delay);
}
}
}
@@ -0,0 +1,31 @@
package dev.caskeleton.application.notification.platform.policy;
import java.time.Duration;
import java.util.Objects;
/**
* When a failed delivery is tried again: the backoff between attempts, and how long an ambiguous
* submission waits before the provider is asked what happened.
*
* <p>One value so its rules have one home. The retry settings build it from their keys and the
* policy reads it; neither restates what a valid timing is.
*
* @param backoff the delay between attempts
* @param reconcileDelay how long after an ambiguous submission reconciliation first asks; zero asks
* at once
*/
public record RetryTiming(RetryBackoff backoff, Duration reconcileDelay) {
/** The shipped timing: the default backoff, reconciliation after a minute. */
public static final RetryTiming DEFAULT =
new RetryTiming(RetryBackoff.DEFAULT, Duration.ofMinutes(1));
public RetryTiming {
Objects.requireNonNull(backoff, "backoff");
Objects.requireNonNull(reconcileDelay, "reconcileDelay");
if (reconcileDelay.isNegative()) {
throw new IllegalStateException(
"the reconcile delay must not be negative, was " + reconcileDelay);
}
}
}
@@ -19,7 +19,7 @@ public record RouteCandidate(
Objects.requireNonNull(contactPointId, "contactPointId");
Objects.requireNonNull(providerProfileId, "providerProfileId");
if (routeIndex < 0) {
throw new IllegalArgumentException("routeIndex");
throw new IllegalStateException("routeIndex must be >= 0, was " + routeIndex);
}
}
@@ -27,7 +27,7 @@ public record RoutingContext(
Objects.requireNonNull(expiresAt, "expiresAt");
Objects.requireNonNull(now, "now");
if (routeCursor < 0) {
throw new IllegalArgumentException("routeCursor");
throw new IllegalStateException("routeCursor must be >= 0, was " + routeCursor);
}
}
@@ -16,10 +16,10 @@ public record RoutingDecision(
Objects.requireNonNull(selected, "selected");
Objects.requireNonNull(reasonCode, "reasonCode");
if (reasonCode.isBlank()) {
throw new IllegalArgumentException("reasonCode");
throw new IllegalStateException("a routing decision needs a reason code");
}
if (reconciliationRequired && (retryAllowed || fallbackAllowed)) {
throw new IllegalArgumentException(
throw new IllegalStateException(
"an attempt awaiting reconciliation may not also be retried or fallen back");
}
}
@@ -0,0 +1,16 @@
/**
* The notification platform's delivery policy: who may be sent to (eligibility: consent,
* preference, suppression), what counts as the same request twice (deduplication), and which route
* to try and when to retry, reroute or stop.
*
* <p>The values the platform, or a policy it calls, assembles ({@link RetryTiming}, {@link
* RetryBackoff}, {@link RetryBudget}, {@link RetryContext}, {@link RetryDecision.RetryAfter},
* {@link RouteCandidate}, {@link RoutingContext}, {@link RoutingDecision}, {@link
* EligibilityResult}) are built from settings, the shipped defaults, its own counters and stored
* delivery state: what they refuse never comes from a request. A refusal is a server fault, {@link
* IllegalStateException}, not the {@code IllegalArgumentException} the web layer would answer with
* a 400 (manual 06). The records that carry what a request may send ({@link ConsentRecord}, {@link
* PreferenceRecord}, {@link RecipientIdentity}, {@link SuppressionEntry}) refuse with {@code
* IllegalArgumentException}.
*/
package dev.caskeleton.application.notification.platform.policy;
@@ -22,7 +22,7 @@ class AdminOperationExecutorTest {
private final InMemoryAdminOperationStore store = new InMemoryAdminOperationStore();
@Test
@DisplayName("처음 claim한 operation만 claim을 쥔 채 한 쓰기 트랜잭션 안에서 부수 효과를 실행한다")
@DisplayName("처음 claim한 operation만 claim을 쥔 채 부수 효과를 실행하고, 트랜잭션은 열지 않는다")
void claimedOperationIsTheOnlyOutcomeThatRunsTheSideEffect() {
// given
DirectTransactionPort transactions = new DirectTransactionPort();
@@ -31,7 +31,7 @@ class AdminOperationExecutorTest {
// when
AdminOperationResult result =
executor.execute(
executor.runClaimed(
"op-1", FINGERPRINT, ACTOR, "ADMIN_PROVIDER_STATE", sideEffect(sideEffects));
// then
@@ -41,12 +41,10 @@ class AdminOperationExecutorTest {
sideEffects.get(),
store.claim("op-1", FINGERPRINT, ACTOR, "ADMIN_PROVIDER_STATE"),
transactions.committed()))
.as("the operation saves its own result; until then the id answers in-progress")
.containsExactly(
"op-1",
1,
AdminOperationClaim.inProgress(),
List.of(DirectTransactionPort.Boundary.WRITE));
.as(
"the operation saves its own result; until then the id answers in-progress. The"
+ " use case owns the write transaction the claim runs in")
.containsExactly("op-1", 1, AdminOperationClaim.inProgress(), List.of());
}
@Test
@@ -62,7 +60,7 @@ class AdminOperationExecutorTest {
// when
AdminOperationResult replayed =
executor.execute(
executor.runClaimed(
"op-1", FINGERPRINT, ACTOR, "ADMIN_PROVIDER_STATE", sideEffect(sideEffects));
// then
@@ -82,7 +80,7 @@ class AdminOperationExecutorTest {
Throwable thrown =
catchThrowable(
() ->
executor.execute(
executor.runClaimed(
"op-1", FINGERPRINT, ACTOR, "ADMIN_REDRIVE", sideEffect(sideEffects)));
// then
@@ -103,7 +101,7 @@ class AdminOperationExecutorTest {
Throwable thrown =
catchThrowable(
() ->
executor.execute(
executor.runClaimed(
"op-1", FINGERPRINT, ACTOR, "ADMIN_REDRIVE", sideEffect(sideEffects)));
// then
@@ -7,17 +7,17 @@ import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.Test;
class AdminOperationCommandFingerprintTest {
class AdminOperationRequestFingerprintTest {
private final AdminOperationCommandFingerprint fingerprints =
new AdminOperationCommandFingerprint();
private final AdminOperationRequestFingerprint fingerprints =
new AdminOperationRequestFingerprint();
@Test
void fingerprintIsStableSha256AndChangesWithCommandMeaning() {
void fingerprintIsStableSha256AndChangesWithRequestMeaning() {
DeliveryAttemptId attempt = new DeliveryAttemptId(UUID.fromString("00000000-0000-0000-0000-1"));
RedriveCommand first = new RedriveCommand("op-1", attempt, "retry", true, false);
RedriveCommand same = new RedriveCommand("another-id", attempt, "retry", true, false);
RedriveCommand changed = new RedriveCommand("op-1", attempt, "different", true, false);
RedriveRequest first = new RedriveRequest("op-1", attempt, "retry", true, false);
RedriveRequest same = new RedriveRequest("another-id", attempt, "retry", true, false);
RedriveRequest changed = new RedriveRequest("op-1", attempt, "different", true, false);
assertThat(fingerprints.of(first)).matches("[0-9a-f]{64}");
assertThat(fingerprints.of(same)).isEqualTo(fingerprints.of(first));
@@ -31,10 +31,10 @@ class AdminOperationCommandFingerprintTest {
DeliveryAttemptId second =
new DeliveryAttemptId(UUID.fromString("00000000-0000-0000-0000-000000000002"));
ReconcileCommand ordered =
new ReconcileCommand("op-1", List.of(first, second), "reconcile", false);
ReconcileCommand reversed =
new ReconcileCommand("op-2", List.of(second, first), "reconcile", false);
ReconcileRequest ordered =
new ReconcileRequest("op-1", List.of(first, second), "reconcile", false);
ReconcileRequest reversed =
new ReconcileRequest("op-2", List.of(second, first), "reconcile", false);
assertThat(fingerprints.of(ordered)).isEqualTo(fingerprints.of(reversed));
}
@@ -27,9 +27,9 @@ import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemor
import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryRecipientQueue;
import dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent;
import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort;
import dev.caskeleton.application.notification.platform.policy.SuppressionEntry;
import dev.caskeleton.application.notification.platform.policy.SuppressionId;
import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort;
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.ProviderRuntimeState;
import dev.caskeleton.application.notification.platform.provider.ReconciliationResult;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
@@ -42,10 +42,14 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class NotificationAdminApplicationServiceTest {
/**
* The four operator-plane use cases, each its own entrypoint with its own permission (round9 review
* 2026-11-12, RR9-05-07: one service implemented all four behind an interface no use-case rule
* saw).
*/
class NotificationAdminUseCasesTest {
private static final Clock CLOCK =
Clock.fixed(Instant.parse("2026-09-20T00:00:00Z"), ZoneOffset.UTC);
@@ -56,15 +60,16 @@ class NotificationAdminApplicationServiceTest {
@Test
void providerStateMutationClaimsBeforeCallingTheRuntime() {
Fixture fixture = new Fixture();
SetProviderStateCommand command =
new SetProviderStateCommand(
ProviderStateRequest request =
new ProviderStateRequest(
"op-1",
new ProviderProfileId("ses-primary"),
ProviderRuntimeState.DISABLED,
"provider maintenance",
false);
AdminOperationResult result = fixture.service.setProviderState(command, ACTOR);
AdminOperationResult result =
fixture.providerState.handle(new ChangeProviderStateCommand(request, ACTOR));
assertThat(result.operationId()).isEqualTo("op-1");
assertThat(fixture.operations.claims).isEqualTo(1);
@@ -77,18 +82,40 @@ class NotificationAdminApplicationServiceTest {
.containsExactly("ADMIN_PROVIDER_STATE");
}
@Test
void providerStateClaimAndChangeCommitInTheUseCasesOneWriteTransaction() {
// given
Fixture fixture = new Fixture();
ProviderStateRequest request =
new ProviderStateRequest(
"op-tx",
new ProviderProfileId("ses-primary"),
ProviderRuntimeState.DRAINING,
"provider maintenance",
false);
// when
fixture.providerState.handle(new ChangeProviderStateCommand(request, ACTOR));
// then
assertThat(List.of(fixture.transactions.committed(), fixture.operations.claimsInTransaction))
.as("a claim outside the transaction would commit while the change rolled back")
.containsExactly(List.of(DirectTransactionPort.Boundary.WRITE), List.of(true));
}
@Test
void providerStateDryRunDoesNotClaimOrMutateRuntime() {
Fixture fixture = new Fixture();
SetProviderStateCommand command =
new SetProviderStateCommand(
ProviderStateRequest request =
new ProviderStateRequest(
"op-dry",
new ProviderProfileId("ses-primary"),
ProviderRuntimeState.DRAINING,
"inspect only",
true);
AdminOperationResult result = fixture.service.setProviderState(command, ACTOR);
AdminOperationResult result =
fixture.providerState.handle(new ChangeProviderStateCommand(request, ACTOR));
assertThat(result.dryRun()).isTrue();
assertThat(fixture.operations.claims).isZero();
@@ -97,7 +124,6 @@ class NotificationAdminApplicationServiceTest {
}
@Test
@DisplayName("tenant 범위 운영자는 다른 tenant의 attempt를 reconcile할 수 없다")
void aTenantScopedOperatorCannotReconcileAnotherTenantsAttempt() {
// given
Fixture fixture = new Fixture();
@@ -109,11 +135,13 @@ class NotificationAdminApplicationServiceTest {
"operator-b",
Set.of(NotificationAdminAuthority.RECONCILE),
Optional.of(new TenantId("tenant-b")));
ReconcileCommand command =
new ReconcileCommand("op-r", List.of(foreign.attemptId()), "stuck attempt", false);
ReconcileRequest request =
new ReconcileRequest("op-r", List.of(foreign.attemptId()), "stuck attempt", false);
// when
Throwable failure = catchThrowable(() -> fixture.service.reconcile(command, tenantB));
Throwable failure =
catchThrowable(
() -> fixture.reconcile.handle(new ReconcileDeliveriesCommand(request, tenantB)));
// then
assertThat(failure)
@@ -124,7 +152,6 @@ class NotificationAdminApplicationServiceTest {
}
@Test
@DisplayName("tenant 범위 운영자는 모든 tenant가 공유하는 provider 상태를 바꿀 수 없다")
void aTenantScopedOperatorCannotChangeAGlobalProviderState() {
// given
Fixture fixture = new Fixture();
@@ -133,8 +160,8 @@ class NotificationAdminApplicationServiceTest {
"operator-b",
Set.of(NotificationAdminAuthority.PROVIDER_CONTROL),
Optional.of(new TenantId("tenant-b")));
SetProviderStateCommand command =
new SetProviderStateCommand(
ProviderStateRequest request =
new ProviderStateRequest(
"op-p",
new ProviderProfileId("ses-primary"),
ProviderRuntimeState.DISABLED,
@@ -142,7 +169,9 @@ class NotificationAdminApplicationServiceTest {
false);
// when
Throwable failure = catchThrowable(() -> fixture.service.setProviderState(command, tenantB));
Throwable failure =
catchThrowable(
() -> fixture.providerState.handle(new ChangeProviderStateCommand(request, tenantB)));
// then
assertThat(failure)
@@ -154,7 +183,6 @@ class NotificationAdminApplicationServiceTest {
}
@Test
@DisplayName("운영자 reconcile은 DB 트랜잭션을 연 채로 provider에 묻지 않는다")
void reconcileAsksTheProviderWithNoTransactionOpen() {
// given
List<Boolean> transactionOpenDuringProviderCall = new ArrayList<>();
@@ -182,9 +210,10 @@ class NotificationAdminApplicationServiceTest {
"operator-1", Set.of(NotificationAdminAuthority.RECONCILE), Optional.empty());
// when
fixture.service.reconcile(
new ReconcileCommand("op-rc", List.of(attempt.attemptId()), "stuck attempt", false),
operator);
fixture.reconcile.handle(
new ReconcileDeliveriesCommand(
new ReconcileRequest("op-rc", List.of(attempt.attemptId()), "stuck attempt", false),
operator));
// then
assertThat(transactionOpenDuringProviderCall)
@@ -192,6 +221,132 @@ class NotificationAdminApplicationServiceTest {
.containsExactly(false);
}
@Test
void redriveReturnsTheDeliveryToTheQueueUnderItsClaim() {
// given
Fixture fixture = new Fixture();
DeliveryAttemptSnapshot attempt = attemptOf(new TenantId("tenant-a"));
AttemptSnapshots.store(
fixture.requests, fixture.attempts, attempt, RecipientDeliveryState.FAILED);
AdminActor operator =
new AdminActor("operator-1", Set.of(NotificationAdminAuthority.REDRIVE), Optional.empty());
RedriveRequest request =
new RedriveRequest("op-rd", attempt.attemptId(), "provider outage", true, false);
// when
fixture.redrive.handle(new RedriveDeliveryCommand(request, operator));
// then
assertThat(
List.of(
fixture.recipients.find(attempt.recipientDeliveryId()).orElseThrow().state(),
fixture.operations.claimsInTransaction,
fixture.audit.events.stream().map(NotificationAuditEvent::action).toList()))
.containsExactly(
RecipientDeliveryState.READY_TO_DISPATCH, List.of(true), List.of("ADMIN_REDRIVE"));
}
@Test
void aRedriveReadsItsAttemptInsideTheWriteTransaction() {
// given
Fixture fixture = new Fixture();
DeliveryAttemptSnapshot attempt = attemptOf(new TenantId("tenant-a"));
AttemptSnapshots.store(
fixture.requests, fixture.attempts, attempt, RecipientDeliveryState.FAILED);
List<Boolean> openWhileReading = new ArrayList<>();
fixture.attempts.beforeSnapshot(id -> openWhileReading.add(fixture.transactions.active()));
AdminActor operator =
new AdminActor("operator-1", Set.of(NotificationAdminAuthority.REDRIVE), Optional.empty());
// when
fixture.redrive.handle(
new RedriveDeliveryCommand(
new RedriveRequest("op-rd-tx", attempt.attemptId(), "provider outage", true, false),
operator));
// then
assertThat(List.of(openWhileReading, fixture.transactions.committed()))
.as("the checks read the attempt the claim then redrives, in one transaction")
.containsExactly(List.of(true), List.of(DirectTransactionPort.Boundary.WRITE));
}
@Test
void aReconcileDryRunChecksItsTenantsInsideAReadTransaction() {
// given
Fixture fixture = new Fixture();
DeliveryAttemptSnapshot attempt = attemptOf(new TenantId("tenant-a"));
AttemptSnapshots.store(
fixture.requests, fixture.attempts, attempt, RecipientDeliveryState.DISPATCHING);
List<Boolean> openWhileReading = new ArrayList<>();
fixture.attempts.beforeSnapshot(id -> openWhileReading.add(fixture.transactions.active()));
AdminActor operator =
new AdminActor(
"operator-1", Set.of(NotificationAdminAuthority.RECONCILE), Optional.empty());
// when
fixture.reconcile.handle(
new ReconcileDeliveriesCommand(
new ReconcileRequest("op-rc-tx", List.of(attempt.attemptId()), "stuck attempt", true),
operator));
// then
assertThat(List.of(openWhileReading, fixture.transactions.committed()))
.containsExactly(List.of(true), List.of(DirectTransactionPort.Boundary.READ));
}
@Test
void aRedriveDryRunReadsInOneReadTransactionAndClaimsNothing() {
// given
Fixture fixture = new Fixture();
DeliveryAttemptSnapshot attempt = attemptOf(new TenantId("tenant-a"));
AttemptSnapshots.store(
fixture.requests, fixture.attempts, attempt, RecipientDeliveryState.FAILED);
AdminActor operator =
new AdminActor("operator-1", Set.of(NotificationAdminAuthority.REDRIVE), Optional.empty());
RedriveRequest request =
new RedriveRequest("op-rd-dry", attempt.attemptId(), "provider outage", true, true);
// when
fixture.redrive.handle(new RedriveDeliveryCommand(request, operator));
// then
assertThat(List.of(fixture.transactions.committed(), fixture.operations.claimsInTransaction))
.containsExactly(List.of(DirectTransactionPort.Boundary.READ), List.of());
}
@Test
void anOperatorSuppressionIsStoredUnderItsClaim() {
// given
Fixture fixture = new Fixture();
TenantId tenant = new TenantId("tenant-a");
AdminActor operator =
new AdminActor(
"operator-1", Set.of(NotificationAdminAuthority.SUPPRESS), Optional.of(tenant));
SuppressionRequest request =
new SuppressionRequest(
"op-s",
tenant,
SuppressionScope.CONTACT_POINT,
SuppressionReason.ADMIN_BLOCK,
"c".repeat(64),
Optional.empty(),
false,
"reported abuse",
false);
// when
AdminOperationResult result =
fixture.suppression.handle(new ChangeSuppressionCommand(request, operator));
// then
assertThat(
List.of(
result.affected(),
fixture.suppressions.activeFor(tenant, "c".repeat(64), CLOCK.instant()).size(),
fixture.operations.claimsInTransaction))
.containsExactly(1, 1, List.of(true));
}
private static DeliveryAttemptSnapshot attemptOf(TenantId tenantId) {
return new DeliveryAttemptSnapshot(
new DeliveryAttemptId(UUID.fromString("00000000-0000-7000-8000-000000000011")),
@@ -225,7 +380,11 @@ class NotificationAdminApplicationServiceTest {
private final RecordingOperations operations = new RecordingOperations();
private final RecordingAudit audit = new RecordingAudit();
private final DirectTransactionPort transactions = new DirectTransactionPort();
private final NotificationAdminApplicationService service;
private final InMemorySuppressionStore suppressions = new InMemorySuppressionStore();
private final ChangeProviderStateUseCase providerState;
private final ReconcileDeliveriesUseCase reconcile;
private final RedriveDeliveryUseCase redrive;
private final ChangeSuppressionUseCase suppression;
private Fixture() {
this(null);
@@ -235,24 +394,42 @@ class NotificationAdminApplicationServiceTest {
* @param gateway the provider the reconciliation asks, or null for one that supports nothing
*/
private Fixture(ReconciliationGatewayPort gateway) {
operations.transactions = transactions;
ReconciliationService reconciliation =
gateway == null
? PlatformCollaborators.reconciliation(attempts, recipients, CLOCK)
: PlatformCollaborators.reconciliation(attempts, recipients, gateway, CLOCK);
service =
new NotificationAdminApplicationService(
providerState =
new ChangeProviderStateUseCase(
new AdminAuthorizationGuard(), runtime, operations, audit, transactions, CLOCK);
redrive =
new RedriveDeliveryUseCase(
new AdminAuthorizationGuard(),
new DuplicateRiskGuard(),
attempts,
recipients,
reconciliation,
new UnusedSuppressionStore(),
runtime,
operations,
audit,
transactions,
CLOCK);
suppression =
new ChangeSuppressionUseCase(
new AdminAuthorizationGuard(),
suppressions,
operations,
audit,
transactions,
new PlatformFakes.SequentialIds(),
CLOCK);
reconcile =
new ReconcileDeliveriesUseCase(
new AdminAuthorizationGuard(),
attempts,
reconciliation,
operations,
audit,
transactions,
CLOCK);
}
}
@@ -277,6 +454,8 @@ class NotificationAdminApplicationServiceTest {
}
private static final class RecordingOperations implements AdminOperationStorePort {
private final List<Boolean> claimsInTransaction = new ArrayList<>();
private DirectTransactionPort transactions;
private int claims;
private int saved;
@@ -293,9 +472,10 @@ class NotificationAdminApplicationServiceTest {
@Override
public AdminOperationClaim claim(
String operationId, String commandFingerprint, AdminActor actor, String action) {
String operationId, String requestFingerprint, AdminActor actor, String action) {
claims++;
assertThat(commandFingerprint).matches("[0-9a-f]{64}");
claimsInTransaction.add(transactions.active());
assertThat(requestFingerprint).matches("[0-9a-f]{64}");
return AdminOperationClaim.claimed();
}
}
@@ -308,25 +488,4 @@ class NotificationAdminApplicationServiceTest {
events.add(event);
}
}
private static final class UnusedSuppressionStore implements SuppressionStorePort {
@Override
public List<SuppressionEntry> activeFor(
dev.caskeleton.application.notification.platform.api.TenantId tenantId,
String targetFingerprint,
Instant at) {
return List.of();
}
@Override
public SuppressionEntry upsert(SuppressionEntry entry) {
throw new UnsupportedOperationException();
}
@Override
public Optional<SuppressionEntry> remove(
dev.caskeleton.application.notification.platform.api.TenantId tenantId, SuppressionId id) {
return Optional.empty();
}
}
}
@@ -0,0 +1,90 @@
package dev.caskeleton.application.notification.platform.dispatch;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId;
import dev.caskeleton.application.notification.platform.api.TenantId;
import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState;
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.transaction.testkit.DirectTransactionPort;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* The scheduler's claim, run through its {@code @SystemInvoked} use case.
*
* <p>The claim used to run with no transaction of the scheduler's own: the store's statement was
* its whole boundary. It now commits in the use case's write transaction.
*/
class ClaimDueDeliveriesUseCaseTest {
private static final Instant NOW = Instant.parse("2026-11-13T09:00:00Z");
private static final Duration LEASE = Duration.ofMinutes(2);
private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore();
private final InMemoryRecipientQueue queue =
new InMemoryRecipientQueue(requests, Clock.fixed(NOW, ZoneOffset.UTC));
private final DirectTransactionPort transactions = new DirectTransactionPort();
private final ClaimDueDeliveriesUseCase useCase =
new ClaimDueDeliveriesUseCase(queue, transactions);
@Test
@DisplayName("due 발송은 쓰기 트랜잭션 하나에서 이 worker의 lease로 claim된다")
void aDueDeliveryIsClaimedForTheWorkerInOneWriteTransaction() {
// given
RecipientDeliveryId due = dueJob();
// when
List<RecipientLease> claimed =
useCase.handle(new ClaimDueDeliveriesCommand("worker-1", 10, LEASE));
// then
assertThat(
List.of(
claimed.stream().map(RecipientLease::recipientDeliveryId).toList(),
claimed.stream().map(RecipientLease::owner).toList(),
claimed.stream().map(RecipientLease::leaseUntil).toList(),
transactions.committed()))
.containsExactly(
List.of(due),
List.of("worker-1"),
List.of(NOW.plus(LEASE)),
List.of(DirectTransactionPort.Boundary.WRITE));
}
@Test
@DisplayName("한 번에 0개를 claim하라는 command는 조립의 잘못으로 실패한다")
void aClaimOfNothingIsTheAssemblysFault() {
// when
Throwable refused = catchThrowable(() -> new ClaimDueDeliveriesCommand("worker-1", 0, LEASE));
// then
assertThat(refused)
.isInstanceOf(IllegalStateException.class)
.hasMessage("limit must be positive");
}
private RecipientDeliveryId dueJob() {
var request =
NotificationRows.request(new TenantId("tenant-a"), "idem-" + UUID.randomUUID(), NOW);
var job =
NotificationRows.job(
request,
RecipientDeliveryState.READY_TO_DISPATCH,
Optional.of(NOW.minusSeconds(1)),
Optional.empty(),
NOW);
requests.insert(request, List.of(job));
return job.id();
}
}
@@ -0,0 +1,78 @@
package dev.caskeleton.application.notification.platform.dispatch;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId;
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.policy.NotificationEligibilityPolicy;
import dev.caskeleton.application.notification.platform.policy.RetryDecision;
import dev.caskeleton.application.notification.platform.policy.RoutingDecisionEngine;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* The scheduler's dispatch of one claimed delivery, run through its {@code @SystemInvoked} use
* case. The use case holds no boundary of its own; the dispatch service opens each one.
*/
class DispatchClaimedDeliveryUseCaseTest {
private static final Instant NOW = Instant.parse("2026-11-13T09:00:00Z");
private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC);
private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore();
private final InMemoryRecipientQueue recipients = new InMemoryRecipientQueue(requests, CLOCK);
private final InMemoryDeliveryAttemptStore attempts = new InMemoryDeliveryAttemptStore(requests);
private final DirectTransactionPort transactions = new DirectTransactionPort();
private final PlatformFakes.UnreachableGateway gateway = new PlatformFakes.UnreachableGateway();
private final DispatchClaimedDeliveryUseCase useCase =
new DispatchClaimedDeliveryUseCase(
new NotificationDispatchService(
requests,
recipients,
attempts,
new DispatchPipeline(
new InMemoryContactPointStore(CLOCK),
NotificationEligibilityPolicy.permitAll(),
new PlatformFakes.RecordingMetrics()),
new RoutingDecisionEngine(),
context -> new RetryDecision.Stop("unused"),
new DeliveryAttemptFactory(new PlatformFakes.SequentialIds()),
PlatformCollaborators.outcomeRecorder(attempts, recipients),
gateway,
command -> {
throw new AssertionError("a lease whose delivery is gone renders nothing");
},
recipients,
transactions,
CLOCK,
3,
Duration.ofSeconds(5)));
@Test
@DisplayName("delivery가 사라진 lease는 dispatch 서비스의 읽기·쓰기 경계에서 풀리고 provider에 닿지 않는다")
void aLeaseWhoseDeliveryIsGoneIsReleasedWithoutReachingTheProvider() {
// given
RecipientLease gone =
new RecipientLease(
new RecipientDeliveryId(UUID.randomUUID()), "worker-a", 1L, NOW.plusSeconds(30));
// when
useCase.handle(new DispatchClaimedDeliveryCommand(gone));
// then
assertThat(List.of(transactions.committed(), gateway.calls()))
.containsExactly(
List.of(DirectTransactionPort.Boundary.READ, DirectTransactionPort.Boundary.WRITE), 0);
}
}
@@ -32,8 +32,8 @@ import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemor
import dev.caskeleton.application.notification.platform.policy.DefaultNotificationRetryPolicy;
import dev.caskeleton.application.notification.platform.policy.JitterSource;
import dev.caskeleton.application.notification.platform.policy.NotificationEligibilityPolicy;
import dev.caskeleton.application.notification.platform.policy.RetryBackoff;
import dev.caskeleton.application.notification.platform.policy.RetryDecision;
import dev.caskeleton.application.notification.platform.policy.RetryTiming;
import dev.caskeleton.application.notification.platform.policy.RoutingDecisionEngine;
import dev.caskeleton.application.notification.platform.port.in.SubmitNotificationCommand;
import dev.caskeleton.application.notification.platform.provider.ProviderCapabilities;
@@ -70,7 +70,7 @@ class NotificationDispatchServiceTest {
new InMemoryRecipientQueue(requests, Clock.fixed(NOW, ZoneOffset.UTC));
InMemoryDeliveryAttemptStore attempts = new InMemoryDeliveryAttemptStore(requests);
DirectTransactionPort transactions = new DirectTransactionPort();
FailingGateway gateway = new FailingGateway();
PlatformFakes.UnreachableGateway gateway = new PlatformFakes.UnreachableGateway();
NotificationDispatchService service =
new NotificationDispatchService(
requests,
@@ -104,7 +104,7 @@ class NotificationDispatchServiceTest {
// The WRITE boundary after the read is the release; the queue has no row to show it on.
assertThat(transactions.committed()).containsExactly(Boundary.READ, Boundary.WRITE);
assertThat(gateway.calls).isZero();
assertThat(gateway.calls()).isZero();
}
@Test
@@ -500,8 +500,7 @@ class NotificationDispatchServiceTest {
NotificationEligibilityPolicy.permitAll(),
new PlatformFakes.RecordingMetrics()),
new RoutingDecisionEngine(),
new DefaultNotificationRetryPolicy(
RetryBackoff.DEFAULT, JitterSource.none(), Duration.ofMinutes(1)),
new DefaultNotificationRetryPolicy(RetryTiming.DEFAULT, JitterSource.none()),
new DeliveryAttemptFactory(new PlatformFakes.SequentialIds()),
PlatformCollaborators.outcomeRecorder(attempts, recipients),
gateway,
@@ -631,26 +630,4 @@ class NotificationDispatchServiceTest {
throw new AssertionError("nothing may be submitted through a profile that is gone");
}
}
private static final class FailingGateway implements ProviderDispatchGatewayPort {
private int calls;
@Override
public ProviderProfileSnapshot profile(ProviderProfileId profileId) {
calls++;
throw new AssertionError("gateway profile must not be reached");
}
@Override
public ProviderRuntimeState state(ProviderProfileId profileId) {
calls++;
throw new AssertionError("gateway state must not be reached");
}
@Override
public ProviderSubmissionResult submit(ProviderSubmission submission) {
calls++;
throw new AssertionError("provider submit must not be reached");
}
}
}
@@ -14,6 +14,10 @@ import dev.caskeleton.application.notification.platform.api.routing.DeliveryStra
import dev.caskeleton.application.notification.platform.api.routing.ExplicitChannel;
import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort;
import dev.caskeleton.application.notification.platform.policy.RouteCandidate;
import dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot;
import dev.caskeleton.application.notification.platform.provider.ProviderRuntimeState;
import dev.caskeleton.application.notification.platform.provider.ProviderSubmission;
import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
@@ -35,6 +39,35 @@ public final class PlatformFakes {
private PlatformFakes() {}
/** A provider gateway the dispatch under test must not reach; it counts what reached it. */
public static final class UnreachableGateway implements ProviderDispatchGatewayPort {
private int calls;
/** How many calls reached the gateway. */
public int calls() {
return calls;
}
@Override
public ProviderProfileSnapshot profile(ProviderProfileId profileId) {
calls++;
throw new AssertionError("gateway profile must not be reached");
}
@Override
public ProviderRuntimeState state(ProviderProfileId profileId) {
calls++;
throw new AssertionError("gateway state must not be reached");
}
@Override
public ProviderSubmissionResult submit(ProviderSubmission submission) {
calls++;
throw new AssertionError("provider submit must not be reached");
}
}
/** Metrics sink that keeps what it was told, so tag discipline stays assertable. */
public static final class RecordingMetrics implements NotificationMetricsPort {
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.notification.platform.dispatch;
package dev.caskeleton.application.notification.platform.dispatch;
import static org.assertj.core.api.Assertions.assertThat;
@@ -6,14 +6,14 @@ import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId;
import dev.caskeleton.application.notification.platform.api.NormalizedEventType;
import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent;
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJob;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort;
import dev.caskeleton.application.notification.platform.provider.ReconciliationResult;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -29,117 +29,190 @@ import org.junit.jupiter.api.Test;
* in {@code RECONCILIATION_REQUIRED} permanently. The job table for exactly this has existed since
* V3 with no entity, no store and no worker.
*/
class ReconciliationJobWorkerTest {
class ReconcileOutstandingAttemptsUseCaseTest {
private static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z");
private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC);
private static final Duration CLAIM_LEASE = Duration.ofMinutes(2);
private static final Duration DELIVERY_LEASE = Duration.ofMinutes(2);
private static final int MAX_ADDITIONAL_ATTEMPTS = 2;
private final RecordingJobs jobs = new RecordingJobs();
private final Map<DeliveryAttemptId, ReconciliationResult> answers = new java.util.HashMap<>();
private final Map<DeliveryAttemptId, ReconciliationResult> answers = new HashMap<>();
private final List<DeliveryAttemptId> asked = new ArrayList<>();
private final DirectTransactionPort transactions = new DirectTransactionPort();
private final ReconciliationJobWorker worker =
new ReconciliationJobWorker(
jobs, answers::get, CLOCK, Duration.ofMinutes(5), CLAIM_LEASE, 10, 3);
private final ReconcileOutstandingAttemptsUseCase useCase =
new ReconcileOutstandingAttemptsUseCase(
jobs,
attemptId -> {
asked.add(attemptId);
return answers.get(attemptId);
},
transactions,
CLOCK,
DELIVERY_LEASE,
10,
MAX_ADDITIONAL_ATTEMPTS);
@Test
@DisplayName("a confirmed outcome completes the job")
void aConfirmedOutcomeCompletesTheJob() {
// given
ReconciliationJob job = due(0);
answers.put(job.attemptId(), new ReconciliationResult.Confirmed(event()));
assertThat(worker.reconcileOnce()).isEqualTo(1);
assertThat(jobs.completed).containsExactly(job.id());
// when
int settled = useCase.handle(new ReconcileOutstandingAttemptsCommand());
// then
assertThat(List.of(settled, jobs.completed)).containsExactly(1, List.of(job.id()));
}
@Test
@DisplayName("an unsupported provider is not asked in a loop")
void anUnsupportedProviderIsNotAskedInALoop() {
@DisplayName("상태 조회가 없는 provider는 다시 묻지 않고 job을 끝낸다. 답이 바뀌지 않는다")
void anUnsupportedProviderIsCompletedRatherThanAskedAgain() {
// given
ReconciliationJob job = due(0);
answers.put(job.attemptId(), new ReconciliationResult.Unsupported());
assertThat(worker.reconcileOnce()).isEqualTo(1);
assertThat(jobs.completed)
.as(
"without a status-query capability the answer will not change; the attempt stays"
+ " visibly ambiguous for an operator instead")
.containsExactly(job.id());
assertThat(jobs.rescheduled).isEmpty();
// when
useCase.handle(new ReconcileOutstandingAttemptsCommand());
// then
assertThat(List.of(jobs.completed, jobs.rescheduled))
.as("the attempt stays visibly ambiguous for an operator instead")
.containsExactly(List.of(job.id()), List.of());
}
@Test
@DisplayName("a still-unknown outcome is asked again at the provider's own next time")
void aStillUnknownOutcomeIsAskedAgain() {
void aStillUnknownOutcomeIsAskedAgainAtTheProvidersOwnNextTime() {
// given
ReconciliationJob job = due(0);
Instant providerSuggested = NOW.plus(Duration.ofHours(2));
answers.put(job.attemptId(), new ReconciliationResult.StillUnknown(providerSuggested));
assertThat(worker.reconcileOnce()).isZero();
assertThat(jobs.rescheduled).containsExactly(Map.entry(job.id(), providerSuggested));
assertThat(jobs.completed).isEmpty();
// when
useCase.handle(new ReconcileOutstandingAttemptsCommand());
// then
assertThat(List.of(jobs.rescheduled, jobs.completed))
.containsExactly(List.of(Map.entry(job.id(), providerSuggested)), List.of());
}
@Test
@DisplayName("a retryable failure is asked again after the backoff")
void aRetryableFailureIsAskedAgain() {
void aRetryableFailureIsAskedAgainOneDeliveryLeaseLater() {
// given
ReconciliationJob job = due(0);
answers.put(job.attemptId(), new ReconciliationResult.Failed("PROVIDER_TIMEOUT", true));
assertThat(worker.reconcileOnce()).isZero();
assertThat(jobs.rescheduled)
.containsExactly(Map.entry(job.id(), NOW.plus(Duration.ofMinutes(5))));
// when
useCase.handle(new ReconcileOutstandingAttemptsCommand());
// then
assertThat(jobs.rescheduled).containsExactly(Map.entry(job.id(), NOW.plus(DELIVERY_LEASE)));
}
@Test
@DisplayName("a non-retryable failure completes the job")
void aNonRetryableFailureCompletesTheJob() {
// given
ReconciliationJob job = due(0);
answers.put(job.attemptId(), new ReconciliationResult.Failed("ATTEMPT_UNKNOWN", false));
assertThat(worker.reconcileOnce()).isEqualTo(1);
// when
useCase.handle(new ReconcileOutstandingAttemptsCommand());
// then
assertThat(jobs.completed).containsExactly(job.id());
}
@Test
@DisplayName("a job that has asked enough times stops asking")
void aJobThatHasAskedEnoughTimesStopsAsking() {
ReconciliationJob job = due(3);
@DisplayName("첫 질문과 추가 시도 2번, 모두 3번을 물은 job은 더 묻지 않고 끝난다")
void aJobThatAskedOnceMoreThanItsAdditionalAttemptsStopsAsking() {
// given
ReconciliationJob job = due(MAX_ADDITIONAL_ATTEMPTS + 1);
assertThat(worker.reconcileOnce()).isEqualTo(1);
assertThat(jobs.completed)
// when
useCase.handle(new ReconcileOutstandingAttemptsCommand());
// then
assertThat(List.of(asked, jobs.completed))
.as("an outcome that has not arrived after this many tries is an operator's decision")
.containsExactly(job.id());
assertThat(answers).isEmpty();
.containsExactly(List.of(), List.of(job.id()));
}
@Test
@DisplayName("one job throwing does not stop the rest of the pass")
void oneJobThrowingDoesNotStopTheRest() {
@DisplayName("2번 물은 job은 추가 시도가 남아 한 번 더 묻는다")
void aJobWithAnAdditionalAttemptLeftIsAskedAgain() {
// given
ReconciliationJob job = due(MAX_ADDITIONAL_ATTEMPTS);
answers.put(job.attemptId(), new ReconciliationResult.Unsupported());
// when
useCase.handle(new ReconcileOutstandingAttemptsCommand());
// then
assertThat(asked).containsExactly(job.attemptId());
}
@Test
void oneJobThrowingDoesNotStopTheRestOfThePass() {
// given
// The failing job has no answer registered, so the reconciler returns null and the switch
// throws — which is exactly the shape of a provider refusing connections.
ReconciliationJob failing = due(0);
ReconciliationJob healthy = due(0);
answers.put(healthy.attemptId(), new ReconciliationResult.Confirmed(event()));
// The failing job has no answer registered, so the reconciler returns null and the switch
// throws — which is exactly the shape of a provider refusing connections.
assertThat(worker.reconcileOnce()).isEqualTo(1);
assertThat(jobs.completed).containsExactly(healthy.id());
assertThat(jobs.rescheduled).hasSize(1);
assertThat(jobs.rescheduled.get(0).getKey()).isEqualTo(failing.id());
// when
useCase.handle(new ReconcileOutstandingAttemptsCommand());
// then
assertThat(List.of(jobs.completed, jobs.rescheduled.stream().map(Map.Entry::getKey).toList()))
.containsExactly(List.of(healthy.id()), List.of(failing.id()));
}
@Test
@DisplayName("한 번의 pass는 설정된 lease 동안 소유하도록 job을 claim한다")
void aPassClaimsItsJobsForTheConfiguredLease() {
@DisplayName("한 번의 pass는 delivery lease 동안 소유하도록 job을 claim한다")
void aPassClaimsItsJobsForOneDeliveryLease() {
// given
due(0);
// when
worker.reconcileOnce();
useCase.handle(new ReconcileOutstandingAttemptsCommand());
// then
assertThat(jobs.claimLeases)
.as("without a lease the claim ends with the statement and every instance takes the job")
.containsExactly(CLAIM_LEASE);
.containsExactly(DELIVERY_LEASE);
}
@Test
@DisplayName("provider에는 트랜잭션 없이 묻고, job 기록은 그 앞뒤의 쓰기 트랜잭션에서 한다")
void theProviderIsAskedWithNoTransactionOpenAndTheJobIsRecordedInOne() {
// given
due(0);
List<Boolean> openWhileAsking = new ArrayList<>();
ReconcileOutstandingAttemptsUseCase observing =
new ReconcileOutstandingAttemptsUseCase(
jobs,
attemptId -> {
openWhileAsking.add(transactions.active());
return new ReconciliationResult.Unsupported();
},
transactions,
CLOCK,
DELIVERY_LEASE,
10,
MAX_ADDITIONAL_ATTEMPTS);
// when
observing.handle(new ReconcileOutstandingAttemptsCommand());
// then
assertThat(List.of(openWhileAsking, transactions.committed()))
.as("the claim and the completion each commit; the provider call holds no connection")
.containsExactly(
List.of(false),
List.of(DirectTransactionPort.Boundary.WRITE, DirectTransactionPort.Boundary.WRITE));
}
private ReconciliationJob due(int attempts) {

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