From 642b7e0d18790262fff5b471b9febe68a7d9c6d0 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Tue, 29 Sep 2026 12:44:29 +0900 Subject: [PATCH] =?UTF-8?q?review-followup=20Wave=203=20=EB=9D=BC=EC=9A=B4?= =?UTF-8?q?=EB=93=9C=203(P23):=20notification=20=E2=80=94=20SES=EB=A5=BC?= =?UTF-8?q?=20AWS=20SDK=20sesv2=EB=A1=9C,=20persistence-notification=20lea?= =?UTF-8?q?f=20=EC=B6=94=EC=B6=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 결정 17: 자체 JDK HTTP gateway·SigV4 서명기 삭제, SES를 AWS SDK v2 `sesv2`로(기존 설정 계약 유지, SDK 재시도 끔, 기본 자격 증명 체인 끔, endpoint 라우팅 검사 유지) — 로컬 가짜 서버로 실제 SDK client 계약 테스트 - S2-#1b: notification persistence를 `adapter:outbound:persistence-notification`으로(migration V1–V10 바이트·위치 동일, persistence-jpa → application-notification edge 제거), composition이 새 leaf를 가져옴 - 레지스트리 2개 삭제, provider 상태 전이표 하나, `ProviderCapabilities.dispatchOnly(...)`, dispatch record 전이 메서드, 미조립 회전 경로·중복 제출 진입점·테스트 전용 생성자 삭제 - 통합: at-rest 계약 테스트가 새 leaf 경로를 보고 `src/main/java`만 훑게(ORCH-new-2), app-bootstrap 알림 선택 주석(P23-new-3) 검증: ./gradlew check architectureCheck verifyDependencyLocks verifyPublicPathSnapshot :app-bootstrap:verifyEnvKeys configContractCheck :app-bootstrap:integrationTest :sample-portfolio:integrationTest persistence-jpa jpaPlatformContractTest jpaPlatformMigrationTest --continue 통과(704 task) Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/notification-platform.yml | 3 +- docs/architecture/jpa-api-surface.txt | 49 +--- docs/capability-status.md | 21 ++ docs/notification/api-surface-snapshot.txt | 21 +- docs/notification/callback-reconciliation.md | 4 + docs/notification/configuration-reference.md | 4 +- docs/notification/module-mapping.md | 24 +- docs/notification/operations.md | 1 - .../W3-P23.md | 70 ++++++ .../2026-09-25-review-followup-status.md | 32 +-- .../plans/2026-09-25-review-followup.md | 2 +- .../outbound/notification/build.gradle | 16 ++ .../outbound/notification/gradle.lockfile | 32 ++- .../autoconfigure/AssembledProvider.java | 22 +- .../NotificationCallbackProviderConfig.java | 76 ++++-- .../NotificationPlatformCoreConfig.java | 15 -- .../NotificationPlatformProviderConfig.java | 34 +-- .../NotificationPlatformRegistriesConfig.java | 28 +-- .../NotificationPlatformSettings.java | 30 +-- .../NotificationProviderAssembly.java | 19 +- .../NotificationSesProviderConfig.java | 4 +- .../ProviderCallbackAssembler.java | 12 - .../SesProviderCallbackAssembler.java | 7 - .../SesProviderRuntimeAssembler.java | 15 +- .../MapProviderEventProjectorRegistry.java | 37 --- .../platform/dispatch/CredentialProbe.java | 9 - .../CredentialValidationException.java | 19 -- .../dispatch/MapTemplateRendererRegistry.java | 31 --- .../platform/dispatch/ProviderRuntime.java | 150 +++++++----- .../dispatch/ProviderRuntimeRotator.java | 69 ------ .../dispatch/RuntimeDrainCoordinator.java | 46 ---- .../{http => }/NotificationEndpoints.java | 2 +- .../platform/provider/ProviderResults.java | 25 +- .../http/JdkNotificationHttpGateway.java | 216 ------------------ .../http/NotificationHttpGateway.java | 20 -- .../http/NotificationHttpRequest.java | 64 ------ .../http/NotificationHttpResponse.java | 66 ------ .../NotificationHttpTransportException.java | 35 --- .../provider/ses/AwsSignatureV4Signer.java | 147 ------------ .../platform/provider/ses/SesClients.java | 57 +++++ .../provider/ses/SesDeliveryProjector.java | 18 -- .../provider/ses/SesFailureClassifier.java | 92 +++++++- .../ses/SesNotificationProviderAdapter.java | 101 ++++---- .../provider/ses/SesProviderProperties.java | 2 +- .../provider/ses/SesRequestMapper.java | 134 +++++------ .../smtp/SmtpNotificationProviderAdapter.java | 3 +- .../CanonicalNotificationRenderer.java | 18 +- .../ThymeleafNotificationRenderer.java | 50 ---- ...NotificationPayloadAtRestContractTest.java | 11 +- ...ficationPlatformCoreConfigurationTest.java | 3 - .../NotificationPlatformSettingsTest.java | 12 +- .../NotificationProviderAssemblyTest.java | 42 +--- .../NotificationSecretRequirementsTest.java | 2 +- .../NotificationSecretsValidationTest.java | 10 +- .../SesProviderRuntimeAssemblerTest.java | 5 - .../SmtpProviderRuntimeAssemblerTest.java | 3 +- .../SnsCertificateCacheTest.java | 13 +- .../dispatch/ProviderRuntimeRegistryTest.java | 60 +---- .../dispatch/ProviderRuntimeStateTest.java | 84 +++++++ .../{http => }/EndpointGuardCallSiteTest.java | 2 +- .../{http => }/EndpointRoutabilityTest.java | 2 +- ...dkNotificationHttpGatewaySecurityTest.java | 135 ----------- .../SesCommitmentClassificationTest.java} | 35 +-- .../SesNotificationProviderAdapterTest.java | 52 ++++- .../CanonicalNotificationRendererTest.java | 1 - ...rTest.java => ThymeleafRenderingTest.java} | 7 +- .../platform/testkit/ContractAdapters.java | 12 +- .../outbound/persistence-jpa/build.gradle | 18 +- .../PersistenceJpaAutoConfiguration.java | 2 - .../config/JpaAdapterComponentsConfig.java | 2 +- .../config/PersistenceJpaConfig.java | 32 ++- ...ficationBackgroundPassIntegrationTest.java | 36 +-- .../persistence/JpaModuleBoundaryTest.java | 4 - .../PersistenceJpaAutoConfigurationTest.java | 2 - .../PersistenceEntityScanCoverageTest.java | 77 ++----- .../AppliedMigrationImmutabilityTest.java | 35 ++- .../persistence-notification/build.gradle | 32 +++ .../persistence-notification/gradle.lockfile | 183 +++++++++++++++ .../NotificationJpaPersistenceConfig.java | 0 .../NotificationSchemaActivation.java | 0 .../NotificationSchemaStream.java | 0 .../NotificationJpaPersistenceFacade.java | 18 +- .../platform/AdminAuditEntity.java | 0 .../platform/AdminAuditJpaRepository.java | 0 .../AdminOperationResultPayloadCodec.java | 0 .../notification/platform/ConsentEntity.java | 0 .../platform/ConsentJpaRepository.java | 0 .../platform/ContactPointEntity.java | 0 .../platform/ContactPointJpaRepository.java | 0 .../platform/DeduplicationClaimEntity.java | 0 .../DeduplicationClaimJpaRepository.java | 0 .../platform/DeliveryAttemptEntity.java | 0 .../DeliveryAttemptJpaRepository.java | 0 .../JdbcNotificationServingState.java | 0 .../platform/JdbcReconciliationJobStore.java | 0 .../platform/JpaAdminOperationStore.java | 0 .../platform/JpaContactPointStore.java | 0 .../platform/JpaDeliveryAttemptStore.java | 0 .../platform/JpaNotificationRequestStore.java | 0 .../platform/JpaNotificationSideEffect.java} | 4 +- .../platform/JpaPolicyStores.java | 0 .../platform/JpaProviderEventLedger.java | 0 .../platform/JpaRecipientDeliveryStore.java | 0 .../platform/JpaRecipientLeaseStore.java | 0 .../platform/JpaSuppressionStore.java | 0 .../platform/JpaTemplateRegistry.java | 0 .../platform/NotificationRecordMapper.java | 0 .../platform/NotificationRequestEntity.java | 0 .../NotificationRequestJpaRepository.java | 0 .../platform/PreferenceEntity.java | 0 .../platform/PreferenceJpaRepository.java | 0 .../platform/ProviderEventEntity.java | 0 .../platform/ProviderEventJpaRepository.java | 0 .../platform/RecipientClaimSql.java | 0 .../platform/RecipientDeliveryEntity.java | 0 .../RecipientDeliveryJpaRepository.java | 0 .../platform/SuppressionEntity.java | 0 .../platform/SuppressionJpaRepository.java | 0 .../platform/TemplateVersionEntity.java | 0 .../TemplateVersionJpaRepository.java | 0 .../platform/TenantBoundRepositoryGuard.java | 0 .../inbox/InboxCommitEventPublisher.java | 0 .../platform/inbox/InboxItemEntity.java | 0 .../inbox/InboxItemJpaRepository.java | 0 .../inbox/InboxOutboxRecordFactory.java | 0 .../platform/inbox/JpaNotificationInbox.java | 0 ...ot.autoconfigure.AutoConfiguration.imports | 1 + .../V10__variables_payload_envelope_guard.sql | 0 .../V1__notification_platform_core.sql | 0 ...ation_platform_contact_template_policy.sql | 0 .../V3__notification_platform_inbox_admin.sql | 0 ...tion_platform_alignment_and_activation.sql | 0 .../V5__notification_recipient_expiry.sql | 0 .../V6__notification_projection_facts.sql | 0 .../V7__notification_collapse.sql | 0 .../V8__notification_admin_claim.sql | 0 .../V9__notification_evidence_certainty.sql | 0 ...NotificationPersistenceActivationTest.java | 76 ++++++ ...ficationSchemaActivationLifecycleTest.java | 0 .../AdminOperationResultPayloadCodecTest.java | 0 .../NotificationRepositoryDiscoveryTest.java | 0 .../NotificationRepositorySurfaceTest.java | 0 .../platform/RecipientClaimSqlTest.java | 0 .../platform/inbox/InboxItemEntityTest.java | 0 src/app-bootstrap/build.gradle | 2 +- src/app-bootstrap/gradle.lockfile | 2 + .../ProviderEventProjectionService.java | 20 +- .../callback/ProviderEventProjector.java | 7 +- .../ProviderEventProjectorRegistry.java | 11 - .../callback/StandardDeliveryProjector.java | 19 +- .../dispatch/DeliveryAttemptRecord.java | 80 +++++++ .../dispatch/DispatchOutcomeRecorder.java | 57 +---- .../dispatch/NotificationDispatchService.java | 209 ++++------------- .../NotificationSubmissionService.java | 16 -- .../dispatch/ProviderOutcomeClassifier.java | 59 +++++ .../dispatch/RecipientDeliveryRecord.java | 136 +++++++++++ .../dispatch/TemplateRendererRegistry.java | 11 - .../provider/ProviderCapabilities.java | 36 +++ .../NotificationTemplateRenderer.java | 14 +- .../callback/ProjectionMergeContractTest.java | 6 +- .../callback/ProviderEventLateMatchTest.java | 7 +- .../dispatch/DispatchOutcomeRecorderTest.java | 9 +- .../NotificationDispatchServiceTest.java | 65 +++--- .../dispatch/NotificationPlatformNoops.java | 3 +- .../NotificationSubmissionServiceTest.java | 57 +++-- .../ProviderOutcomeClassifierTest.java | 65 ++++++ .../provider/ProviderSpiContractTest.java | 42 ++++ .../notification-platform/README.md | 13 +- .../notification-platform/build.gradle | 6 + .../notification-platform/gradle.lockfile | 75 +++++- .../NotificationDeliveryConfiguration.java | 12 +- src/config/architecture/modules.json | 12 +- 172 files changed, 1865 insertions(+), 2151 deletions(-) create mode 100644 docs/reviews/2026-09-25-review-followup-results/W3-P23.md delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/MapProviderEventProjectorRegistry.java delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/CredentialProbe.java delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/CredentialValidationException.java delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/MapTemplateRendererRegistry.java delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRotator.java delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/RuntimeDrainCoordinator.java rename src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/{http => }/NotificationEndpoints.java (99%) delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/JdkNotificationHttpGateway.java delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpGateway.java delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpRequest.java delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpResponse.java delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpTransportException.java delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/AwsSignatureV4Signer.java create mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesClients.java delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesDeliveryProjector.java delete mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/ThymeleafNotificationRenderer.java rename src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/{http => }/EndpointGuardCallSiteTest.java (99%) rename src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/{http => }/EndpointRoutabilityTest.java (99%) delete mode 100644 src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/JdkNotificationHttpGatewaySecurityTest.java rename src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/{http/HttpCommitmentClassificationTest.java => ses/SesCommitmentClassificationTest.java} (82%) rename src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/template/{ThymeleafNotificationRendererTest.java => ThymeleafRenderingTest.java} (97%) create mode 100644 src/adapter/outbound/persistence-notification/build.gradle create mode 100644 src/adapter/outbound/persistence-notification/gradle.lockfile rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaPersistenceConfig.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationSchemaActivation.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationSchemaStream.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java (94%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditEntity.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditJpaRepository.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodec.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentEntity.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentJpaRepository.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointEntity.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointJpaRepository.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimEntity.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimJpaRepository.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptEntity.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptJpaRepository.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcNotificationServingState.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcReconciliationJobStore.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaAdminOperationStore.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaContactPointStore.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaDeliveryAttemptStore.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationRequestStore.java (100%) rename src/adapter/outbound/{persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationSideEffectStore.java => persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationSideEffect.java} (96%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaPolicyStores.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaProviderEventLedger.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientDeliveryStore.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientLeaseStore.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaSuppressionStore.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaTemplateRegistry.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRecordMapper.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestEntity.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestJpaRepository.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceEntity.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceJpaRepository.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventEntity.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventJpaRepository.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSql.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryEntity.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryJpaRepository.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionEntity.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionJpaRepository.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionEntity.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionJpaRepository.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TenantBoundRepositoryGuard.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxCommitEventPublisher.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntity.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemJpaRepository.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxOutboxRecordFactory.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/JpaNotificationInbox.java (100%) create mode 100644 src/adapter/outbound/persistence-notification/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/resources/db/migration/jpa/notification-platform/V10__variables_payload_envelope_guard.sql (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/resources/db/migration/jpa/notification-platform/V1__notification_platform_core.sql (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/resources/db/migration/jpa/notification-platform/V2__notification_platform_contact_template_policy.sql (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/resources/db/migration/jpa/notification-platform/V3__notification_platform_inbox_admin.sql (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/resources/db/migration/jpa/notification-platform/V4__notification_platform_alignment_and_activation.sql (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/resources/db/migration/jpa/notification-platform/V5__notification_recipient_expiry.sql (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/resources/db/migration/jpa/notification-platform/V6__notification_projection_facts.sql (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/resources/db/migration/jpa/notification-platform/V7__notification_collapse.sql (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/resources/db/migration/jpa/notification-platform/V8__notification_admin_claim.sql (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/main/resources/db/migration/jpa/notification-platform/V9__notification_evidence_certainty.sql (100%) create mode 100644 src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationPersistenceActivationTest.java rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationSchemaActivationLifecycleTest.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodecTest.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositoryDiscoveryTest.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositorySurfaceTest.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSqlTest.java (100%) rename src/adapter/outbound/{persistence-jpa => persistence-notification}/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntityTest.java (100%) delete mode 100644 src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjectorRegistry.java create mode 100644 src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ProviderOutcomeClassifier.java delete mode 100644 src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/TemplateRendererRegistry.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/ProviderOutcomeClassifierTest.java diff --git a/.github/workflows/notification-platform.yml b/.github/workflows/notification-platform.yml index 85f682a0..127c10b2 100644 --- a/.github/workflows/notification-platform.yml +++ b/.github/workflows/notification-platform.yml @@ -20,8 +20,9 @@ on: # assembles, binds and migrates at all. - 'src/application-core/src/**/notification/**' - 'src/adapter/outbound/notification/**' + - 'src/adapter/outbound/persistence-notification/**' + # The notification real-PostgreSQL qualifications still run in the JPA leaf's lane. - 'src/adapter/outbound/persistence-jpa/src/**/notification/**' - - 'src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/**' - 'src/adapter/inbound/web-notification/**' - 'src/composition/notification-platform/**' - 'src/app-bootstrap/src/main/resources/application*.yml' diff --git a/docs/architecture/jpa-api-surface.txt b/docs/architecture/jpa-api-surface.txt index a1ccd83c..c02213ed 100644 --- a/docs/architecture/jpa-api-surface.txt +++ b/docs/architecture/jpa-api-surface.txt @@ -5,7 +5,7 @@ # root yet. # Update only after review with: # ./gradlew :adapter:outbound:persistence-jpa:updateJpaApiSurface -PapproveJpaApiSurfaceChange -# types: 214 +# types: 167 dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName dev.caskeleton.adapter.outbound.persistence.api.capability.CapabilitySupport dev.caskeleton.adapter.outbound.persistence.api.capability.JpaCapability @@ -112,53 +112,6 @@ dev.caskeleton.adapter.outbound.persistence.lock.LockRegistryDistributedLockAdap dev.caskeleton.adapter.outbound.persistence.lock.LockSettings dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy dev.caskeleton.adapter.outbound.persistence.migration.SchemaManagementMode -dev.caskeleton.adapter.outbound.persistence.notification.NotificationJpaPersistenceConfig -dev.caskeleton.adapter.outbound.persistence.notification.NotificationSchemaActivation -dev.caskeleton.adapter.outbound.persistence.notification.NotificationSchemaStream -dev.caskeleton.adapter.outbound.persistence.notification.configuration.NotificationJpaPersistenceFacade -dev.caskeleton.adapter.outbound.persistence.notification.platform.AdminAuditEntity -dev.caskeleton.adapter.outbound.persistence.notification.platform.AdminAuditJpaRepository -dev.caskeleton.adapter.outbound.persistence.notification.platform.ConsentEntity -dev.caskeleton.adapter.outbound.persistence.notification.platform.ConsentJpaRepository -dev.caskeleton.adapter.outbound.persistence.notification.platform.ContactPointEntity -dev.caskeleton.adapter.outbound.persistence.notification.platform.ContactPointJpaRepository -dev.caskeleton.adapter.outbound.persistence.notification.platform.DeduplicationClaimEntity -dev.caskeleton.adapter.outbound.persistence.notification.platform.DeduplicationClaimJpaRepository -dev.caskeleton.adapter.outbound.persistence.notification.platform.DeliveryAttemptEntity -dev.caskeleton.adapter.outbound.persistence.notification.platform.DeliveryAttemptJpaRepository -dev.caskeleton.adapter.outbound.persistence.notification.platform.JdbcNotificationServingState -dev.caskeleton.adapter.outbound.persistence.notification.platform.JdbcReconciliationJobStore -dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaAdminOperationStore -dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaContactPointStore -dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaDeliveryAttemptStore -dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationRequestStore -dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationSideEffectStore -dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaPolicyStores -dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaProviderEventLedger -dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientDeliveryStore -dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientLeaseStore -dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaSuppressionStore -dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaTemplateRegistry -dev.caskeleton.adapter.outbound.persistence.notification.platform.NotificationRecordMapper -dev.caskeleton.adapter.outbound.persistence.notification.platform.NotificationRequestEntity -dev.caskeleton.adapter.outbound.persistence.notification.platform.NotificationRequestJpaRepository -dev.caskeleton.adapter.outbound.persistence.notification.platform.PreferenceEntity -dev.caskeleton.adapter.outbound.persistence.notification.platform.PreferenceJpaRepository -dev.caskeleton.adapter.outbound.persistence.notification.platform.ProviderEventEntity -dev.caskeleton.adapter.outbound.persistence.notification.platform.ProviderEventJpaRepository -dev.caskeleton.adapter.outbound.persistence.notification.platform.RecipientClaimSql -dev.caskeleton.adapter.outbound.persistence.notification.platform.RecipientDeliveryEntity -dev.caskeleton.adapter.outbound.persistence.notification.platform.RecipientDeliveryJpaRepository -dev.caskeleton.adapter.outbound.persistence.notification.platform.SuppressionEntity -dev.caskeleton.adapter.outbound.persistence.notification.platform.SuppressionJpaRepository -dev.caskeleton.adapter.outbound.persistence.notification.platform.TemplateVersionEntity -dev.caskeleton.adapter.outbound.persistence.notification.platform.TemplateVersionJpaRepository -dev.caskeleton.adapter.outbound.persistence.notification.platform.TenantBoundRepositoryGuard -dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.InboxCommitEventPublisher -dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.InboxItemEntity -dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.InboxItemJpaRepository -dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.InboxOutboxRecordFactory -dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.JpaNotificationInbox dev.caskeleton.adapter.outbound.persistence.observation.JpaMetricTags dev.caskeleton.adapter.outbound.persistence.observation.LowCardinality dev.caskeleton.adapter.outbound.persistence.observation.MicrometerQueryObservation diff --git a/docs/capability-status.md b/docs/capability-status.md index 7f662bea..3656c0b2 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -446,3 +446,24 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap | application-core 테스트 `malformedReportData` | `src/application-core/src/test/java/dev/caskeleton/application/outbox/` (relay 테스트) | `6d27356e` | blank aggregate id를 가진 claim이 canonical 모델에서 만들어질 수 없음 | | `EventJson`(sample 이벤트 JSON 문자열 조립, P15에서 신설) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/EventJson.java` | `25de288a` | P18 통합: sample 발행기가 canonical `PortfolioEventOutbox` + encoder로 옮겨 호출자 0 | | `DomainContextSettings`(`ca-skeleton.domain-context.strategy`, P18이 service-runtime으로 옮긴 사본) | `src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/context/DomainContextSettings.java` | `e1dafd00`(P18 worktree) | P18 통합: P25 A-10c가 전략 선택 설정을 없앰 — `DomainContextConfig`가 `ThreadLocalDomainContextPropagator`를 직접 만든다 | +| `ProviderRuntimeRotator` | `src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRotator.java` | `0ed7bc8d` | S4-#3c: main 참조 0, production 입력 없는 회전 경로 | +| `RuntimeDrainCoordinator` | `.../notification/platform/dispatch/RuntimeDrainCoordinator.java` | `0ed7bc8d` | S4-#3c: rotator만 사용 | +| `CredentialProbe` | `.../notification/platform/dispatch/CredentialProbe.java` | `0ed7bc8d` | S4-#3c: 구현체 0, rotator만 사용 | +| `CredentialValidationException` | `.../notification/platform/dispatch/CredentialValidationException.java` | `0ed7bc8d` | S4-#3c: rotator만 던짐 | +| `NotificationSubmissionService.submit/schedule/accept` | `src/application-notification/.../platform/dispatch/NotificationSubmissionService.java` | `0ed7bc8d` | S1-#10b: main 호출자 0, use case와 3벌 중복 | +| `NotificationPlatformSettings.Provider` 8-인자 생성자 | `.../notification/platform/autoconfigure/NotificationPlatformSettings.java` | `0ed7bc8d` | S4-#15: 테스트 호환용 오버로드 | +| `TemplateRendererRegistry` | `src/application-notification/.../platform/dispatch/TemplateRendererRegistry.java` | `ce863643` | S1-#9: 모든 channel에 같은 renderer | +| `MapTemplateRendererRegistry` | `.../notification/platform/dispatch/MapTemplateRendererRegistry.java` | `ce863643` | S1-#9 | +| `ThymeleafNotificationRenderer` | `.../notification/platform/template/ThymeleafNotificationRenderer.java` | `ce863643` | S1-#9: `CanonicalNotificationRenderer` 위임 래퍼뿐 | +| `ProviderEventProjectorRegistry` | `src/application-notification/.../platform/callback/ProviderEventProjectorRegistry.java` | `ce863643` | S1-#9: 모든 provider에 같은 projector | +| `MapProviderEventProjectorRegistry` | `.../notification/platform/callback/MapProviderEventProjectorRegistry.java` | `ce863643` | S1-#9 | +| `SesDeliveryProjector` | `.../notification/platform/provider/ses/SesDeliveryProjector.java` | `ce863643` | S1-#9: `StandardDeliveryProjector` 상속만 | +| `ProviderCallbackAssembler.projector()`, `AssembledProvider.projector`, `AssembledPlatform.projectors`, `NO_PROJECTOR` 분기 | `.../notification/platform/autoconfigure/*`, `ProviderEventProjectionService.java` | `ce863643` | S1-#9: 슬롯이 늘 같은 규칙을 가리킴 | +| `ProviderRuntime.moveTo`와 `mark*`별 조건 | `.../notification/platform/dispatch/ProviderRuntime.java` | `ce863643` | S4-#14b: 전이표 하나로 대체 | +| `JdkNotificationHttpGateway` | `.../notification/platform/provider/http/JdkNotificationHttpGateway.java` | `bff135d6` | S4-lead-3(결정 17): AWS SDK sesv2로 교체 | +| `NotificationHttpGateway`·`NotificationHttpRequest`·`NotificationHttpResponse`·`NotificationHttpTransportException` | `.../notification/platform/provider/http/` | `bff135d6` | S4-lead-3 | +| `AwsSignatureV4Signer` | `.../notification/platform/provider/ses/AwsSignatureV4Signer.java` | `bff135d6` | S4-lead-3: SDK가 서명 | +| `notificationHttpGateway` bean | `.../notification/platform/autoconfigure/NotificationPlatformCoreConfig.java` | `bff135d6` | S4-lead-3 | +| `JdkNotificationHttpGatewaySecurityTest` | `.../test/.../provider/http/JdkNotificationHttpGatewaySecurityTest.java` | `bff135d6` | 대상 gateway 삭제 | +| `PersistenceJpaConfig.OPT_IN_NOTIFICATION_PACKAGE`, coverage 테스트 opt-in 표 | `src/adapter/outbound/persistence-jpa/.../config/PersistenceJpaConfig.java`, `PersistenceEntityScanCoverageTest.java` | `90fcc8ba` | S2-#1b: 알림 패키지가 leaf 밖으로 | +| `PostgreSqlNotificationBackgroundPassIntegrationTest.replayMarksAnEventWithNoProjectorFailed` | `src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/.../readiness/` | `ce863643` | S1-#9: `NO_PROJECTOR` 분기 삭제 | diff --git a/docs/notification/api-surface-snapshot.txt b/docs/notification/api-surface-snapshot.txt index 0aa046fa..3c45b144 100644 --- a/docs/notification/api-surface-snapshot.txt +++ b/docs/notification/api-surface-snapshot.txt @@ -2,7 +2,7 @@ # Every top-level public type under the platform packages. Growth is a reviewed change. # Update only after review with: # ./gradlew :adapter:outbound:notification:updateNotificationApiSurface -PapproveNotificationApiSurfaceChange -# types: 380 +# types: 365 dev.caskeleton.adapter.outbound.notification.NotificationConfig dev.caskeleton.adapter.outbound.notification.NotificationRoutesSettings dev.caskeleton.adapter.outbound.notification.core.FailOpenNotificationProvider @@ -25,7 +25,6 @@ dev.caskeleton.adapter.outbound.notification.platform.autoconfigure.SmtpProvider dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackLimits dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationResult dev.caskeleton.adapter.outbound.notification.platform.callback.MapProviderCallbackAdapterRegistry -dev.caskeleton.adapter.outbound.notification.platform.callback.MapProviderEventProjectorRegistry dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapter dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapterRegistry dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackVerificationRequest @@ -33,11 +32,8 @@ dev.caskeleton.adapter.outbound.notification.platform.callback.VerifiedCallback dev.caskeleton.adapter.outbound.notification.platform.dispatch.AttemptPermit dev.caskeleton.adapter.outbound.notification.platform.dispatch.CapabilityReconciliationGateway dev.caskeleton.adapter.outbound.notification.platform.dispatch.ConfiguredProfileCatalog -dev.caskeleton.adapter.outbound.notification.platform.dispatch.CredentialProbe -dev.caskeleton.adapter.outbound.notification.platform.dispatch.CredentialValidationException dev.caskeleton.adapter.outbound.notification.platform.dispatch.JacksonRoutingPlanCodec dev.caskeleton.adapter.outbound.notification.platform.dispatch.LoggingInboxSignalPublisher -dev.caskeleton.adapter.outbound.notification.platform.dispatch.MapTemplateRendererRegistry dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationBackgroundWorkers dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationDispatchProperties dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationSchedulerWorker @@ -45,11 +41,9 @@ dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderAttemptLi 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.ProviderRuntimeRotator 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.RuntimeDrainCoordinator dev.caskeleton.adapter.outbound.notification.platform.dispatch.SingleTenantContext dev.caskeleton.adapter.outbound.notification.platform.dispatch.UuidV7Generator dev.caskeleton.adapter.outbound.notification.platform.observation.LoggingNotificationAudit @@ -60,17 +54,11 @@ dev.caskeleton.adapter.outbound.notification.platform.observation.NotificationHe dev.caskeleton.adapter.outbound.notification.platform.observation.NotificationServingThresholds dev.caskeleton.adapter.outbound.notification.platform.provider.EmailAttachments dev.caskeleton.adapter.outbound.notification.platform.provider.EmailRecipients +dev.caskeleton.adapter.outbound.notification.platform.provider.NotificationEndpoints dev.caskeleton.adapter.outbound.notification.platform.provider.ProviderResults dev.caskeleton.adapter.outbound.notification.platform.provider.UnconfiguredAttachmentResolver -dev.caskeleton.adapter.outbound.notification.platform.provider.http.JdkNotificationHttpGateway -dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationEndpoints -dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpGateway -dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpRequest -dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpResponse -dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpTransportException -dev.caskeleton.adapter.outbound.notification.platform.provider.ses.AwsSignatureV4Signer dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesCallbackAdapter -dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesDeliveryProjector +dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesClients dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesEventNormalizer dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesFailureClassifier dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesNotificationProviderAdapter @@ -104,7 +92,6 @@ dev.caskeleton.adapter.outbound.notification.platform.template.PlaceholderTempla dev.caskeleton.adapter.outbound.notification.platform.template.Sha256MessageDigestAdapter dev.caskeleton.adapter.outbound.notification.platform.template.TemplateSlotMode dev.caskeleton.adapter.outbound.notification.platform.template.TemplateSlotPolicy -dev.caskeleton.adapter.outbound.notification.platform.template.ThymeleafNotificationRenderer dev.caskeleton.adapter.outbound.notification.platform.template.ThymeleafStringTemplateEngine dev.caskeleton.adapter.outbound.notification.slack.webhook.SlackClient dev.caskeleton.adapter.outbound.notification.slack.webhook.SlackNotificationAdapterConfig @@ -210,7 +197,6 @@ dev.caskeleton.application.notification.platform.callback.ProjectionStatus dev.caskeleton.application.notification.platform.callback.ProviderEventLedger dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService dev.caskeleton.application.notification.platform.callback.ProviderEventProjector -dev.caskeleton.application.notification.platform.callback.ProviderEventProjectorRegistry dev.caskeleton.application.notification.platform.callback.ProviderEventRecord dev.caskeleton.application.notification.platform.callback.ProviderEventRecordId dev.caskeleton.application.notification.platform.callback.ProviderEventSource @@ -274,7 +260,6 @@ dev.caskeleton.application.notification.platform.dispatch.RequestFingerprint dev.caskeleton.application.notification.platform.dispatch.ScheduleNotificationApplicationUseCase dev.caskeleton.application.notification.platform.dispatch.SubmitNotificationApplicationUseCase dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint -dev.caskeleton.application.notification.platform.dispatch.TemplateRendererRegistry dev.caskeleton.application.notification.platform.dispatch.TenantContextPort dev.caskeleton.application.notification.platform.inbox.CreateInboxItemCommand dev.caskeleton.application.notification.platform.inbox.InboxContentCodecPort diff --git a/docs/notification/callback-reconciliation.md b/docs/notification/callback-reconciliation.md index 46a9db58..23e0dc36 100644 --- a/docs/notification/callback-reconciliation.md +++ b/docs/notification/callback-reconciliation.md @@ -50,3 +50,7 @@ writes projections directly. Where a provider has no status-query capability, the platform records `Unsupported` and leaves the attempt ambiguous. It does not infer a final status. + +The shipped families, SES and SMTP, have no reconciliation: their assemblers contribute no +`ReconciliationCapability`, so every reconciliation job for them ends `Unsupported`. The slot on +`AssembledProvider` is for a provider family an adopter assembles with a status query of its own. diff --git a/docs/notification/configuration-reference.md b/docs/notification/configuration-reference.md index b3cecee2..e8643617 100644 --- a/docs/notification/configuration-reference.md +++ b/docs/notification/configuration-reference.md @@ -84,8 +84,8 @@ An enabled SES profile adds a typed `ses` block: | Field | Meaning | |---|---| -| `ses.endpoint` | SES API base URI; the mapper appends `/v2/email/outbound-emails` | -| `ses.region` | SigV4 region | +| `ses.endpoint` | SES API base URI, used as the AWS SDK client's endpoint override | +| `ses.region` | AWS region the SDK signs for | | `ses.sender-identity` | verified SES From identity | | `ses.access-key-id` | AWS access key id; identifier only, not secret material | | `ses.configuration-set` | optional SES configuration-set name | diff --git a/docs/notification/module-mapping.md b/docs/notification/module-mapping.md index ad52520c..b6276e46 100644 --- a/docs/notification/module-mapping.md +++ b/docs/notification/module-mapping.md @@ -42,8 +42,8 @@ that owns its responsibility. No public contract, evidence rule, or reliability | `notification-observability` (Micrometer impl) | `adapter:outbound:notification` | `…platform.observation` | | `notification-admin-runtime` | `adapter:outbound:notification` | `…platform.admin` | | `notification-spring-boot-starter` | `adapter:outbound:notification` | `…platform.autoconfigure` | -| `notification-persistence-jpa` | `adapter:outbound:persistence-jpa` | `dev.caskeleton.adapter.outbound.persistence.notification.platform` | -| `notification-inbox-jpa` | `adapter:outbound:persistence-jpa` | `…persistence.notification.platform.inbox` | +| `notification-persistence-jpa` | `adapter:outbound:persistence-notification` | `dev.caskeleton.adapter.outbound.persistence.notification.platform` | +| `notification-inbox-jpa` | `adapter:outbound:persistence-notification` | `…persistence.notification.platform.inbox` | | `notification-callback-mvc` | `adapter:inbound:web-notification` | `dev.caskeleton.adapter.inbound.web.notification.platform.callback` | | `notification-submission-mvc` | `adapter:inbound:web-notification` | `dev.caskeleton.adapter.inbound.web.notification.platform.submission` | | application composition (use cases, callback bridge, `config/module-defaults/notification.yml`) | `composition:notification-platform` | `dev.caskeleton.composition.notification` | @@ -57,9 +57,9 @@ by the leaf DAG that the registry already enforces: ```text application-core (all *-api, provider SPI, policy, callback contracts) ↑ ↑ ↑ -adapter:outbound:notification adapter:outbound:persistence-jpa adapter:inbound:web-notification - ↑ ↑ (→ adapter:inbound:web) - └──────────── composition:notification-platform ────┘ +adapter:outbound:notification adapter:outbound:persistence-notification adapter:inbound:web-notification + ↑ ↑ (runtimeOnly, with persistence-jpa) ↑ (→ adapter:inbound:web) + └──────────── composition:notification-platform ───────────────────────┘ ↑ app-bootstrap (one line) ``` @@ -68,14 +68,14 @@ Two plan edges cannot be expressed as project edges in this repository, and are 1. `notification-email-ses` → `httpclient platform`. (The Twilio, FCM, APNs, Web Push and Webhook adapters that shared this edge were removed: none had an assembler.) - `adapter-outbound-notification` is not allowed to depend on `adapter-outbound-httpclient`. - The provider adapters therefore call - `dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpGateway`, - an adapter-local port with a JDK `java.net.http.HttpClient` default implementation. - `app-bootstrap` sees both leaves and is the supported place to substitute an implementation backed - by the HTTP Client Platform (TLS/timeout/circuit-breaker/SSRF/dynamic-target policy reuse). + `adapter-outbound-notification` is not allowed to depend on `adapter-outbound-httpclient`, and + SES no longer needs it: the SES adapter sends through the AWS SDK v2 `sesv2` client (owner + decision 17), which signs requests itself. The adapter-local JDK HTTP gateway and SigV4 signer + were deleted with that change. The client is built per profile with SDK retries off, no default + credential chain (each request carries its profile's credential) and the profile's endpoint, + which still passes the notification routability guard. 2. `notification-inbox-jpa` → `optional messaging outbox integration`. - `adapter-outbound-persistence-jpa` may not depend on `adapter-outbound-messaging`; the inbox + `adapter-outbound-persistence-notification` may not depend on `adapter-outbound-messaging`; the inbox publishes through the existing persistence outbox tables plus the `NotificationInboxSignalPort` application port, and `app-bootstrap` binds the relay. diff --git a/docs/notification/operations.md b/docs/notification/operations.md index c817c9d2..dc47f3ff 100644 --- a/docs/notification/operations.md +++ b/docs/notification/operations.md @@ -24,7 +24,6 @@ something to ask about). | Retry budget per provider profile | A provider outage turning every queued notification into its own retry loop | | Ambiguous attempts block automatic fallback | A push whose response was lost arriving alongside the "just in case" SMS | | Permits released during backoff | A slow provider pinning the whole concurrency budget on work that is only waiting | -| Bounded drain on rotation | A provider that never answers holding a credential rotation open forever | | Fail-fast intake on capacity | An unbounded in-memory queue absorbing a burst it cannot survive | ## Scheduling diff --git a/docs/reviews/2026-09-25-review-followup-results/W3-P23.md b/docs/reviews/2026-09-25-review-followup-results/W3-P23.md new file mode 100644 index 00000000..c1ca02d2 --- /dev/null +++ b/docs/reviews/2026-09-25-review-followup-results/W3-P23.md @@ -0,0 +1,70 @@ +# W3-P23 — Wave 3 notification + +worktree: `/home/donghyeon/workspace/chat-gpt-container/codebase/clean-architecture-backend-template/.claude/worktrees/agent-ad4733015ca936d70`, 브랜치 `worktree-agent-ad4733015ca936d70` (base `0ed7bc8d`) + +커밋: +- `ce863643` review-followup P23 D: 알림 회전 경로·제출 서비스 진입점·Provider 짧은 생성자 삭제 +- `bff135d6` review-followup P23 W1: 알림 레지스트리 삭제·전이표·capability factory·dispatch 전이 메서드 +- `90fcc8ba` review-followup P23 W1: SES를 AWS SDK v2 sesv2로 교체, 자체 JDK gateway·SigV4 서명기 삭제 +- `fd59ef14` review-followup P23 W2: notification persistence를 adapter:outbound:persistence-notification leaf로 추출 + +추가한 Flyway migration 버전: 없음(기존 notification V1–V10을 바이트 그대로 이동만 함). + +## 행 결과 +| ID | 결과 | 근거 | +|---|---|---| +| S1-#4 | 완료 | 구조 변경(결함 아님, 기존 동작 테스트로 회귀 확인). record 재조립 4곳을 전이 메서드로: `application-notification/.../dispatch/DeliveryAttemptRecord.java:97`(`completed`)·`:135`(`closedBeforeSubmission`), `RecipientDeliveryRecord.java:73`(`advancedRoute`)·`:113`(`failedBeforeAttempt`)·`:156`(`afterAttempt`)·`:194`(`terminalStateFor`, 종료 상태 계산 1곳). catch 3분기는 `ProviderOutcomeClassifier.java:31`(`fromException`), 호출은 `NotificationDispatchService.java:332`. `DispatchOutcomeRecorder`는 `attempt.completed`·`current.afterAttempt` 두 줄. 새 테스트 `ProviderOutcomeClassifierTest`(3건) PASS, `NotificationDispatchServiceTest`·`DispatchOutcomeRecorderTest` 그대로 PASS. 남은 점: 생성자 인자는 여전히 15개(`NotificationDispatchService.java:82`, registry→renderer로 바뀐 것뿐). 인자는 모두 실제 포트·정책이라 수정 방향에 없는 묶음 record를 새로 만들지 않았다 | +| S1-#9 | 완료 | `TemplateRendererRegistry`·`MapTemplateRendererRegistry`·`ThymeleafNotificationRenderer`, `ProviderEventProjectorRegistry`·`MapProviderEventProjectorRegistry`·`SesDeliveryProjector` 삭제(`bff135d6`). renderer 하나(`CanonicalNotificationRenderer`, channel은 `RenderCommand`에서; `NotificationPlatformProviderConfig.java:53`)와 projector 하나(`StandardDeliveryProjector`; `NotificationPlatformRegistriesConfig.java:38`)를 직접 주입. `ProviderEventProjector.providerId()`·`NotificationTemplateRenderer.channel()`, `AssembledProvider`/`AssembledPlatform`의 projector 슬롯, `ProviderCallbackAssembler.projector()`, `NO_PROJECTOR` 분기 삭제. 테스트 `NotificationProviderAssemblyTest.anSesHardBounceIsProjectedByTheSharedProjector` PASS. PG 테스트 `PostgreSqlNotificationBackgroundPassIntegrationTest.replayMarksAnEventWithNoProjectorFailed`는 그 분기가 없어져 삭제 | +| S1-#10b | 완료 | `NotificationSubmissionService`의 `submit`/`schedule`/private `accept` 삭제(`ce863643`). 테스트는 `SubmitNotificationApplicationUseCase`/`ScheduleNotificationApplicationUseCase`로 호출(`NotificationSubmissionServiceTest`, `NotificationDispatchServiceTest`). 수정 방향의 "두 use case가 private 헬퍼 1개 공유"는 하지 않음: ArchUnit 규칙 `useCaseCapabilityMatchesTransactionPortBoundary`(`ArchitectureViolationFixtureTest.java:272`)가 WRITE_REPOSITORY use case마다 `TransactionPort.inWrite`를 직접 호출하길 요구하므로 공유 헬퍼로 빼면 규칙 위반. 3벌→2벌(각 3줄) | +| S2-#1b | 완료 | 새 leaf `src/adapter/outbound/persistence-notification`(`fd59ef14`): `persistence/notification/**` main 50개·단위 테스트 6개·`db/migration/jpa/notification-platform/V1–V10` `git mv`(바이트·classpath 위치 동일 → Flyway version·checksum 동일). `modules.json`에 leaf 추가(allowed: application-core, application-notification), persistence-jpa의 `application-notification` edge 삭제, composition-notification-platform에 persistence-notification·persistence-jpa edge 추가(`runtimeOnly`, NEW-11 방식). facade는 이 leaf의 `@AutoConfiguration`(JPA 루트보다 먼저, `NotificationJpaPersistenceFacade.java:92`). `OPT_IN_NOTIFICATION_PACKAGE`·coverage 테스트의 opt-in 표·`JpaModuleBoundaryTest` notification 행 삭제. `AppliedMigrationImmutabilityTest`가 새 위치도 읽고 pin은 그대로(`applied-migrations.sha256` 변경 없음). 새 테스트 `NotificationPersistenceActivationTest`(2건) PASS. PG 테스트는 fileserver 선례대로 persistence-jpa `postgresqlIntegrationTest`에 test-scope edge로 남김(readiness card·evidence manifest 경로 유지). 수정 방향의 "목록 2개 삭제"는 하지 않음: 두 capability leaf가 `dev.caskeleton.adapter.outbound.persistence.*` 패키지 아래에 있어, 루트를 스캔하면 다른 jar의 entity까지 들어가 `ddl-auto=validate`가 다시 깨진다. 대신 `PersistenceJpaConfig.ROOT_PACKAGE`와 `PersistenceEntityScanCoverageTest.theRootIsNeverScanned`로 고정 | +| S2-#6c | 완료 | 추출 뒤 persistence-jpa 안의 `capability_schema_registry` 확인 SQL은 `PostgreSqlOwnerSafeIdempotencyStore.java:66` 하나뿐. notification 사본(`persistence-notification/.../NotificationSchemaActivation.java:29`)은 fileserver와 같은 처지(jpa edge 없는 capability leaf)가 되어 행의 "fileserver는 자기 사본 유지" 규칙을 그대로 따름. 두 capability의 공용화(support로)는 P18(idempotency 이동)·P24(fileserver)와 겹쳐 이번에 하지 않음 | +| S2-#8a | 남음 | 이유: 알림은 이미 feature config의 명시적 `@Bean` 한 방식(`NotificationJpaPersistenceFacade`, 이번에 이 leaf의 auto-configuration root로). 남은 대상 — `JpaAdapterComponentsConfig`의 stereotype 스캔(outbox·idempotency·lock 등), `persistence-fileserver`의 `@ComponentScan`+클래스별 `@ConditionalOnProperty`, Mongo — 은 동시에 도는 P18(outbox·멱등성 패키지 이동)·P24(fileserver)가 같은 파일을 옮기고 있어 충돌을 피해 손대지 않음. 통합 뒤 한 묶음으로 | +| S2-#13b | 남음 | 알림 부분만 완료: `JpaNotificationSideEffectStore` → `JpaNotificationSideEffect`(`NotificationSideEffectPort`), 나머지 알림 구현은 이미 ``(`JdbcReconciliationJobStore` 포함). 이유: 행에 열거된 나머지(`OutboxStoreAdapter`, `CanonicalOutboxAppendAdapter`, `PostgreSqlOwnerSafeIdempotencyStore` — P18, `JpaFileQuotaService` — P24, `SpringTransactionPort`·`LockRegistryDistributedLockAdapter` — core)는 다른 묶음 소유이고 S1-#18b와 함께 기계적 개명으로 해야 함 | +| S4-#3c | 완료 | `ProviderRuntimeRotator`·`RuntimeDrainCoordinator`·`CredentialProbe`·`CredentialValidationException` 삭제(`ce863643`). reconciliation 슬롯은 남김: `NotificationPlatformProviderConfig`의 `reconciliationGateway`는 이미 `platform.reconciliations()`를 받으므로(행 근거의 "항상 빈 reconciliations"는 현재 코드와 다름) adopter가 조립한 status-query family에는 production 입력이 있다. `docs/notification/callback-reconciliation.md`에 "SES/SMTP는 reconciliation 없음" 추가, `AssembledProvider` javadoc에도. `operations.md`의 "Bounded drain on rotation" 행 삭제. `ProviderRuntimeRegistryTest`의 rotator 테스트 3건 삭제·1건은 `registry.replace`로 | +| S4-#4b | 완료 | `ProviderCapabilities.dispatchOnly(maxPayloadBytes, maxTtl)`(`ProviderCapabilities.java:52`)와 `withStatusCallback()`. main의 `new ProviderCapabilities(` 0곳(SMTP·SES 모두 factory). 새 테스트 `ProviderSpiContractTest.aDispatchOnlyProviderClaimsNothingAndAddsTheCallbackByName` PASS | +| S4-#9 | 완료 | HTTP provider가 SES 하나이고 이제 SDK client를 씀(`90fcc8ba`). 공통 send 템플릿·`provider/http` 패키지 자체가 삭제됨. `ProviderResults`는 SES 분류기만 쓰는 상태·전송 분류 함수로 남음 | +| S4-#14b | 완료 | `ProviderRuntime.java:223`(`Transition` enum) + `:240`(`EnumMap` 표 `SOURCES`) + `:271`(`apply` 하나). 7개 `mark*`/`resumeHealthy`는 한 줄씩. 표는 target 상태가 아니라 전이로 키를 잡음: HEALTHY로 가는 길이 둘(성공 신호=THROTTLED·DEGRADED에서만, 운영자 resume=AUTH_FAILED 외 전부)이라 `EnumMap>` 하나로는 표현 불가. 새 테스트 `ProviderRuntimeStateTest.everyTransitionFromEveryStateEndsWhereTheTableSays`(6상태×7전이, 반환값까지) PASS, 기존 상태 테스트 PASS. 동작 차이 하나: 이미 AUTH_FAILED인 runtime에 인증 실패가 또 오면 전에는 reason을 덮어썼고 이제는 처음 reason을 유지 | +| S4-#15 | 완료 | 미조립 provider 필드·문자열 분기는 Wave 1(P3)에서 이미 삭제됨(`resolved == ProviderType.SES` enum 비교). 남은 테스트 호환용 8-인자 `Provider` 오버로드 삭제(`ce863643`), 레코드 생성자 하나(`NotificationPlatformSettings.java:211`, `:229`) | +| S4-lead-3 | 완료 | 소유자 결정 17. `SesNotificationProviderAdapter.java:113` `client.sendEmail`(AWS SDK v2 `sesv2` 2.30.0, 카탈로그 `awsSdk`·SDK BOM, objectstorage와 같은 버전). client는 `SesClients.java`: SDK 재시도 끔(`:54` `AwsRetryStrategy.doNotRetry()`), 기본 자격 증명 체인 대신 던지는 provider, 설정 endpoint(라우팅 가드 통과)를 `endpointOverride`, Apache client(redirect 안 따라감). 자격 증명은 기존 계약 유지(설정 `access-key-id` + `ProviderCredentialManager`의 프로필·세대별 secret)로 요청마다 `AwsRequestOverrideConfiguration`에 실음. `JdkNotificationHttpGateway`·`NotificationHttpGateway/Request/Response/TransportException`·`AwsSignatureV4Signer`·`notificationHttpGateway` bean 삭제. SNS 인증서 fetch는 callback 설정 안의 redirect 없음·64KiB 상한 JDK 요청. 검증: SDK client를 로컬 HTTP 가짜(`ProviderFaultHarness`)에 `endpointOverride`로 붙인 계약 테스트 `SesNotificationProviderAdapterTest` 17건(수락·거절·응답 유실=AMBIGUOUS·throttle·첨부 raw MIME·프로필별 서명·경로 `/v2/email/outbound-emails`) + 새 `theSdkRetriesNothingSoAServerErrorIsOneRequest`·`aMessageRejectedAnswerIsAPermanentRejection` PASS, `CrossProviderContractSuiteTest` 5건 PASS. env 키·설정 키 변경 없음 | +| S4-lead-5 | 완료 | S4-#4b와 같음 | + +## 제거된 코드 +| 대상 | 경로 | 마지막으로 존재한 커밋 | 이유 | +|---|---|---|---| +| `ProviderRuntimeRotator` | `src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRotator.java` | `0ed7bc8d` | S4-#3c: main 참조 0, production 입력 없는 회전 경로 | +| `RuntimeDrainCoordinator` | `.../notification/platform/dispatch/RuntimeDrainCoordinator.java` | `0ed7bc8d` | S4-#3c: rotator만 사용 | +| `CredentialProbe` | `.../notification/platform/dispatch/CredentialProbe.java` | `0ed7bc8d` | S4-#3c: 구현체 0, rotator만 사용 | +| `CredentialValidationException` | `.../notification/platform/dispatch/CredentialValidationException.java` | `0ed7bc8d` | S4-#3c: rotator만 던짐 | +| `NotificationSubmissionService.submit/schedule/accept` | `src/application-notification/.../platform/dispatch/NotificationSubmissionService.java` | `0ed7bc8d` | S1-#10b: main 호출자 0, use case와 3벌 중복 | +| `NotificationPlatformSettings.Provider` 8-인자 생성자 | `.../notification/platform/autoconfigure/NotificationPlatformSettings.java` | `0ed7bc8d` | S4-#15: 테스트 호환용 오버로드 | +| `TemplateRendererRegistry` | `src/application-notification/.../platform/dispatch/TemplateRendererRegistry.java` | `ce863643` | S1-#9: 모든 channel에 같은 renderer | +| `MapTemplateRendererRegistry` | `.../notification/platform/dispatch/MapTemplateRendererRegistry.java` | `ce863643` | S1-#9 | +| `ThymeleafNotificationRenderer` | `.../notification/platform/template/ThymeleafNotificationRenderer.java` | `ce863643` | S1-#9: `CanonicalNotificationRenderer` 위임 래퍼뿐 | +| `ProviderEventProjectorRegistry` | `src/application-notification/.../platform/callback/ProviderEventProjectorRegistry.java` | `ce863643` | S1-#9: 모든 provider에 같은 projector | +| `MapProviderEventProjectorRegistry` | `.../notification/platform/callback/MapProviderEventProjectorRegistry.java` | `ce863643` | S1-#9 | +| `SesDeliveryProjector` | `.../notification/platform/provider/ses/SesDeliveryProjector.java` | `ce863643` | S1-#9: `StandardDeliveryProjector` 상속만 | +| `ProviderCallbackAssembler.projector()`, `AssembledProvider.projector`, `AssembledPlatform.projectors`, `NO_PROJECTOR` 분기 | `.../notification/platform/autoconfigure/*`, `ProviderEventProjectionService.java` | `ce863643` | S1-#9: 슬롯이 늘 같은 규칙을 가리킴 | +| `ProviderRuntime.moveTo`와 `mark*`별 조건 | `.../notification/platform/dispatch/ProviderRuntime.java` | `ce863643` | S4-#14b: 전이표 하나로 대체 | +| `JdkNotificationHttpGateway` | `.../notification/platform/provider/http/JdkNotificationHttpGateway.java` | `bff135d6` | S4-lead-3(결정 17): AWS SDK sesv2로 교체 | +| `NotificationHttpGateway`·`NotificationHttpRequest`·`NotificationHttpResponse`·`NotificationHttpTransportException` | `.../notification/platform/provider/http/` | `bff135d6` | S4-lead-3 | +| `AwsSignatureV4Signer` | `.../notification/platform/provider/ses/AwsSignatureV4Signer.java` | `bff135d6` | S4-lead-3: SDK가 서명 | +| `notificationHttpGateway` bean | `.../notification/platform/autoconfigure/NotificationPlatformCoreConfig.java` | `bff135d6` | S4-lead-3 | +| `JdkNotificationHttpGatewaySecurityTest` | `.../test/.../provider/http/JdkNotificationHttpGatewaySecurityTest.java` | `bff135d6` | 대상 gateway 삭제 | +| `PersistenceJpaConfig.OPT_IN_NOTIFICATION_PACKAGE`, coverage 테스트 opt-in 표 | `src/adapter/outbound/persistence-jpa/.../config/PersistenceJpaConfig.java`, `PersistenceEntityScanCoverageTest.java` | `90fcc8ba` | S2-#1b: 알림 패키지가 leaf 밖으로 | +| `PostgreSqlNotificationBackgroundPassIntegrationTest.replayMarksAnEventWithNoProjectorFailed` | `src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/.../readiness/` | `ce863643` | S1-#9: `NO_PROJECTOR` 분기 삭제 | + +(이동만 한 것: `persistence-jpa`의 `persistence/notification/**`, `db/migration/jpa/notification-platform/**`, 알림 단위 테스트 → `adapter/outbound/persistence-notification`, 마지막으로 옛 위치에 존재한 커밋 `90fcc8ba`. `provider/http/NotificationEndpoints` → `provider/NotificationEndpoints`.) + +## 새로 발견한 결함 +- `P23-new-1`: `persistence-fileserver`의 `db/migration/jpa/fileserver/V1–V5`가 `applied-migrations.sha256`에 pin되어 있지 않다. fileserver 추출 때 `AppliedMigrationImmutabilityTest`가 persistence-jpa 디렉터리만 읽게 남아 이 stream은 checksum 고정이 없다. 이번에 알림 stream은 새 위치까지 읽게 고쳤고(`AppliedMigrationImmutabilityTest.MIGRATION_ROOTS`), fileserver는 P24 소유라 고치지 않음(같은 목록에 `../persistence-fileserver/...` 한 줄 + pin 5줄이면 됨). +- `P23-new-2`: SES `SesV2Client`는 프로필마다 assembler가 만들고 닫지 않는다(Apache 연결 풀). 프로필은 기동 때 한 번 조립되므로 누수는 프로세스당 프로필 수로 고정이지만 종료 시 정리 훅이 없다. 옛 JDK gateway도 공유 client를 닫지 않았으므로 새 결함은 아니다. 고치지 않음. +- `P23-new-3`: `app-bootstrap/build.gradle:155` 주석 "알림 (persistence-jpa 줄도 함께 푼다)"은 이제 틀렸다(composition이 persistence-jpa를 `runtimeOnly`로 가져옴). app-bootstrap은 P18이 고치는 파일이라 건드리지 않음. 통합 때 주석 수정 필요. + +## 검증 +- `:application-notification:check`, `:adapter:outbound:notification:check`, `:adapter:outbound:persistence-notification:check`, `:adapter:outbound:persistence-jpa:check`, `:adapter:inbound:web-notification:check`, `:composition:notification-platform:check` — 통과 +- `architectureCheck`, `verifyDependencyLocks`, `:app-bootstrap:test` — 통과 +- notification document/env lane: `:adapter:outbound:notification:notificationDocumentContractTest`, `:composition:notification-platform:notificationEnvironmentContractTest` — 통과 +- notification PG lane(Docker, 실제 PostgreSQL): `postgresqlNotificationSchemaActivationIntegrationTest` 8/8, `jpaPlatformContractTest` 216/216(알림 관련 63), `jpaPlatformMigrationTest` 45/45(알림 관련 24), 실패·skip 0 +- API surface 재승인: notification 380→376(D)→370(W1)→365(SES 교체), JPA 214→167(알림 47개 이동, 삭제만) +- lockfile 재생성: notification, persistence-notification(새), persistence-jpa, composition:notification-platform, app-bootstrap +- env 키 변경 없음 → `verifyEnvKeys` 불필요 diff --git a/docs/reviews/2026-09-25-review-followup-status.md b/docs/reviews/2026-09-25-review-followup-status.md index 67f201a8..d72f12c8 100644 --- a/docs/reviews/2026-09-25-review-followup-status.md +++ b/docs/reviews/2026-09-25-review-followup-status.md @@ -777,15 +777,15 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S1-#2b / S2-#4b | Required | append 포트 2개(legacy·canonical)가 같은 `outbox_event`에 공존, `ClaimedOutboxEvent` sealed 합집합 유지 (= X1-#1) | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **application-core:** `ClaimedOutboxEvent`는 이제 sealed 합집합이 아니다. `record(ValidatedIntegrationEvent event, OutboxEventStatus status, int attemptCount)`(`ClaimedOutboxEvent.java:19`)다.
**persistence-jpa:** legacy adapter와 entity의 `payload`·`idempotencyKey` 접근자를 삭제했다. canonical metadata가 불완전한 row는 claim할 때 DEAD가 된다. claim SQL(PG·H2)에서 legacy CASE를 없앴다.
**V19:** 미발행 pre-canonical row가 있으면 migration이 실패한다. CHECK `ck_outbox_event_canonical_unless_published`를 추가했다.
**테스트:** `PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.aRowWithoutTheCanonicalEnvelopeIsRefusedUnlessItIsPublished`·`aPublishedPreCanonicalRowIsKeptForTheReaper`·`theCanonicalOnlyMigrationRefusesADatabaseThatStillHoldsAnUndeliveredPreCanonicalRow` PASS(jpaPlatformContractTest 221, 이 클래스 9/9). `H2ClaimSqlTest`, `OutboxStoreAdapterTest` PASS. | - | 결정(2026-09-25): canonical 통일 — 템플릿 JSON encoder 제공, `LegacyOutboxAppendPort` 소비자 4곳 이전 후 legacy 포트·legacy Kafka 발행 경로 삭제
S2-#4b: 결정(2026-09-25): canonical 통일 → legacy adapter·컬럼 접근자 삭제(적용된 migration 유지) | | S1-#3a | Required | 호출자 없는 cache executor 20종·`LeaseWatchdog`·`TransactionCompletionResolver`·inbox·filepublication·`EphemeralFanoutPort` | 해당 없음(코드 삭제) | 「제거된 코드」 application-core cache 20종, `LeaseWatchdog`, `TransactionCompletionResolver`, same-store inbox, `FilePublicationPort`, `EphemeralFanoutPort` 행 | - | - | | S1-#3b | Required | `lease/*` 399줄: Redis 구현만 있고 use case 호출자 0 (= X1-#6) | 남음 | `application-core/.../lease/`(13파일 399줄) 참조는 `cache-redis/.../lease/RedisDistributedLeaseAdapter.java`·`RedisLeaseConfig.java`뿐. JDBC `DistributedLockPort`도 비즈니스 소비자 0. cache-redis README가 lease를 제공 capability로 명시 | W4 | 결정(2026-09-25): lock·lease 둘 다 capability로 유지 — 포트별 추상 계약 테스트를 fake와 어댑터가 함께 통과 | -| S1-#4 | Required | `NotificationDispatchService` 생성자 15개, record 필드별 재조립·실패 분류가 한 클래스에 (B-5 구조 원인) | 남음 | `application-notification/.../dispatch/NotificationDispatchService.java:72`(인자 15개), `:208`·`:485` record 재조립, `:255-288` catch 분기, `:475`·`:513` 종료 상태 두 번 계산. `DispatchOutcomeRecorder.java:67,110` 재조립 2곳 | W3 | `DeliveryAttemptRecord.completed(result, at)`·`RecipientDeliveryRecord.advancedRoute(now)` 전이 메서드 추가, catch 분기는 `ProviderOutcomeClassifier` 정적 메서드로 분리 | +| S1-#4 | Required | `NotificationDispatchService` 생성자 15개, record 필드별 재조립·실패 분류가 한 클래스에 (B-5 구조 원인) | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): 구조 변경(결함 아님, 기존 동작 테스트로 회귀 확인). record 재조립 4곳을 전이 메서드로: `application-notification/.../dispatch/DeliveryAttemptRecord.java:97`(`completed`)·`:135`(`closedBeforeSubmission`), `RecipientDeliveryRecord.java:73`(`advancedRoute`)·`:113`(`failedBeforeAttempt`)·`:156`(`afterAttempt`)·`:194`(`terminalStateFor`, 종료 상태 계산 1곳). catch 3분기는 `ProviderOutcomeClassifier.java:31`(`fromException`), 호출은 `NotificationDispatchService.java:332`. `DispatchOutcomeRecorder`는 `attempt.completed`·`current.afterAttempt` 두 줄. 새 테스트 `ProviderOutcomeClassifierTest`(3건) PASS, `NotificationDispatchServiceTest`·`DispatchOutcomeRecorderTest` 그대로 PASS. 남은 점: 생성자 인자는 여전히 15개(`NotificationDispatchService.java:82`, registry→renderer로 바뀐 것뿐). 인자는 모두 실제 포트·정책이라 수정 방향에 없는 묶음 record를 새로 만들지 않았다 | - | `DeliveryAttemptRecord.completed(result, at)`·`RecipientDeliveryRecord.advancedRoute(now)` 전이 메서드 추가, catch 분기는 `ProviderOutcomeClassifier` 정적 메서드로 분리 | | S1-#5 | Required | fileserver retire 절차 3곳 복사, admin `forceDelete`는 content 없는 레코드를 DELETING에 남김 (C-4 관련) | 완료 | Wave 1–2 P4 (fcddab7e·Wave 2 커밋): `FileserverAdminServiceTest.forceDeletingAFileThatWasNeverPublishedRetiresItCompletely` FAIL(`expected: DELETED but was: DELETING`)→PASS. 세 호출부가 `src/application-fileserver/.../cleanup/FileRetirement.java:40` 하나를 쓴다: `DefaultFileLifecycleService.java:84`, `DefaultFileserverAdminService.java:167`, `DefaultUploadApplicationService.java:265`. `cleanup` 패키지에 둔 이유: 세 호출 패키지가 이미 cleanup을 의존하고 cleanup은 그들을 의존하지 않아 새 패키지 순환이 생기지 않는다 | - | `retire(FileRecord)` 하나로 합치고 content 없으면 DELETING→DELETED 전이를 세 호출부 모두에 적용 | | S1-#6a | Required | fileserver 단일 구현 인터페이스 6개(fake 없음) | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `1ec8f087`·`8e731b9f`. 구현 1개·대역 0인 `WriterLeaseCoordinator`·`TransferAdmissionController` 인터페이스를 지우고 `Default*`가 그 이름을 가짐, `FileStateMachine`은 S1-#13으로 삭제. 수정 방향과 다르게 남긴 3개와 이유: `FileLifecycleService`는 web-fileserver `FileLifecycleController`가 부르는 inbound 포트라 `INBOUND_ADAPTERS_DEPEND_ON_PORTS_NOT_APPLICATION_SERVICES`(architectureTest)가 구체 클래스 의존을 금지(없앴다가 architectureTest FAIL로 복원), `CleanupService`·`FileReconciliationService`는 composition `FileserverCleanupWorkerTest`·`FileserverStructuredLoggingTest`가 람다/익명 대역으로 구현(두 번째 구현 존재 — 현황표 근거 "fake 없음"이 틀림). `FileserverUseCaseContractDeviationTest.KNOWN_DEVIATIONS` 갱신 | - | 인터페이스 6개 삭제, `Default*`를 인터페이스 이름으로 개명 | | S1-#6b | Required | fileserver 인바운드가 use-case 계약 밖(capability gate 미적용) | 남음 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): 사유: 결정 필요 — transport 연산 약 30개를 `CommandUseCase`/`QueryUseCase` + `@UseCaseCapability`로 바꾸면 `MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`(architectureTest) 때문에 쓰기 연산마다 `@RequiresPermission("file:…")`이 필요하고, 그 annotation은 web `RequiresPermissionAuthorizationManager`가 `AuthorizationPort`로 런타임에 강제한다. 즉 기존 `FileAccessPolicyPort`(역할·소유자 검사, C-8a) 위에 권한 게이트가 하나 더 생기고, 배포는 새 권한 이름을 부여해야 기존 업로드·다운로드가 계속 된다. (1) fileserver 연산에 method-security 권한을 추가할지(추가하면 권한 이름 체계), 아니면 (2) `RepositoryAccess`/권한 규칙에서 fileserver를 예외로 둘지를 정해야 한다(`docs/fileserver/design-deviations.md` §5가 ADR로 열어 둔 질문). 승인자: 저장소 소유자 결정 필요
결정 32(2026-09-28): 권한 추가로 결정 → 남음, P28 | W3 | transport가 부르는 연산을 `*UseCase` + `@UseCaseCapability`로 선언 | | S1-#7 | Consider | 에러 코드마다 예외 서브클래스, 타입 분기는 몇 개뿐 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `6d6c69fe`. `FileserverException`을 구체 클래스로(`api/error/FileserverException.java:37` `of(code, message)`, `notReady(fileId, state)`). catch/instanceof로 타입 분기하는 5개(`FileNotFoundException`·`FileAlreadyExistsException`·`InvalidPathException`·`UploadOffsetMismatchException`·`AmbiguousCompletionException`)만 남기고 17개 삭제, 생성 지점 약 110곳을 `new FileserverException(message, context)`/`FileserverException.of(CODE, …)`로. 테스트의 타입 분기(`MvcUploadExecutorSaturationTest`, PG `aReleasedReservationCanNeverBeCommittedOrExtended`)는 `code()` 비교로. fileserver 5개 leaf `check`·PG lane 3개 PASS | - | base를 구체 클래스 + `of(code, …)`, 서브클래스는 catch로 타입 분기하는 5개만 남김 | | S1-#8 | Consider | `PolicyTransactionPort` 계열이 호출 1곳용 | 해당 없음(코드 삭제) | 「제거된 코드」 `PolicyTransactionPort` 계열·`SpringPolicyTransactionPort`·`FileserverCompensationTransaction` 행. grep 0건 | - | - | -| S1-#9 | Consider | 같은 전략만 담은 레지스트리 2개 | 남음 | `application-notification/.../callback/ProviderEventProjectorRegistry.java:7`(Twilio/Ses projector는 `StandardDeliveryProjector` 상속만), `dispatch/TemplateRendererRegistry.java:7` + `adapter/outbound/notification/.../NotificationPlatformProviderConfig.java:57-65`(모든 channel에 같은 engine) | W3 | 레지스트리·`Map*Registry` 삭제, 구현체 직접 주입 | +| S1-#9 | Consider | 같은 전략만 담은 레지스트리 2개 | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): `TemplateRendererRegistry`·`MapTemplateRendererRegistry`·`ThymeleafNotificationRenderer`, `ProviderEventProjectorRegistry`·`MapProviderEventProjectorRegistry`·`SesDeliveryProjector` 삭제(`bff135d6`). renderer 하나(`CanonicalNotificationRenderer`, channel은 `RenderCommand`에서; `NotificationPlatformProviderConfig.java:53`)와 projector 하나(`StandardDeliveryProjector`; `NotificationPlatformRegistriesConfig.java:38`)를 직접 주입. `ProviderEventProjector.providerId()`·`NotificationTemplateRenderer.channel()`, `AssembledProvider`/`AssembledPlatform`의 projector 슬롯, `ProviderCallbackAssembler.projector()`, `NO_PROJECTOR` 분기 삭제. 테스트 `NotificationProviderAssemblyTest.anSesHardBounceIsProjectedByTheSharedProjector` PASS. PG 테스트 `PostgreSqlNotificationBackgroundPassIntegrationTest.replayMarksAnEventWithNoProjectorFailed`는 그 분기가 없어져 삭제 | - | 레지스트리·`Map*Registry` 삭제, 구현체 직접 주입 | | S1-#10a | Consider | `NotificationOrchestrator`·Reactor facade (= B-8) | 해당 없음(코드 삭제) | 「제거된 코드」 `NotificationOrchestrator`, Notification Reactor facade 행 | - | - | -| S1-#10b | Consider | 제출 흐름 `prepare→inWrite→recordAccepted`가 서비스 public 진입점과 use case 2개에 3벌 | 남음 | `application-notification/.../dispatch/NotificationSubmissionService.java:79,83,183-188`(main 호출자 0, 테스트만), `SubmitNotificationApplicationUseCase.java:45-49`, `ScheduleNotificationApplicationUseCase.java:45-49` | W3 | 서비스의 `submit`/`schedule`/`accept` 삭제(테스트는 use case로), 두 use case는 scheduleAt만 다른 private 헬퍼 1개 공유 | +| S1-#10b | Consider | 제출 흐름 `prepare→inWrite→recordAccepted`가 서비스 public 진입점과 use case 2개에 3벌 | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): `NotificationSubmissionService`의 `submit`/`schedule`/private `accept` 삭제(`ce863643`). 테스트는 `SubmitNotificationApplicationUseCase`/`ScheduleNotificationApplicationUseCase`로 호출(`NotificationSubmissionServiceTest`, `NotificationDispatchServiceTest`). 수정 방향의 "두 use case가 private 헬퍼 1개 공유"는 하지 않음: ArchUnit 규칙 `useCaseCapabilityMatchesTransactionPortBoundary`(`ArchitectureViolationFixtureTest.java:272`)가 WRITE_REPOSITORY use case마다 `TransactionPort.inWrite`를 직접 호출하길 요구하므로 공유 헬퍼로 빼면 규칙 위반. 3벌→2벌(각 3줄) | - | 서비스의 `submit`/`schedule`/`accept` 삭제(테스트는 use case로), 두 use case는 scheduleAt만 다른 private 헬퍼 1개 공유 | | S1-#11 | Consider | SHA-256 헬퍼 분산, `MessageDigestPort`가 stdlib를 포트로 감쌈, `RequestFingerprint` 이름 충돌 (= X2 P1-5) | 남음 | `application-notification/.../dispatch/MessageDigestPort.java:4` + `adapter/outbound/notification/.../Sha256MessageDigestAdapter.java`, main 33파일이 `MessageDigest.getInstance("SHA-256")` 직접, `RequestFingerprint` 2개(`application-core/.../idempotency/RequestFingerprint.java:17`, `application-notification/.../dispatch/RequestFingerprint.java:15`) | W3 | 기존 `application-core/.../messaging/contract/Sha256`에 `hex(byte[])` 두고 포트·어댑터 삭제, notification 쪽은 `PlanFingerprint`로 개명 | | S1-#12 | Consider | fileserver content SPI 확장 4개 구현·호출 0 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `b4fe7c8b`. `AsyncContentStore`·`CopyCapableContentStore`·`CapacityAwareContentStore`·`DelegatedDownloadStore`와 전용 타입 3개 삭제, `BlockingContentStore`를 `adapter/outbound/fileserver/.../platform/local/BlockingContentStore.java`로 이동. 표면 검사는 `BlockingContentStoreSurfaceTest.noMethodNamesAFilesystemOrFrameworkType`·`theStoreDeclaresTheExactDesignSurface`로 옮기고, application에는 `ContentStoreCapabilitiesTest` | - | 확장 4개 삭제, `BlockingContentStore`는 `adapter:outbound:fileserver` 내부로 이동 | | S1-#13 | Consider | `FileStateMachine` 인터페이스+구현+bean이 전이표 Map 하나 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `1ec8f087`. `FileState.canTransitionTo`/`requireTransitionTo`(`api/FileState.java:40`), `FileStateMachine`·`DefaultFileStateMachine`·bean(`FileserverVerificationConfiguration`, PG 테스트 context) 삭제, `JpaFileMetadataStore` 생성자에서 인자 제거. `FileStateTransitionTest.everyStatePairMatchesTheDesignTransitionTable` PASS | - | `FileState.canTransitionTo(target)` enum 메서드로 대체 | @@ -808,7 +808,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S1-lead-5 | 권고 | persistence-jpa `SpringPolicyTransactionPort` 정리 | 해당 없음(코드 삭제) | 「제거된 코드」 `SpringPolicyTransactionPort`… 행 | - | - | | S1-lead-6 | 권고 | fileserver 전이 규칙이 Java와 SQL 두 곳 | 완료 | Wave 1–2 P4 (fcddab7e·Wave 2 커밋): SQL의 허용 상태 문자열을 없애고 `JpaFileMetadataStore`가 전이표(`FileStateMachine.canTransition(s, DELETING)`)에서 목록을 만들어 파라미터로 넘긴다: `src/adapter/outbound/persistence-fileserver/.../repository/FileTransitionRepository.java:73`, `JpaFileMetadataStore.java:56`. 동작이 바뀐 게 아니라 중복 제거라 FAIL 재현 대상이 없음. PG `aRecordInAStateWithNoDeletingEdgeIsNotMarkedDeleting`(VERIFYING 거부)·기존 `logicalDeleteMovesTheRecordOutOfPublicReadability` PASS | - | SQL의 허용 상태 목록을 `FileState` 전이표에서 파라미터로 넘기거나, 두 목록이 같은지 단언하는 테스트 추가 | | S2-#1a | Required | JPA `notification/crypto` 505줄 테스트 전용 사본 | 해당 없음(코드 삭제) | 「제거된 코드」 "JPA notification crypto 6종과 테스트" 행 | - | - | -| S2-#1b | Required | persistence-jpa가 notification persistence를 품음(jpa→application-notification edge) | 남음 | `adapter/outbound/persistence-jpa/build.gradle:38` `implementation project(':application-notification')`, `persistence/notification/**` 6,573줄, `PersistenceJpaConfig.java:40-80` 19개 패키지 목록 ×2, `:88` `OPT_IN_NOTIFICATION_PACKAGE`, `PersistenceEntityScanCoverageTest.java:46`. 계획 W4가 추출을 적었으나 registry에 `persistence-notification` 없음 | W3 | `persistence-fileserver/build.gradle` 방식으로 `adapter:outbound:persistence-notification` leaf 추출, 목록 2개·상수·coverage 테스트 삭제 | +| S2-#1b | Required | persistence-jpa가 notification persistence를 품음(jpa→application-notification edge) | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): 새 leaf `src/adapter/outbound/persistence-notification`(`fd59ef14`): `persistence/notification/**` main 50개·단위 테스트 6개·`db/migration/jpa/notification-platform/V1–V10` `git mv`(바이트·classpath 위치 동일 → Flyway version·checksum 동일). `modules.json`에 leaf 추가(allowed: application-core, application-notification), persistence-jpa의 `application-notification` edge 삭제, composition-notification-platform에 persistence-notification·persistence-jpa edge 추가(`runtimeOnly`, NEW-11 방식). facade는 이 leaf의 `@AutoConfiguration`(JPA 루트보다 먼저, `NotificationJpaPersistenceFacade.java:92`). `OPT_IN_NOTIFICATION_PACKAGE`·coverage 테스트의 opt-in 표·`JpaModuleBoundaryTest` notification 행 삭제. `AppliedMigrationImmutabilityTest`가 새 위치도 읽고 pin은 그대로(`applied-migrations.sha256` 변경 없음). 새 테스트 `NotificationPersistenceActivationTest`(2건) PASS. PG 테스트는 fileserver 선례대로 persistence-jpa `postgresqlIntegrationTest`에 test-scope edge로 남김(readiness card·evidence manifest 경로 유지). 수정 방향의 "목록 2개 삭제"는 하지 않음: 두 capability leaf가 `dev.caskeleton.adapter.outbound.persistence.*` 패키지 아래에 있어, 루트를 스캔하면 다른 jar의 entity까지 들어가 `ddl-auto=validate`가 다시 깨진다. 대신 `PersistenceJpaConfig.ROOT_PACKAGE`와 `PersistenceEntityScanCoverageTest.theRootIsNeverScanned`로 고정 | - | `persistence-fileserver/build.gradle` 방식으로 `adapter:outbound:persistence-notification` leaf 추출, 목록 2개·상수·coverage 테스트 삭제 | | S2-#2a | Required | Mongo: 바인딩 안 되는 `advanced.*.enabled`, 구현 없는 인터페이스 10개, reactive·change stream | 해당 없음(코드 삭제) | 「제거된 코드」 Mongo advanced 바인딩·search/vector·time series·GridFS·`MongoDataKeyResolver` 등·reactive·change stream 행. 인터페이스 9개 grep 0, `MongoTenantMigrationCheckpointStore`는 구현 생김(`MongoTenantMigrationCoordinator.java:96`) | - | - | | S2-#2b | Required | persistence-mongo 약 23k줄 플랫폼에 소비자 없음 | 완료 | 소유자 결정(계획 Wave 3 "분류 2는 완성해서 포장")으로 라이브러리 유지: `adapter/outbound/persistence-mongo/README.md:135` 라이브러리 API 표, 한 줄 조립 주석 `app-bootstrap/build.gradle:146`. main 23.2k→18.6k줄 | - | - | | S2-#3a | Required | 두 번째 트랜잭션·재시도 엔진, 거짓 Javadoc | 해당 없음(코드 삭제) | 「제거된 코드」 "JPA 두 번째 트랜잭션·재시도 엔진 19종", `JpaTransactionAutoConfiguration`, retry 계열 행. `persistence/transaction/`에 `SpringTransactionPort` 하나, CLAUDE.md:91-92가 "retries nothing"으로 갱신 | - | - | @@ -816,16 +816,16 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S2-#4a | Required | JPA outbox V2·inbox·멱등성 v1 공존 | 해당 없음(코드 삭제) | 「제거된 코드」 JPA outbox V2 adapter·migration stream·통합 테스트, same-store inbox, JPA v1 멱등성 store 행 | - | - | | S2-#5 | Required | Mongo reactive 쌍둥이 스택 (= F-3, F-7) | 해당 없음(코드 삭제) | 「제거된 코드」 Mongo reactive 경로·change stream 행. `mongo/reactive`·`changestream` 디렉터리 없음, main의 reactor 참조 0 | - | - | | S2-#6a | Required | owner-lease claim 절차·`digestFields` 복사(inbox·polling) | 해당 없음(코드 삭제) | `PostgreSqlSameStoreInboxAdapter`·`PostgreSqlPollingDeliveryAdapter`·`PostgreSqlImmutableOutboxAppendAdapter` 삭제(「제거된 코드」 same-store inbox, JPA outbox V2 adapter 행). claim 절차는 멱등성 store에만 남음 | - | - | -| S2-#6c | Required | `capability_schema_registry` 확인 SQL 복사 | 남음 | `persistence-jpa/.../notification/NotificationSchemaActivation.java:33`, `postgresql/idempotency/PostgreSqlOwnerSafeIdempotencyStore.java:70`, `persistence-fileserver/.../FileserverSchemaActivation.java:30` (조건이 `>= 4`/`= 2`로 서로 다름) | W3 | persistence-jpa 안 2곳은 `CapabilitySchemaRequirement` record 하나로, fileserver는 jpa edge가 없어 자기 사본 유지(또는 support로) | +| S2-#6c | Required | `capability_schema_registry` 확인 SQL 복사 | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): 추출 뒤 persistence-jpa 안의 `capability_schema_registry` 확인 SQL은 `PostgreSqlOwnerSafeIdempotencyStore.java:66` 하나뿐. notification 사본(`persistence-notification/.../NotificationSchemaActivation.java:29`)은 fileserver와 같은 처지(jpa edge 없는 capability leaf)가 되어 행의 "fileserver는 자기 사본 유지" 규칙을 그대로 따름. 두 capability의 공용화(support로)는 P18(idempotency 이동)·P24(fileserver)와 겹쳐 이번에 하지 않음 | - | persistence-jpa 안 2곳은 `CapabilitySchemaRequirement` record 하나로, fileserver는 jpa edge가 없어 자기 사본 유지(또는 support로) | | S2-#7 | Required | JPA 플랫폼 라이브러리가 지원 표면 밖 | 완료 | 단일 구현 인터페이스 8개 grep 0(「제거된 코드」 work-claim·upsert 실행기, 단일 구현 인터페이스 행), 남은 라이브러리는 소유자 결정(Wave 3)대로 `adapter/outbound/persistence-jpa/README.md:61` 라이브러리 API 표에 명시. main 26.3k→20.0k줄 | - | - | -| S2-#8a | Consider | 조립 방식 3가지, 게이트 반복 | 남음 | `persistence-jpa/.../config/JpaAdapterComponentsConfig.java`(스캔 stereotype 16개), `notification/configuration/NotificationJpaPersistenceFacade.java`, `persistence-fileserver/.../FileserverJpaPersistenceConfig.java` + fileserver main `@ConditionalOnProperty` 10개, Mongo 6개 | W3 | feature config별 명시적 `@Bean` 한 방식으로, 클래스별 stereotype·조건 제거 | +| S2-#8a | Consider | 조립 방식 3가지, 게이트 반복 | 남음 | `persistence-jpa/.../config/JpaAdapterComponentsConfig.java`(스캔 stereotype 16개), `notification/configuration/NotificationJpaPersistenceFacade.java`, `persistence-fileserver/.../FileserverJpaPersistenceConfig.java` + fileserver main `@ConditionalOnProperty` 10개, Mongo 6개
Wave 3 W3-P23: 미완 — 이유: 알림은 이미 feature config의 명시적 `@Bean` 한 방식(`NotificationJpaPersistenceFacade`, 이번에 이 leaf의 auto-configuration root로). 남은 대상 — `JpaAdapterComponentsConfig`의 stereotype 스캔(outbox·idempotency·lock 등), `persistence-fileserver`의 `@ComponentScan`+클래스별 `@ConditionalOnProperty`, Mongo — 은 동시에 도는 P18(outbox·멱등성 패키지 이동)·P24(fileserver)가 같은 파일을 옮기고 있어 충돌을 피해 손대지 않음. 통합 뒤 한 묶음으로 | W3 | feature config별 명시적 `@Bean` 한 방식으로, 클래스별 stereotype·조건 제거 | | S2-#8b | Consider | "두 조립 루트가 `dev.caskeleton.adapter`를 스캔한다" 서술이 사실과 다름 | 남음 | `persistence-jpa/.../postgresql/idempotency/PostgreSqlOwnerSafeIdempotencyStore.java:53`, `src/test/.../CandidateAdapterCompositionTest.java:10-18`(현재 `CaSkeletonApplication`은 scan 제외식 없음, sample은 `SamplePortfolioApplication.java:31-40`처럼 좁게 스캔) | W5 | 잘못된 단락 삭제, 전제가 사라진 `CandidateAdapterCompositionTest` 삭제 또는 현재 조립 기준으로 재작성 | | S2-#9a | Consider | 무관한 `inbox` 패키지 2개 | 해당 없음(코드 삭제) | `postgresql/inbox` 삭제(「제거된 코드」 same-store inbox 행) | - | - | | S2-#9b | Consider | feature가 vendor별로 흩어짐 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): 이동만 했다(`910ab7ab`). 새 패키지는 `persistence/outbox/{jpa(+entity),postgresql,h2}`, `persistence/idempotency/{jpa(+entity),postgresql}`다. JPA API surface는 `updateJpaApiSurface -PapproveJpaApiSurfaceChange`로 다시 승인했다. `JpaModuleBoundaryTest`에 autoconfigure→idempotency edge를 기록했다. `verifyJpaApiSurface`·`verifyJpaReadinessRegistry` PASS. | - | feature 기준 패키지(`outbox/{jpa,postgresql,h2}`, `idempotency/{jpa,postgresql}`)로 이동만 | | S2-#10 | Consider | promotion/benchmark gate가 production classpath에 | 해당 없음(코드 삭제) | 「제거된 코드」 `experimental/next/*`, `MongoAdvancedPromotionGate`·`Evidence`, search·vector(benchmark·readiness gate 포함) 행. grep 0 | - | - | | S2-#12 | Consider | Javadoc이 이력을 서술 | 남음 | 재측정: "used to/until now/never was/no longer" 포함 파일 jpa 25·mongo 36·fileserver 6 | W5 | 불변 조건 1~2줄만 남기고 이력은 git/ADR로 | | S2-#13a | Nit | `JpaTransactionAutoConfiguration` 팩토리 2회 생성, `new JpaTransactionSettings(null ×9)` | 해당 없음(코드 삭제) | 「제거된 코드」 두 번째 엔진(`JpaTransactionAutoConfiguration`)·`JpaTransactionSettings` 행 | - | - | -| S2-#13b | Nit | port 구현 이름 규칙 7가지 | 남음 | `OutboxStoreAdapter`, `CanonicalOutboxAppendAdapter`, `Jpa*Store`(notification), `JdbcReconciliationJobStore`, `PostgreSqlOwnerSafeIdempotencyStore`, `SpringTransactionPort`, `LockRegistryDistributedLockAdapter`, `persistence-fileserver/.../JpaFileQuotaService` | W3 | `` 규칙 하나로 개명(S1-#18b와 함께) | +| S2-#13b | Nit | port 구현 이름 규칙 7가지 | 남음 | `OutboxStoreAdapter`, `CanonicalOutboxAppendAdapter`, `Jpa*Store`(notification), `JdbcReconciliationJobStore`, `PostgreSqlOwnerSafeIdempotencyStore`, `SpringTransactionPort`, `LockRegistryDistributedLockAdapter`, `persistence-fileserver/.../JpaFileQuotaService`
Wave 3 W3-P23: 미완 — 알림 부분만 완료: `JpaNotificationSideEffectStore` → `JpaNotificationSideEffect`(`NotificationSideEffectPort`), 나머지 알림 구현은 이미 ``(`JdbcReconciliationJobStore` 포함). 이유: 행에 열거된 나머지(`OutboxStoreAdapter`, `CanonicalOutboxAppendAdapter`, `PostgreSqlOwnerSafeIdempotencyStore` — P18, `JpaFileQuotaService` — P24, `SpringTransactionPort`·`LockRegistryDistributedLockAdapter` — core)는 다른 묶음 소유이고 S1-#18b와 함께 기계적 개명으로 해야 함 | W3 | `` 규칙 하나로 개명(S1-#18b와 함께) | | S2-#14a | Nit | jpa CLAUDE.md의 "NoSQL은 미래 모듈"·MapStruct 절이 현실과 다름 | 남음 | `adapter/outbound/persistence-jpa/CLAUDE.md:17-19,202-206`(Mongo leaf 이미 존재), `:309-330` MapStruct 절(의존성 없음) | W5 | NoSQL 문장을 현재 leaf 기준으로 고치고 MapStruct 절 삭제 | | S2-#14b | Nit | jpa API surface 파일에 옮겨간 타입 | 남음 | `docs/architecture/jpa-adopter-api-surface.txt:11` `...persistence.fileserver.FileserverSchemaActivation`(지금은 persistence-fileserver leaf) | W5 | 해당 줄 삭제(필요하면 fileserver 쪽 surface로) | | S2-#14c | Nit | Mongo CLAUDE.md `MongoAdvancedProperties` 오기 | 완료 | `6d27356e`: 해당 이름 없음, `adapter/outbound/persistence-mongo/CLAUDE.md:146`이 "flags have no configuration property"로 갱신(`MongoAdvancedSettings`도 삭제) | - | - | @@ -883,32 +883,32 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S4-#2 | Required | messaging R1 compiler/encoder 체인·realtime fanout 미연결 | 완료 | `src/adapter/outbound/messaging` main 13파일 765줄(`core`·`outbox`·`platformbridge`·`autoconfigure`만). NetworkNT는 `build.gradle`에 `testImplementation`만. `JsonSchemaIntegrationEventEncoder`·`CompiledMessagingDescriptor`·`MessagingDurableFanoutAdapter` grep 0건. 「제거된 코드」 표 119–122행과 `realtime/` 행, `6d27356e` | - | - | | S4-#3a | Required | notification 미조립 provider 5종(APNs·FCM·Twilio·WebPush·Webhook) | 완료 | Wave 1–2 P3 (fcddab7e·Wave 2 커밋): D 커밋 `38d31b98`. `provider/{apns,fcm,twilio,webpush,webhook}` main·test 삭제, `SesSuppressionUpdater` 삭제. `ProviderType`은 SES·SMTP만(`ntf-adapter/autoconfigure/ProviderType.java:26-30`). 5종만 쓰던 설정 필드 `topic`·`vapid-public-key`·`callback-signing-secret-ref` 삭제(`NotificationPlatformSettings.java` Provider), `SecretPurpose.VAPID_SIGNING`·`vapid-signing-key`·env 키 2개(`APP_NOTIFICATION_PLATFORM_VAPID_SIGNING_KEY`, `_KEY_ID`)를 `notification.yml`·`.env.example`·`env-keys.yaml`·`secrets-classification.yaml`·`scripts/run-compose-runtime-smoke.sh`에서 삭제. 문서: `docs/notification/{configuration-reference,support-matrix,module-mapping,provider-runbooks}.md`, `composition/notification-platform/README.md`. 새 테스트 `NotificationPlatformSettingsTest.aRemovedProviderTypeFailsStartupAsUnknown`(5종 → "unknown provider type"). API surface 416→379 재승인. `verifyEnvKeys` OK | - | 5개 패키지 삭제. `ProviderType`에서 APNS·FCM·TWILIO·WEB_PUSH·WEBHOOK 제거. `docs/notification/configuration-reference.md:69,106-114` 표 정리. 「제거된 코드」 표에 행 추가 | | S4-#3b | Required | SES callback은 조립되는데 projector 없음 → 모든 callback 이벤트가 `NO_PROJECTOR`로 실패 처리 | 완료 | Wave 1–2 P3 (fcddab7e·Wave 2 커밋): `NotificationProviderAssemblyTest.anSesHardBounceIsProjectedRatherThanFailedForWantOfAProjector` FAIL(컴파일: `providerEventProjectorRegistry(AssembledPlatform, List)` 없음 — registry가 빈 bean 목록으로만 만들어지던 구조)→PASS(hard bounce → `DeliveryOutcome.BOUNCED`). 빈 슬롯 유지·연결: `ProviderCallbackAssembler.projector()` 추가, SES는 `SesDeliveryProjector`(`SesProviderCallbackAssembler.java:34`), assembly가 콜백을 만들 때 projector를 `AssembledPlatform.projectors`에 넣음(`NotificationProviderAssembly.java:134`, INGEST_ONLY 포함), registry는 `platform.projectors()` + 선언된 bean(`NotificationPlatformRegistriesConfig.java:46`). `SesSuppressionUpdater`는 소유자 승인 삭제(D)라 연결하지 않았다 — suppression은 `ProviderEventProjectionService`의 `NotificationSideEffectPort` 경로가 이미 처리 | - | SES callback assembler가 `SesDeliveryProjector`를 `AssembledProvider`에 싣고, registry는 `AssembledPlatform.projectors()`로 만든다. suppression을 적용하려면 `SesSuppressionUpdater`도 연결. SES callback이 bounce를 반영하는지 통합 테스트 1개 추가 | -| S4-#3c | Required | reconciliation 슬롯·자격증명 회전 경로에 production 입력 없음 | 남음 | `TwilioReconciliationCapability`·`ProviderRuntimeRotator` main 참조 0건. `RuntimeDrainCoordinator`·`CredentialProbe`는 `ProviderRuntimeRotator`만 참조하고 `CredentialProbe` 구현체는 0개. `NotificationPlatformProviderConfig.java:148`이 항상 빈 `reconciliations`로 gateway를 만듦. 두 assembler 모두 `AssembledProvider.dispatchOnly`(`SesProviderRuntimeAssembler.java:98`, `SmtpProviderRuntimeAssembler.java:112`) | W3 | `ProviderRuntimeRotator`·`RuntimeDrainCoordinator`·`CredentialProbe` 삭제. reconciliation 슬롯은 #3a와 함께 지우거나, 남길 경우 README에 "SES/SMTP는 reconciliation 없음" 한 줄 | +| S4-#3c | Required | reconciliation 슬롯·자격증명 회전 경로에 production 입력 없음 | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): `ProviderRuntimeRotator`·`RuntimeDrainCoordinator`·`CredentialProbe`·`CredentialValidationException` 삭제(`ce863643`). reconciliation 슬롯은 남김: `NotificationPlatformProviderConfig`의 `reconciliationGateway`는 이미 `platform.reconciliations()`를 받으므로(행 근거의 "항상 빈 reconciliations"는 현재 코드와 다름) adopter가 조립한 status-query family에는 production 입력이 있다. `docs/notification/callback-reconciliation.md`에 "SES/SMTP는 reconciliation 없음" 추가, `AssembledProvider` javadoc에도. `operations.md`의 "Bounded drain on rotation" 행 삭제. `ProviderRuntimeRegistryTest`의 rotator 테스트 3건 삭제·1건은 `registry.replace`로 | - | `ProviderRuntimeRotator`·`RuntimeDrainCoordinator`·`CredentialProbe` 삭제. reconciliation 슬롯은 #3a와 함께 지우거나, 남길 경우 README에 "SES/SMTP는 reconciliation 없음" 한 줄 | | S4-#4a | Required | SMTP capability 값이 두 곳에서 다름 | 완료 | Wave 1–2 P7 (fcddab7e·Wave 2 커밋): `SmtpProviderRuntimeAssemblerTest.theAssembledProfileDeclaresTheAdaptersOwnCapabilities` FAIL(`maxPayloadBytes=26214400` vs `25000000`)→PASS. assembler에 있던 capability 사본 `capabilities()`를 지우고, snapshot이 SES처럼 `adapter.capabilities()`를 쓴다: `src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SmtpProviderRuntimeAssembler.java:108,115-134`. 값은 어댑터 쪽(25,000,000 B, 1일) 하나로 정했다. P3가 바꾼 테스트 `profile()` 줄은 건드리지 않았다. 커밋 `3a39b6b5` | - | assembler의 `capabilities()` 사본을 지우고 `adapter.capabilities()`를 쓴다. 값 하나로 확정 | -| S4-#4b | Required | `ProviderCapabilities` 위치 인자 11개를 8곳에서 `new` | 남음 | `application-notification/…/provider/ProviderCapabilities.java:12-23`(boolean 8개 + int·long·Duration). main에서 `new ProviderCapabilities(` 8곳(SMTP assembler, SMTP·SES·APNs·FCM·Twilio·WebPush·Webhook adapter). #3a를 하면 3곳이 남음 | W3 | #3a 이후 `ProviderCapabilities.dispatchOnly(maxPayloadBytes, maxTtl)` 같은 named factory 하나 추가 | +| S4-#4b | Required | `ProviderCapabilities` 위치 인자 11개를 8곳에서 `new` | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): `ProviderCapabilities.dispatchOnly(maxPayloadBytes, maxTtl)`(`ProviderCapabilities.java:52`)와 `withStatusCallback()`. main의 `new ProviderCapabilities(` 0곳(SMTP·SES 모두 factory). 새 테스트 `ProviderSpiContractTest.aDispatchOnlyProviderClaimsNothingAndAddsTheCallbackByName` PASS | - | #3a 이후 `ProviderCapabilities.dispatchOnly(maxPayloadBytes, maxTtl)` 같은 named factory 하나 추가 | | S4-#5 | Required | `LocalPersistentControlPlane`(1,470줄)이 7가지 일을 함 | 해당 없음(코드 삭제) | S4-#1과 함께 삭제. `LocalPersistentControlPlane` grep 0건. 「제거된 코드」 표 76행 | - | - | | S4-#6 | Required | "attested root 아래 private shard" 구현 3벌 | 해당 없음(코드 삭제) | `LocalPersistentControlPlane`·`LocalPersistentPayloadOperations`·`LocalPersistentRootAttestor`·`LocalPublicationJournal`·`LocalFilePublicationAdapter` 모두 grep 0건. 남은 `forceDirectory`는 `platform/local/ContentPublishVerification.java:106` 하나. 「제거된 코드」 표 76행 | - | - | | S4-#7 | Required | 손으로 만든 flat JSON parser 2개 | 해당 없음(코드 삭제) | `FileserverControlRecordCodec`·`LocalPublicationJournalCodec` grep 0건. 「제거된 코드」 표 76행 | - | - | | S4-#8 | Consider | 원시 String 검증 73곳을 Value Object로 | 해당 없음(코드 삭제) | 대상 `FileserverControlRecordCodec`·`FileserverR2Validation` 삭제. 남은 `requireText` 9곳은 모두 설정 검증(`FileserverPlatformSettings.java:54-313`) | - | - | -| S4-#9 | Consider | notification HTTP provider 공통 템플릿이 반만 있음 | 남음 | HTTP adapter 5개가 여전히 각자 send 템플릿을 구현(`Apns`/`Ses`/`TwilioSms`/`WebPush`/`WebhookNotificationProviderAdapter`). main `new ProviderFailure(` 25곳 | W3 | #3a를 하면 HTTP provider가 SES 하나만 남아 자동으로 해소됨. 그때 이 행을 닫는다(별도 helper 불필요) | +| S4-#9 | Consider | notification HTTP provider 공통 템플릿이 반만 있음 | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): HTTP provider가 SES 하나이고 이제 SDK client를 씀(`90fcc8ba`). 공통 send 템플릿·`provider/http` 패키지 자체가 삭제됨. `ProviderResults`는 SES 분류기만 쓰는 상태·전송 분류 함수로 남음 | - | #3a를 하면 HTTP provider가 SES 하나만 남아 자동으로 해소됨. 그때 이 행을 닫는다(별도 helper 불필요) | | S4-#10 | Consider | objectstorage legacy adoption은 켜면 기동 실패 | 완료 | `maintenance/`, `ObjectStorageLegacyMigrationConfig`, `LegacyObjectAdoptionSettings`, readiness Evidence/Card, `ObjectControlRecordEnvelope` grep 0건(`git diff 208077fd 6d27356e`에서 -860줄). 「제거된 코드」 표 84–86행 | - | - | | S4-#11a | Consider | objectstorage legacy·신규 두 세대 공존 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `e8b6bae0`. S1-#17b와 같은 커밋: `ObjectStoragePort`·`StoredObject`·`FilesystemObjectStorageAdapter`·`S3ObjectStorageAdapter`·`ObjectStorageConfig`·`ObjectStorageSettings`·`LegacyObjectStorageActivationGuard`, `ObjectStorageCapabilitySettings.Legacy`와 `app.object-storage.legacy.*`, `docs/objectstorage/env-fields.yaml` legacy 10행 삭제. `ObjectStorageAutoConfiguration`은 canonical 조건 하나. app-bootstrap `ObjectStorageCompositionIntegrationTest`를 semantic 포트 round trip으로(`selectedObjectStorageLeafRoundTripsThroughTheSemanticPorts` PASS) | - | sample을 신규 포트로 옮긴 뒤 `ObjectStoragePort`·`StoredObject`·legacy 어댑터 2개·`ObjectStorageConfig`·`LegacyObjectStorageActivationGuard` 삭제 | | S4-#11b | Consider | objectstorage 패키지 위치 불명확(port 구현이 `config/`에, managed publish가 router inline) (≈ D-7, D-8) | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `806c4ca9`. `Routing{Mutation,Read,ScanMaintenance}Adapter`를 `routing/`로, managed publish를 `kernel/ManagedObjectPublicationKernel`로 추출(router의 `publish`는 위임 한 줄). 빈 `RoutingObjectDirectGrantAdapter`는 D-7b에서 이미 삭제 | - | `Routing*Adapter`를 `routing/`로 옮기고, managed publish 부분을 `kernel/`로 추출. 빈 `RoutingObjectDirectGrantAdapter` 삭제 | | S4-#12 | Consider | `SelectedObjectStorageProviderFactory`가 type-unsafe service locator (≈ D-7) | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): 코드 변경은 D-7a(`2c7b3d25`)에서 됨: `Object` 슬롯 3개·생성자 3개·`Class.cast` 삭제. 지금 `config/SelectedObjectStorageProviderFactory.java`는 타입 있는 필드 2개(provider, controlStore) + close action. record로 바꾸지 않은 이유: exactly-once close에 `AtomicBoolean` 상태가 필요 | - | direct/multipart 슬롯 제거 후 `record ProviderInstance(ObjectStorageProvider, ObjectControlStore, Runnable close)`로 교체. direct/multipart 삭제(1차 D-7)와 같이 진행 | | S4-#13 | Consider | provider 1개인데 fileserver R2 routing 계층 | 해당 없음(코드 삭제) | `RoutingFilePublicationAdapter`·`FilePublicationProvider`·`LocalPersistentPublicationProvider` grep 0건. 「제거된 코드」 표 76행 | - | - | | S4-#14a | Consider | `ProviderRuntime`의 무조건 덮어쓰기가 운영자 결정·인증 실패를 지움 | 완료 | Wave 1–2 P7 (fcddab7e·Wave 2 커밋): `ProviderRuntimeStateTest.anOperatorStateDoesNotLetResumeClearAnAuthenticationFailure`(DISABLED·DRAINING) FAIL→PASS. `aLateAuthenticationFailureDoesNotOverwriteAnOperatorState`(DISABLED·DRAINING) FAIL(`expected DISABLED but was AUTHENTICATION_FAILED`)→PASS. 전이 규칙은 `ProviderRuntime.moveTo` 한 곳에 있다(`src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntime.java:229-255`). AUTH_FAILED는 rotation(새 runtime)으로만 벗어나고, DISABLED/DRAINING은 인증 실패로 덮이지 않는다. `markAuthenticationFailed`가 이제 적용 여부를 boolean으로 돌려준다. `RegistryProviderRuntimeControl.java:36`은 그 값을 그대로 반환한다(전에는 항상 true). notification API surface(type 목록)는 바뀌지 않았다(`verifyNotificationApiSurface` 통과). 커밋 `3a39b6b5` | - | 전이 규칙을 한 곳에 둔다. AUTH_FAILED는 rotation으로만 벗어나고, DISABLED/DRAINING은 인증 실패로 덮이지 않게. 두 순서에 대한 테스트 추가 | -| S4-#14b | Consider | 상태 전이 규칙이 7개 메서드에 흩어짐 | 남음 | `ProviderRuntime.java:127-245`에 `mark*`/`resumeHealthy` 7개가 각자 `updateAndGet` 조건을 가짐. `RegistryProviderRuntimeControl.java:30` switch | W3 | `EnumMap>` 전이표 + `transition(target, reason)` 하나로 (#14a와 같이) | -| S4-#15 | Consider | Settings가 모든 provider 필드를 한 record에 담음 | 남음 | `NotificationPlatformSettings.java:211-223`의 `Provider`가 `topic`·`vapidPublicKey`·`callbackSigningSecretRef`를 가짐(APNs·WebPush·Twilio 전용). `:288`은 `switch (resolved.name())` 문자열 분기. `:229-258`은 테스트 호환용 11-인자 오버로드 | W3 | #3a와 함께 미조립 provider 필드·분기 삭제, enum switch로 바꾸고 11-인자 오버로드 삭제 | +| S4-#14b | Consider | 상태 전이 규칙이 7개 메서드에 흩어짐 | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): `ProviderRuntime.java:223`(`Transition` enum) + `:240`(`EnumMap` 표 `SOURCES`) + `:271`(`apply` 하나). 7개 `mark*`/`resumeHealthy`는 한 줄씩. 표는 target 상태가 아니라 전이로 키를 잡음: HEALTHY로 가는 길이 둘(성공 신호=THROTTLED·DEGRADED에서만, 운영자 resume=AUTH_FAILED 외 전부)이라 `EnumMap>` 하나로는 표현 불가. 새 테스트 `ProviderRuntimeStateTest.everyTransitionFromEveryStateEndsWhereTheTableSays`(6상태×7전이, 반환값까지) PASS, 기존 상태 테스트 PASS. 동작 차이 하나: 이미 AUTH_FAILED인 runtime에 인증 실패가 또 오면 전에는 reason을 덮어썼고 이제는 처음 reason을 유지 | - | `EnumMap>` 전이표 + `transition(target, reason)` 하나로 (#14a와 같이) | +| S4-#15 | Consider | Settings가 모든 provider 필드를 한 record에 담음 | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): 미조립 provider 필드·문자열 분기는 Wave 1(P3)에서 이미 삭제됨(`resolved == ProviderType.SES` enum 비교). 남은 테스트 호환용 8-인자 `Provider` 오버로드 삭제(`ce863643`), 레코드 생성자 하나(`NotificationPlatformSettings.java:211`, `:229`) | - | #3a와 함께 미조립 provider 필드·분기 삭제, enum switch로 바꾸고 11-인자 오버로드 삭제 | | S4-#16a | Nit | notification·fileserver 이력 서술 주석 | 남음 | 예: `ProviderType.java:10-15`, `:85`("used to bind successfully"), `NotificationProviderAssembly.java:30`, `MapProviderCallbackAdapterRegistry.java:10-11`(BOOT-017). grep 근사로 notification 37줄, fileserver 12줄 | W5 | 주석을 현재 동작만 설명하도록 줄이고, 이력은 commit/ADR로 | | S4-#16b | Nit | objectstorage main의 inline FQN | 남음 | grep 근사 92줄. 예: `ObjectStorageConfig.java:30`, `control/CanonicalJsonObjectControlRecordCodec.java:649,847-862`, `s3/S3ClientPolicy.java:137` | W5 | import로 바꾼다(Spotless/Checkstyle 규칙으로 막을지는 선택) | | S4-#17a | Nit | fileserver `*Config`/`*Configuration` 혼재, 클래스 이름의 버전 라벨 | 해당 없음(코드 삭제) | 루트 `*Config`(`FileserverR2Config` 등)와 `R2PublishedReferenceCodec` 삭제. 남은 fileserver 설정 8개는 모두 `*Configuration` | - | - | | S4-#17b | Nit | notification `*ProviderProperties`는 `@ConfigurationProperties`가 아닌 파생 값 | 남음 | `Apns`/`Fcm`/`Ses`/`Smtp`/`Twilio`/`WebPushProviderProperties` 6개. 어느 것도 `@ConfigurationProperties`가 아님 | W5 | #3a 이후 남는 `Ses`·`SmtpProviderProperties`를 `*ProviderProfile`로 이름 변경 | | S4-lead-1 | 권고 | 손으로 만든 canonical JSON codec이 3개 leaf에 있음 (= X1-8) | 해당 없음(코드 삭제) | fileserver 2벌·messaging `DeterministicEnvelopeWriter` 삭제. 남은 건 objectstorage `control/CanonicalJson{Reader,Writer}.java` 하나라 중복 아님 | - | - | | S4-lead-2 | 권고 | 로컬 보안 파일시스템 primitive가 fileserver·objectstorage에 따로 있음 | 남음 | fileserver `platform/local/SafeFileChannelFactory.java:250`(`SecureDirectoryStream`)·`SecureDirectoryWalk.java`. objectstorage `filesystem/LocalObjectPathGuard.java:62-117`은 경로 검사 후 사용 방식(`rejectExistingLinks` → 생성). 방식과 검사가 다름. objectstorage는 `adapter-outbound-support` edge가 없음
Wave 3 W3-P24: 미완 — 이유: fileserver primitive 중 `SecureDirectoryWalk`는 JDK만 쓰지만 `SafeFileChannelFactory`는 `IOException`을 Fileserver 에러 코드로 바꾸는 번역을 품고 있어, support로 올리려면 에러 어휘를 떼어 내야 한다. 그리고 objectstorage `LocalObjectPathGuard`는 Path를 돌려주고 호출자(`LocalDevObjectDataStore`·`LocalDevObjectControlStore`·`LocalObjectStreamTransfer`, 약 520줄)가 `Files.*`로 여는 구조라, primitive를 쓰려면 이 I/O를 fd 기준(`SecureDirectoryStream`) 연산으로 다시 써야 한다. registry edge 추가만으로는 끝나지 않는 보안 민감 재작성이라 별도 묶음(권고 행)으로 남김 | W3 | fileserver 쪽 primitive를 `adapter:outbound:support`로 올리고, objectstorage에 support edge를 추가해서 `LocalObjectPathGuard`가 그것을 쓴다(registry 수정 포함) | -| S4-lead-3 | 권고 | notification 자체 JDK HTTP gateway·SigV4 서명기 vs httpclient leaf·AWS SDK | 남음 | `provider/http/*` 464줄(`JdkNotificationHttpGateway` 외), `ses/AwsSignatureV4Signer.java` 147줄. notification `build.gradle`에는 AWS SDK·httpclient 의존 없음. objectstorage만 AWS SDK를 씀 | W3 | 결정(2026-09-25): AWS SDK(sesv2)로 교체, 자체 JDK gateway·SigV4 서명기 삭제 | +| S4-lead-3 | 권고 | notification 자체 JDK HTTP gateway·SigV4 서명기 vs httpclient leaf·AWS SDK | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): 소유자 결정 17. `SesNotificationProviderAdapter.java:113` `client.sendEmail`(AWS SDK v2 `sesv2` 2.30.0, 카탈로그 `awsSdk`·SDK BOM, objectstorage와 같은 버전). client는 `SesClients.java`: SDK 재시도 끔(`:54` `AwsRetryStrategy.doNotRetry()`), 기본 자격 증명 체인 대신 던지는 provider, 설정 endpoint(라우팅 가드 통과)를 `endpointOverride`, Apache client(redirect 안 따라감). 자격 증명은 기존 계약 유지(설정 `access-key-id` + `ProviderCredentialManager`의 프로필·세대별 secret)로 요청마다 `AwsRequestOverrideConfiguration`에 실음. `JdkNotificationHttpGateway`·`NotificationHttpGateway/Request/Response/TransportException`·`AwsSignatureV4Signer`·`notificationHttpGateway` bean 삭제. SNS 인증서 fetch는 callback 설정 안의 redirect 없음·64KiB 상한 JDK 요청. 검증: SDK client를 로컬 HTTP 가짜(`ProviderFaultHarness`)에 `endpointOverride`로 붙인 계약 테스트 `SesNotificationProviderAdapterTest` 17건(수락·거절·응답 유실=AMBIGUOUS·throttle·첨부 raw MIME·프로필별 서명·경로 `/v2/email/outbound-emails`) + 새 `theSdkRetriesNothingSoAServerErrorIsOneRequest`·`aMessageRejectedAnswerIsAPermanentRejection` PASS, `CrossProviderContractSuiteTest` 5건 PASS. env 키·설정 키 변경 없음 | - | 결정(2026-09-25): AWS SDK(sesv2)로 교체, 자체 JDK gateway·SigV4 서명기 삭제 | | S4-lead-4a | 권고 | adapter `LocalJsonSchemaRegistry` vs vendored `messaging-schema-json` | 해당 없음(코드 삭제) | `LocalJsonSchemaRegistry` grep 0건. 「제거된 코드」 표 123행 | - | - | | S4-lead-4b | 권고 | `adapter:outbound:messaging-kafka`(R0 seam) vs vendored `messaging/messaging-kafka` | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **삭제:** `core/MessageBroker` 계열(MessageBroker, MessagePublisher, OutboundMessage, OutboundMessagePublisher, DisabledMessagePublisher)과 `OutboxEnvelopeJson`, `adapter:outbound:messaging-kafka`의 Java 코드 전부.
**relay 경로:** relay는 claim한 row의 `ValidatedIntegrationEvent`를 bridge로만 보낸다(`OutboxMessagePublishAdapter(IntegrationEventPublishPort)`, `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapter.java:23`).
**leaf를 남긴 이유:** 계획은 leaf 삭제였다. 대신 bridge+starter-kafka를 싣는 코드 없는 capability 묶음으로 남겼다. 한 줄 선택이 유지되고, bridge leaf는 broker 중립으로 남는다.
**테스트:** `KafkaCapabilityActivationTest` PASS. | - | legacy `OutboxEvent`에 canonical metadata를 채우는 migration 후 relay를 bridge로 바꾸고 `adapter:outbound:messaging-kafka`와 `core/MessageBroker` 계열 삭제 | -| S4-lead-5 | 권고 | `ProviderCapabilities` 위치 인자 11개 → named factory | 남음 | S4-#4b와 같음 | W3 | S4-#4b 참조 | +| S4-lead-5 | 권고 | `ProviderCapabilities` 위치 인자 11개 → named factory | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): S4-#4b와 같음 | - | S4-#4b 참조 | | S5-#1a | Required | WebProblem 어휘(`ProblemCode`·`ProblemCatalog`·yaml·핸들러·writer) (= X2-P2-1) | 완료 | `ProblemCatalog`·`WebProblem`·`problem-catalog.yaml`·`ThrottleProblemWriter`·`WebMvcBudgetExceptionHandler` grep 0건. 「제거된 코드」 표 99·104·105행, `6d27356e` | - | - | | S5-#1b | Required | 검증 규칙표 두 벌(`ClientSafeValidationDetails` vs `WebValidationIssueMapper`) | 완료 | `W/validation/` 삭제(표 103행). 남은 것은 `web/error/ClientSafeValidationDetails.java` 하나 | - | - | | S5-#1c | Required | fileserver가 운영에서 problem+json을 보냄(Envelope와 다른 형식) (= X2-P2-3) | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): X2-P2-3a와 같은 작업·같은 테스트. 식별 필드는 Envelope `details`(`fileId`·`uploadId`·`expectedOffset`·`currentOffset`·`state`·`ambiguous`·`reconciliationRequired`), tus·Retry-After·Content-Range 헤더 유지(`FileserverProblemHeaderParityTest` PASS). batch 항목도 `ApiError`(`FileUploadControllerTest` `$.results[1].error.code` PASS) | - | 소유자 결정대로 `ErrorResponseFactory` Envelope로 바꾸고 `FileserverProblem`·`FileserverProblemFactory`·`FileserverProblemTitles`를 삭제. 파일 식별 필드(fileId·uploadId·offset)는 Envelope `details`로. tus 헤더와 Retry-After·`Content-Range` 헤더는 유지(`FileserverProblemHeaders`) | @@ -1204,3 +1204,7 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검 | P18-new-1 | 발견 | messaging outbox의 손으로 쓴 header JSON reader가 `\\`로 끝나는 값에서 다음 header를 삼켰다. | 완료 | Wave 3 P18: PostgreSQL `jsonb_object`/`jsonb_each_text`, `OutboxPostgresIT.aHeaderValueEndingInABackslashRoundTripsWithoutSwallowingTheNextHeader` FAIL→PASS | - | - | | P18-new-2 | 발견 | root `CLAUDE.md`가 legacy outbox/realtime seam이 `src/messaging/CLAUDE.md`에 기록돼 있다고 적음(cutover 끝남). | 완료 | Wave 3 라운드 2 통합: `CLAUDE.md` Module families 문장 수정 | - | - | | P18-new-3 | 발견 | actuator security chain이 auto-configuration이 되어, web security를 직접 켜지 않은 조립은 Boot 기본 actuator chain을 받는다(설계 노트). | 남음 | Wave 3 P18 결과 파일, `composition/service-runtime/.../ManagementSecurityConfig.java` | W5 | service-runtime README에 켜짐 조건 명시 | +| P23-new-1 | 발견 | fileserver migration V1–V5가 `applied-migrations.sha256`에 고정돼 있지 않다. | 남음 | Wave 3 P23 결과 파일 | W3 | `AppliedMigrationImmutabilityTest`에 fileserver 경로 추가 + 5줄. P28 | +| P23-new-2 | 발견 | profile마다 만드는 SES SDK client를 닫지 않는다(기동 때 한 번이라 유한). | 남음 | Wave 3 P23 결과 파일 | W3 | provider 종료 시 close. P28 | +| P23-new-3 | 발견 | `app-bootstrap/build.gradle` 알림 선택 줄 주석이 persistence-jpa 줄을 함께 풀라고 함(composition이 직접 가져옴). | 완료 | Wave 3 라운드 3 통합: 주석 수정 | - | - | +| ORCH-new-2 | 발견 | `NotificationPayloadAtRestContractTest`가 저장소 소스·migration을 읽지만 test inputs를 선언하지 않아(`notification/build.gradle:98`이 필요 없다고 주장) 파일이 옮겨져도 up-to-date로 건너뜀. P23 worktree에서 통과, main 통합에서 실패(옛 `persistence-jpa` 경로·`build/` 경합 walk). | 남음 | 경로와 walk 범위는 통합 때 수정(`src/main/java`만) | W4 | 읽는 파일을 test `inputs`로 선언(CLAUDE.md build-logic 규칙) | diff --git a/docs/superpowers/plans/2026-09-25-review-followup.md b/docs/superpowers/plans/2026-09-25-review-followup.md index a93e97c0..67ca2fb6 100644 --- a/docs/superpowers/plans/2026-09-25-review-followup.md +++ b/docs/superpowers/plans/2026-09-25-review-followup.md @@ -228,7 +228,7 @@ W1·W2 잔여 21행(Wave 2.5)은 P14로 1라운드에서 함께 처리한다. W1 | P22 | 3 | Redis 구조 · startup rule | `G-4i` `G-6b` `G-7a` `G-7c` `G-7d` `G-7e` `G-8` `X1-지도-lock / lease / fencing` `S1-#15c` `S3-#3a` `S3-#3b` `S3-#4b` `S3-#5` `S3-#9` `S6-#2c` `S6-#3a` | | P23 | 3 | notification: SES → sesv2(결정 17), `persistence-notification` 추출, SRP | `S1-#4` `S1-#9` `S1-#10b` `S2-#1b` `S2-#6c` `S2-#8a` `S2-#13b` `S4-#3c` `S4-#4b` `S4-#9` `S4-#14b` `S4-#15` `S4-lead-3` `S4-lead-5` | | P27 | 3 | 빌드 잔여(결정 28·29·31): O3-5 나머지(`ca.release-provenance`·auxiliary → `jvm-test-suite`), messaging 카드 검증 leaf 테스트로, cosign 서명, `INTERNAL_ERROR` retryable=false, persistence-fileserver `ca.api-surface` | `BUILD-결론-1` `BUILD-O3-5` `X1-#7a` `X1-지도-readiness…` `BUILD-계획-C` `P15-new-3` `P16-new-6` | -| P28 | 3 | 로컬 보안 파일시스템 primitive 공용화(보안 민감 재작성, P24에서 분리) + fileserver 잔여 | `S4-lead-2` `P24-new-2` `P25-new-2` `P24-new-3` `S6-#10a` `S1-#6b` `S1-#18b`(결정 32) | +| P28 | 3 | 로컬 보안 파일시스템 primitive 공용화(보안 민감 재작성, P24에서 분리) + fileserver 잔여 | `S4-lead-2` `P24-new-2` `P25-new-2` `P24-new-3` `S6-#10a` `S1-#6b` `S1-#18b`(결정 32) `S2-#8a` `S2-#13b` `P23-new-1` `P23-new-2` | | P20 | 4 | 3-B 설정 prefix `app.*`(결정 16), strict 바인딩 | `X2-P1-3c` `S3-lead-2` `S3-lead-4` `S6-#14` `P11-new-1` | - [x] 라운드 1: P14 · P15 · P16 · P17 → 통합·검증·커밋 (2026-09-28, `9fdb0af4`·`c4a066df`·라운드 1 마무리 커밋) diff --git a/src/adapter/outbound/notification/build.gradle b/src/adapter/outbound/notification/build.gradle index 93381d14..48fc13e9 100644 --- a/src/adapter/outbound/notification/build.gradle +++ b/src/adapter/outbound/notification/build.gradle @@ -50,6 +50,22 @@ dependencies { exclude group: 'com.fasterxml.jackson.dataformat', module: 'jackson-dataformat-yaml' } + // Amazon SES through the AWS SDK v2 `sesv2` client (owner decision 17, review S4-lead-3). It + // replaced a hand-written JDK HTTP gateway and SigV4 signer. The version is the catalog's + // `awsSdk`, the same one object storage uses, imported as the SDK BOM below and stated on each + // artifact so a composition that takes this leaf with one line resolves it without repeating the + // platform. The sync client runs on the SDK's Apache client, which follows no redirects; the + // Netty async client sesv2 would otherwise bring along has no caller here. + implementation("software.amazon.awssdk:sesv2:${libs.versions.awsSdk.get()}") { + exclude group: 'software.amazon.awssdk', module: 'netty-nio-client' + } + implementation "software.amazon.awssdk:apache-client:${libs.versions.awsSdk.get()}" +} + +dependencyManagement { + imports { + mavenBom "software.amazon.awssdk:bom:${libs.versions.awsSdk.get()}" + } } // The exclusion above as something resolution enforces: this rule fails the build the moment any diff --git a/src/adapter/outbound/notification/gradle.lockfile b/src/adapter/outbound/notification/gradle.lockfile index 3bcf61c2..40a2db21 100644 --- a/src/adapter/outbound/notification/gradle.lockfile +++ b/src/adapter/outbound/notification/gradle.lockfile @@ -36,6 +36,7 @@ com.networknt:json-schema-validator:3.0.2=compileClasspath,runtimeClasspath,test com.puppycrawl.tools:checkstyle:13.5.0=checkstyle com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle +commons-codec:commons-codec:1.19.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle commons-io:commons-io:2.21.0=spotbugs commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -62,8 +63,8 @@ org.apache.bcel:bcel:6.12.0=spotbugs org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle -org.apache.httpcomponents:httpclient:4.5.13=checkstyle -org.apache.httpcomponents:httpcore:4.4.16=checkstyle +org.apache.httpcomponents:httpclient:4.5.13=checkstyle,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.httpcomponents:httpcore:4.4.16=checkstyle,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.apache.logging.log4j:log4j-api:2.25.5=compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath org.apache.logging.log4j:log4j-core:2.25.5=spotbugs org.apache.logging.log4j:log4j-to-slf4j:2.25.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -116,6 +117,7 @@ org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.reactivestreams:reactive-streams:1.0.4=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -164,6 +166,32 @@ org.unbescape:unbescape:1.1.6.RELEASE=compileClasspath,runtimeClasspath,testComp org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath org.yaml:snakeyaml:2.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:annotations:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:apache-client:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:auth:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:aws-core:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:aws-json-protocol:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:checksums-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:checksums:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:endpoints-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth-aws-eventstream:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth-aws:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:http-client-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:identity-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:json-utils:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:metrics-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:profiles:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:protocol-core:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:regions:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:retries-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:retries:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:sdk-core:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:sesv2:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:third-party-jackson-core:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:utils:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.eventstream:eventstream:1.0.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath tools.jackson.core:jackson-core:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath tools.jackson.core:jackson-databind:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath tools.jackson:jackson-bom:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/AssembledProvider.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/AssembledProvider.java index 6c0ba6fc..51912e7b 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/AssembledProvider.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/AssembledProvider.java @@ -3,7 +3,6 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapter; import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderRuntime; import dev.caskeleton.application.notification.platform.api.routing.Channel; -import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector; import dev.caskeleton.application.notification.platform.provider.ReconciliationCapability; import java.util.Objects; import java.util.Optional; @@ -11,26 +10,29 @@ import java.util.Optional; /** * One provider profile, assembled into everything the platform needs from it. * - *

The pieces used to be registered independently — a runtime here, a callback adapter there, a - * projector in a third list — and nothing checked that a profile had contributed all of the ones it - * needs. A callback-enabled profile with no callback adapter was a context that started and then - * failed on the first provider event, which is hours after the mistake was made and in a component - * that did not make it. + *

The pieces used to be registered independently — a runtime here, a callback adapter there — + * and nothing checked that a profile had contributed all of the ones it needs. A callback-enabled + * profile with no callback adapter was a context that started and then failed on the first provider + * event, which is hours after the mistake was made and in a component that did not make it. * *

Returning them together makes the incomplete contribution unrepresentable: an assembler either * produces a working profile or fails, and it fails at startup. * + *

There is no projector slot. Every provider's events obey the same projection table ({@code + * StandardDeliveryProjector}), so the projector is one bean rather than a per-profile contribution. + * + *

The shipped families, SES and SMTP, contribute no reconciliation: the slot is for a family an + * adopter assembles with a status query of its own. + * * @param runtime the dispatch runtime, bound to its credential generation * @param channel the channel this profile serves * @param callback the callback adapter, when the family has one - * @param projector the provider-event projector, when the family has one * @param reconciliation the status-query capability, when the family supports one */ public record AssembledProvider( ProviderRuntime runtime, Channel channel, Optional callback, - Optional projector, Optional reconciliation) { /** Validates the contribution. */ @@ -38,7 +40,6 @@ public record AssembledProvider( Objects.requireNonNull(runtime, "runtime"); Objects.requireNonNull(channel, "channel"); Objects.requireNonNull(callback, "callback"); - Objects.requireNonNull(projector, "projector"); Objects.requireNonNull(reconciliation, "reconciliation"); if (runtime.profile().channel() != channel) { throw new IllegalArgumentException( @@ -57,7 +58,6 @@ public record AssembledProvider( * @return the contribution */ public static AssembledProvider dispatchOnly(ProviderRuntime runtime, Channel channel) { - return new AssembledProvider( - runtime, channel, Optional.empty(), Optional.empty(), Optional.empty()); + return new AssembledProvider(runtime, channel, Optional.empty(), Optional.empty()); } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java index 9158a2d1..f583615e 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java @@ -1,19 +1,22 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpGateway; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpRequest; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SnsCertificateProvider; import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.time.Duration; -import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.function.Function; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; @@ -34,15 +37,63 @@ class NotificationCallbackProviderConfig { */ static final int MAX_CACHED_SNS_CERTIFICATES = 64; + /** How long a certificate fetch may take, connection included. */ + static final Duration SNS_CERTIFICATE_TIMEOUT = Duration.ofSeconds(3); + /** - * Default SNS certificate source, using the same bounded, no-redirect HTTP gateway as providers. + * The largest certificate document read. A PEM certificate is a few kilobytes; the cap keeps a + * misbehaving host from choosing how much of the heap a callback costs. + */ + static final int MAX_SNS_CERTIFICATE_BYTES = 65_536; + + /** + * Default SNS certificate source: a bounded, no-redirect fetch, cached. * - *

The fetch happens outside the map. It used to run inside {@code computeIfAbsent}, which - * holds a lock across the network call, and the cache had no bound on URLs a caller supplies. + *

The URL has already passed {@code SnsSignatureVerifier}'s host check ({@code + * sns..amazonaws.com} over HTTPS) before it reaches this fetch. */ @Bean @ConditionalOnMissingBean - public SnsCertificateProvider snsCertificateProvider(NotificationHttpGateway gateway) { + public SnsCertificateProvider snsCertificateProvider() { + HttpClient client = + HttpClient.newBuilder() + .followRedirects(HttpClient.Redirect.NEVER) + .connectTimeout(SNS_CERTIFICATE_TIMEOUT) + .build(); + return cachingCertificates(uri -> fetchCertificate(client, uri)); + } + + private static byte[] fetchCertificate(HttpClient client, URI uri) { + HttpRequest request = + HttpRequest.newBuilder(uri).timeout(SNS_CERTIFICATE_TIMEOUT).GET().build(); + try { + HttpResponse response = + client.send(request, HttpResponse.BodyHandlers.ofInputStream()); + try (InputStream body = response.body()) { + if (response.statusCode() / 100 != 2) { + throw new IllegalStateException( + "SNS signing certificate fetch failed with HTTP " + response.statusCode()); + } + return body.readNBytes(MAX_SNS_CERTIFICATE_BYTES); + } + } catch (IOException unreachable) { + throw new IllegalStateException("SNS signing certificate could not be fetched", unreachable); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("SNS signing certificate fetch was interrupted", interrupted); + } + } + + /** + * The certificate cache over a fetch. + * + *

The fetch happens outside the map. It used to run inside {@code computeIfAbsent}, which + * holds a lock across the network call, and the cache had no bound on URLs a caller supplies. + * + * @param fetch the raw certificate document at a URL + * @return the cached, subject-checked provider + */ + static SnsCertificateProvider cachingCertificates(Function fetch) { return new SnsCertificateProvider() { private final ConcurrentMap cache = new ConcurrentHashMap<>(); @@ -63,20 +114,13 @@ class NotificationCallbackProviderConfig { } private PublicKey fetch(URI uri) { - var response = - gateway.exchange( - new NotificationHttpRequest( - "GET", uri, Map.of(), new byte[0], Duration.ofSeconds(3))); - if (!response.isSuccessful()) { - throw new IllegalStateException( - "SNS signing certificate fetch failed with HTTP " + response.statusCode()); - } + byte[] document = fetch.apply(uri); X509Certificate certificate; try { certificate = (X509Certificate) CertificateFactory.getInstance("X.509") - .generateCertificate(new ByteArrayInputStream(response.body())); + .generateCertificate(new ByteArrayInputStream(document)); certificate.checkValidity(); } catch (CertificateException malformed) { throw new IllegalArgumentException( diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfig.java index d9e9efff..10045300 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfig.java @@ -1,7 +1,5 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.JdkNotificationHttpGateway; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpGateway; import dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmContactPointProtector; import dev.caskeleton.adapter.outbound.notification.platform.template.JacksonNotificationVariablesCodec; import dev.caskeleton.adapter.outbound.notification.platform.template.JsonSchemaVariableValidator; @@ -13,7 +11,6 @@ import dev.caskeleton.application.notification.platform.dispatch.NotificationVar import dev.caskeleton.application.notification.platform.security.ContactPointProtector; import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider; import dev.caskeleton.application.notification.platform.template.TemplateVariableValidator; -import java.time.Duration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -92,16 +89,4 @@ class NotificationPlatformCoreConfig { public ContactPointProtector notificationContactPointProtector(SecretMaterialProvider secrets) { return new AesGcmContactPointProtector(secrets); } - - /** - * Default provider transport. - * - *

Replaced in the composition root when the HTTP Client Platform is bound, which is the - * supported way to reuse its TLS, circuit-breaker and SSRF policy. - */ - @Bean - @ConditionalOnMissingBean - public NotificationHttpGateway notificationHttpGateway() { - return new JdkNotificationHttpGateway(Duration.ofSeconds(2)); - } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformProviderConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformProviderConfig.java index 83d384ab..fe86317a 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformProviderConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformProviderConfig.java @@ -2,20 +2,15 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; import dev.caskeleton.adapter.outbound.notification.platform.dispatch.CapabilityReconciliationGateway; import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ConfiguredProfileCatalog; -import dev.caskeleton.adapter.outbound.notification.platform.dispatch.MapTemplateRendererRegistry; import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderRuntimeRegistry; import dev.caskeleton.adapter.outbound.notification.platform.dispatch.RegistryProviderDispatchGateway; import dev.caskeleton.adapter.outbound.notification.platform.template.CanonicalNotificationRenderer; import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationTemplateEngine; -import dev.caskeleton.adapter.outbound.notification.platform.template.ThymeleafNotificationRenderer; -import dev.caskeleton.adapter.outbound.notification.platform.template.ThymeleafStringTemplateEngine; -import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.dispatch.AttachmentIntegrityGuard; import dev.caskeleton.application.notification.platform.dispatch.NotificationRoutePlannerPort; import dev.caskeleton.application.notification.platform.dispatch.PolicyRoutePlanner; import dev.caskeleton.application.notification.platform.dispatch.ProviderDispatchGatewayPort; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort; -import dev.caskeleton.application.notification.platform.dispatch.TemplateRendererRegistry; import dev.caskeleton.application.notification.platform.provider.AttachmentResolver; import dev.caskeleton.application.notification.platform.template.NotificationTemplateRenderer; import dev.caskeleton.application.notification.platform.template.TemplateRegistry; @@ -46,35 +41,20 @@ import org.springframework.context.annotation.Configuration; class NotificationPlatformProviderConfig { /** - * Channel renderers built on the configured engine and the shared validator. + * The renderer every channel uses, on the configured engine and the shared validator. * *

Every channel gets the same engine on purpose. Rendering the email body with one engine and * the push body with another would mean two escaping policies for the same variable, and the * content digest — which a retry uses to prove it sent the same thing — would depend on which - * channel rendered it. + * channel rendered it. So there is one renderer, not one per channel behind a lookup. */ @Bean - public TemplateRendererRegistry notificationTemplateRendererRegistry( + @ConditionalOnMissingBean + public NotificationTemplateRenderer notificationTemplateRenderer( TemplateRegistry templates, TemplateVariableValidator validator, NotificationTemplateEngine engine) { - List renderers = - List.of(Channel.values()).stream() - .map(channel -> renderer(channel, templates, validator, engine)) - .toList(); - return new MapTemplateRendererRegistry(renderers); - } - - private static NotificationTemplateRenderer renderer( - Channel channel, - TemplateRegistry templates, - TemplateVariableValidator validator, - NotificationTemplateEngine engine) { - // Named types rather than one generic renderer, so a stack trace and a bean name say which - // engine actually produced the content. - return engine instanceof ThymeleafStringTemplateEngine thymeleaf - ? new ThymeleafNotificationRenderer(channel, templates, validator, thymeleaf) - : new CanonicalNotificationRenderer(channel, templates, validator, engine); + return new CanonicalNotificationRenderer(templates, validator, engine); } /** @@ -115,8 +95,8 @@ class NotificationPlatformProviderConfig { @Bean @ConditionalOnMissingBean public NotificationProviderAssembly.AssembledPlatform assembledNotificationPlatform( - java.util.List assemblers, - java.util.List callbackAssemblers, + List assemblers, + List callbackAssemblers, NotificationPlatformSettings settings) { // The persistence facade already refuses to start until the notification schema stream is // applied and promoted, and it declares that bean before its stores. Duplicating the gate here diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformRegistriesConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformRegistriesConfig.java index 522ff886..229aaeef 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformRegistriesConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformRegistriesConfig.java @@ -2,15 +2,11 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackLimits; import dev.caskeleton.adapter.outbound.notification.platform.callback.MapProviderCallbackAdapterRegistry; -import dev.caskeleton.adapter.outbound.notification.platform.callback.MapProviderEventProjectorRegistry; import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapterRegistry; -import dev.caskeleton.application.notification.platform.api.ProviderId; import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector; -import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectorRegistry; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import dev.caskeleton.application.notification.platform.callback.StandardDeliveryProjector; import java.util.Set; +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; @@ -32,23 +28,15 @@ import org.springframework.context.annotation.Configuration; class NotificationPlatformRegistriesConfig { /** - * Projector lookup by provider family. + * The projection rules every provider's events obey. * - *

Built from what assembly produced, which is where a family's projector comes from; a - * projector bean a deployment declares itself is added on top and wins for its family. Built from - * the bean list alone it was always empty, because nothing declared one. + *

One bean, not a lookup by provider family: every family's projector was the same table under + * a different id. A deployment that needs different rules declares its own bean. */ @Bean - public ProviderEventProjectorRegistry providerEventProjectorRegistry( - NotificationProviderAssembly.AssembledPlatform platform, - List projectors) { - Map byProvider = new HashMap<>(); - platform - .projectors() - .values() - .forEach(projector -> byProvider.put(projector.providerId(), projector)); - projectors.forEach(projector -> byProvider.put(projector.providerId(), projector)); - return new MapProviderEventProjectorRegistry(byProvider); + @ConditionalOnMissingBean + public ProviderEventProjector providerEventProjector() { + return new StandardDeliveryProjector(); } /** Callback adapter lookup by configured profile. */ diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettings.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettings.java index 9a67f429..f9e2014d 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettings.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettings.java @@ -219,34 +219,14 @@ public record NotificationPlatformSettings( int ratePerSecond, Ses ses) { - @ConstructorBinding - public Provider {} - /** - * Constructor for families that do not need a typed family block. + * Binds one profile. {@code ses} is null for every family but SES. * - *

Keeping this overload means SMTP profiles do not carry a meaningless SES argument. + *

One constructor: a second, shorter overload existed only so tests could leave out the SES + * block, and a binder that sees two constructors needs an annotation to know which one it may + * use. */ - public Provider( - String type, - boolean enabled, - boolean primaryForChannel, - String environment, - String credentialProfile, - Duration timeout, - int maxConcurrency, - int ratePerSecond) { - this( - type, - enabled, - primaryForChannel, - environment, - credentialProfile, - timeout, - maxConcurrency, - ratePerSecond, - null); - } + public Provider {} /** * Fail the boot when a profile cannot possibly work. diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssembly.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssembly.java index 725caa42..5d57a7c6 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssembly.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssembly.java @@ -4,7 +4,6 @@ import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCa import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderRuntimeRegistry; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; import dev.caskeleton.application.notification.platform.api.routing.Channel; -import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector; import dev.caskeleton.application.notification.platform.provider.ReconciliationCapability; import java.util.ArrayList; import java.util.EnumMap; @@ -110,7 +109,6 @@ public final class NotificationProviderAssembly { ProviderRuntimeRegistry runtimes = new ProviderRuntimeRegistry(); Map routes = new EnumMap<>(Channel.class); Map callbacks = new LinkedHashMap<>(); - Map projectors = new LinkedHashMap<>(); Map reconciliations = new LinkedHashMap<>(); Map> claimants = new EnumMap<>(Channel.class); @@ -128,12 +126,6 @@ public final class NotificationProviderAssembly { settings.callbacks().enabled() && callbackAssembler != null ? callbackAssembler.assemble(profileId, profile) : null; - if (callback != null) { - // With the callback, in both modes: an INGEST_ONLY deployment still projects the events it - // accepts onto the deliveries an earlier serving deployment made. - projectors.put(id, callbackAssembler.projector()); - } - // INGEST_ONLY is deliberately callback-capable without being dispatch-capable. Building a // runtime or a route here would make an ingest-only deployment able to send merely because a // provider transport happened to be present on the classpath. @@ -177,7 +169,6 @@ public final class NotificationProviderAssembly { callbacks.put(id, callback); } }); - assembled.projector().ifPresent(projector -> projectors.put(id, projector)); assembled.reconciliation().ifPresent(capability -> reconciliations.put(id, capability)); } @@ -185,12 +176,7 @@ public final class NotificationProviderAssembly { refuseEmptyPlatform(routes, mode); return new AssembledPlatform( - runtimes, - Map.copyOf(routes), - Map.copyOf(callbacks), - Map.copyOf(projectors), - Map.copyOf(reconciliations), - mode); + runtimes, Map.copyOf(routes), Map.copyOf(callbacks), Map.copyOf(reconciliations), mode); } private static String missingAssemblerMessage(String profileId, ProviderType type) { @@ -264,7 +250,6 @@ public final class NotificationProviderAssembly { * @param runtimes the registry the dispatch gateway routes through * @param routes the channel-to-profile map the route planner uses * @param callbacks callback adapters by profile - * @param projectors provider-event projectors by profile * @param reconciliations status-query capabilities by profile * @param mode whether this deployment can deliver */ @@ -272,7 +257,6 @@ public final class NotificationProviderAssembly { ProviderRuntimeRegistry runtimes, Map routes, Map callbacks, - Map projectors, Map reconciliations, NotificationPlatformMode mode) { @@ -281,7 +265,6 @@ public final class NotificationProviderAssembly { Objects.requireNonNull(runtimes, "runtimes"); routes = Map.copyOf(Objects.requireNonNull(routes, "routes")); callbacks = Map.copyOf(Objects.requireNonNull(callbacks, "callbacks")); - projectors = Map.copyOf(Objects.requireNonNull(projectors, "projectors")); reconciliations = Map.copyOf(Objects.requireNonNull(reconciliations, "reconciliations")); Objects.requireNonNull(mode, "mode"); } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSesProviderConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSesProviderConfig.java index 10714471..b7295bbe 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSesProviderConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSesProviderConfig.java @@ -1,6 +1,5 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpGateway; import dev.caskeleton.adapter.outbound.notification.platform.security.ProviderCredentialManager; import dev.caskeleton.application.notification.platform.dispatch.AttachmentIntegrityGuard; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; @@ -16,11 +15,10 @@ class NotificationSesProviderConfig { @Bean @ConditionalOnMissingBean(name = "sesProviderRuntimeAssembler") public ProviderRuntimeAssembler sesProviderRuntimeAssembler( - NotificationHttpGateway gateway, AttachmentIntegrityGuard attachmentGuard, ContactPointProtector protector, ProviderCredentialManager credentials, Clock clock) { - return new SesProviderRuntimeAssembler(gateway, attachmentGuard, protector, credentials, clock); + return new SesProviderRuntimeAssembler(attachmentGuard, protector, credentials, clock); } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/ProviderCallbackAssembler.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/ProviderCallbackAssembler.java index 00fba3ac..f5f05f4b 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/ProviderCallbackAssembler.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/ProviderCallbackAssembler.java @@ -1,7 +1,6 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapter; -import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector; /** * Builds the callback verifier for one configured provider profile. @@ -24,15 +23,4 @@ interface ProviderCallbackAssembler { * @return the profile-specific verifier */ ProviderCallbackAdapter assemble(String profileId, NotificationPlatformSettings.Provider profile); - - /** - * How this family's verified events move a delivery's projection. - * - *

Required of every callback-capable family. The SES callback was assembled with no projector - * anywhere, so every event it accepted was stored and then marked failed with {@code - * NO_PROJECTOR}: verified bounces and complaints that never reached a delivery. - * - * @return the family's projector - */ - ProviderEventProjector projector(); } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderCallbackAssembler.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderCallbackAssembler.java index 1aadd738..25cb4acf 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderCallbackAssembler.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderCallbackAssembler.java @@ -2,11 +2,9 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapter; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesCallbackAdapter; -import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesDeliveryProjector; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesEventNormalizer; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SnsCertificateProvider; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SnsSignatureVerifier; -import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector; import java.time.Duration; import java.util.Objects; import java.util.Set; @@ -29,11 +27,6 @@ final class SesProviderCallbackAssembler implements ProviderCallbackAssembler { return ProviderType.SES; } - @Override - public ProviderEventProjector projector() { - return new SesDeliveryProjector(); - } - @Override public ProviderCallbackAdapter assemble( String profileId, NotificationPlatformSettings.Provider profile) { diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderRuntimeAssembler.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderRuntimeAssembler.java index 9d5453e5..312dc22f 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderRuntimeAssembler.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderRuntimeAssembler.java @@ -2,8 +2,7 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderAttemptLimiter; import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderRuntime; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpGateway; -import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.AwsSignatureV4Signer; +import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesClients; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesFailureClassifier; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesNotificationProviderAdapter; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesProviderProperties; @@ -27,19 +26,16 @@ import java.util.Properties; /** Turns a configured SES profile into a dispatchable runtime. */ final class SesProviderRuntimeAssembler implements ProviderRuntimeAssembler { - private final NotificationHttpGateway gateway; private final AttachmentIntegrityGuard attachmentGuard; private final ContactPointProtector protector; private final ProviderCredentialManager credentials; private final Clock clock; public SesProviderRuntimeAssembler( - NotificationHttpGateway gateway, AttachmentIntegrityGuard attachmentGuard, ContactPointProtector protector, ProviderCredentialManager credentials, Clock clock) { - this.gateway = Objects.requireNonNull(gateway, "gateway"); this.attachmentGuard = Objects.requireNonNull(attachmentGuard, "attachmentGuard"); this.protector = Objects.requireNonNull(protector, "protector"); this.credentials = Objects.requireNonNull(credentials, "credentials"); @@ -71,19 +67,16 @@ final class SesProviderRuntimeAssembler implements ProviderRuntimeAssembler { profile.timeout()); SesRequestMapper mapper = new SesRequestMapper( - properties, - new AwsSignatureV4Signer(), - new SmtpMimeMessageFactory(Session.getInstance(new Properties()))); + properties, new SmtpMimeMessageFactory(Session.getInstance(new Properties()))); SesNotificationProviderAdapter adapter = new SesNotificationProviderAdapter( - gateway, + SesClients.create(properties), mapper, attachmentGuard, new SesFailureClassifier(), protector, credentials, - ses.accessKeyId(), - clock); + ses.accessKeyId()); ProviderProfileSnapshot snapshot = new ProviderProfileSnapshot( diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/MapProviderEventProjectorRegistry.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/MapProviderEventProjectorRegistry.java deleted file mode 100644 index 09be9bb4..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/MapProviderEventProjectorRegistry.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.callback; - -import dev.caskeleton.application.notification.platform.api.ProviderId; -import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector; -import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectorRegistry; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * Provider-to-projector lookup over a map fixed at assembly time. - * - *

Moved out of the composition root alongside {@link MapProviderCallbackAdapterRegistry} - * (BOOT-017). It was a lambda there rather than an anonymous class, which is why the ArchUnit rule - * that caught its sibling could not see it — a lambda implementing an interface leaves no class for - * the rule to inspect. Leaving it behind would have meant the boundary held only where a tool - * happened to be able to check it, which is a worse state than not having the rule: the code would - * look compliant and be inconsistent. - */ -public final class MapProviderEventProjectorRegistry implements ProviderEventProjectorRegistry { - - private final Map byProvider; - - /** - * Creates the registry. - * - * @param byProvider the projectors this deployment declared, copied defensively - */ - public MapProviderEventProjectorRegistry(Map byProvider) { - this.byProvider = Map.copyOf(Objects.requireNonNull(byProvider, "byProvider")); - } - - @Override - public Optional find(ProviderId providerId) { - return Optional.ofNullable(byProvider.get(providerId)); - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/CredentialProbe.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/CredentialProbe.java deleted file mode 100644 index b41729af..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/CredentialProbe.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.dispatch; - -/** Verifies a candidate generation before it becomes the current one. */ -@FunctionalInterface -public interface CredentialProbe { - - /** Return false when the candidate credential is not usable. */ - boolean isUsable(ProviderRuntime candidate); -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/CredentialValidationException.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/CredentialValidationException.java deleted file mode 100644 index 20c658fd..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/CredentialValidationException.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.dispatch; - -import dev.caskeleton.application.notification.platform.api.error.FailureCategory; -import dev.caskeleton.application.notification.platform.api.error.NotificationException; -import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; -import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor; - -/** Raised when a candidate credential generation fails its probe before any cutover. */ -public class CredentialValidationException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public CredentialValidationException() { - super( - NotificationFailureDescriptor.preDispatch( - NotificationFailureCode.PROVIDER_CONFIGURATION_INVALID, - FailureCategory.AUTHENTICATION)); - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/MapTemplateRendererRegistry.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/MapTemplateRendererRegistry.java deleted file mode 100644 index b2e3d8db..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/MapTemplateRendererRegistry.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.dispatch; - -import dev.caskeleton.application.notification.platform.api.routing.Channel; -import dev.caskeleton.application.notification.platform.dispatch.TemplateRendererRegistry; -import dev.caskeleton.application.notification.platform.template.NotificationTemplateRenderer; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** Channel-to-renderer lookup built at wiring time. */ -public final class MapTemplateRendererRegistry implements TemplateRendererRegistry { - - private final Map renderers; - - public MapTemplateRendererRegistry(List renderers) { - Objects.requireNonNull(renderers, "renderers"); - Map byChannel = new EnumMap<>(Channel.class); - renderers.forEach(renderer -> byChannel.put(renderer.channel(), renderer)); - this.renderers = Map.copyOf(byChannel); - } - - @Override - public NotificationTemplateRenderer rendererFor(Channel channel) { - NotificationTemplateRenderer renderer = renderers.get(channel); - if (renderer == null) { - throw new IllegalStateException("no renderer registered for the channel"); - } - return renderer; - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntime.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntime.java index a007aa24..9097e61b 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntime.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntime.java @@ -7,8 +7,13 @@ import dev.caskeleton.application.notification.platform.api.error.ProviderUnavai import dev.caskeleton.application.notification.platform.provider.NotificationProviderAdapter; import dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot; import dev.caskeleton.application.notification.platform.provider.ProviderRuntimeState; +import java.util.Collections; +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.concurrent.atomic.AtomicReference; /** @@ -131,7 +136,7 @@ public final class ProviderRuntime { */ public boolean markAuthenticationFailed(String reasonCode) { Objects.requireNonNull(reasonCode, "reasonCode"); - return moveTo(ProviderRuntimeState.AUTHENTICATION_FAILED, Optional.of(reasonCode)); + return apply(Transition.FAIL_AUTHENTICATION, Optional.of(reasonCode)); } /** @@ -140,15 +145,7 @@ public final class ProviderRuntime { * @return whether it is now throttled */ public boolean markThrottled() { - return health - .updateAndGet( - current -> - current.state() == ProviderRuntimeState.HEALTHY - ? new RuntimeHealth( - ProviderRuntimeState.THROTTLED, Optional.of("THROTTLED")) - : current) - .state() - == ProviderRuntimeState.THROTTLED; + return apply(Transition.THROTTLE, Optional.of("THROTTLED")); } /** @@ -158,55 +155,30 @@ public final class ProviderRuntime { */ public boolean markDegraded(String reasonCode) { Objects.requireNonNull(reasonCode, "reasonCode"); - return health - .updateAndGet( - current -> - current.state() == ProviderRuntimeState.HEALTHY - ? new RuntimeHealth(ProviderRuntimeState.DEGRADED, Optional.of(reasonCode)) - : current) - .state() - == ProviderRuntimeState.DEGRADED; + return apply(Transition.DEGRADE, Optional.of(reasonCode)); } /** * Return to healthy after a successful attempt. * - *

A success clears throttling and degradation and nothing else. It does not clear an - * authentication failure — the credential the provider rejected is still the credential in use, - * and only a rotation replaces it. It does not resume a draining or disabled runtime either; - * those states are decisions, not symptoms. - * - *

The reason is cleared only when the state actually changes. Clearing it unconditionally left - * {@code AUTHENTICATION_FAILED} with no reason attached, so an operator reading the runtime was - * shown a failure the platform could no longer explain. + *

A success clears throttling and degradation and nothing else; see {@link + * Transition#RECOVER}. * * @return whether the runtime is now healthy */ public boolean markHealthy() { - return health - .updateAndGet( - current -> - switch (current.state()) { - case THROTTLED, DEGRADED -> - new RuntimeHealth(ProviderRuntimeState.HEALTHY, Optional.empty()); - default -> current; - }) - .state() - == ProviderRuntimeState.HEALTHY; + return apply(Transition.RECOVER, Optional.empty()); } /** * Clear an operator-imposed state. * - *

This is the admin counterpart of {@link #markHealthy()}: it resumes a runtime that an - * operator drained or disabled. It still refuses {@code AUTHENTICATION_FAILED}, because declaring - * a provider healthy does not give it a credential the provider will accept — the caller is told - * so rather than being handed a runtime that will fail on its first attempt. + *

This is the admin counterpart of {@link #markHealthy()}; see {@link Transition#RESUME}. * * @return whether the runtime is now healthy */ public boolean resumeHealthy() { - return moveTo(ProviderRuntimeState.HEALTHY, Optional.empty()); + return apply(Transition.RESUME, Optional.empty()); } /** @@ -215,7 +187,7 @@ public final class ProviderRuntime { * @return whether it is now draining; an authentication failure is kept */ public boolean markDraining() { - return moveTo(ProviderRuntimeState.DRAINING, Optional.of("DRAINING")); + return apply(Transition.DRAIN, Optional.of("DRAINING")); } /** @@ -224,34 +196,88 @@ public final class ProviderRuntime { * @return whether it is now disabled; an authentication failure is kept */ public boolean markDisabled() { - return moveTo(ProviderRuntimeState.DISABLED, Optional.of("DISABLED")); + return apply(Transition.DISABLE, Optional.of("DISABLED")); } /** - * The transition rule between an authentication failure and the operator states, in one place. + * Every transition a runtime makes, with the states it may start from, in one table. * - *

{@code AUTHENTICATION_FAILED} is left only by rotation, which replaces the whole runtime: an - * operator disable or drain on top of it used to overwrite it, and a later resume then declared - * the rejected credential healthy. An operator's {@code DISABLED} or {@code DRAINING} is a - * decision a late authentication failure from an in-flight attempt does not overwrite. + *

The rules used to live in seven methods, each with its own {@code updateAndGet} condition, + * and reading "what can leave {@code AUTHENTICATION_FAILED}" meant reading all seven. The table + * is keyed by transition rather than by target state because {@code HEALTHY} is reached two ways + * with different sources: a successful attempt clears only the symptoms it disproves, while an + * operator's resume also clears the operator states. + * + *

The rules the table states: + * + *

    + *
  • {@code AUTHENTICATION_FAILED} is left by nothing here — only rotation, which replaces the + * whole runtime. An operator disable or drain on top of it used to overwrite it, and a + * later resume then declared the rejected credential healthy. + *
  • An operator's {@code DISABLED} or {@code DRAINING} is a decision; a late provider signal + * from an attempt already in flight does not overwrite it. + *
  • A success does not resume a draining or disabled runtime, and does not clear an + * authentication failure: the credential the provider rejected is still the one in use. + *
*/ - private boolean moveTo(ProviderRuntimeState target, Optional reason) { + private enum Transition { + THROTTLE(ProviderRuntimeState.THROTTLED), + DEGRADE(ProviderRuntimeState.DEGRADED), + RECOVER(ProviderRuntimeState.HEALTHY), + FAIL_AUTHENTICATION(ProviderRuntimeState.AUTHENTICATION_FAILED), + RESUME(ProviderRuntimeState.HEALTHY), + DRAIN(ProviderRuntimeState.DRAINING), + DISABLE(ProviderRuntimeState.DISABLED); + + private final ProviderRuntimeState target; + + Transition(ProviderRuntimeState target) { + this.target = target; + } + } + + /** The table: the states each transition may start from. Read-only after class init. */ + private static final Map> SOURCES = sources(); + + private static Map> sources() { + Set exceptAuthenticationFailed = + Collections.unmodifiableSet( + EnumSet.complementOf(EnumSet.of(ProviderRuntimeState.AUTHENTICATION_FAILED))); + Map> table = new EnumMap<>(Transition.class); + table.put(Transition.THROTTLE, Set.of(ProviderRuntimeState.HEALTHY)); + table.put(Transition.DEGRADE, Set.of(ProviderRuntimeState.HEALTHY)); + table.put( + Transition.RECOVER, Set.of(ProviderRuntimeState.THROTTLED, ProviderRuntimeState.DEGRADED)); + table.put( + Transition.FAIL_AUTHENTICATION, + Set.of( + ProviderRuntimeState.HEALTHY, + ProviderRuntimeState.THROTTLED, + ProviderRuntimeState.DEGRADED)); + table.put(Transition.RESUME, exceptAuthenticationFailed); + table.put(Transition.DRAIN, exceptAuthenticationFailed); + table.put(Transition.DISABLE, exceptAuthenticationFailed); + return Collections.unmodifiableMap(table); + } + + /** + * Applies one transition, or keeps the current health when the table does not allow it. + * + *

Being in the target state already is not a change: the health, and the reason it carries, + * are kept. One write, so the state and the reason it carries are never observed apart. + * + * @return whether the runtime is now in the transition's target state + */ + private boolean apply(Transition transition, Optional reason) { return health .updateAndGet( - current -> { - ProviderRuntimeState from = current.state(); - boolean operatorState = - from == ProviderRuntimeState.DISABLED - || from == ProviderRuntimeState.DRAINING; - boolean kept = - target == ProviderRuntimeState.AUTHENTICATION_FAILED - ? operatorState - : from == ProviderRuntimeState.AUTHENTICATION_FAILED; - // One write, so the state and the reason it carries are never observed apart. - return kept ? current : new RuntimeHealth(target, reason); - }) + current -> + SOURCES.get(transition).contains(current.state()) + && current.state() != transition.target + ? new RuntimeHealth(transition.target, reason) + : current) .state() - == target; + == transition.target; } /** diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRotator.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRotator.java deleted file mode 100644 index c9cd5ec3..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRotator.java +++ /dev/null @@ -1,69 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.dispatch; - -import dev.caskeleton.application.notification.platform.api.ProviderProfileId; -import dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent; -import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort; -import java.time.Clock; -import java.time.Duration; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * Credential and certificate rotation. - * - *

The candidate is probed before the swap. Validating after cutover would mean a typo - * in a rotated secret takes the provider down and only then tells anyone; validating first makes a - * bad candidate a no-op that leaves the working generation in place. - * - *

Only the generation and key id reach the audit trail — never the credential material itself. - */ -public final class ProviderRuntimeRotator { - - private final ProviderRuntimeRegistry registry; - private final CredentialProbe probe; - private final RuntimeDrainCoordinator drainCoordinator; - private final NotificationAuditPort audit; - private final Clock clock; - private final Duration drainTimeout; - - public ProviderRuntimeRotator( - ProviderRuntimeRegistry registry, - CredentialProbe probe, - RuntimeDrainCoordinator drainCoordinator, - NotificationAuditPort audit, - Clock clock, - Duration drainTimeout) { - this.registry = Objects.requireNonNull(registry, "registry"); - this.probe = Objects.requireNonNull(probe, "probe"); - this.drainCoordinator = Objects.requireNonNull(drainCoordinator, "drainCoordinator"); - this.audit = Objects.requireNonNull(audit, "audit"); - this.clock = Objects.requireNonNull(clock, "clock"); - this.drainTimeout = Objects.requireNonNull(drainTimeout, "drainTimeout"); - } - - /** Cut over to a new credential generation. */ - public void rotate(ProviderProfileId profileId, ProviderRuntime candidate) { - Objects.requireNonNull(profileId, "profileId"); - Objects.requireNonNull(candidate, "candidate"); - if (!candidate.profile().profileId().equals(profileId)) { - throw new IllegalArgumentException("candidate belongs to a different profile"); - } - if (!probe.isUsable(candidate)) { - throw new CredentialValidationException(); - } - - Optional previous = registry.replace(candidate); - audit.record( - new NotificationAuditEvent( - "PROVIDER_CREDENTIAL_ROTATION", - "system", - Optional.of("ROTATION"), - Optional.empty(), - clock.instant(), - Map.of( - "providerProfile", profileId.value(), - "generation", Long.toString(candidate.generation())))); - previous.ifPresent(runtime -> drainCoordinator.drain(runtime, drainTimeout)); - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/RuntimeDrainCoordinator.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/RuntimeDrainCoordinator.java deleted file mode 100644 index 8db03d07..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/RuntimeDrainCoordinator.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.dispatch; - -import java.time.Duration; -import java.util.Objects; - -/** - * Waits for a replaced generation to finish its in-flight attempts. - * - *

The deadline comes from {@link System#nanoTime()}, not from the injectable clock. A drain - * timeout is a real elapsed-time budget: driving it from a test clock that never advances turns the - * loop into a hang, and driving it from a wall clock makes it sensitive to time adjustments. - * - *

Draining is bounded on purpose. A provider that never answers must not hold a credential - * rotation open forever, so after the timeout the generation is abandoned and its attempts follow - * the normal ambiguity and reconciliation path rather than being cancelled mid-flight. - */ -public final class RuntimeDrainCoordinator { - - private final Duration pollInterval; - - public RuntimeDrainCoordinator(Duration pollInterval) { - this.pollInterval = Objects.requireNonNull(pollInterval, "pollInterval"); - if (pollInterval.isNegative() || pollInterval.isZero()) { - throw new IllegalArgumentException("pollInterval"); - } - } - - /** Drain a generation, returning whether it finished within the timeout. */ - public boolean drain(ProviderRuntime runtime, Duration timeout) { - Objects.requireNonNull(runtime, "runtime"); - Objects.requireNonNull(timeout, "timeout"); - long deadlineNanos = System.nanoTime() + timeout.toNanos(); - while (runtime.activeAttempts() > 0) { - if (System.nanoTime() - deadlineNanos >= 0) { - return false; - } - try { - Thread.sleep(pollInterval.toMillis()); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return false; - } - } - return true; - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationEndpoints.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/NotificationEndpoints.java similarity index 99% rename from src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationEndpoints.java rename to src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/NotificationEndpoints.java index 4be0ec29..c29eb1e3 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationEndpoints.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/NotificationEndpoints.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.notification.platform.provider.http; +package dev.caskeleton.adapter.outbound.notification.platform.provider; import java.net.URI; import java.util.Locale; diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ProviderResults.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ProviderResults.java index 3536d27b..7dd0eae6 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ProviderResults.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ProviderResults.java @@ -1,6 +1,5 @@ package dev.caskeleton.adapter.outbound.notification.platform.provider; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpTransportException; import dev.caskeleton.application.notification.platform.api.error.FailureCategory; import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; import dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence; @@ -10,27 +9,33 @@ import java.time.Duration; import java.util.Optional; /** - * Shared translation from a transport failure into an evidence-carrying result. + * Translation from a provider's transport failure or status code into an evidence-carrying result. * - *

Every HTTP provider adapter routes its transport failures through here, so the rule that - * "committed body plus no response equals ambiguous" is written once rather than re-derived per - * provider. + *

The rule that "committed body plus no response equals ambiguous" is written once here rather + * than re-derived per provider. */ public final class ProviderResults { private ProviderResults() {} - /** Classify a transport failure. */ + /** + * Classify a transport failure. + * + * @param reasonCode a short machine code for the failure, never its message + * @param requestBodyCommitted whether the request may have reached the provider + * @param elapsed how long the call ran + * @return ambiguous when the body may have been sent, not-submitted otherwise + */ public static ProviderSubmissionResult fromTransport( - NotificationHttpTransportException failure, Duration elapsed) { - if (failure.requestBodyCommitted()) { + String reasonCode, boolean requestBodyCommitted, Duration elapsed) { + if (requestBodyCommitted) { return ProviderSubmissionResult.ambiguous( new ProviderFailure( NotificationFailureCode.PROVIDER_RESPONSE_LOST, FailureCategory.AMBIGUOUS_SUBMISSION, false, Optional.empty(), - Optional.of(failure.reasonCode())), + Optional.of(reasonCode)), ProviderExecutionEvidence.responseLost(), elapsed); } @@ -40,7 +45,7 @@ public final class ProviderResults { FailureCategory.TRANSIENT_PROVIDER, true, Optional.empty(), - Optional.of(failure.reasonCode())), + Optional.of(reasonCode)), elapsed); } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/JdkNotificationHttpGateway.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/JdkNotificationHttpGateway.java deleted file mode 100644 index e6ee65fd..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/JdkNotificationHttpGateway.java +++ /dev/null @@ -1,216 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.provider.http; - -import java.io.IOException; -import java.io.InputStream; -import java.io.UncheckedIOException; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.net.http.HttpTimeoutException; -import java.time.Duration; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Default gateway on the JDK HTTP client. - * - *

Redirects are never followed. A provider redirect would move a signed, credential-bearing - * request to a host the profile never approved. - * - *

Timeout and connection-reset failures are translated into an explicit statement about whether - * the body was committed, because that single bit is what separates a safe retry from a duplicate. - */ -public final class JdkNotificationHttpGateway implements NotificationHttpGateway { - - // Restricted headers the JDK client refuses to let a caller set. - private static final Set RESTRICTED = - Set.of("connection", "content-length", "expect", "host", "upgrade"); - - private final HttpClient client; - private final boolean allowLoopback; - - public JdkNotificationHttpGateway(Duration connectTimeout) { - this(connectTimeout, false); - } - - public JdkNotificationHttpGateway(Duration connectTimeout, boolean allowLoopback) { - this( - HttpClient.newBuilder() - .followRedirects(HttpClient.Redirect.NEVER) - .connectTimeout(Objects.requireNonNull(connectTimeout, "connectTimeout")) - .build(), - allowLoopback); - } - - public JdkNotificationHttpGateway(HttpClient client) { - this(client, false); - } - - public JdkNotificationHttpGateway(HttpClient client, boolean allowLoopback) { - this.client = Objects.requireNonNull(client, "client"); - this.allowLoopback = allowLoopback; - } - - @Override - public NotificationHttpResponse exchange(NotificationHttpRequest request) { - Objects.requireNonNull(request, "request"); - NotificationEndpoints.requireExternallyRoutable( - request.uri(), "notification provider endpoint", allowLoopback); - HttpRequest.Builder builder = - HttpRequest.newBuilder(request.uri()) - .timeout(request.timeout()) - .method(request.method(), HttpRequest.BodyPublishers.ofByteArray(request.body())); - request - .headers() - .forEach( - (name, values) -> { - if (!RESTRICTED.contains(name)) { - values.forEach(value -> builder.header(name, value)); - } - }); - - // The request timeout covers the exchange up to the response headers and nothing after them, - // so the body read gets its own deadline: whatever is left of the same budget. - long deadlineNanos = System.nanoTime() + request.timeout().toNanos(); - try { - // Bounded, not ofByteArray(). A provider response is diagnostic — a status, some headers, an - // error document — and reading it without a cap makes the sender's heap a function of what - // the far end chooses to send. A chunked response with no end is a single-request outage. - HttpResponse response = - client.send(builder.build(), HttpResponse.BodyHandlers.ofInputStream()); - byte[] body = readBounded(response.body(), MAX_RESPONSE_BYTES, deadlineNanos); - return new NotificationHttpResponse( - response.statusCode(), Map.copyOf(response.headers().map()), body); - } catch (UncheckedIOException bodyFailure) { - throw new NotificationHttpTransportException( - "TRANSPORT_FAILURE", bodyWasLikelyCommitted(bodyFailure.getCause()), bodyFailure); - } catch (HttpTimeoutException timeout) { - // The request timed out after the body was published, so the provider may well have it. - throw new NotificationHttpTransportException("RESPONSE_TIMEOUT", true, timeout); - } catch (IOException failure) { - throw new NotificationHttpTransportException( - "TRANSPORT_FAILURE", bodyWasLikelyCommitted(failure), failure); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new NotificationHttpTransportException("INTERRUPTED", true, interrupted); - } - } - - /** - * Whether the request body may have reached the provider. - * - *

Decided from the exception's type, not from its message. The previous version - * lower-cased {@code getMessage()} and looked for "connection refused", "unresolved", "no route - * to host" and "connect timed out" — none of which is a contract. Those strings come from the - * platform's C library and the JDK's own wording; they are localised on some platforms, they - * changed between JDK releases, and a proxy that reports a refused connection in its own words - * would be read as "the body was sent". - * - *

The JDK does expose the distinction as types. {@link ConnectException} and {@link - * UnknownHostException} are raised while establishing the connection, so no request byte can have - * been written. Everything else stays committed — the default is deliberately the pessimistic - * one, because guessing "not committed" turns an unknown into an automatic resend. - */ - private static boolean bodyWasLikelyCommitted(IOException failure) { - // Depth-bounded rather than cycle-detecting: a cause chain can be circular (two exceptions - // each initCause'd to the other), and an unbounded walk over one hangs the dispatch thread. - // Ten is far deeper than any real transport wrapping. - Throwable cause = failure; - for (int depth = 0; cause != null && depth < 10; depth++, cause = cause.getCause()) { - if (cause instanceof java.net.ConnectException - || cause instanceof java.net.UnknownHostException - || cause instanceof java.net.NoRouteToHostException) { - return false; - } - } - return true; - } - - /** - * The largest provider response body this gateway retains. - * - *

64 KiB: far more than any provider's acknowledgement or error document, and small enough - * that a hostile or broken endpoint cannot make it interesting. - */ - public static final int MAX_RESPONSE_BYTES = 65_536; - - /** Closes body streams whose deadline passed; a daemon, so it never holds the JVM open. */ - private static final ScheduledExecutorService BODY_DEADLINES = - Executors.newSingleThreadScheduledExecutor( - task -> { - Thread thread = new Thread(task, "notification-http-body-deadline"); - thread.setDaemon(true); - return thread; - }); - - /** - * Reads the body up to the cap and no later than the deadline, on the caller's thread. - * - *

Truncating at the cap rather than failing: the status code is the part that decides the - * outcome, and a provider that accepted the message and then wrote a large body should not turn - * into an ambiguous submission. Closing the stream at the cap cancels the subscription. Mapping - * {@code ofByteArray()} looked bounded but buffered the whole body before cutting it, so an - * endless chunked response still held the thread and grew the heap until the far end stopped. - * - *

The deadline is the other half. A provider that trickles bytes and never reaches the cap - * held the dispatch thread for as long as it cared to — the request timeout had already been - * satisfied by the headers. At the deadline the stream is closed from outside, and the exchange - * is a response timeout: the body was sent, so the provider may well have the message. - */ - private static byte[] readBounded(InputStream stream, int maxBytes, long deadlineNanos) - throws HttpTimeoutException { - AtomicBoolean expired = new AtomicBoolean(); - long remaining = Math.max(0L, deadlineNanos - System.nanoTime()); - ScheduledFuture watchdog = - BODY_DEADLINES.schedule( - () -> { - expired.set(true); - closeQuietly(stream); - }, - remaining, - TimeUnit.NANOSECONDS); - byte[] body; - try (InputStream closing = stream) { - body = closing.readNBytes(maxBytes); - } catch (IOException failure) { - if (expired.get()) { - throw bodyDeadlineExceeded(); - } - throw new UncheckedIOException(failure); - } finally { - watchdog.cancel(false); - } - // A stream closed from outside may end as a short read rather than an exception. - if (expired.get()) { - throw bodyDeadlineExceeded(); - } - return body; - } - - private static HttpTimeoutException bodyDeadlineExceeded() { - return new HttpTimeoutException("response body was not received before the request timeout"); - } - - private static void closeQuietly(InputStream stream) { - try { - stream.close(); - } catch (IOException ignored) { - // The reader sees the closed stream; there is nothing more to do here. - } - } - - /** Header map helper for adapters. */ - public static Map> headers(Map singleValued) { - return singleValued.entrySet().stream() - .collect( - java.util.stream.Collectors.toUnmodifiableMap( - Map.Entry::getKey, entry -> List.of(entry.getValue()))); - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpGateway.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpGateway.java deleted file mode 100644 index a0c19265..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpGateway.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.provider.http; - -/** - * The only way a provider adapter in this leaf reaches the network. - * - *

It exists as a port because the registry does not permit {@code adapter-outbound-notification - * → adapter-outbound-httpclient}. The composition root sees both leaves and is the supported place - * to substitute an implementation backed by the HTTP Client Platform, which brings its own TLS, - * circuit breaker, SSRF and dynamic-target policy. - */ -public interface NotificationHttpGateway { - - /** - * Execute one request. - * - * @throws NotificationHttpTransportException when no response could be read; the exception states - * whether the request body was already committed - */ - NotificationHttpResponse exchange(NotificationHttpRequest request); -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpRequest.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpRequest.java deleted file mode 100644 index 1123dfbf..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpRequest.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.provider.http; - -import java.net.URI; -import java.time.Duration; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; - -/** One outbound provider HTTP request. */ -@SuppressWarnings("ArrayRecordComponent") // defensive copies on construction and on every accessor -public record NotificationHttpRequest( - String method, URI uri, Map> headers, byte[] body, Duration timeout) { - - public NotificationHttpRequest { - Objects.requireNonNull(method, "method"); - Objects.requireNonNull(uri, "uri"); - Objects.requireNonNull(headers, "headers"); - Objects.requireNonNull(body, "body"); - Objects.requireNonNull(timeout, "timeout"); - if (timeout.isNegative() || timeout.isZero()) { - throw new IllegalArgumentException("timeout must be finite and positive"); - } - headers = - headers.entrySet().stream() - .collect( - java.util.stream.Collectors.toUnmodifiableMap( - entry -> entry.getKey().toLowerCase(Locale.ROOT), - entry -> List.copyOf(entry.getValue()))); - body = body.clone(); - } - - @Override - public byte[] body() { - return body.clone(); - } - - @Override - public boolean equals(Object other) { - return other instanceof NotificationHttpRequest request - && method.equals(request.method) - && uri.equals(request.uri) - && headers.equals(request.headers) - && Arrays.equals(body, request.body) - && timeout.equals(request.timeout); - } - - @Override - public int hashCode() { - return Objects.hash(method, uri, headers, Arrays.hashCode(body), timeout); - } - - @Override - public String toString() { - // The URI is redacted because a Web Push endpoint is a capability URL and the request body may - // be a rendered message. - return "NotificationHttpRequest[method=" - + method - + ", uri=redacted, bytes=" - + body.length - + "]"; - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpResponse.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpResponse.java deleted file mode 100644 index de43312c..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpResponse.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.provider.http; - -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** One provider HTTP response. */ -@SuppressWarnings("ArrayRecordComponent") // defensive copies on construction and on every accessor -public record NotificationHttpResponse( - int statusCode, Map> headers, byte[] body) { - - public NotificationHttpResponse { - Objects.requireNonNull(headers, "headers"); - Objects.requireNonNull(body, "body"); - headers = - headers.entrySet().stream() - .collect( - java.util.stream.Collectors.toUnmodifiableMap( - entry -> entry.getKey().toLowerCase(Locale.ROOT), - entry -> List.copyOf(entry.getValue()))); - body = body.clone(); - } - - @Override - public byte[] body() { - return body.clone(); - } - - /** Body decoded as UTF-8. */ - public String bodyAsString() { - return new String(body, StandardCharsets.UTF_8); - } - - /** First value of a header, matched case-insensitively. */ - public Optional header(String name) { - List values = headers.get(name.toLowerCase(Locale.ROOT)); - return values == null || values.isEmpty() ? Optional.empty() : Optional.of(values.get(0)); - } - - /** Whether the status is 2xx. */ - public boolean isSuccessful() { - return statusCode >= 200 && statusCode < 300; - } - - @Override - public boolean equals(Object other) { - return other instanceof NotificationHttpResponse response - && statusCode == response.statusCode - && headers.equals(response.headers) - && Arrays.equals(body, response.body); - } - - @Override - public int hashCode() { - return Objects.hash(statusCode, headers, Arrays.hashCode(body)); - } - - @Override - public String toString() { - return "NotificationHttpResponse[status=" + statusCode + ", bytes=" + body.length + "]"; - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpTransportException.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpTransportException.java deleted file mode 100644 index 750d6511..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/NotificationHttpTransportException.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.provider.http; - -import java.util.Objects; - -/** - * A provider HTTP call that produced no usable response. - * - *

{@code requestBodyCommitted} is the field that decides everything downstream: a connection - * that failed before the body was written is a safe retry, while one that failed after it was - * written is an ambiguous submission that must not be resent automatically. - */ -public class NotificationHttpTransportException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final boolean requestBodyCommitted; - private final String reasonCode; - - public NotificationHttpTransportException( - String reasonCode, boolean requestBodyCommitted, Throwable cause) { - super(reasonCode, cause); - this.reasonCode = Objects.requireNonNull(reasonCode, "reasonCode"); - this.requestBodyCommitted = requestBodyCommitted; - } - - /** Whether the request body reached the provider before the failure. */ - public boolean requestBodyCommitted() { - return requestBodyCommitted; - } - - /** Bounded reason code, safe for logs and metrics. */ - public String reasonCode() { - return reasonCode; - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/AwsSignatureV4Signer.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/AwsSignatureV4Signer.java deleted file mode 100644 index 91f5f16d..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/AwsSignatureV4Signer.java +++ /dev/null @@ -1,147 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.provider.ses; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.HexFormat; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.TreeMap; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -/** - * AWS Signature Version 4. - * - *

Implemented here rather than pulled in with an SDK because the SDK would also bring its own - * HTTP client, retry policy and credential chain — three things this platform already owns and - * whose duplication would quietly move retry ownership out of the notification retry policy. - */ -public final class AwsSignatureV4Signer { - - private static final String ALGORITHM = "AWS4-HMAC-SHA256"; - private static final DateTimeFormatter AMZ_DATE = - DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC); - private static final DateTimeFormatter DATE_STAMP = - DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneOffset.UTC); - - /** Signed headers to add to a request. */ - public record SignedHeaders(String authorization, String amzDate, String contentSha256) { - - public SignedHeaders { - Objects.requireNonNull(authorization, "authorization"); - Objects.requireNonNull(amzDate, "amzDate"); - Objects.requireNonNull(contentSha256, "contentSha256"); - } - } - - /** Sign one request. */ - public SignedHeaders sign( - String method, - String canonicalUri, - String canonicalQuery, - Map headers, - byte[] body, - String accessKeyId, - byte[] secretAccessKey, - String region, - String service, - Instant signedAt) { - Objects.requireNonNull(method, "method"); - Objects.requireNonNull(canonicalUri, "canonicalUri"); - Objects.requireNonNull(canonicalQuery, "canonicalQuery"); - Objects.requireNonNull(headers, "headers"); - Objects.requireNonNull(body, "body"); - Objects.requireNonNull(signedAt, "signedAt"); - - String amzDate = AMZ_DATE.format(signedAt); - String dateStamp = DATE_STAMP.format(signedAt); - String payloadHash = hex(sha256(body)); - - TreeMap canonicalHeaders = new TreeMap<>(); - headers.forEach( - (name, value) -> canonicalHeaders.put(name.toLowerCase(Locale.ROOT), value.trim())); - canonicalHeaders.put("x-amz-date", amzDate); - canonicalHeaders.put("x-amz-content-sha256", payloadHash); - - StringBuilder canonicalHeaderBlock = new StringBuilder(); - canonicalHeaders.forEach( - (name, value) -> canonicalHeaderBlock.append(name).append(':').append(value).append('\n')); - String signedHeaderNames = String.join(";", canonicalHeaders.keySet()); - - String canonicalRequest = - method - + '\n' - + canonicalUri - + '\n' - + canonicalQuery - + '\n' - + canonicalHeaderBlock - + '\n' - + signedHeaderNames - + '\n' - + payloadHash; - - String credentialScope = dateStamp + "/" + region + "/" + service + "/aws4_request"; - String stringToSign = - ALGORITHM - + '\n' - + amzDate - + '\n' - + credentialScope - + '\n' - + hex(sha256(canonicalRequest.getBytes(StandardCharsets.UTF_8))); - - byte[] signingKey = signingKey(secretAccessKey, dateStamp, region, service); - String signature = hex(hmac(signingKey, stringToSign.getBytes(StandardCharsets.UTF_8))); - - String authorization = - ALGORITHM - + " Credential=" - + accessKeyId - + "/" - + credentialScope - + ", SignedHeaders=" - + signedHeaderNames - + ", Signature=" - + signature; - return new SignedHeaders(authorization, amzDate, payloadHash); - } - - private static byte[] signingKey( - byte[] secretAccessKey, String dateStamp, String region, String service) { - byte[] key = - ("AWS4" + new String(secretAccessKey, StandardCharsets.UTF_8)) - .getBytes(StandardCharsets.UTF_8); - byte[] dateKey = hmac(key, dateStamp.getBytes(StandardCharsets.UTF_8)); - byte[] regionKey = hmac(dateKey, region.getBytes(StandardCharsets.UTF_8)); - byte[] serviceKey = hmac(regionKey, service.getBytes(StandardCharsets.UTF_8)); - return hmac(serviceKey, "aws4_request".getBytes(StandardCharsets.UTF_8)); - } - - private static byte[] hmac(byte[] key, byte[] data) { - try { - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(key, "HmacSHA256")); - return mac.doFinal(data); - } catch (java.security.GeneralSecurityException failure) { - throw new IllegalStateException("HmacSHA256 is required by the Java platform", failure); - } - } - - private static byte[] sha256(byte[] value) { - try { - return MessageDigest.getInstance("SHA-256").digest(value); - } catch (NoSuchAlgorithmException failure) { - throw new IllegalStateException("SHA-256 is required by the Java platform", failure); - } - } - - private static String hex(byte[] value) { - return HexFormat.of().formatHex(value); - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesClients.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesClients.java new file mode 100644 index 00000000..4ab65f3f --- /dev/null +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesClients.java @@ -0,0 +1,57 @@ +package dev.caskeleton.adapter.outbound.notification.platform.provider.ses; + +import java.time.Duration; +import java.util.Objects; +import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; +import software.amazon.awssdk.awscore.retry.AwsRetryStrategy; +import software.amazon.awssdk.http.apache.ApacheHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.sesv2.SesV2Client; + +/** + * Builds the SES client one provider profile sends through. + * + *

Three settings are the point of this class rather than defaults left to the SDK: + * + *

    + *
  • No SDK retries. A retry after a lost response can send the mail twice, and deciding + * whether to resend is what the notification retry policy and the evidence model are for. + *
  • No default credential chain. Every request carries its profile's credential as a + * request override (see {@link SesRequestMapper}); a request that somehow did not would + * otherwise be signed with whatever the host environment happened to provide. This provider + * fails instead. + *
  • The configured endpoint. It has already passed the routability guard in {@link + * SesProviderProperties}; the SDK's Apache client follows no redirects, so a signed request + * cannot be moved to a host the profile never approved. + *
+ */ +public final class SesClients { + + /** Connection establishment budget; the whole call is bounded by the profile's timeout. */ + static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(2); + + private static final AwsCredentialsProvider NO_DEFAULT_CREDENTIALS = + () -> { + throw new IllegalStateException( + "an SES request reached the client without its profile credential"); + }; + + private SesClients() {} + + /** + * A client for one profile. + * + * @param properties the profile's validated SES settings + * @return a client that retries nothing and signs only with per-request credentials + */ + public static SesV2Client create(SesProviderProperties properties) { + Objects.requireNonNull(properties, "properties"); + return SesV2Client.builder() + .region(Region.of(properties.region())) + .endpointOverride(properties.endpoint()) + .credentialsProvider(NO_DEFAULT_CREDENTIALS) + .httpClientBuilder(ApacheHttpClient.builder().connectionTimeout(CONNECT_TIMEOUT)) + .overrideConfiguration(override -> override.retryStrategy(AwsRetryStrategy.doNotRetry())) + .build(); + } +} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesDeliveryProjector.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesDeliveryProjector.java deleted file mode 100644 index e0c7ac2c..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesDeliveryProjector.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.provider.ses; - -import dev.caskeleton.application.notification.platform.api.ProviderId; -import dev.caskeleton.application.notification.platform.callback.StandardDeliveryProjector; - -/** - * SES projector. - * - *

SES adds no transition of its own: delivery, bounce and complaint all obey the shared table, - * and the interesting SES-specific behaviour — a complaint arriving after a delivery — is exactly - * what the shared table already gets right. - */ -public final class SesDeliveryProjector extends StandardDeliveryProjector { - - public SesDeliveryProjector() { - super(new ProviderId("ses")); - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesFailureClassifier.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesFailureClassifier.java index cfe49e50..e83269a6 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesFailureClassifier.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesFailureClassifier.java @@ -1,19 +1,38 @@ package dev.caskeleton.adapter.outbound.notification.platform.provider.ses; import dev.caskeleton.adapter.outbound.notification.platform.provider.ProviderResults; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpResponse; import dev.caskeleton.application.notification.platform.api.error.FailureCategory; import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; import dev.caskeleton.application.notification.platform.provider.ProviderFailure; +import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult; +import java.net.ConnectException; +import java.net.NoRouteToHostException; +import java.net.UnknownHostException; +import java.time.Duration; import java.util.Optional; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException; +import software.amazon.awssdk.core.exception.ApiCallTimeoutException; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.services.sesv2.model.AccountSuspendedException; +import software.amazon.awssdk.services.sesv2.model.MailFromDomainNotVerifiedException; +import software.amazon.awssdk.services.sesv2.model.MessageRejectedException; +import software.amazon.awssdk.services.sesv2.model.SendingPausedException; +import software.amazon.awssdk.services.sesv2.model.TooManyRequestsException; -/** Maps SES error responses onto the stable failure vocabulary. */ +/** + * Maps what the SES client threw onto the stable failure vocabulary. + * + *

An error SES answered is classified by the SDK's typed exception, not by searching the body + * for a name: the SDK already parsed the error type the service reported. A transport failure is + * classified by whether the request may have reached SES, because that one bit separates a safe + * retry from a duplicate. + */ public final class SesFailureClassifier { - /** Classify a non-2xx SES response. */ - public ProviderFailure classify(NotificationHttpResponse response) { - String body = response.bodyAsString(); - if (body.contains("MessageRejected")) { + /** Classify an error SES answered. */ + public ProviderFailure classify(AwsServiceException error) { + if (error instanceof MessageRejectedException) { return new ProviderFailure( NotificationFailureCode.PROVIDER_REJECTED, FailureCategory.PERMANENT_PROVIDER, @@ -21,7 +40,8 @@ public final class SesFailureClassifier { Optional.empty(), Optional.of("MessageRejected")); } - if (body.contains("MailFromDomainNotVerified") || body.contains("SendingPausedException")) { + if (error instanceof MailFromDomainNotVerifiedException + || error instanceof SendingPausedException) { return new ProviderFailure( NotificationFailureCode.PROVIDER_CONFIGURATION_INVALID, FailureCategory.AUTHORIZATION, @@ -29,15 +49,16 @@ public final class SesFailureClassifier { Optional.empty(), Optional.of("SenderIdentityNotReady")); } - if (body.contains("TooManyRequestsException") || response.statusCode() == 429) { + Optional retryAfter = ProviderResults.retryAfter(retryAfterHeader(error)); + if (error instanceof TooManyRequestsException || error.statusCode() == 429) { return new ProviderFailure( NotificationFailureCode.PROVIDER_THROTTLED, FailureCategory.THROTTLED, true, - ProviderResults.retryAfter(response.header("retry-after")), + retryAfter, Optional.of("TooManyRequests")); } - if (body.contains("AccountSuspendedException")) { + if (error instanceof AccountSuspendedException) { return new ProviderFailure( NotificationFailureCode.PROVIDER_AUTHORIZATION_FAILED, FailureCategory.AUTHORIZATION, @@ -45,7 +66,54 @@ public final class SesFailureClassifier { Optional.empty(), Optional.of("AccountSuspended")); } - return ProviderResults.fromStatus( - response.statusCode(), ProviderResults.retryAfter(response.header("retry-after"))); + return ProviderResults.fromStatus(error.statusCode(), retryAfter); + } + + /** + * Classify a failure that left no answer from SES. + * + * @param failure what the client threw + * @param elapsed how long the call ran + * @return ambiguous when the request may have been sent, not-submitted when it cannot have been + */ + public ProviderSubmissionResult fromTransport(SdkClientException failure, Duration elapsed) { + boolean timedOut = + failure instanceof ApiCallTimeoutException + || failure instanceof ApiCallAttemptTimeoutException; + return ProviderResults.fromTransport( + timedOut ? "RESPONSE_TIMEOUT" : "TRANSPORT_FAILURE", + requestMayHaveBeenSent(failure), + elapsed); + } + + /** + * Whether the request body may have reached SES. + * + *

Decided from the exception's type, not from its message. Messages come from the + * platform's C library and the JDK's wording; they are localised on some systems and have changed + * between releases. {@link ConnectException}, {@link UnknownHostException} and {@link + * NoRouteToHostException} are raised while establishing the connection, so no request byte can + * have been written. Everything else stays committed — the default is deliberately the + * pessimistic one, because guessing "not committed" turns an unknown into an automatic resend. + * + *

Depth-bounded rather than cycle-detecting: a cause chain can be circular, and an unbounded + * walk over one hangs the dispatch thread. Ten is far deeper than any real transport wrapping. + */ + static boolean requestMayHaveBeenSent(Throwable failure) { + Throwable cause = failure; + for (int depth = 0; cause != null && depth < 10; depth++, cause = cause.getCause()) { + if (cause instanceof ConnectException + || cause instanceof UnknownHostException + || cause instanceof NoRouteToHostException) { + return false; + } + } + return true; + } + + private static Optional retryAfterHeader(AwsServiceException error) { + return Optional.ofNullable(error.awsErrorDetails()) + .map(details -> details.sdkHttpResponse()) + .flatMap(response -> response.firstMatchingHeader("retry-after")); } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapter.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapter.java index ed22fc17..3dd40381 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapter.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapter.java @@ -2,13 +2,7 @@ package dev.caskeleton.adapter.outbound.notification.platform.provider.ses; import dev.caskeleton.adapter.outbound.notification.platform.provider.EmailAttachments; import dev.caskeleton.adapter.outbound.notification.platform.provider.EmailRecipients; -import dev.caskeleton.adapter.outbound.notification.platform.provider.ProviderResults; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpGateway; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpRequest; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpResponse; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpTransportException; import dev.caskeleton.adapter.outbound.notification.platform.security.ProviderCredentialManager; -import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationJsonMapper; import dev.caskeleton.application.notification.platform.api.ProviderId; import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.contact.EmailAddress; @@ -19,56 +13,60 @@ import dev.caskeleton.application.notification.platform.provider.ProviderSubmiss import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult; import dev.caskeleton.application.notification.platform.provider.ResolvedAttachment; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; -import java.time.Clock; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.List; import java.util.Objects; -import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.AwsCredentials; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.services.sesv2.SesV2Client; +import software.amazon.awssdk.services.sesv2.model.SendEmailRequest; +import software.amazon.awssdk.services.sesv2.model.SendEmailResponse; /** - * Amazon SES submission. + * Amazon SES submission, through the AWS SDK v2 {@code sesv2} client. * *

{@code MessageId} is stored as the provider request id and mapped to {@code * PROVIDER_ACCEPTED}. SES documents that it can accept a request and still decline to send — for a * virus finding or a bad personalisation — so promoting acceptance to delivery would be wrong by * the provider's own contract, not merely conservative. * - *

Retry ownership stays with the notification retry policy: the gateway performs no blind retry, - * because a resend after a lost response is exactly the decision the evidence model must make. + *

Retry ownership stays with the notification retry policy: the client is built with the SDK's + * retries turned off, because a resend after a lost response is exactly the decision the evidence + * model must make. */ public final class SesNotificationProviderAdapter implements NotificationProviderAdapter { private static final ProviderId PROVIDER_ID = new ProviderId("ses"); - private final NotificationHttpGateway gateway; + private final SesV2Client client; private final SesRequestMapper mapper; private final AttachmentIntegrityGuard attachmentGuard; private final SesFailureClassifier classifier; private final ContactPointProtector protector; private final ProviderCredentialManager credentials; private final String accessKeyId; - private final Clock clock; public SesNotificationProviderAdapter( - NotificationHttpGateway gateway, + SesV2Client client, SesRequestMapper mapper, AttachmentIntegrityGuard attachmentGuard, SesFailureClassifier classifier, ContactPointProtector protector, ProviderCredentialManager credentials, - String accessKeyId, - Clock clock) { - this.gateway = Objects.requireNonNull(gateway, "gateway"); + String accessKeyId) { + this.client = Objects.requireNonNull(client, "client"); this.mapper = Objects.requireNonNull(mapper, "mapper"); this.attachmentGuard = Objects.requireNonNull(attachmentGuard, "attachmentGuard"); this.classifier = Objects.requireNonNull(classifier, "classifier"); this.protector = Objects.requireNonNull(protector, "protector"); this.credentials = Objects.requireNonNull(credentials, "credentials"); this.accessKeyId = Objects.requireNonNull(accessKeyId, "accessKeyId"); - this.clock = Objects.requireNonNull(clock, "clock"); } @Override @@ -86,18 +84,8 @@ public final class SesNotificationProviderAdapter implements NotificationProvide // The payload ceiling is the mapper's own constant rather than a second copy of the number: // the runtime plans against what is declared here and the mapper refuses against what it holds, // and two spellings of the same limit is one of them being wrong. - return new ProviderCapabilities( - false, - false, - true, - false, - false, - false, - false, - false, - 1, - SesRequestMapper.MAX_MESSAGE_BYTES, - Duration.ofDays(1)); + return ProviderCapabilities.dispatchOnly(SesRequestMapper.MAX_MESSAGE_BYTES, Duration.ofDays(1)) + .withStatusCallback(); } @Override @@ -114,46 +102,37 @@ public final class SesNotificationProviderAdapter implements NotificationProvide // attachment only reaches the wire through the raw MIME message the mapper builds from these // streams, so they have to be open for exactly that long and no longer. List opened = EmailAttachments.open(attachmentGuard, submission); - NotificationHttpRequest request; + SendEmailRequest request; try { - request = - mapper.map( - submission, - address.normalized(), - opened, - accessKeyId, - // This profile's credential at the generation the submission was planned against, not - // the platform's one current provider credential. Sharing a single key across every - // profile made one leaked SES account's key a leak of every provider account, and - // made a per-profile rotation inexpressible. - credentials.materialFor( - submission.profile().profileId(), submission.profile().credentialGeneration()), - clock.instant()); + request = mapper.map(submission, address.normalized(), opened, credentialOf(submission)); } finally { EmailAttachments.closeAll(opened); } try { - NotificationHttpResponse response = gateway.exchange(request); - Duration elapsed = elapsedSince(startedNanos); - if (response.isSuccessful()) { - return ProviderSubmissionResult.accepted(messageId(response), "Accepted", elapsed); - } - return ProviderSubmissionResult.rejected(classifier.classify(response), elapsed); - } catch (NotificationHttpTransportException transportFailure) { - return ProviderResults.fromTransport(transportFailure, elapsedSince(startedNanos)); + SendEmailResponse response = client.sendEmail(request); + return ProviderSubmissionResult.accepted( + response.messageId(), "Accepted", elapsedSince(startedNanos)); + } catch (AwsServiceException answered) { + return ProviderSubmissionResult.rejected( + classifier.classify(answered), elapsedSince(startedNanos)); + } catch (SdkClientException noAnswer) { + return classifier.fromTransport(noAnswer, elapsedSince(startedNanos)); } } - private static String messageId(NotificationHttpResponse response) { - try { - var node = NotificationJsonMapper.mapper().readTree(response.bodyAsString()); - return Optional.ofNullable(node.get("MessageId")).map(value -> value.asString()).orElse(null); - } catch (RuntimeException unparseable) { - // A 2xx without a parseable body is still acceptance; the platform simply has no provider - // request id to reconcile against later. - return null; - } + /** + * This profile's credential at the generation the submission was planned against. + * + *

Not the platform's one current provider credential. Sharing a single key across every + * profile made one leaked SES account's key a leak of every provider account, and made a + * per-profile rotation inexpressible. + */ + private AwsCredentials credentialOf(ProviderSubmission submission) { + byte[] secret = + credentials.materialFor( + submission.profile().profileId(), submission.profile().credentialGeneration()); + return AwsBasicCredentials.create(accessKeyId, new String(secret, StandardCharsets.UTF_8)); } private static Duration elapsedSince(long startedNanos) { diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesProviderProperties.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesProviderProperties.java index c33cb2c8..fed51cb8 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesProviderProperties.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesProviderProperties.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.notification.platform.provider.ses; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationEndpoints; +import dev.caskeleton.adapter.outbound.notification.platform.provider.NotificationEndpoints; import java.net.URI; import java.time.Duration; import java.util.Objects; diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesRequestMapper.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesRequestMapper.java index 26747b6b..db1a5c3a 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesRequestMapper.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesRequestMapper.java @@ -1,9 +1,6 @@ package dev.caskeleton.adapter.outbound.notification.platform.provider.ses; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.JdkNotificationHttpGateway; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpRequest; import dev.caskeleton.adapter.outbound.notification.platform.provider.smtp.SmtpMimeMessageFactory; -import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationJsonMapper; import dev.caskeleton.application.notification.platform.api.content.EmailContent; import dev.caskeleton.application.notification.platform.api.error.FailureCategory; import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; @@ -15,17 +12,21 @@ import dev.caskeleton.application.notification.platform.provider.ResolvedAttachm import jakarta.mail.MessagingException; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.Base64; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import java.util.Objects; +import software.amazon.awssdk.auth.credentials.AwsCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.services.sesv2.model.Body; +import software.amazon.awssdk.services.sesv2.model.Content; +import software.amazon.awssdk.services.sesv2.model.Destination; +import software.amazon.awssdk.services.sesv2.model.Message; +import software.amazon.awssdk.services.sesv2.model.RawMessage; +import software.amazon.awssdk.services.sesv2.model.SendEmailRequest; /** - * Builds the signed SES v2 send request. + * Builds the SES v2 {@code SendEmail} request. * *

Two content shapes, chosen by what the notification actually carries. {@code Simple} is a * subject and two bodies and nothing else, so an email that declares an attachment is assembled as @@ -39,9 +40,12 @@ import java.util.Objects; * rejection that keeps a subject from turning a notification into someone else's mail are decided * once; two builders would be two places for those answers to drift apart. * - *

What the raw path still cannot express is refused before the request is signed, so nothing has + *

What the raw path still cannot express is refused before the request is sent, so nothing has * been sent when it happens: content that is not email, an attachment the resolver did not hand * back, and a message larger than SES will accept. + * + *

Signing is the SDK's. Each request carries, as request overrides, the credential of the + * profile at the generation the submission was planned against, and the profile's call timeout. */ public final class SesRequestMapper { @@ -55,95 +59,71 @@ public final class SesRequestMapper { */ public static final long MAX_MESSAGE_BYTES = 10_000_000L; - private static final String PATH = "/v2/email/outbound-emails"; + private static final String UTF_8 = "UTF-8"; private final SesProviderProperties properties; - private final AwsSignatureV4Signer signer; private final SmtpMimeMessageFactory mimeFactory; - public SesRequestMapper( - SesProviderProperties properties, - AwsSignatureV4Signer signer, - SmtpMimeMessageFactory mimeFactory) { + public SesRequestMapper(SesProviderProperties properties, SmtpMimeMessageFactory mimeFactory) { this.properties = Objects.requireNonNull(properties, "properties"); - this.signer = Objects.requireNonNull(signer, "signer"); this.mimeFactory = Objects.requireNonNull(mimeFactory, "mimeFactory"); } /** - * Map one submission into a signed request. + * Map one submission into a request. * + * @param submission the submission + * @param recipientAddress the revealed recipient address * @param attachments the already resolved and verified attachments, open for the length of this * call; the caller closes them + * @param credentials the profile's credential, used to sign this request only + * @return the request, ready to send */ - public NotificationHttpRequest map( + public SendEmailRequest map( ProviderSubmission submission, String recipientAddress, List attachments, - String accessKeyId, - byte[] secretAccessKey, - Instant signedAt) { + AwsCredentials credentials) { Objects.requireNonNull(submission, "submission"); Objects.requireNonNull(recipientAddress, "recipientAddress"); Objects.requireNonNull(attachments, "attachments"); + Objects.requireNonNull(credentials, "credentials"); if (!(submission.content().content() instanceof EmailContent email)) { throw new IllegalArgumentException("SES requires email content"); } - Map payload = new LinkedHashMap<>(); - payload.put("FromEmailAddress", properties.senderIdentity()); - payload.put("Destination", Map.of("ToAddresses", List.of(recipientAddress))); - payload.put("Content", content(submission, email, recipientAddress, attachments)); - properties.configurationSet().ifPresent(name -> payload.put("ConfigurationSetName", name)); - - byte[] body = - NotificationJsonMapper.mapper() - .writeValueAsString(payload) - .getBytes(StandardCharsets.UTF_8); - String host = properties.endpoint().getHost(); - - var signed = - signer.sign( - "POST", - PATH, - "", - Map.of("host", host, "content-type", "application/json"), - body, - accessKeyId, - secretAccessKey, - properties.region(), - "ses", - signedAt); - - return new NotificationHttpRequest( - "POST", - URI.create(properties.endpoint().toString() + PATH), - JdkNotificationHttpGateway.headers( - Map.of( - "content-type", "application/json", - "x-amz-date", signed.amzDate(), - "x-amz-content-sha256", signed.contentSha256(), - "authorization", signed.authorization())), - body, - properties.timeout()); + SendEmailRequest.Builder request = + SendEmailRequest.builder() + .fromEmailAddress(properties.senderIdentity()) + .destination(Destination.builder().toAddresses(recipientAddress).build()) + .overrideConfiguration( + AwsRequestOverrideConfiguration.builder() + .credentialsProvider(StaticCredentialsProvider.create(credentials)) + .apiCallTimeout(properties.timeout()) + .build()); + properties.configurationSet().ifPresent(request::configurationSetName); + if (email.attachments().isEmpty()) { + request.content(content -> content.simple(simple(email))); + } else { + RawMessage raw = raw(submission, email, recipientAddress, attachments); + request.content(content -> content.raw(raw)); + } + return request.build(); } /** - * The content shape this email needs. + * The raw MIME shape an email with attachments needs. * *

The decision is made from what the content declares, not from what was handed in: * an email that declares an attachment and arrives with fewer than it declared must not fall back * to {@code Simple}, because that is precisely the send that leaves the document behind and * reports success. */ - private Map content( + private RawMessage raw( ProviderSubmission submission, EmailContent email, String recipientAddress, List attachments) { - if (email.attachments().isEmpty()) { - return Map.of("Simple", simple(email)); - } if (attachments.size() != email.attachments().size()) { throw rejection( new IllegalStateException( @@ -153,11 +133,11 @@ public final class SesRequestMapper { + attachments.size() + " were opened")); } - return Map.of("Raw", Map.of("Data", rawMessage(submission, recipientAddress, attachments))); + return RawMessage.builder().data(rawMessage(submission, recipientAddress, attachments)).build(); } - /** The MIME message, base64 encoded as the SES v2 JSON binding requires for a blob. */ - private String rawMessage( + /** The MIME message; the SDK base64-encodes it for the JSON binding. */ + private SdkBytes rawMessage( ProviderSubmission submission, String recipientAddress, List attachments) { @@ -178,19 +158,17 @@ public final class SesRequestMapper { NotificationFailureDescriptor.preDispatch( NotificationFailureCode.PROVIDER_PAYLOAD_LIMIT, FailureCategory.INVALID_PAYLOAD)); } - return Base64.getEncoder().encodeToString(message); + return SdkBytes.fromByteArray(message); } - private static Map simple(EmailContent email) { - Map simple = new LinkedHashMap<>(); - simple.put("Subject", Map.of("Data", email.subject(), "Charset", "UTF-8")); - Map bodyParts = new LinkedHashMap<>(); - bodyParts.put("Text", Map.of("Data", email.textBody(), "Charset", "UTF-8")); - email - .htmlBody() - .ifPresent(html -> bodyParts.put("Html", Map.of("Data", html, "Charset", "UTF-8"))); - simple.put("Body", bodyParts); - return simple; + private static Message simple(EmailContent email) { + Body.Builder body = Body.builder().text(text(email.textBody())); + email.htmlBody().ifPresent(html -> body.html(text(html))); + return Message.builder().subject(text(email.subject())).body(body.build()).build(); + } + + private static Content text(String data) { + return Content.builder().data(data).charset(UTF_8).build(); } /** diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpNotificationProviderAdapter.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpNotificationProviderAdapter.java index 88c3006c..50bd8f8f 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpNotificationProviderAdapter.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpNotificationProviderAdapter.java @@ -71,8 +71,7 @@ public final class SmtpNotificationProviderAdapter implements NotificationProvid public ProviderCapabilities capabilities() { // SMTP offers no status callback, no status query and no provider-side idempotency, so the // runtime must never plan a reconciliation for it. - return new ProviderCapabilities( - false, false, false, false, false, false, false, false, 1, 25_000_000L, Duration.ofDays(1)); + return ProviderCapabilities.dispatchOnly(25_000_000L, Duration.ofDays(1)); } @Override diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/CanonicalNotificationRenderer.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/CanonicalNotificationRenderer.java index f0cb06f7..e2f96b86 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/CanonicalNotificationRenderer.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/CanonicalNotificationRenderer.java @@ -25,7 +25,11 @@ import java.util.Objects; import java.util.Optional; /** - * The reference renderer for every stable channel. + * The reference renderer for every stable channel, one instance for all of them. + * + *

The engine is the only thing that varies between deployments (Thymeleaf or the placeholder + * engine); validation order, channel content assembly and the content digest are this class's + * contract whichever engine renders the slots. * *

Rendering is deterministic and the digest covers channel, template coordinate, resolved locale * and every rendered field. That digest is stored on the attempt, which is what lets a retry prove @@ -36,27 +40,19 @@ import java.util.Optional; */ public final class CanonicalNotificationRenderer implements NotificationTemplateRenderer { - private final Channel channel; private final TemplateRegistry templates; private final TemplateVariableValidator validator; private final NotificationTemplateEngine engine; public CanonicalNotificationRenderer( - Channel channel, TemplateRegistry templates, TemplateVariableValidator validator, NotificationTemplateEngine engine) { - this.channel = Objects.requireNonNull(channel, "channel"); this.templates = Objects.requireNonNull(templates, "templates"); this.validator = Objects.requireNonNull(validator, "validator"); this.engine = Objects.requireNonNull(engine, "engine"); } - @Override - public Channel channel() { - return channel; - } - @Override public RenderedNotificationContent render(RenderCommand command) { Objects.requireNonNull(command, "command"); @@ -69,7 +65,7 @@ public final class CanonicalNotificationRenderer implements NotificationTemplate command.requestedLocale()); validator.validate(template.variableSchema(), command.variables()); - NotificationContent content = buildContent(template, command.variables()); + NotificationContent content = buildContent(command.channel(), template, command.variables()); String digest = NotificationDigest.hex( command.channel().name() @@ -85,7 +81,7 @@ public final class CanonicalNotificationRenderer implements NotificationTemplate } private NotificationContent buildContent( - NotificationTemplateVersion template, Map variables) { + Channel channel, NotificationTemplateVersion template, Map variables) { return switch (channel) { case EMAIL -> new EmailContent( diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/ThymeleafNotificationRenderer.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/ThymeleafNotificationRenderer.java deleted file mode 100644 index b7e6a77d..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/ThymeleafNotificationRenderer.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.template; - -import dev.caskeleton.application.notification.platform.api.routing.Channel; -import dev.caskeleton.application.notification.platform.template.NotificationTemplateRenderer; -import dev.caskeleton.application.notification.platform.template.RenderCommand; -import dev.caskeleton.application.notification.platform.template.RenderedNotificationContent; -import dev.caskeleton.application.notification.platform.template.TemplateRegistry; -import dev.caskeleton.application.notification.platform.template.TemplateVariableValidator; -import java.util.Objects; - -/** - * Reference renderer backed by Thymeleaf. - * - *

Composition rather than a parallel implementation: validation order, channel content assembly - * and the content digest are the renderer's contract, and the engine is the only thing that - * differs. A second hand-written renderer is how two of them end up computing different digests for - * the same template — which quietly breaks the retry-sent-the-same-content guarantee the digest - * exists for. - * - *

No Thymeleaf type appears on this class's signature, so the application-side template contract - * stays engine-free and a deployment can swap engines without recompiling anything above the - * adapter. - */ -public final class ThymeleafNotificationRenderer implements NotificationTemplateRenderer { - - private final CanonicalNotificationRenderer delegate; - - public ThymeleafNotificationRenderer( - Channel channel, - TemplateRegistry templates, - TemplateVariableValidator validator, - ThymeleafStringTemplateEngine engine) { - this.delegate = - new CanonicalNotificationRenderer( - Objects.requireNonNull(channel, "channel"), - Objects.requireNonNull(templates, "templates"), - Objects.requireNonNull(validator, "validator"), - Objects.requireNonNull(engine, "engine")); - } - - @Override - public Channel channel() { - return delegate.channel(); - } - - @Override - public RenderedNotificationContent render(RenderCommand command) { - return delegate.render(command); - } -} diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPayloadAtRestContractTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPayloadAtRestContractTest.java index 0fdc28d7..b94e77cf 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPayloadAtRestContractTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPayloadAtRestContractTest.java @@ -97,7 +97,7 @@ class NotificationPayloadAtRestContractTest { Path mapper = repositoryRoot() .resolve( - "src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/" + "src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/" + "persistence/notification/platform/NotificationRecordMapper.java"); assertThat(read(mapper)) .as( @@ -115,7 +115,7 @@ class NotificationPayloadAtRestContractTest { Path store = repositoryRoot() .resolve( - "src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/" + "src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/" + "persistence/notification/platform/JpaNotificationRequestStore.java"); String source = read(store); @@ -159,7 +159,7 @@ class NotificationPayloadAtRestContractTest { Files.exists( repositoryRoot() .resolve( - "src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/" + "src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/" + "notification-platform/V10__variables_payload_envelope_guard.sql"))) .as( "a fork that wired the store itself meets its plaintext rows at migration time rather " @@ -174,8 +174,11 @@ class NotificationPayloadAtRestContractTest { "application-core", "adapter/outbound/notification", "adapter/outbound/persistence-jpa", + "adapter/outbound/persistence-notification", "app-bootstrap") - .map(root::resolve) + // Walk only the production sources: a module root also holds build/, which a parallel + // build rewrites while this walk is in it. + .map(module -> root.resolve(module).resolve("src/main/java")) .filter(Files::isDirectory) .flatMap( moduleRoot -> { diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfigurationTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfigurationTest.java index b7431d47..72bc4107 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfigurationTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfigurationTest.java @@ -2,7 +2,6 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpGateway; 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; @@ -40,7 +39,6 @@ class NotificationPlatformCoreConfigurationTest { assertThat(context).hasNotFailed(); assertThat(context).doesNotHaveBean(MessageDigestPort.class); assertThat(context).doesNotHaveBean(TemplateVariableValidator.class); - assertThat(context).doesNotHaveBean(NotificationHttpGateway.class); }); } @@ -51,7 +49,6 @@ class NotificationPlatformCoreConfigurationTest { context -> { assertThat(context).hasSingleBean(MessageDigestPort.class); assertThat(context).hasSingleBean(TemplateVariableValidator.class); - assertThat(context).hasSingleBean(NotificationHttpGateway.class); }); } diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettingsTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettingsTest.java index f3adaccb..af5c56ce 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettingsTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettingsTest.java @@ -37,7 +37,15 @@ class NotificationPlatformSettingsTest { () -> properties( new NotificationPlatformSettings.Provider( - "SES", true, false, "PRODUCTION", "cred-1", Duration.ofSeconds(3), 8, 20))) + "SES", + true, + false, + "PRODUCTION", + "cred-1", + Duration.ofSeconds(3), + 8, + 20, + null))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("ses settings block"); } @@ -184,6 +192,6 @@ class NotificationPlatformSettingsTest { /** A profile with only the common fields set; an SES one is therefore missing its block. */ private static NotificationPlatformSettings.Provider sesShaped(String type, boolean enabled) { return new NotificationPlatformSettings.Provider( - type, enabled, false, "PRODUCTION", "profile-key", Duration.ofSeconds(3), 8, 20); + type, enabled, false, "PRODUCTION", "profile-key", Duration.ofSeconds(3), 8, 20, null); } } diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java index 222ada3f..8e7ec0d5 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java @@ -28,11 +28,9 @@ import dev.caskeleton.application.notification.platform.callback.DeliveryProject import dev.caskeleton.application.notification.platform.callback.ProjectionResult; import dev.caskeleton.application.notification.platform.callback.ProjectionStatus; import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector; -import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectorRegistry; import dev.caskeleton.application.notification.platform.callback.ProviderEventRecord; import dev.caskeleton.application.notification.platform.callback.ProviderEventRecordId; import dev.caskeleton.application.notification.platform.callback.ProviderEventSource; -import dev.caskeleton.application.notification.platform.callback.StandardDeliveryProjector; import dev.caskeleton.application.notification.platform.provider.NotificationProviderAdapter; import dev.caskeleton.application.notification.platform.provider.ProviderCapabilities; import dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot; @@ -62,8 +60,7 @@ import org.junit.jupiter.api.Test; class NotificationProviderAssemblyTest { private static final ProviderCapabilities NO_CAPABILITIES = - new ProviderCapabilities( - false, false, false, false, false, false, false, false, 1, 1_024L, Duration.ofMinutes(1)); + ProviderCapabilities.dispatchOnly(1_024L, Duration.ofMinutes(1)); @Test @DisplayName("a configured profile becomes a runtime and a route") @@ -270,36 +267,15 @@ class NotificationProviderAssemblyTest { } @Test - @DisplayName("SES 콜백의 hard bounce는 SES projector를 찾아 배달 결과에 반영된다") - void anSesHardBounceIsProjectedRatherThanFailedForWantOfAProjector() { + @DisplayName("SES 콜백의 hard bounce는 모든 provider가 공유하는 projector로 배달 결과에 반영된다") + void anSesHardBounceIsProjectedByTheSharedProjector() { // given - NotificationPlatformSettings settings = - new NotificationPlatformSettings( - true, - NotificationPlatformMode.INGEST_ONLY, - NotificationPlatformSettings.Dispatch.defaults(), - new NotificationPlatformSettings.Callbacks(true, 1_024, Duration.ofMinutes(5)), - Map.of("ses-events", profile("SES", true, false))); - NotificationProviderAssembly.AssembledPlatform platform = - new NotificationProviderAssembly( - List.of(), - List.of( - new SesProviderCallbackAssembler( - url -> { - throw new AssertionError("no certificate is fetched to project"); - }, - Duration.ofMinutes(5)))) - .assemble(settings, NotificationPlatformMode.INGEST_ONLY); - ProviderEventProjectorRegistry registry = - new NotificationPlatformRegistriesConfig() - .providerEventProjectorRegistry(platform, List.of()); + ProviderEventProjector projector = + new NotificationPlatformRegistriesConfig().providerEventProjector(); // when ProjectionResult result = - registry - .find(new ProviderId("ses")) - .orElseThrow() - .project(sesAttempt(), hardBounce(), DeliveryProjection.accepted()); + projector.project(sesAttempt(), hardBounce(), DeliveryProjection.accepted()); // then assertThat(result.projection().deliveryOutcome()).isEqualTo(DeliveryOutcome.BOUNCED); @@ -475,12 +451,6 @@ class NotificationProviderAssemblyTest { } }; } - - @Override - public ProviderEventProjector projector() { - return new StandardDeliveryProjector( - new ProviderId(type.name().toLowerCase(java.util.Locale.ROOT))); - } }; } } diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSecretRequirementsTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSecretRequirementsTest.java index 792bad14..a14024c6 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSecretRequirementsTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSecretRequirementsTest.java @@ -100,7 +100,7 @@ class NotificationSecretRequirementsTest { private static NotificationPlatformSettings.Provider smtp() { return new NotificationPlatformSettings.Provider( - "SMTP", true, true, "PRODUCTION", "smtp-main", Duration.ofSeconds(3), 8, 20); + "SMTP", true, true, "PRODUCTION", "smtp-main", Duration.ofSeconds(3), 8, 20, null); } private static NotificationPlatformSettings.Provider ses() { diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSecretsValidationTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSecretsValidationTest.java index 684b8a8e..f8ec7e2b 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSecretsValidationTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSecretsValidationTest.java @@ -365,7 +365,15 @@ class NotificationSecretsValidationTest { private static NotificationPlatformSettings.Provider smtp() { return new NotificationPlatformSettings.Provider( - "SMTP", true, true, "PRODUCTION", "smtp-main", java.time.Duration.ofSeconds(3), 8, 20); + "SMTP", + true, + true, + "PRODUCTION", + "smtp-main", + java.time.Duration.ofSeconds(3), + 8, + 20, + null); } private static NotificationPlatformSettings.Provider ses(List allowedTopicArns) { diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderRuntimeAssemblerTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderRuntimeAssemblerTest.java index af6a0202..2378a3bb 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderRuntimeAssemblerTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderRuntimeAssemblerTest.java @@ -3,7 +3,6 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpResponse; import dev.caskeleton.adapter.outbound.notification.platform.security.ProviderCredentialManager; import dev.caskeleton.adapter.outbound.notification.platform.security.SecurityFixtures; import dev.caskeleton.application.notification.platform.api.routing.Channel; @@ -13,12 +12,10 @@ import dev.caskeleton.application.notification.platform.security.AccessContext; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; import dev.caskeleton.application.notification.platform.security.ProtectedContactPoint; import java.net.URI; -import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; -import java.util.Map; import org.junit.jupiter.api.Test; class SesProviderRuntimeAssemblerTest { @@ -57,8 +54,6 @@ class SesProviderRuntimeAssemblerTest { private static SesProviderRuntimeAssembler assembler(ProviderCredentialManager credentials) { return new SesProviderRuntimeAssembler( - request -> - new NotificationHttpResponse(200, Map.of(), "{}".getBytes(StandardCharsets.UTF_8)), new AttachmentIntegrityGuard((reference, context) -> null), protector(), credentials, diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SmtpProviderRuntimeAssemblerTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SmtpProviderRuntimeAssemblerTest.java index aaf80775..9e807279 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SmtpProviderRuntimeAssemblerTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SmtpProviderRuntimeAssemblerTest.java @@ -51,7 +51,6 @@ class SmtpProviderRuntimeAssemblerTest { assertThat(assembled.callback()) .as("SMTP has no callback adapter; claiming one fails on the first provider event instead") .isEmpty(); - assertThat(assembled.projector()).isEmpty(); assertThat(assembled.reconciliation()) .as("handing a message to a relay is the end of what the sender can observe") .isEmpty(); @@ -110,7 +109,7 @@ class SmtpProviderRuntimeAssemblerTest { private static NotificationPlatformSettings.Provider profile() { return new NotificationPlatformSettings.Provider( - "SMTP", true, true, "local", "smtp-local", Duration.ofSeconds(10), 4, 8); + "SMTP", true, true, "local", "smtp-local", Duration.ofSeconds(10), 4, 8, null); } /** Not a lambda: the protector has three operations, and only one of them is exercised here. */ diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateCacheTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateCacheTest.java index 038ca736..95fe8daa 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateCacheTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateCacheTest.java @@ -3,12 +3,9 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpGateway; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpResponse; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SnsCertificateProvider; import java.net.URI; import java.nio.charset.StandardCharsets; -import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -99,13 +96,11 @@ class SnsCertificateCacheTest { } private SnsCertificateProvider serving(String pem) { - NotificationHttpGateway gateway = - request -> { + return NotificationCallbackProviderConfig.cachingCertificates( + uri -> { fetches.incrementAndGet(); - return new NotificationHttpResponse( - 200, Map.of(), pem.getBytes(StandardCharsets.US_ASCII)); - }; - return new NotificationCallbackProviderConfig().snsCertificateProvider(gateway); + return pem.getBytes(StandardCharsets.US_ASCII); + }); } private static URI url(int index) { diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistryTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistryTest.java index 46a8ac0f..ff8f01e5 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistryTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistryTest.java @@ -7,8 +7,6 @@ import dev.caskeleton.application.notification.platform.api.ProviderId; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; import dev.caskeleton.application.notification.platform.api.error.ProviderUnavailableException; import dev.caskeleton.application.notification.platform.api.routing.Channel; -import dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent; -import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort; import dev.caskeleton.application.notification.platform.provider.NotificationProviderAdapter; import dev.caskeleton.application.notification.platform.provider.ProviderCapabilities; import dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot; @@ -19,8 +17,6 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; @@ -66,7 +62,7 @@ class ProviderRuntimeRegistryTest { registry.register(runtime(1)); var oldPermit = registry.current(PROFILE).acquireAttempt(); - rotator(registry, candidate -> true).rotate(PROFILE, runtime(2)); + registry.replace(runtime(2)); var newPermit = registry.current(PROFILE).acquireAttempt(); assertThat(oldPermit.generation()).isEqualTo(1); @@ -76,17 +72,6 @@ class ProviderRuntimeRegistryTest { assertThat(registry.drainingGenerations(PROFILE)).isEmpty(); } - @Test - void failedNewCredentialKeepsOldRuntimeActive() { - var registry = new ProviderRuntimeRegistry(); - registry.register(runtime(1)); - - assertThatThrownBy(() -> rotator(registry, candidate -> false).rotate(PROFILE, runtime(2))) - .isInstanceOf(CredentialValidationException.class); - assertThat(registry.current(PROFILE).generation()).isEqualTo(1); - assertThat(registry.current(PROFILE).state()).isEqualTo(ProviderRuntimeState.HEALTHY); - } - @Test void concurrencyLimitFailsFastRatherThanQueueing() { var runtime = runtime(1); @@ -97,38 +82,6 @@ class ProviderRuntimeRegistryTest { runtime.acquireAttempt().close(); } - @Test - void rotationAuditRecordsGenerationButNoCredentialMaterial() { - var registry = new ProviderRuntimeRegistry(); - registry.register(runtime(1)); - var audit = new RecordingAudit(); - - new ProviderRuntimeRotator( - registry, - candidate -> true, - new RuntimeDrainCoordinator(Duration.ofMillis(1)), - audit, - CLOCK, - Duration.ofMillis(1)) - .rotate(PROFILE, runtime(2)); - - assertThat(audit.events).hasSize(1); - assertThat(audit.events.get(0).boundedAttributes()).containsEntry("generation", "2"); - assertThat(audit.events.get(0).boundedAttributes().values()) - .noneMatch(value -> value.contains("key")); - } - - private static ProviderRuntimeRotator rotator( - ProviderRuntimeRegistry registry, CredentialProbe probe) { - return new ProviderRuntimeRotator( - registry, - probe, - new RuntimeDrainCoordinator(Duration.ofMillis(1)), - new RecordingAudit(), - CLOCK, - Duration.ofMillis(1)); - } - private static ProviderRuntime runtime(long generation) { return new ProviderRuntime( new ProviderProfileSnapshot( @@ -178,15 +131,4 @@ class ProviderRuntimeRegistryTest { return CompletableFuture.failedFuture(new UnsupportedOperationException()); } } - - /** Audit port that keeps what it was told. */ - private static final class RecordingAudit implements NotificationAuditPort { - - private final List events = new ArrayList<>(); - - @Override - public void record(NotificationAuditEvent event) { - events.add(event); - } - } } diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeStateTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeStateTest.java index 671dd27b..641d3bd4 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeStateTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeStateTest.java @@ -29,6 +29,7 @@ import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; /** @@ -182,6 +183,89 @@ class ProviderRuntimeStateTest { new ProviderRuntime.RuntimeHealth(operatorState, Optional.of(operatorState.name()))); } + @ParameterizedTest(name = "{0}") + @DisplayName("각 상태에서 일곱 전이의 결과가 전이표와 같다") + @CsvSource( + textBlock = + """ + # from, throttle, degrade, recover, failAuth, resume, drain, disable + HEALTHY, THROTTLED, DEGRADED, HEALTHY, AUTHENTICATION_FAILED, HEALTHY, DRAINING, DISABLED + THROTTLED, THROTTLED, THROTTLED, HEALTHY, AUTHENTICATION_FAILED, HEALTHY, DRAINING, DISABLED + DEGRADED, DEGRADED, DEGRADED, HEALTHY, AUTHENTICATION_FAILED, HEALTHY, DRAINING, DISABLED + AUTHENTICATION_FAILED, AUTHENTICATION_FAILED, AUTHENTICATION_FAILED, AUTHENTICATION_FAILED, AUTHENTICATION_FAILED, AUTHENTICATION_FAILED, AUTHENTICATION_FAILED, AUTHENTICATION_FAILED + DISABLED, DISABLED, DISABLED, DISABLED, DISABLED, HEALTHY, DRAINING, DISABLED + DRAINING, DRAINING, DRAINING, DRAINING, DRAINING, HEALTHY, DRAINING, DISABLED + """) + void everyTransitionFromEveryStateEndsWhereTheTableSays( + ProviderRuntimeState from, + ProviderRuntimeState afterThrottle, + ProviderRuntimeState afterDegrade, + ProviderRuntimeState afterRecover, + ProviderRuntimeState afterFailAuthentication, + ProviderRuntimeState afterResume, + ProviderRuntimeState afterDrain, + ProviderRuntimeState afterDisable) { + // given + Map expected = new java.util.LinkedHashMap<>(); + expected.put("throttle", afterThrottle); + expected.put("degrade", afterDegrade); + expected.put("recover", afterRecover); + expected.put("failAuthentication", afterFailAuthentication); + expected.put("resume", afterResume); + expected.put("drain", afterDrain); + expected.put("disable", afterDisable); + + // when + Map actual = new java.util.LinkedHashMap<>(); + expected.keySet().forEach(operation -> actual.put(operation, afterOperation(from, operation))); + + // then + assertThat(actual).isEqualTo(expected); + } + + private static ProviderRuntimeState afterOperation(ProviderRuntimeState from, String operation) { + ProviderRuntime runtime = runtime(1, 1); + boolean arrived = + switch (from) { + case HEALTHY -> true; + case THROTTLED -> runtime.markThrottled(); + case DEGRADED -> runtime.markDegraded("UPSTREAM_5XX"); + case AUTHENTICATION_FAILED -> runtime.markAuthenticationFailed("INVALID_CREDENTIAL"); + case DISABLED -> runtime.markDisabled(); + case DRAINING -> runtime.markDraining(); + }; + assertThat(arrived).as("setting up " + from).isTrue(); + boolean reported = + switch (operation) { + case "throttle" -> runtime.markThrottled(); + case "degrade" -> runtime.markDegraded("UPSTREAM_5XX"); + case "recover" -> runtime.markHealthy(); + case "failAuthentication" -> runtime.markAuthenticationFailed("INVALID_CREDENTIAL"); + case "resume" -> runtime.resumeHealthy(); + case "drain" -> runtime.markDraining(); + case "disable" -> runtime.markDisabled(); + default -> throw new IllegalArgumentException(operation); + }; + // The boolean each operation returns is "is the runtime now in my target state"; checking it + // against the observed state keeps the two answers from drifting apart. + assertThat(reported) + .as(from + " " + operation) + .isEqualTo(targetOf(operation) == runtime.state()); + return runtime.state(); + } + + private static ProviderRuntimeState targetOf(String operation) { + return switch (operation) { + case "throttle" -> ProviderRuntimeState.THROTTLED; + case "degrade" -> ProviderRuntimeState.DEGRADED; + case "recover", "resume" -> ProviderRuntimeState.HEALTHY; + case "failAuthentication" -> ProviderRuntimeState.AUTHENTICATION_FAILED; + case "drain" -> ProviderRuntimeState.DRAINING; + case "disable" -> ProviderRuntimeState.DISABLED; + default -> throw new IllegalArgumentException(operation); + }; + } + private static boolean moveByOperator(ProviderRuntime runtime, ProviderRuntimeState state) { return switch (state) { case DISABLED -> runtime.markDisabled(); diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/EndpointGuardCallSiteTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/EndpointGuardCallSiteTest.java similarity index 99% rename from src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/EndpointGuardCallSiteTest.java rename to src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/EndpointGuardCallSiteTest.java index 53531bd2..be09f43a 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/EndpointGuardCallSiteTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/EndpointGuardCallSiteTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.notification.platform.provider.http; +package dev.caskeleton.adapter.outbound.notification.platform.provider; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/EndpointRoutabilityTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/EndpointRoutabilityTest.java similarity index 99% rename from src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/EndpointRoutabilityTest.java rename to src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/EndpointRoutabilityTest.java index 8a369404..2996c549 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/EndpointRoutabilityTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/EndpointRoutabilityTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.notification.platform.provider.http; +package dev.caskeleton.adapter.outbound.notification.platform.provider; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/JdkNotificationHttpGatewaySecurityTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/JdkNotificationHttpGatewaySecurityTest.java deleted file mode 100644 index 69757081..00000000 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/JdkNotificationHttpGatewaySecurityTest.java +++ /dev/null @@ -1,135 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.provider.http; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.catchThrowable; - -import com.sun.net.httpserver.HttpServer; -import java.io.IOException; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.URI; -import java.time.Duration; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; - -class JdkNotificationHttpGatewaySecurityTest { - - @Test - void productionGatewayRejectsLoopbackBeforeOpeningAConnection() { - JdkNotificationHttpGateway gateway = new JdkNotificationHttpGateway(Duration.ofSeconds(1)); - NotificationHttpRequest request = - new NotificationHttpRequest( - "POST", - URI.create("https://127.0.0.1:9/provider"), - Map.of(), - new byte[] {1}, - Duration.ofSeconds(1)); - - assertThatThrownBy(() -> gateway.exchange(request)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("deployment"); - } - - @Test - @Timeout(value = 20, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) - @DisplayName("끝나지 않는 응답 body는 상한까지만 읽고 나머지를 기다리지 않는다") - void aResponseBodyThatNeverEndsIsCutAtTheCapWithoutWaitingForItsEnd() throws IOException { - // given - CountDownLatch release = new CountDownLatch(1); - HttpServer server = - HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); - server.createContext( - "/provider", - exchange -> { - exchange.sendResponseHeaders(200, 0); - OutputStream body = exchange.getResponseBody(); - body.write(new byte[JdkNotificationHttpGateway.MAX_RESPONSE_BYTES * 2]); - body.flush(); - try { - // The rest of the body never comes: a chunked stream with no terminating chunk. - release.await(30, TimeUnit.SECONDS); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } - exchange.close(); - }); - server.start(); - JdkNotificationHttpGateway gateway = - new JdkNotificationHttpGateway(Duration.ofSeconds(1), true); - NotificationHttpRequest request = - new NotificationHttpRequest( - "POST", - URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/provider"), - Map.of(), - new byte[] {1}, - Duration.ofSeconds(10)); - - try { - // when - NotificationHttpResponse response = gateway.exchange(request); - - // then - assertThat(response.body()).hasSize(JdkNotificationHttpGateway.MAX_RESPONSE_BYTES); - } finally { - release.countDown(); - server.stop(0); - } - } - - @Test - @Timeout(value = 15, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) - @DisplayName("상한 아래에서 멈춘 응답 body는 요청 timeout에 끊겨 RESPONSE_TIMEOUT으로 끝난다") - void aResponseBodyThatStallsBelowTheCapEndsAtTheRequestTimeout() throws IOException { - // given - CountDownLatch release = new CountDownLatch(1); - HttpServer server = - HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); - server.createContext( - "/provider", - exchange -> { - exchange.sendResponseHeaders(200, 0); - OutputStream body = exchange.getResponseBody(); - body.write(new byte[16]); - body.flush(); - try { - // A trickle that never reaches the cap and never ends. - release.await(30, TimeUnit.SECONDS); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } - exchange.close(); - }); - server.start(); - JdkNotificationHttpGateway gateway = - new JdkNotificationHttpGateway(Duration.ofSeconds(1), true); - NotificationHttpRequest request = - new NotificationHttpRequest( - "POST", - URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/provider"), - Map.of(), - new byte[] {1}, - Duration.ofSeconds(2)); - - try { - // when - Throwable thrown = catchThrowable(() -> gateway.exchange(request)); - - // then - assertThat(thrown) - .isInstanceOf(NotificationHttpTransportException.class) - .extracting( - failure -> ((NotificationHttpTransportException) failure).reasonCode(), - failure -> ((NotificationHttpTransportException) failure).requestBodyCommitted()) - .containsExactly("RESPONSE_TIMEOUT", true); - } finally { - release.countDown(); - server.stop(0); - } - } -} diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/HttpCommitmentClassificationTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCommitmentClassificationTest.java similarity index 82% rename from src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/HttpCommitmentClassificationTest.java rename to src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCommitmentClassificationTest.java index e9c6f694..2a1d2885 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/http/HttpCommitmentClassificationTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCommitmentClassificationTest.java @@ -1,16 +1,15 @@ -package dev.caskeleton.adapter.outbound.notification.platform.provider.http; +package dev.caskeleton.adapter.outbound.notification.platform.provider.ses; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; -import java.lang.reflect.Method; import java.net.ConnectException; import java.net.NoRouteToHostException; import java.net.SocketException; import java.net.UnknownHostException; -import java.util.Locale; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import software.amazon.awssdk.core.exception.SdkClientException; /** * Whether the request body reached the provider — decided from a type, not from prose. @@ -24,7 +23,7 @@ import org.junit.jupiter.api.Test; *

Getting this wrong is expensive in one direction. A body wrongly judged committed makes the * attempt ambiguous, and an ambiguous attempt is deliberately never retried and never falls back. */ -class HttpCommitmentClassificationTest { +class SesCommitmentClassificationTest { @Test @DisplayName("a connect failure is classified before the write, whatever it says") @@ -77,16 +76,24 @@ class HttpCommitmentClassificationTest { assertThat(committed(first)).isTrue(); } + @Test + @DisplayName("SDK가 감싼 연결 실패도 전송 전으로 분류한다") + void aConnectFailureWrappedByTheSdkIsStillBeforeTheWrite() { + // given + SdkClientException wrapped = + SdkClientException.builder() + .message("Unable to execute HTTP request") + .cause(new ConnectException("refused")) + .build(); + + // when + boolean committed = SesFailureClassifier.requestMayHaveBeenSent(wrapped); + + // then + assertThat(committed).isFalse(); + } + private static boolean committed(IOException failure) { - try { - Method classifier = - JdkNotificationHttpGateway.class.getDeclaredMethod( - "bodyWasLikelyCommitted", IOException.class); - classifier.setAccessible(true); - return (boolean) classifier.invoke(null, failure); - } catch (ReflectiveOperationException unreachable) { - throw new IllegalStateException( - "the classifier moved; this test exists to pin it".toLowerCase(Locale.ROOT), unreachable); - } + return SesFailureClassifier.requestMayHaveBeenSent(failure); } } diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapterTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapterTest.java index 041b0b35..b2025b4e 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapterTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapterTest.java @@ -4,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.adapter.outbound.notification.platform.provider.UnconfiguredAttachmentResolver; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.JdkNotificationHttpGateway; import dev.caskeleton.adapter.outbound.notification.platform.provider.smtp.SmtpMimeMessageFactory; import dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmContactPointProtector; import dev.caskeleton.adapter.outbound.notification.platform.security.ProviderCredentialManager; @@ -20,6 +19,7 @@ import dev.caskeleton.application.notification.platform.api.content.EmailOptions import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; import dev.caskeleton.application.notification.platform.api.error.AttachmentIntegrityException; import dev.caskeleton.application.notification.platform.api.error.AttachmentUnavailableException; +import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; import dev.caskeleton.application.notification.platform.api.error.ProviderPayloadLimitException; import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.contact.EmailAddress; @@ -45,6 +45,7 @@ import java.util.Map; import java.util.Optional; import java.util.Properties; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class SesNotificationProviderAdapterTest extends ProviderAdapterContract { @@ -108,11 +109,47 @@ class SesNotificationProviderAdapterTest extends ProviderAdapterContract { adapter().submit(submission()).toCompletableFuture().join(); var recorded = harness.received().get(0); - assertThat(recorded.header("Authorization").orElseThrow()).startsWith("AWS4-HMAC-SHA256"); - assertThat(recorded.header("X-Amz-Content-Sha256")).isPresent(); + assertThat(recorded.method()).isEqualTo("POST"); + assertThat(recorded.uri().getPath()).isEqualTo("/v2/email/outbound-emails"); + assertThat(recorded.header("Authorization").orElseThrow()) + .startsWith("AWS4-HMAC-SHA256 Credential=AKIAEXAMPLE/") + .contains("/ap-northeast-2/ses/aws4_request"); + assertThat(recorded.header("X-Amz-Date")).isPresent(); assertThat(recorded.uri().toString()).doesNotContain(ProviderFixtures.SECRET_EMAIL); } + @Test + @DisplayName("SDK는 재시도하지 않는다: 5xx 응답도 요청 한 번으로 끝나고 재시도 판단은 정책에 남는다") + void theSdkRetriesNothingSoAServerErrorIsOneRequest() { + // given + harness.respondWith(503, "{\"message\":\"unavailable\"}", Map.of()); + + // when + var result = adapter().submit(submission()).toCompletableFuture().join(); + + // then + assertThat(harness.received()).hasSize(1); + assertThat(result.failure().orElseThrow().retryable()).isTrue(); + } + + @Test + @DisplayName("SES가 MessageRejected로 답하면 재시도하지 않는 PROVIDER_REJECTED다") + void aMessageRejectedAnswerIsAPermanentRejection() { + // given + harness.respondWith( + 400, + "{\"message\":\"Email address is not verified.\"}", + Map.of("x-amzn-ErrorType", "MessageRejected")); + + // when + var result = adapter().submit(submission()).toCompletableFuture().join(); + + // then + assertThat(result.failure().orElseThrow().code()) + .isEqualTo(NotificationFailureCode.PROVIDER_REJECTED); + assertThat(result.failure().orElseThrow().retryable()).isFalse(); + } + @Test void contentWithNoAttachmentStaysOnTheSimpleShape() { harness.respondWith(200, successBody(), Map.of()); @@ -257,17 +294,14 @@ class SesNotificationProviderAdapterTest extends ProviderAdapterContract { Optional.empty(), Duration.ofSeconds(3)); return new SesNotificationProviderAdapter( - new JdkNotificationHttpGateway(Duration.ofSeconds(2), true), + SesClients.create(properties), new SesRequestMapper( - properties, - new AwsSignatureV4Signer(), - new SmtpMimeMessageFactory(Session.getInstance(new Properties()))), + properties, new SmtpMimeMessageFactory(Session.getInstance(new Properties()))), new AttachmentIntegrityGuard(attachments), new SesFailureClassifier(), protector, credentials, - "AKIAEXAMPLE", - CLOCK); + "AKIAEXAMPLE"); } /** The {@code Content} object of a recorded request. */ diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/template/CanonicalNotificationRendererTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/template/CanonicalNotificationRendererTest.java index 6ba89f7f..7abdf043 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/template/CanonicalNotificationRendererTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/template/CanonicalNotificationRendererTest.java @@ -91,7 +91,6 @@ class CanonicalNotificationRendererTest { private static CanonicalNotificationRenderer renderer(VariableSchema schema) { return new CanonicalNotificationRenderer( - Channel.EMAIL, new FixedTemplateRegistry(schema), new JsonSchemaVariableValidator(), new PlaceholderTemplateEngine()); diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/template/ThymeleafNotificationRendererTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/template/ThymeleafRenderingTest.java similarity index 97% rename from src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/template/ThymeleafNotificationRendererTest.java rename to src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/template/ThymeleafRenderingTest.java index de4160b1..6c6fcb9e 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/template/ThymeleafNotificationRendererTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/template/ThymeleafRenderingTest.java @@ -31,7 +31,7 @@ import org.thymeleaf.templatemode.TemplateMode; * *

The escaping test is the reason this engine exists at all. */ -class ThymeleafNotificationRendererTest { +class ThymeleafRenderingTest { private static final String REQUIRED_CODE_SCHEMA = "{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"," @@ -112,9 +112,8 @@ class ThymeleafNotificationRendererTest { assertThat(engine.render("[(${value})]", Map.of("value", "a & b"))).isEqualTo("a & b"); } - private static ThymeleafNotificationRenderer renderer(VariableSchema schema) { - return new ThymeleafNotificationRenderer( - Channel.EMAIL, + private static CanonicalNotificationRenderer renderer(VariableSchema schema) { + return new CanonicalNotificationRenderer( new FixedTemplateRegistry(schema), new JsonSchemaVariableValidator(), new ThymeleafStringTemplateEngine()); diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ContractAdapters.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ContractAdapters.java index ffca3b26..ba132e37 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ContractAdapters.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ContractAdapters.java @@ -1,8 +1,7 @@ package dev.caskeleton.adapter.outbound.notification.platform.testkit; import dev.caskeleton.adapter.outbound.notification.platform.provider.UnconfiguredAttachmentResolver; -import dev.caskeleton.adapter.outbound.notification.platform.provider.http.JdkNotificationHttpGateway; -import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.AwsSignatureV4Signer; +import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesClients; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesFailureClassifier; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesNotificationProviderAdapter; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesProviderProperties; @@ -74,17 +73,14 @@ public final class ContractAdapters { Duration.ofSeconds(3)); var adapter = new SesNotificationProviderAdapter( - new JdkNotificationHttpGateway(Duration.ofSeconds(2), true), + SesClients.create(properties), new SesRequestMapper( - properties, - new AwsSignatureV4Signer(), - new SmtpMimeMessageFactory(Session.getInstance(new Properties()))), + properties, new SmtpMimeMessageFactory(Session.getInstance(new Properties()))), new AttachmentIntegrityGuard(new UnconfiguredAttachmentResolver()), new SesFailureClassifier(), protector, SecurityFixtures.credentials("ses-primary"), - "AKIAEXAMPLE", - CLOCK); + "AKIAEXAMPLE"); return new Case( "ses", adapter, diff --git a/src/adapter/outbound/persistence-jpa/build.gradle b/src/adapter/outbound/persistence-jpa/build.gradle index c9242d0d..af9b37c4 100644 --- a/src/adapter/outbound/persistence-jpa/build.gradle +++ b/src/adapter/outbound/persistence-jpa/build.gradle @@ -34,10 +34,10 @@ auxiliarySourceSets { dependencies { implementation project(':application-core') - implementation project(':application-notification') - // No `application-fileserver`. The Fileserver capability's entities, repositories and adapters - // were a package in this leaf, and that is how every application with a database also resolved - // the Fileserver use cases. They are `adapter:outbound:persistence-fileserver` now. + // No `application-fileserver` and no `application-notification`. Each capability's entities, + // repositories and adapters were a package in this leaf, and that is how every application with + // a database also resolved that capability's use cases. They are + // `adapter:outbound:persistence-fileserver` and `adapter:outbound:persistence-notification` now. implementation project(':shared-contract') // Typed startup failures, the EnvironmentPostProcessor order, the readiness-group merge and the // module-defaults loader this leaf's startup policy and shipped settings go through. @@ -92,6 +92,12 @@ dependencies { // dependency graph — the thing Build Composition governs — is untouched. postgresqlIntegrationTestImplementation project(':adapter:outbound:persistence-fileserver') postgresqlIntegrationTestImplementation project(':application-fileserver') + // The notification capability's persistence moved out the same way, and its real-PostgreSQL + // qualifications stay here for the same reason: this lane owns the container, the Flyway wiring + // and the readiness cards that name those tests (config/jpa/readiness-cards.yaml). Test scope + // only. + postgresqlIntegrationTestImplementation project(':adapter:outbound:persistence-notification') + postgresqlIntegrationTestImplementation 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 @@ -243,6 +249,9 @@ tasks.named('test') { inputs.dir(new File(rootProject.projectDir.parentFile, '.github/workflows')) inputs.file(file('build.gradle')) inputs.dir(file('src/jpaPlatformPerformanceTest/java')) + // AppliedMigrationImmutabilityTest pins the notification stream where it now lives. + inputs.dir(file('../persistence-notification/src/main/resources/db/migration')) + .withPropertyName('notificationMigrations') } // verifyJpaApiSurface — every public type this leaf exposes is a committed decision. @@ -275,6 +284,7 @@ apiSurface { adopterSources = fileTree(rootProject.projectDir) { include '*/**/src/main/java/**/*.java' exclude '**/build/**', 'adapter/outbound/persistence-jpa/**', 'adapter/outbound/persistence-fileserver/**', + 'adapter/outbound/persistence-notification/**', 'build-logic/**', 'optional-platforms/**' } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfiguration.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfiguration.java index 461b1fd2..4e274031 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfiguration.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfiguration.java @@ -3,7 +3,6 @@ package dev.caskeleton.adapter.outbound.persistence.autoconfigure; import dev.caskeleton.adapter.outbound.persistence.config.JpaAdapterComponentsConfig; import dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings; import dev.caskeleton.adapter.outbound.persistence.h2.H2PersistenceConfig; -import dev.caskeleton.adapter.outbound.persistence.notification.configuration.NotificationJpaPersistenceFacade; import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlPersistenceConfig; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -28,7 +27,6 @@ import org.springframework.context.annotation.Import; JpaAdapterComponentsConfig.class, PostgreSqlPersistenceConfig.class, H2PersistenceConfig.class, - NotificationJpaPersistenceFacade.class, PostgreSqlIdempotencyStoreConfig.class }) class PersistenceJpaAutoConfiguration {} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfig.java index e39e3410..3ed431f2 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfig.java @@ -36,7 +36,7 @@ import org.springframework.context.annotation.FilterType; *

  • {@code ..persistence.fileserver} — gated on its own capability switch, scanned by {@code * FileserverJpaPersistenceConfig} in the {@code persistence-fileserver} leaf; *
  • {@code ..persistence.notification} — assembled explicitly, bean by bean, by {@code - * NotificationJpaPersistenceFacade}. + * NotificationJpaPersistenceFacade} in the {@code persistence-notification} leaf. * * *

    Components under these packages keep their own {@code @ConditionalOnProperty} guards; being diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceJpaConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceJpaConfig.java index 74125feb..b26c8b41 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceJpaConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceJpaConfig.java @@ -11,17 +11,16 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; * simple name avoids {@code JpaConfig} to dodge a bean-name collision with the sample module. See * README "config". * - *

    The package list is enumerated rather than given as the persistence root, and two omissions - * are deliberate. {@code ...persistence.notification} and {@code ...persistence.fileserver} are - * opt-in capabilities whose schema streams are not in the default Flyway location, so - * their tables do not exist in a deployment that never asked for them. Scanning the whole root put - * those entities into the persistence unit unconditionally, and {@code ddl-auto=validate} then - * looked for {@code notification_request} and {@code fs_cleanup_item} in deployments that had - * switched both capabilities off — failing the boot over capabilities they had declined. {@code - * NotificationJpaPersistenceConfig} (imported by {@code NotificationJpaPersistenceFacade}) and - * {@code FileserverJpaPersistenceConfig} (the {@code persistence-fileserver} leaf's own - * auto-configuration) own those scans, each behind the same switch its adapter beans already - * carried. + *

    The package list is enumerated rather than given as the persistence root. {@code + * ...persistence.notification} and {@code ...persistence.fileserver} are opt-in + * capabilities whose schema streams are not in the default Flyway location, so their tables do not + * exist in a deployment that never asked for them. Both are their own leaves now ({@code + * persistence-notification}, {@code persistence-fileserver}) but keep packages under this root, and + * a package scan reads every jar on the classpath: scanning the root would put their entities into + * the persistence unit unconditionally again, and {@code ddl-auto=validate} would look for {@code + * notification_request} and {@code fs_cleanup_item} in deployments that had switched both + * capabilities off. Each leaf's own auto-configuration owns its scan, behind the same switch its + * adapter beans carry. * *

    The fileserver case was the more expensive of the two: it blocked every JPA-on Compose lane, * and it was invisible under H2, whose {@code create-drop} builds whatever the entities describe. @@ -83,13 +82,8 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; public class PersistenceJpaConfig { /** - * An opt-in sub-package deliberately excluded above, named so a test can assert the exclusion. + * The persistence root. The scans above must never name it, because the opt-in capability leaves + * keep their packages under it; see the class comment. */ - public static final String OPT_IN_NOTIFICATION_PACKAGE = - "dev.caskeleton.adapter.outbound.persistence.notification"; - - // OPT_IN_FILESERVER_PACKAGE used to sit beside the notification one. It is gone because the - // package is: the Fileserver capability's persistence is - // `adapter:outbound:persistence-fileserver` - // now, so this leaf cannot scan it by accident and has nothing to exclude. + public static final String ROOT_PACKAGE = "dev.caskeleton.adapter.outbound.persistence"; } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java index 6a5f4566..982d5787 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java @@ -137,12 +137,7 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { projection = new ProviderEventProjectionService( ledger, - providerId -> - switch (providerId.value()) { - case "ses" -> Optional.of(new DeliveredProjector(providerId)); - case "broken" -> Optional.of(new ThrowingProjector(providerId)); - default -> Optional.empty(); - }, + new DeliveredProjector(), attempts, attempts, (attempt, facts) -> {}, @@ -231,20 +226,6 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { assertThat(eventRow(event)).containsExactly(attempt.toString(), "APPLIED", null); } - @Test - void replayMarksAnEventWithNoProjectorFailed() { - // given - UUID delivery = insertDelivery("COMPLETED", null, null); - UUID attempt = insertStartedAttempt(delivery, "orphan", null); - UUID event = insertPendingEvent(attempt, null); - - // when - replay().replayOnce(); - - // then - assertThat(eventRow(event)).containsExactly(attempt.toString(), "FAILED", "NO_PROJECTOR"); - } - @Test void replayMarksAnEventWhoseProjectionThrowsFailed() { // given @@ -480,26 +461,21 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { } } - private record DeliveredProjector(ProviderId providerId) implements ProviderEventProjector { + /** Delivers every event, except for the provider named "broken", whose projection throws. */ + private static final class DeliveredProjector implements ProviderEventProjector { @Override public ProjectionResult project( DeliveryAttemptSnapshot attempt, ProviderEventRecord event, DeliveryProjection current) { + if (attempt.providerId().equals(new ProviderId("broken"))) { + throw new IllegalStateException("projector defect"); + } return ProjectionResult.applied( current.withDelivery(DeliveryOutcome.DELIVERED, EvidenceLevel.DEVICE_DELIVERED), "DELIVERED"); } } - private record ThrowingProjector(ProviderId providerId) implements ProviderEventProjector { - - @Override - public ProjectionResult project( - DeliveryAttemptSnapshot attempt, ProviderEventRecord event, DeliveryProjection current) { - throw new IllegalStateException("projector defect"); - } - } - private static final class EmptyAttributes implements NotificationVariablesCodecPort { @Override diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaModuleBoundaryTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaModuleBoundaryTest.java index 44a7deb6..bd07f7b0 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaModuleBoundaryTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaModuleBoundaryTest.java @@ -82,7 +82,6 @@ class JpaModuleBoundaryTest { // The PostgreSQL idempotency store, which lives with its feature // (idempotency.postgresql) and is registered from here. "idempotency", - "notification", "observation", "postgresql", "security", @@ -99,7 +98,6 @@ class JpaModuleBoundaryTest { Map.entry("idempotency", Set.of("api", "audit", "failure")), Map.entry("lock", Set.of("api")), Map.entry("migration", Set.of("api")), - Map.entry("notification", Set.of("api", "audit", "failure", "springdata")), Map.entry("observation", Set.of("api")), // Retained live-event history. No edge to `outbox` even though both are append-and-read // logs: the outbox is a delivery queue whose rows are consumed and retired, and this is a @@ -152,8 +150,6 @@ class JpaModuleBoundaryTest { Set.of( // The contracts other leaves are meant to speak. "api", - // Capability configuration facades, each assembling its own capability's internals. - "notification.configuration", // Cross-cutting seams a composition root legitimately wires. "transaction", "security", diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfigurationTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfigurationTest.java index c0ee0b79..52852987 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfigurationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfigurationTest.java @@ -5,7 +5,6 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.config.JpaAdapterComponentsConfig; import dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings; import dev.caskeleton.adapter.outbound.persistence.h2.H2PersistenceConfig; -import dev.caskeleton.adapter.outbound.persistence.notification.configuration.NotificationJpaPersistenceFacade; import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlPersistenceConfig; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -71,7 +70,6 @@ class PersistenceJpaAutoConfigurationTest { // No FileserverJpaPersistenceConfig. The Fileserver capability's persistence is its own // leaf now and publishes its own auto-configuration, so this root importing it would be // the coupling that put `application-fileserver` on every application's classpath. - NotificationJpaPersistenceFacade.class, PostgreSqlIdempotencyStoreConfig.class); } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceEntityScanCoverageTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceEntityScanCoverageTest.java index 538f800c..9ae8e235 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceEntityScanCoverageTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceEntityScanCoverageTest.java @@ -2,7 +2,6 @@ package dev.caskeleton.adapter.outbound.persistence.config; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.persistence.notification.NotificationJpaPersistenceConfig; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; @@ -37,21 +36,6 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; */ class PersistenceEntityScanCoverageTest { - /** Each opt-in capability: its package, its own configuration, and the switch that gates it. */ - private record OptInCapability(String packageName, Class configuration, String switchPrefix) {} - - private static final List OPT_IN = - List.of( - new OptInCapability( - PersistenceJpaConfig.OPT_IN_NOTIFICATION_PACKAGE, - NotificationJpaPersistenceConfig.class, - "ca-skeleton.notification.platform") - // Fileserver used to be the second row. It is not an opt-in package of this leaf any - // more — it is `adapter:outbound:persistence-fileserver`, its own module, which is a - // stronger answer to the same question: a package that is not here cannot be scanned by - // accident, so there is nothing for this test to assert about it. - ); - /** Sub-packages that hold no JPA entity or repository and therefore need no scan. */ private static final Set NOT_SCANNED = Set.of( @@ -61,10 +45,11 @@ class PersistenceEntityScanCoverageTest { "config", // Startup guards and the management view: no entity, no repository. "startup", - "h2", - // The opt-in capability, scanned by its own gated configuration instead. Fileserver was - // the second one and is not listed because the package is gone from this leaf entirely. - "notification"); + "h2"); + + // No opt-in capability package is listed: notification and fileserver are their own + // leaves now (persistence-notification, persistence-fileserver), each scanning its own + // package behind its own switch. @Test @DisplayName("every persistence sub-package is either scanned or explicitly exempt") @@ -100,56 +85,22 @@ class PersistenceEntityScanCoverageTest { } @Test - @DisplayName("no opt-in package is in the always-installed scan") - void noOptInPackageIsScannedUnconditionally() { + @DisplayName("the always-installed scan never names the persistence root") + void theRootIsNeverScanned() { + // given List entityPackages = List.of(PersistenceJpaConfig.class.getAnnotation(EntityScan.class).basePackages()); + + // when List repositoryPackages = List.of( PersistenceJpaConfig.class.getAnnotation(EnableJpaRepositories.class).basePackages()); - for (OptInCapability capability : OPT_IN) { - assertThat(entityPackages) - .as( - "scanning %s here puts its tables into ddl-auto=validate for every deployment", - capability.packageName()) - .doesNotContain(capability.packageName()); - assertThat(repositoryPackages).doesNotContain(capability.packageName()); - } + // then assertThat(entityPackages) - .as("and naming the root would scan every one of them by inclusion") - .doesNotContain("dev.caskeleton.adapter.outbound.persistence"); - } - - @Test - @DisplayName("each opt-in scan is behind the same switch as its own beans") - void everyOptInScanIsGatedByItsCapabilitySwitch() { - for (OptInCapability capability : OPT_IN) { - var condition = - capability - .configuration() - .getAnnotation( - org.springframework.boot.autoconfigure.condition.ConditionalOnProperty.class); - - assertThat(condition) - .as( - "%s must carry the capability condition, or the scan is unconditional again", - capability.configuration().getSimpleName()) - .isNotNull(); - assertThat(condition.prefix()).isEqualTo(capability.switchPrefix()); - assertThat(condition.name()).containsExactly("enabled"); - assertThat(condition.havingValue()).isEqualTo("true"); - assertThat(List.of(capability.configuration().getAnnotation(EntityScan.class).basePackages())) - .containsExactly(capability.packageName()); - assertThat( - List.of( - capability - .configuration() - .getAnnotation(EnableJpaRepositories.class) - .basePackages())) - .as("entities without repositories is half a scan, and fails at the first query") - .containsExactly(capability.packageName()); - } + .as("the capability leaves keep packages under the root, so naming it scans them all") + .doesNotContain(PersistenceJpaConfig.ROOT_PACKAGE); + assertThat(repositoryPackages).doesNotContain(PersistenceJpaConfig.ROOT_PACKAGE); } private static Set scannedLeafNames(Class configuration) { diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java index 87c59834..3eb6bb6a 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java @@ -9,6 +9,7 @@ import java.nio.file.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HexFormat; +import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Stream; @@ -22,7 +23,20 @@ import org.junit.jupiter.api.Test; */ class AppliedMigrationImmutabilityTest { - private static final Path MIGRATIONS = Path.of("src/main/resources/db/migration"); + /** + * Every tree whose migrations run against the database this leaf owns. + * + *

    The notification capability's stream moved to {@code + * adapter:outbound:persistence-notification} with its bytes and its classpath location unchanged + * ({@code db/migration/jpa/notification-platform}), so a database that applied it still + * validates. Its pins stayed in this manifest and are checked where the files now live: moving a + * migration must not be the way it stops being frozen. + */ + private static final List MIGRATION_ROOTS = + List.of( + Path.of("src/main/resources/db/migration"), + Path.of("../persistence-notification/src/main/resources/db/migration")); + private static final Path MANIFEST = Path.of("src/test/resources/db/applied-migrations.sha256"); @Test @@ -67,12 +81,19 @@ class AppliedMigrationImmutabilityTest { private static Map currentChecksums() throws IOException { Map checksums = new TreeMap<>(); - try (Stream files = Files.walk(MIGRATIONS)) { - for (Path file : - files.filter(path -> path.getFileName().toString().matches("V\\d+__.+\\.sql")).toList()) { - checksums.put( - MIGRATIONS.relativize(file).toString().replace('\\', '/'), - sha256(Files.readString(file))); + for (Path root : MIGRATION_ROOTS) { + try (Stream files = Files.walk(root)) { + for (Path file : + files + .filter(path -> path.getFileName().toString().matches("V\\d+__.+\\.sql")) + .toList()) { + String key = root.relativize(file).toString().replace('\\', '/'); + String previous = checksums.put(key, sha256(Files.readString(file))); + if (previous != null) { + throw new IllegalStateException( + key + " exists in two migration trees; the classpath would load one at random"); + } + } } } return checksums; diff --git a/src/adapter/outbound/persistence-notification/build.gradle b/src/adapter/outbound/persistence-notification/build.gradle new file mode 100644 index 00000000..c55bb99a --- /dev/null +++ b/src/adapter/outbound/persistence-notification/build.gradle @@ -0,0 +1,32 @@ +plugins { + id 'ca.spring-library' +} + +// The Notification capability's relational persistence. +// +// It was a package inside `adapter:outbound:persistence-jpa`, and that is why every application +// that needed a database also resolved the notification use cases: the capability's entities, +// Spring Data repositories, stores and its Flyway stream were compiled into the leaf every +// deployment with a database depends on, so `application-notification` came with them (review +// 2026-09-24 S2-#1b). Extracted the way `adapter:outbound:persistence-fileserver` was. +// +// The package was self-contained — it imported `application.notification`, JPA, Hibernate, Spring +// Data, JDBC and Flyway, and not one type from any other `persistence.*` package — so the move +// needed no seam. It does not depend on `persistence-jpa`: it contributes entities, repositories +// and stores to whatever persistence unit the application already has. +// +// The migrations moved with their bytes and their classpath location unchanged +// (`db/migration/jpa/notification-platform`), so Flyway computes the same version and checksum +// for every file and a database that already applied the stream validates as before. +// `persistence-jpa`'s AppliedMigrationImmutabilityTest still pins them, where they now live. +dependencies { + implementation project(':application-core') + implementation project(':application-notification') + + implementation 'org.springframework.boot:spring-boot-autoconfigure' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework:spring-jdbc' + implementation 'org.springframework:spring-context' + // NotificationSchemaStream applies the capability's own stream with its own history table. + implementation 'org.flywaydb:flyway-core' +} diff --git a/src/adapter/outbound/persistence-notification/gradle.lockfile b/src/adapter/outbound/persistence-notification/gradle.lockfile new file mode 100644 index 00000000..a67e344c --- /dev/null +++ b/src/adapter/outbound/persistence-notification/gradle.lockfile @@ -0,0 +1,183 @@ +# This is a Gradle generated file for dependency locking. +# Manual edits can break the build and are not advised. +# This file is expected to be part of source control. +biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=compileClasspath,testCompileClasspath +ch.qos.logback:logback-classic:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-core:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-databind:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml:classmate:1.7.3=runtimeClasspath,testRuntimeClasspath +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor +com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs +com.github.spotbugs:spotbugs:4.10.2=spotbugs +com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor +com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs +com.google.code.gson:gson:2.13.2=spotbugs +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.38.0=compileClasspath,testCompileClasspath +com.google.errorprone:error_prone_annotations:2.41.0=spotbugs +com.google.errorprone:error_prone_annotations:2.47.0=checkstyle +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor +com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.guava:guava:33.6.0-jre=checkstyle +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor +com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins +com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath +com.puppycrawl.tools:checkstyle:13.5.0=checkstyle +com.sun.istack:istack-commons-runtime:4.1.2=runtimeClasspath,testRuntimeClasspath +com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath +com.zaxxer:HikariCP:7.0.2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +commons-beanutils:commons-beanutils:1.11.0=checkstyle +commons-collections:commons-collections:3.2.2=checkstyle +commons-io:commons-io:2.21.0=spotbugs +commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +info.picocli:picocli:4.7.7=checkstyle +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor +io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.inject:jakarta.inject-api:2.0.1=runtimeClasspath,testRuntimeClasspath +jakarta.persistence:jakarta.persistence-api:3.2.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.transaction:jakarta.transaction-api:2.0.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +jaxen:jaxen:2.0.6=spotbugs +net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs +org.antlr:antlr4-runtime:4.13.2=checkstyle,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.bcel:bcel:6.12.0=spotbugs +org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs +org.apache.commons:commons-text:1.15.0=spotbugs +org.apache.commons:commons-text:1.3=checkstyle +org.apache.httpcomponents:httpclient:4.5.13=checkstyle +org.apache.httpcomponents:httpcore:4.4.16=checkstyle +org.apache.logging.log4j:log4j-api:2.25.5=compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-core:2.25.5=spotbugs +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven.doxia:doxia-core:1.12.0=checkstyle +org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle +org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle +org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle +org.apache.tomcat.embed:tomcat-embed-core:11.0.24=testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-el:11.0.24=testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=testCompileClasspath,testRuntimeClasspath +org.apache.xbean:xbean-reflect:3.7=checkstyle +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath +org.aspectj:aspectjweaver:1.9.25.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath +org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle +org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle +org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle +org.codehaus.plexus:plexus-utils:3.3.0=checkstyle +org.dom4j:dom4j:2.2.0=spotbugs +org.eclipse.angus:angus-activation:2.0.3=runtimeClasspath,testRuntimeClasspath +org.flywaydb:flyway-core:11.14.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.glassfish.jaxb:jaxb-core:4.0.9=runtimeClasspath,testRuntimeClasspath +org.glassfish.jaxb:jaxb-runtime:4.0.9=runtimeClasspath,testRuntimeClasspath +org.glassfish.jaxb:txw2:4.0.9=runtimeClasspath,testRuntimeClasspath +org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.hibernate.models:hibernate-models:1.0.1=runtimeClasspath,testRuntimeClasspath +org.hibernate.orm:hibernate-core:7.2.24.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.javassist:javassist:3.28.0-GA=checkstyle +org.jboss.logging:jboss-logging:3.6.3.Final=runtimeClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath +org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath +org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath +org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit:junit-bom:6.1.0=spotbugs +org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath +org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath +org.objenesis:objenesis:3.3=testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath +org.osgi:org.osgi.annotation.bundle:2.0.0=compileClasspath,testCompileClasspath +org.osgi:org.osgi.annotation.versioning:1.1.2=compileClasspath,testCompileClasspath +org.osgi:org.osgi.resource:1.0.0=compileClasspath,testCompileClasspath +org.osgi:org.osgi.service.serviceloader:1.0.0=compileClasspath,testCompileClasspath +org.ow2.asm:asm-analysis:9.10.1=spotbugs +org.ow2.asm:asm-commons:9.10.1=spotbugs +org.ow2.asm:asm-tree:9.10.1=spotbugs +org.ow2.asm:asm-util:9.10.1=spotbugs +org.ow2.asm:asm:9.10.1=spotbugs +org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath +org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.reflections:reflections:0.10.2=checkstyle +org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath +org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j +org.slf4j:slf4j-simple:2.0.18=checkstyle +org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-data-commons:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-data-jpa:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-hibernate:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jdbc:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jpa:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-persistence:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-sql:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-data-jpa:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jdbc:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-logging:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-transaction:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-web-server:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.data:spring-data-commons:4.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.data:spring-data-jpa:4.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-aspects:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-jdbc:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-orm:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-tx:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath +org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs +org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath +org.yaml:snakeyaml:2.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-core:3.1.5=testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-databind:3.1.5=testCompileClasspath,testRuntimeClasspath +tools.jackson:jackson-bom:3.1.5=testCompileClasspath,testRuntimeClasspath +empty= diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaPersistenceConfig.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaPersistenceConfig.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaPersistenceConfig.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaPersistenceConfig.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationSchemaActivation.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationSchemaActivation.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationSchemaActivation.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationSchemaActivation.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationSchemaStream.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationSchemaStream.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationSchemaStream.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationSchemaStream.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java similarity index 94% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java index b31d2f56..33154131 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java @@ -11,7 +11,7 @@ import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaAdmi import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaContactPointStore; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaDeliveryAttemptStore; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationRequestStore; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationSideEffectStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationSideEffect; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaPolicyStores; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaProviderEventLedger; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientDeliveryStore; @@ -54,9 +54,9 @@ import dev.caskeleton.application.notification.platform.template.TemplateContent import dev.caskeleton.application.notification.platform.template.TemplateRegistry; import java.time.Clock; import java.util.Locale; +import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.jdbc.core.JdbcOperations; @@ -66,6 +66,14 @@ import org.springframework.jdbc.core.JdbcOperations; *

    This is the only place that sees both the application ports and the persistence adapter, which * is what keeps application-core free of JPA and the persistence leaf free of use-case policy. * + *

    This is the {@code adapter:outbound:persistence-notification} leaf's own auto-configuration + * root. It used to be imported by {@code persistence-jpa}'s root, which is how that leaf came to + * depend on {@code application-notification} and every deployment with a database resolved the + * notification use cases. It is ordered before the JPA root because the {@code @EntityScan} it + * imports contributes packages to the persistence unit, and a contribution that arrives after the + * {@code EntityManagerFactory} is built arrives too late to be in it — the same reason the + * fileserver leaf's root is ordered there. + * *

    It lives in the persistence leaf, not in the composition root. As a bootstrap class it * imported twenty-two persistence implementation types by name — every store, every repository, the * record mapper — which made all of them cross-leaf source contracts: moving one to another @@ -81,7 +89,9 @@ import org.springframework.jdbc.core.JdbcOperations; * closed now: the scan moved to {@code NotificationJpaPersistenceConfig} behind the same switch, * and {@link NotificationSchemaActivation} refuses startup until the stream is promoted. */ -@Configuration(proxyBeanMethods = false) +@AutoConfiguration( + beforeName = + "dev.caskeleton.adapter.outbound.persistence.autoconfigure.PersistenceJpaAutoConfiguration") @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", @@ -232,7 +242,7 @@ public class NotificationJpaPersistenceFacade { @Bean public NotificationSideEffectPort notificationSideEffectPort( ContactPointStorePort contactPoints, SuppressionStorePort suppressions, Clock clock) { - return new JpaNotificationSideEffectStore(contactPoints, suppressions, clock); + return new JpaNotificationSideEffect(contactPoints, suppressions, clock); } /** Preference persistence. */ diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditEntity.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditEntity.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditJpaRepository.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditJpaRepository.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodec.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodec.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodec.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodec.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentEntity.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentEntity.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentJpaRepository.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentJpaRepository.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointEntity.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointEntity.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointJpaRepository.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointJpaRepository.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimEntity.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimEntity.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimJpaRepository.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimJpaRepository.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptEntity.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptEntity.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptJpaRepository.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptJpaRepository.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcNotificationServingState.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcNotificationServingState.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcNotificationServingState.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcNotificationServingState.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcReconciliationJobStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcReconciliationJobStore.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcReconciliationJobStore.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcReconciliationJobStore.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaAdminOperationStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaAdminOperationStore.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaAdminOperationStore.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaAdminOperationStore.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaContactPointStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaContactPointStore.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaContactPointStore.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaContactPointStore.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaDeliveryAttemptStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaDeliveryAttemptStore.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaDeliveryAttemptStore.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaDeliveryAttemptStore.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationRequestStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationRequestStore.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationRequestStore.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationRequestStore.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationSideEffectStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationSideEffect.java similarity index 96% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationSideEffectStore.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationSideEffect.java index 79eb7bfc..cafa5156 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationSideEffectStore.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationSideEffect.java @@ -23,13 +23,13 @@ import java.util.UUID; * second says the person does not want this. Both stop sending, but mapping them to one reason * would make the difference invisible to whoever later asks why an address is suppressed. */ -public final class JpaNotificationSideEffectStore implements NotificationSideEffectPort { +public final class JpaNotificationSideEffect implements NotificationSideEffectPort { private final ContactPointStorePort contactPoints; private final SuppressionStorePort suppressions; private final Clock clock; - public JpaNotificationSideEffectStore( + public JpaNotificationSideEffect( ContactPointStorePort contactPoints, SuppressionStorePort suppressions, Clock clock) { this.contactPoints = Objects.requireNonNull(contactPoints, "contactPoints"); this.suppressions = Objects.requireNonNull(suppressions, "suppressions"); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaPolicyStores.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaPolicyStores.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaPolicyStores.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaPolicyStores.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaProviderEventLedger.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaProviderEventLedger.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaProviderEventLedger.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaProviderEventLedger.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientDeliveryStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientDeliveryStore.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientDeliveryStore.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientDeliveryStore.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientLeaseStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientLeaseStore.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientLeaseStore.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientLeaseStore.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaSuppressionStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaSuppressionStore.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaSuppressionStore.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaSuppressionStore.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaTemplateRegistry.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaTemplateRegistry.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaTemplateRegistry.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaTemplateRegistry.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRecordMapper.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRecordMapper.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRecordMapper.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRecordMapper.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestEntity.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestEntity.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestJpaRepository.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestJpaRepository.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceEntity.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceEntity.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceJpaRepository.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceJpaRepository.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventEntity.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventEntity.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventJpaRepository.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventJpaRepository.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSql.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSql.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSql.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSql.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryEntity.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryEntity.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryJpaRepository.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryJpaRepository.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionEntity.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionEntity.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionJpaRepository.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionJpaRepository.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionEntity.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionEntity.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionJpaRepository.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionJpaRepository.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TenantBoundRepositoryGuard.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TenantBoundRepositoryGuard.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TenantBoundRepositoryGuard.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TenantBoundRepositoryGuard.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxCommitEventPublisher.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxCommitEventPublisher.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxCommitEventPublisher.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxCommitEventPublisher.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntity.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntity.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemJpaRepository.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemJpaRepository.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxOutboxRecordFactory.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxOutboxRecordFactory.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxOutboxRecordFactory.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxOutboxRecordFactory.java diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/JpaNotificationInbox.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/JpaNotificationInbox.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/JpaNotificationInbox.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/JpaNotificationInbox.java diff --git a/src/adapter/outbound/persistence-notification/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/outbound/persistence-notification/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..f878c9a3 --- /dev/null +++ b/src/adapter/outbound/persistence-notification/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +dev.caskeleton.adapter.outbound.persistence.notification.configuration.NotificationJpaPersistenceFacade diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V10__variables_payload_envelope_guard.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V10__variables_payload_envelope_guard.sql similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V10__variables_payload_envelope_guard.sql rename to src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V10__variables_payload_envelope_guard.sql diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V1__notification_platform_core.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V1__notification_platform_core.sql similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V1__notification_platform_core.sql rename to src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V1__notification_platform_core.sql diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V2__notification_platform_contact_template_policy.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V2__notification_platform_contact_template_policy.sql similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V2__notification_platform_contact_template_policy.sql rename to src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V2__notification_platform_contact_template_policy.sql diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V3__notification_platform_inbox_admin.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V3__notification_platform_inbox_admin.sql similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V3__notification_platform_inbox_admin.sql rename to src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V3__notification_platform_inbox_admin.sql diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V4__notification_platform_alignment_and_activation.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V4__notification_platform_alignment_and_activation.sql similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V4__notification_platform_alignment_and_activation.sql rename to src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V4__notification_platform_alignment_and_activation.sql diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V5__notification_recipient_expiry.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V5__notification_recipient_expiry.sql similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V5__notification_recipient_expiry.sql rename to src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V5__notification_recipient_expiry.sql diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V6__notification_projection_facts.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V6__notification_projection_facts.sql similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V6__notification_projection_facts.sql rename to src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V6__notification_projection_facts.sql diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V7__notification_collapse.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V7__notification_collapse.sql similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V7__notification_collapse.sql rename to src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V7__notification_collapse.sql diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V8__notification_admin_claim.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V8__notification_admin_claim.sql similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V8__notification_admin_claim.sql rename to src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V8__notification_admin_claim.sql diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V9__notification_evidence_certainty.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V9__notification_evidence_certainty.sql similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/V9__notification_evidence_certainty.sql rename to src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V9__notification_evidence_certainty.sql diff --git a/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationPersistenceActivationTest.java b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationPersistenceActivationTest.java new file mode 100644 index 00000000..0eca476b --- /dev/null +++ b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationPersistenceActivationTest.java @@ -0,0 +1,76 @@ +package dev.caskeleton.adapter.outbound.persistence.notification.configuration; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.persistence.notification.NotificationJpaPersistenceConfig; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.persistence.autoconfigure.EntityScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +/** + * How the leaf turns on: by being on the classpath, behind the capability switch, and early enough + * for its entities to be in the persistence unit. + * + *

    These assertions used to be one row of {@code persistence-jpa}'s entity-scan coverage test, + * back when the notification package was an opt-in package of that leaf. + */ +class NotificationPersistenceActivationTest { + + private static final String PACKAGE = "dev.caskeleton.adapter.outbound.persistence.notification"; + + @Test + @DisplayName("엔티티·리포지토리 스캔은 이 기능 패키지만, 기능 스위치 뒤에서 한다") + void theScanCoversThisPackageOnlyAndIsBehindTheCapabilitySwitch() { + // given + Class configuration = NotificationJpaPersistenceConfig.class; + + // when + ConditionalOnProperty condition = configuration.getAnnotation(ConditionalOnProperty.class); + + // then + assertThat(condition.prefix()).isEqualTo("ca-skeleton.notification.platform"); + assertThat(condition.name()).containsExactly("enabled"); + assertThat(condition.havingValue()).isEqualTo("true"); + assertThat(List.of(configuration.getAnnotation(EntityScan.class).basePackages())) + .containsExactly(PACKAGE); + assertThat(List.of(configuration.getAnnotation(EnableJpaRepositories.class).basePackages())) + .as("entities without repositories is half a scan, and fails at the first query") + .containsExactly(PACKAGE); + } + + @Test + @DisplayName("facade는 JPA 루트보다 먼저 도는 이 leaf의 auto-configuration이다") + void theFacadeIsThisLeafsAutoConfigurationOrderedBeforeTheJpaRoot() throws IOException { + // given + Path imports = + Path.of( + "src/main/resources/META-INF/spring/" + + "org.springframework.boot.autoconfigure.AutoConfiguration.imports"); + + // when + AutoConfiguration root = + NotificationJpaPersistenceFacade.class.getAnnotation(AutoConfiguration.class); + + // then + assertThat(Files.readString(imports, StandardCharsets.UTF_8)) + .contains(NotificationJpaPersistenceFacade.class.getName()); + assertThat(root.beforeName()) + .as("an @EntityScan that arrives after the EntityManagerFactory is built is not in it") + .containsExactly( + "dev.caskeleton.adapter.outbound.persistence.autoconfigure." + + "PersistenceJpaAutoConfiguration"); + assertThat( + NotificationJpaPersistenceFacade.class + .getAnnotation(ConditionalOnProperty.class) + .prefix()) + .isEqualTo("ca-skeleton.notification.platform"); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationSchemaActivationLifecycleTest.java b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationSchemaActivationLifecycleTest.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationSchemaActivationLifecycleTest.java rename to src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationSchemaActivationLifecycleTest.java diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodecTest.java b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodecTest.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodecTest.java rename to src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodecTest.java diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositoryDiscoveryTest.java b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositoryDiscoveryTest.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositoryDiscoveryTest.java rename to src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositoryDiscoveryTest.java diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositorySurfaceTest.java b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositorySurfaceTest.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositorySurfaceTest.java rename to src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositorySurfaceTest.java diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSqlTest.java b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSqlTest.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSqlTest.java rename to src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSqlTest.java diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntityTest.java b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntityTest.java similarity index 100% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntityTest.java rename to src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntityTest.java diff --git a/src/app-bootstrap/build.gradle b/src/app-bootstrap/build.gradle index 72c5fc7c..4b08eb28 100644 --- a/src/app-bootstrap/build.gradle +++ b/src/app-bootstrap/build.gradle @@ -152,7 +152,7 @@ dependencies { // runtimeOnly project(':adapter:inbound:websocket') // WebSocket (STOMP push) // runtimeOnly project(':adapter:inbound:grpc') // gRPC 서버 // runtimeOnly project(':composition:fileserver-platform') // 파일 서버 - // runtimeOnly project(':composition:notification-platform') // 알림 (persistence-jpa 줄도 함께 푼다) + // runtimeOnly project(':composition:notification-platform') // 알림 (persistence-jpa·persistence-notification을 함께 가져온다) // 기본 조립에 있는 application composition. 둘 다 포트만 보고, 필요한 것(outbox store, 멱등성 // provider)이 없으면 아무것도 만들지 않는다. sample-portfolio도 같은 멱등성 모듈을 쓴다. diff --git a/src/app-bootstrap/gradle.lockfile b/src/app-bootstrap/gradle.lockfile index f57461bf..268753dc 100644 --- a/src/app-bootstrap/gradle.lockfile +++ b/src/app-bootstrap/gradle.lockfile @@ -389,6 +389,7 @@ software.amazon.awssdk:apache-client:2.30.0=architectureTestRuntimeClasspath,int software.amazon.awssdk:arns:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath software.amazon.awssdk:auth:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath software.amazon.awssdk:aws-core:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:aws-json-protocol:2.30.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath software.amazon.awssdk:aws-query-protocol:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath software.amazon.awssdk:aws-xml-protocol:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath software.amazon.awssdk:bom:2.30.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath @@ -412,6 +413,7 @@ software.amazon.awssdk:retries-spi:2.30.0=architectureTestRuntimeClasspath,integ software.amazon.awssdk:retries:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath software.amazon.awssdk:s3:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath software.amazon.awssdk:sdk-core:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:sesv2:2.30.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath software.amazon.awssdk:third-party-jackson-core:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath software.amazon.awssdk:utils:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath software.amazon.eventstream:eventstream:1.0.1=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjectionService.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjectionService.java index 2cc069ea..7db02dfb 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjectionService.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjectionService.java @@ -17,7 +17,7 @@ import java.util.Optional; public final class ProviderEventProjectionService { private final ProviderEventLedger ledger; - private final ProviderEventProjectorRegistry projectors; + private final ProviderEventProjector projector; private final DeliveryAttemptResolverPort attemptResolver; private final DeliveryProjectionStorePort projections; private final NotificationSideEffectPort sideEffects; @@ -26,14 +26,14 @@ public final class ProviderEventProjectionService { public ProviderEventProjectionService( ProviderEventLedger ledger, - ProviderEventProjectorRegistry projectors, + ProviderEventProjector projector, DeliveryAttemptResolverPort attemptResolver, DeliveryProjectionStorePort projections, NotificationSideEffectPort sideEffects, TransactionPort transactions, NotificationMetricsPort metrics) { this.ledger = Objects.requireNonNull(ledger, "ledger"); - this.projectors = Objects.requireNonNull(projectors, "projectors"); + this.projector = Objects.requireNonNull(projector, "projector"); this.attemptResolver = Objects.requireNonNull(attemptResolver, "attemptResolver"); this.projections = Objects.requireNonNull(projections, "projections"); this.sideEffects = Objects.requireNonNull(sideEffects, "sideEffects"); @@ -44,9 +44,9 @@ public final class ProviderEventProjectionService { /** * Project one stored event. Safe to call repeatedly for the same event. * - *

    One transaction for all of it, including the attempt lookup. Resolving binds the event and a - * missing projector marks it failed, and both are modifying queries: run before the boundary, - * from a caller with no transaction of its own (the replay worker), they threw every time. + *

    One transaction for all of it, including the attempt lookup. Resolving binds the event, a + * modifying query: run before the boundary, from a caller with no transaction of its own (the + * replay worker), it threw every time. */ public Optional project(ProviderEventRecord event) { Objects.requireNonNull(event, "event"); @@ -77,14 +77,8 @@ public final class ProviderEventProjectionService { if (attempt.isEmpty()) { return Optional.empty(); } - Optional projector = projectors.find(attempt.get().providerId()); - if (projector.isEmpty()) { - ledger.markFailed(event.id(), "NO_PROJECTOR"); - return Optional.empty(); - } - DeliveryProjection current = projections.load(attempt.get().attemptId()); - ProjectionResult result = projector.get().project(attempt.get(), event, current); + ProjectionResult result = projector.project(attempt.get(), event, current); if (result.changed()) { projections.save(attempt.get().attemptId(), result.projection()); // Claimed, not merely conditioned on the facts. The ledger is replayed by design, so "the diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjector.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjector.java index b5d743be..2185a0f1 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjector.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjector.java @@ -1,18 +1,13 @@ package dev.caskeleton.application.notification.platform.callback; -import dev.caskeleton.application.notification.platform.api.ProviderId; - /** - * Channel and provider specific merge rule. + * The merge rule that turns a provider event into a delivery projection. * *

    Implementations must be idempotent and must never compare enum ordinals: {@code sent} arriving * after {@code delivered} is a normal out-of-order callback, not a state regression. */ public interface ProviderEventProjector { - /** Provider family this projector understands. */ - ProviderId providerId(); - /** Merge one event into the current projection. */ ProjectionResult project( DeliveryAttemptSnapshot attempt, ProviderEventRecord event, DeliveryProjection current); diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjectorRegistry.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjectorRegistry.java deleted file mode 100644 index a3a906fd..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjectorRegistry.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.callback; - -import dev.caskeleton.application.notification.platform.api.ProviderId; -import java.util.Optional; - -/** Lookup of the projector that owns a provider family. */ -public interface ProviderEventProjectorRegistry { - - /** Projector for a provider, if one is registered. */ - Optional find(ProviderId providerId); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/StandardDeliveryProjector.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/StandardDeliveryProjector.java index 99f8f251..8ece5e53 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/StandardDeliveryProjector.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/StandardDeliveryProjector.java @@ -1,6 +1,5 @@ package dev.caskeleton.application.notification.platform.callback; -import dev.caskeleton.application.notification.platform.api.ProviderId; import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; @@ -14,22 +13,14 @@ import java.util.Objects; * delivery. A rule of the form "apply the event with the higher rank" silently discards the first * of those and silently overwrites the second. * - *

    Provider adapters subclass this only to add provider-specific events. The rules below are the - * ones every channel must obey, and a subclass that weakens them is a defect, not a customization. + *

    One instance serves every provider. It used to be constructed once per provider id and looked + * up through a registry keyed by it, but every provider's projector was this class with a different + * id and nothing else — a lookup that could only ever return the same rules, and could fail with + * {@code NO_PROJECTOR} for a provider nobody had registered. The rules below are the ones every + * channel must obey, and a subclass that weakens them is a defect, not a customization. */ public class StandardDeliveryProjector implements ProviderEventProjector { - private final ProviderId providerId; - - public StandardDeliveryProjector(ProviderId providerId) { - this.providerId = Objects.requireNonNull(providerId, "providerId"); - } - - @Override - public final ProviderId providerId() { - return providerId; - } - @Override public ProjectionResult project( DeliveryAttemptSnapshot attempt, ProviderEventRecord event, DeliveryProjection current) { diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptRecord.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptRecord.java index ec881b87..68442fd7 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptRecord.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptRecord.java @@ -12,6 +12,8 @@ import dev.caskeleton.application.notification.platform.api.delivery.SubmissionO import dev.caskeleton.application.notification.platform.api.error.FailureCategory; import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence; +import dev.caskeleton.application.notification.platform.provider.ProviderFailure; +import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult; import java.time.Duration; import java.time.Instant; import java.util.Objects; @@ -80,4 +82,82 @@ public record DeliveryAttemptRecord( throw new IllegalArgumentException("credentialGeneration"); } } + + /** + * This attempt, completed with what the provider call proved. + * + *

    The whole evidence, not the {@code .value()} of three of its four facts. Dropping the + * certainty made "proven not sent" and "unknown whether sent" the same stored row, and those two + * decide whether a retry can safely happen. + * + * @param result what the provider said + * @param completedAt when the call finished + * @return the completed attempt; identity, route, generation and digest are unchanged + */ + public DeliveryAttemptRecord completed(ProviderSubmissionResult result, Instant completedAt) { + Objects.requireNonNull(result, "result"); + Objects.requireNonNull(completedAt, "completedAt"); + return new DeliveryAttemptRecord( + id, + recipientDeliveryId, + contactPointId, + attemptNo, + channel, + providerId, + providerProfileId, + result.providerRequestId(), + result.executionEvidence(), + result.submissionOutcome(), + result.deliveryOutcome(), + result.confirmation(), + result.evidenceLevel(), + result.failure().map(ProviderFailure::category), + result.failure().map(ProviderFailure::code), + result.nativeStatus(), + Optional.empty(), + startedAt, + Optional.of(completedAt), + Optional.of(result.elapsed()), + credentialGeneration, + renderedContentDigest); + } + + /** + * This attempt, closed before the provider call started. + * + *

    Nothing was transmitted, so the evidence is {@code notStarted} and the outcome {@code + * NOT_SUBMITTED}: safe to retry, and not something reconciliation needs to ask about. + * + * @param failureCode why the call never started + * @param completedAt when the attempt was closed + * @return the closed attempt + */ + public DeliveryAttemptRecord closedBeforeSubmission(String failureCode, Instant completedAt) { + Objects.requireNonNull(failureCode, "failureCode"); + Objects.requireNonNull(completedAt, "completedAt"); + Duration elapsedSoFar = Duration.between(startedAt, completedAt); + return new DeliveryAttemptRecord( + id, + recipientDeliveryId, + contactPointId, + attemptNo, + channel, + providerId, + providerProfileId, + Optional.empty(), + ProviderExecutionEvidence.notStarted(), + SubmissionOutcome.NOT_SUBMITTED, + DeliveryOutcome.UNKNOWN, + AttemptConfirmation.REJECTED, + EvidenceLevel.NONE, + Optional.empty(), + Optional.of(failureCode), + Optional.empty(), + Optional.empty(), + startedAt, + Optional.of(completedAt), + Optional.of(elapsedSoFar.isNegative() ? Duration.ZERO : elapsedSoFar), + credentialGeneration, + renderedContentDigest); + } } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorder.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorder.java index 2b5f4927..30a5cc79 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorder.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorder.java @@ -1,7 +1,6 @@ package dev.caskeleton.application.notification.platform.dispatch; import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; -import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; import dev.caskeleton.application.notification.platform.observation.NotificationMetricName; import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; @@ -9,7 +8,6 @@ import dev.caskeleton.application.notification.platform.provider.ProviderSubmiss import java.time.Instant; import java.util.Map; import java.util.Objects; -import java.util.Optional; /** * Writes what an attempt proved. @@ -74,33 +72,7 @@ public final class DispatchOutcomeRecorder { Objects.requireNonNull(result, "result"); Objects.requireNonNull(completedAt, "completedAt"); - DeliveryAttemptRecord completed = - new DeliveryAttemptRecord( - attempt.id(), - attempt.recipientDeliveryId(), - attempt.contactPointId(), - attempt.attemptNo(), - attempt.channel(), - attempt.providerId(), - attempt.providerProfileId(), - result.providerRequestId(), - // The whole evidence, not the .value() of three of its four facts. Dropping the - // certainty made "proven not sent" and "unknown whether sent" the same stored row, and - // those two decide whether a retry can safely happen. - result.executionEvidence(), - result.submissionOutcome(), - result.deliveryOutcome(), - result.confirmation(), - result.evidenceLevel(), - result.failure().map(failure -> failure.category()), - result.failure().map(failure -> failure.code()), - result.nativeStatus(), - Optional.empty(), - attempt.startedAt(), - Optional.of(completedAt), - Optional.of(result.elapsed()), - attempt.credentialGeneration(), - attempt.renderedContentDigest()); + DeliveryAttemptRecord completed = attempt.completed(result, completedAt); DeliveryAttemptRecord stored = attempts.recordOutcome(completed); @@ -121,32 +93,7 @@ public final class DispatchOutcomeRecorder { // Only the fields an attempt result decides are this recorder's to change. RecipientDeliveryRecord current = recipients.find(recipient.id()).orElse(recipient); boolean ambiguous = result.confirmation() == AttemptConfirmation.AMBIGUOUS; - RecipientDeliveryRecord updated = - new RecipientDeliveryRecord( - current.id(), - current.notificationId(), - current.tenantId(), - current.recipientRef(), - current.locale(), - current.timeZone(), - current.routingPlan(), - current.routeCursor(), - ambiguous - ? RecipientDeliveryState.RECONCILIATION_REQUIRED - : RecipientDeliveryState.DISPATCHING, - result.submissionOutcome(), - current.deliveryOutcome(), - current.evidenceLevel().strongerOf(result.evidenceLevel()), - current.ambiguousAttemptExists() || ambiguous, - current.duplicateRisk() || ambiguous, - current.nextDispatchAt(), - current.expiresAt(), - current.leaseOwner(), - current.leaseUntil(), - current.attemptCount() + 1, - result.failure().map(failure -> failure.category().name()), - current.createdAt(), - completedAt); + RecipientDeliveryRecord updated = current.afterAttempt(result, completedAt); // Fenced like every write after the claim. An empty result means a new holder owns the row; // the attempt row above still records what this worker's call did, and the fenced next-step // write in the dispatch service will match nothing either. diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchService.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchService.java index b19651f0..b58ff1e7 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchService.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchService.java @@ -1,6 +1,8 @@ package dev.caskeleton.application.notification.platform.dispatch; +import dev.caskeleton.application.notification.platform.api.CollapseSpec; import dev.caskeleton.application.notification.platform.api.NotificationVariable; +import dev.caskeleton.application.notification.platform.api.TenantId; import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; @@ -16,6 +18,7 @@ import dev.caskeleton.application.notification.platform.policy.RouteCandidate; import dev.caskeleton.application.notification.platform.policy.RoutingContext; import dev.caskeleton.application.notification.platform.policy.RoutingDecision; import dev.caskeleton.application.notification.platform.policy.RoutingDecisionEngine; +import dev.caskeleton.application.notification.platform.provider.ProviderCallNotStartedException; import dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence; import dev.caskeleton.application.notification.platform.provider.ProviderFailure; import dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot; @@ -23,12 +26,15 @@ import dev.caskeleton.application.notification.platform.provider.ProviderRuntime import dev.caskeleton.application.notification.platform.provider.ProviderSubmission; import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult; import dev.caskeleton.application.notification.platform.provider.TraceContext; +import dev.caskeleton.application.notification.platform.template.NotificationTemplateRenderer; import dev.caskeleton.application.notification.platform.template.RenderCommand; import dev.caskeleton.application.notification.platform.template.RenderedNotificationContent; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.time.Duration; import java.time.Instant; +import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -53,7 +59,7 @@ public final class NotificationDispatchService { private final DeliveryAttemptFactory attemptFactory; private final DispatchOutcomeRecorder recorder; private final ProviderDispatchGatewayPort gateway; - private final TemplateRendererRegistry renderers; + private final NotificationTemplateRenderer renderer; /** * The encoder that wrote the stored variables payload, used to read it back. @@ -83,7 +89,7 @@ public final class NotificationDispatchService { DeliveryAttemptFactory attemptFactory, DispatchOutcomeRecorder recorder, ProviderDispatchGatewayPort gateway, - TemplateRendererRegistry renderers, + NotificationTemplateRenderer renderer, RecipientLeaseStorePort leases, TransactionPort transactions, Clock clock, @@ -98,7 +104,7 @@ public final class NotificationDispatchService { this.attemptFactory = Objects.requireNonNull(attemptFactory, "attemptFactory"); this.recorder = Objects.requireNonNull(recorder, "recorder"); this.gateway = Objects.requireNonNull(gateway, "gateway"); - this.renderers = Objects.requireNonNull(renderers, "renderers"); + this.renderer = Objects.requireNonNull(renderer, "renderer"); this.leases = Objects.requireNonNull(leases, "leases"); this.transactions = Objects.requireNonNull(transactions, "transactions"); this.clock = Objects.requireNonNull(clock, "clock"); @@ -194,7 +200,10 @@ public final class NotificationDispatchService { // another worker, and writing the stale recipient snapshot could overwrite that newer lease. Instant completedAt = clock.instant(); transactions.inWrite( - () -> attempts.recordOutcome(leaseLostBeforeProviderSubmit(attempt, completedAt))); + () -> + attempts.recordOutcome( + attempt.closedBeforeSubmission( + NotificationFailureCode.DISPATCH_LEASE_LOST, completedAt))); return; } @@ -216,8 +225,7 @@ public final class NotificationDispatchService { saveBeforeAttempt( work, lease, - beforeAttempt( - recipient, + recipient.failedBeforeAttempt( RecipientDeliveryState.FAILED, Optional.empty(), recipient.attemptCount(), @@ -257,15 +265,13 @@ public final class NotificationDispatchService { now)); RecipientDeliveryRecord next = decision instanceof RetryDecision.RetryAfter retry - ? beforeAttempt( - recipient, + ? recipient.failedBeforeAttempt( RecipientDeliveryState.RETRY_WAITING, Optional.of(now.plus(retry.delay())), attemptNumber, FailureCategory.TRANSIENT_PROVIDER, now) - : beforeAttempt( - recipient, + : recipient.failedBeforeAttempt( RecipientDeliveryState.FAILED, Optional.empty(), attemptNumber, @@ -282,38 +288,6 @@ public final class NotificationDispatchService { }); } - private static RecipientDeliveryRecord beforeAttempt( - RecipientDeliveryRecord recipient, - RecipientDeliveryState state, - Optional nextDispatchAt, - int attemptCount, - FailureCategory category, - Instant now) { - return new RecipientDeliveryRecord( - recipient.id(), - recipient.notificationId(), - recipient.tenantId(), - recipient.recipientRef(), - recipient.locale(), - recipient.timeZone(), - recipient.routingPlan(), - recipient.routeCursor(), - state, - recipient.submissionOutcome(), - recipient.deliveryOutcome(), - recipient.evidenceLevel(), - recipient.ambiguousAttemptExists(), - recipient.duplicateRisk(), - nextDispatchAt, - recipient.expiresAt(), - recipient.leaseOwner(), - recipient.leaseUntil(), - attemptCount, - Optional.of(category.name()), - recipient.createdAt(), - now); - } - /** * Recomputes and stores the request status. * @@ -332,37 +306,6 @@ public final class NotificationDispatchService { NotificationRequestStatusPolicy.rollUp(states)); } - private static DeliveryAttemptRecord leaseLostBeforeProviderSubmit( - DeliveryAttemptRecord attempt, Instant completedAt) { - Duration elapsed = Duration.between(attempt.startedAt(), completedAt); - if (elapsed.isNegative()) { - elapsed = Duration.ZERO; - } - return new DeliveryAttemptRecord( - attempt.id(), - attempt.recipientDeliveryId(), - attempt.contactPointId(), - attempt.attemptNo(), - attempt.channel(), - attempt.providerId(), - attempt.providerProfileId(), - Optional.empty(), - ProviderExecutionEvidence.notStarted(), - SubmissionOutcome.NOT_SUBMITTED, - dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome.UNKNOWN, - dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation.REJECTED, - dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel.NONE, - Optional.empty(), - Optional.of(NotificationFailureCode.DISPATCH_LEASE_LOST), - Optional.empty(), - Optional.empty(), - attempt.startedAt(), - Optional.of(completedAt), - Optional.of(elapsed), - attempt.credentialGeneration(), - attempt.renderedContentDigest()); - } - private ProviderSubmissionResult submitOutsideTransaction( DeliveryAttemptRecord attempt, ProviderProfileSnapshot profile, @@ -381,43 +324,12 @@ public final class NotificationDispatchService { // The frozen collapse, not Optional.empty(). The APNs and FCM mappers can send one and // the capability model has a flag for it; the value simply never arrived. requireCollapseSupported(profile, work), - java.util.Map.of(), + Map.of(), TraceContext.NONE); try { return gateway.submit(submission); - } catch ( - dev.caskeleton.application.notification.platform.provider.ProviderCallNotStartedException - notStarted) { - // The adapter knows the transport never started: a payload that failed mapping, a contact - // point that could not be revealed, a profile with no credential. - return ProviderSubmissionResult.notSubmitted(notStarted.toFailure(), Duration.ZERO); - } catch ( - dev.caskeleton.application.notification.platform.api.error.NotificationException - platformFailure) { - // The platform's own failures already say whether the submission could have been transmitted: - // NotificationFailureDescriptor.preDispatch sets ambiguous=false, and every limiter, runtime - // state and configuration rejection uses it. That flag was computed, recorded, and then - // discarded by a catch that treated all of them as "may already have been sent". - var descriptor = platformFailure.descriptor(); - if (!descriptor.ambiguous()) { - return ProviderSubmissionResult.notSubmitted( - ProviderFailure.of(descriptor.code(), descriptor.category(), descriptor.retryable()), - Duration.ZERO); - } - return ProviderSubmissionResult.ambiguous( - ProviderFailure.of(descriptor.code(), descriptor.category(), descriptor.retryable()), - ProviderExecutionEvidence.responseLost(), - Duration.ZERO); - } catch (RuntimeException transportFailure) { - // Anything the adapter did not classify. The bytes may have reached the provider, so the only - // honest record is an ambiguous one — this branch is the residue, not the default. - return ProviderSubmissionResult.ambiguous( - ProviderFailure.of( - NotificationFailureCode.PROVIDER_RESPONSE_LOST, - FailureCategory.AMBIGUOUS_SUBMISSION, - false), - ProviderExecutionEvidence.responseLost(), - Duration.ZERO); + } catch (RuntimeException failure) { + return ProviderOutcomeClassifier.fromException(failure); } } @@ -428,15 +340,14 @@ public final class NotificationDispatchService { * one and which will not — the user sees two. A typed pre-dispatch failure is the honest answer: * nothing is transmitted, and the operator learns that this profile cannot do what was asked. */ - private static Optional - requireCollapseSupported(ProviderProfileSnapshot profile, Work work) { + private static Optional requireCollapseSupported( + ProviderProfileSnapshot profile, Work work) { var collapse = work.request().collapse(); if (collapse.isEmpty()) { return collapse; } if (!profile.capabilities().collapse()) { - throw new dev.caskeleton.application.notification.platform.provider - .ProviderCallNotStartedException( + throw new ProviderCallNotStartedException( NotificationFailureCode.PROVIDER_CONFIGURATION_INVALID, FailureCategory.INVALID_PAYLOAD, false, @@ -446,19 +357,17 @@ public final class NotificationDispatchService { } private RenderedNotificationContent render(Work work, RouteCandidate route) { - return renderers - .rendererFor(route.channel()) - .render( - new RenderCommand( - work.request().template(), - route.channel(), - work.recipient().locale().orElse(work.request().template().locale()), - // Decoded by the encoder that wrote it, not by a JSON codec. The stored payload is - // the canonical form — the same bytes the fingerprint was taken over — and handing - // it to a JSON parser failed on every dispatch: with no variables it is the empty - // string, which Jackson rejects, and with variables it is not JSON at all. - plainVariables(work.request().variablesPayload()), - work.recipient().timeZone())); + return renderer.render( + new RenderCommand( + work.request().template(), + route.channel(), + work.recipient().locale().orElse(work.request().template().locale()), + // Decoded by the encoder that wrote it, not by a JSON codec. The stored payload is + // the canonical form — the same bytes the fingerprint was taken over — and handing + // it to a JSON parser failed on every dispatch: with no variables it is the empty + // string, which Jackson rejects, and with variables it is not JSON at all. + plainVariables(work.request().variablesPayload()), + work.recipient().timeZone())); } /** @@ -492,9 +401,9 @@ public final class NotificationDispatchService { */ private Map plainVariables(String payload) { Map decoded = planEncoder.decodeVariables(payload); - Map plain = new java.util.LinkedHashMap<>(decoded.size()); + Map plain = new LinkedHashMap<>(decoded.size()); decoded.forEach((name, value) -> plain.put(name, value.plain())); - return java.util.Collections.unmodifiableMap(plain); + return Collections.unmodifiableMap(plain); } private Optional load(RecipientLease lease) { @@ -510,8 +419,7 @@ public final class NotificationDispatchService { .map(request -> new Work(request, recipient))); } - private static dev.caskeleton.application.notification.platform.api.TenantId tenantOf( - RecipientDeliveryRecord recipient) { + private static TenantId tenantOf(RecipientDeliveryRecord recipient) { return recipient.tenantId(); } @@ -542,9 +450,7 @@ public final class NotificationDispatchService { true, false, work.recipient().ambiguousAttemptExists() - || result.confirmation() - == dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation - .AMBIGUOUS, + || result.confirmation() == AttemptConfirmation.AMBIGUOUS, work.request().expiresAt(), result.failure().flatMap(ProviderFailure::retryAfter), attempt.attemptNo(), @@ -558,7 +464,7 @@ public final class NotificationDispatchService { RecipientDeliveryState state = decision.reconciliationRequired() ? RecipientDeliveryState.RECONCILIATION_REQUIRED - : terminalStateFor(work); + : RecipientDeliveryRecord.terminalStateFor(work.recipient().submissionOutcome()); transactions.inWrite( () -> { recipients.transitionHeldBy(work.recipient().id(), state, Optional.empty(), lease); @@ -599,13 +505,11 @@ public final class NotificationDispatchService { Optional.of(reconcile.at()), lease); case RetryDecision.Fallback ignored -> - recipients.saveHeldBy(advanceRoute(work.recipient(), now), lease); + recipients.saveHeldBy(work.recipient().advancedRoute(now), lease); case RetryDecision.Stop ignored -> recipients.transitionHeldBy( work.recipient().id(), - attempt.submissionOutcome() == SubmissionOutcome.CONFIRMED_ACCEPTED - ? RecipientDeliveryState.COMPLETED - : RecipientDeliveryState.FAILED, + RecipientDeliveryRecord.terminalStateFor(attempt.submissionOutcome()), Optional.empty(), lease); } @@ -613,39 +517,6 @@ public final class NotificationDispatchService { }); } - private static RecipientDeliveryRecord advanceRoute( - RecipientDeliveryRecord recipient, Instant now) { - return new RecipientDeliveryRecord( - recipient.id(), - recipient.notificationId(), - recipient.tenantId(), - recipient.recipientRef(), - recipient.locale(), - recipient.timeZone(), - recipient.routingPlan(), - recipient.routeCursor() + 1, - RecipientDeliveryState.READY_TO_DISPATCH, - recipient.submissionOutcome(), - recipient.deliveryOutcome(), - recipient.evidenceLevel(), - recipient.ambiguousAttemptExists(), - recipient.duplicateRisk(), - Optional.of(now), - recipient.expiresAt(), - Optional.empty(), - Optional.empty(), - recipient.attemptCount(), - recipient.lastFailureCategory(), - recipient.createdAt(), - now); - } - - private static RecipientDeliveryState terminalStateFor(Work work) { - return work.recipient().submissionOutcome() == SubmissionOutcome.CONFIRMED_ACCEPTED - ? RecipientDeliveryState.COMPLETED - : RecipientDeliveryState.FAILED; - } - /** A loaded recipient job with its request. */ private record Work(NotificationRequestRecord request, RecipientDeliveryRecord recipient) {} } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java index c95c4c56..31d3bef4 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java @@ -76,15 +76,6 @@ public final class NotificationSubmissionService { this.clock = Objects.requireNonNull(clock, "clock"); } - public NotificationReceipt submit(NotificationPlan plan) { - return accept(plan, Optional.empty()); - } - - public NotificationReceipt schedule(NotificationPlan plan, Instant scheduleAt) { - Objects.requireNonNull(scheduleAt, "scheduleAt"); - return accept(plan, Optional.of(scheduleAt)); - } - /** * Everything an acceptance does before a transaction is needed. * @@ -180,13 +171,6 @@ public final class NotificationSubmissionService { Optional scheduleAt, Instant now) {} - private NotificationReceipt accept(NotificationPlan plan, Optional scheduleAt) { - PreparedSubmission prepared = prepare(plan, scheduleAt); - NotificationReceipt receipt = transactions.inWrite(() -> commit(plan, prepared)); - recordAccepted(plan); - return receipt; - } - /** * Claims the deduplication window, when the plan asks for one. * diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ProviderOutcomeClassifier.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ProviderOutcomeClassifier.java new file mode 100644 index 00000000..a3d1eab5 --- /dev/null +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ProviderOutcomeClassifier.java @@ -0,0 +1,59 @@ +package dev.caskeleton.application.notification.platform.dispatch; + +import dev.caskeleton.application.notification.platform.api.error.FailureCategory; +import dev.caskeleton.application.notification.platform.api.error.NotificationException; +import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; +import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor; +import dev.caskeleton.application.notification.platform.provider.ProviderCallNotStartedException; +import dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence; +import dev.caskeleton.application.notification.platform.provider.ProviderFailure; +import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult; +import java.time.Duration; + +/** + * What a provider call that threw instead of returning a result proved. + * + *

    The question is always the same one: could the bytes have reached the provider? The answer + * decides whether a retry is safe or whether the attempt must be reconciled, and it used to be + * spelled out in three {@code catch} blocks inside the dispatch service. + */ +final class ProviderOutcomeClassifier { + + private ProviderOutcomeClassifier() {} + + /** + * The result a thrown provider call stands for. + * + * @param failure what the gateway threw + * @return a not-submitted result when the failure proves nothing was transmitted, an ambiguous + * one otherwise + */ + static ProviderSubmissionResult fromException(RuntimeException failure) { + if (failure instanceof ProviderCallNotStartedException notStarted) { + // The adapter knows the transport never started: a payload that failed mapping, a contact + // point that could not be revealed, a profile with no credential. + return ProviderSubmissionResult.notSubmitted(notStarted.toFailure(), Duration.ZERO); + } + if (failure instanceof NotificationException platformFailure) { + // The platform's own failures already say whether the submission could have been + // transmitted: NotificationFailureDescriptor.preDispatch sets ambiguous=false, and every + // limiter, runtime state and configuration rejection uses it. + NotificationFailureDescriptor descriptor = platformFailure.descriptor(); + ProviderFailure described = + ProviderFailure.of(descriptor.code(), descriptor.category(), descriptor.retryable()); + return descriptor.ambiguous() + ? ProviderSubmissionResult.ambiguous( + described, ProviderExecutionEvidence.responseLost(), Duration.ZERO) + : ProviderSubmissionResult.notSubmitted(described, Duration.ZERO); + } + // Anything the adapter did not classify. The bytes may have reached the provider, so the only + // honest record is an ambiguous one — this branch is the residue, not the default. + return ProviderSubmissionResult.ambiguous( + ProviderFailure.of( + NotificationFailureCode.PROVIDER_RESPONSE_LOST, + FailureCategory.AMBIGUOUS_SUBMISSION, + false), + ProviderExecutionEvidence.responseLost(), + Duration.ZERO); + } +} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/RecipientDeliveryRecord.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/RecipientDeliveryRecord.java index 310e33c5..2e38a833 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/RecipientDeliveryRecord.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/RecipientDeliveryRecord.java @@ -2,11 +2,14 @@ package dev.caskeleton.application.notification.platform.dispatch; import dev.caskeleton.application.notification.platform.api.NotificationId; import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; +import dev.caskeleton.application.notification.platform.api.error.FailureCategory; import dev.caskeleton.application.notification.platform.policy.RouteCandidate; +import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult; import java.time.Instant; import java.util.List; import java.util.Objects; @@ -60,4 +63,137 @@ public record RecipientDeliveryRecord( throw new IllegalArgumentException("routeCursor and attemptCount must not be negative"); } } + + /** + * The next route in the plan, ready to dispatch now, with the lease released. + * + * @param now the transition time + * @return the job moved to its next route + */ + public RecipientDeliveryRecord advancedRoute(Instant now) { + Objects.requireNonNull(now, "now"); + return new RecipientDeliveryRecord( + id, + notificationId, + tenantId, + recipientRef, + locale, + timeZone, + routingPlan, + routeCursor + 1, + RecipientDeliveryState.READY_TO_DISPATCH, + submissionOutcome, + deliveryOutcome, + evidenceLevel, + ambiguousAttemptExists, + duplicateRisk, + Optional.of(now), + expiresAt, + Optional.empty(), + Optional.empty(), + attemptCount, + lastFailureCategory, + createdAt, + now); + } + + /** + * The job after a failure that happened before any attempt row existed. + * + *

    No attempt was made, so nothing about submission or evidence changes; only the state, the + * next pass, the pass count and why. + * + * @param nextState where the job goes + * @param nextDispatchAt when it may be picked up again, if it is + * @param passes how many passes it has had, counting this one + * @param category why it failed + * @param now the transition time + * @return the updated job + */ + public RecipientDeliveryRecord failedBeforeAttempt( + RecipientDeliveryState nextState, + Optional nextDispatchAt, + int passes, + FailureCategory category, + Instant now) { + Objects.requireNonNull(category, "category"); + return new RecipientDeliveryRecord( + id, + notificationId, + tenantId, + recipientRef, + locale, + timeZone, + routingPlan, + routeCursor, + nextState, + submissionOutcome, + deliveryOutcome, + evidenceLevel, + ambiguousAttemptExists, + duplicateRisk, + nextDispatchAt, + expiresAt, + leaseOwner, + leaseUntil, + passes, + Optional.of(category.name()), + createdAt, + now); + } + + /** + * The job after one provider call, with only the fields an attempt result decides changed. + * + *

    An ambiguous result moves the job to reconciliation and marks the duplicate risk; every + * other result leaves it dispatching until the retry decision moves it. The evidence only ever + * gets stronger: a projection that already recorded a delivery keeps it. + * + * @param result what the provider said + * @param completedAt when the call finished + * @return the updated job + */ + public RecipientDeliveryRecord afterAttempt( + ProviderSubmissionResult result, Instant completedAt) { + Objects.requireNonNull(result, "result"); + boolean ambiguous = result.confirmation() == AttemptConfirmation.AMBIGUOUS; + return new RecipientDeliveryRecord( + id, + notificationId, + tenantId, + recipientRef, + locale, + timeZone, + routingPlan, + routeCursor, + ambiguous + ? RecipientDeliveryState.RECONCILIATION_REQUIRED + : RecipientDeliveryState.DISPATCHING, + result.submissionOutcome(), + deliveryOutcome, + evidenceLevel.strongerOf(result.evidenceLevel()), + ambiguousAttemptExists || ambiguous, + duplicateRisk || ambiguous, + nextDispatchAt, + expiresAt, + leaseOwner, + leaseUntil, + attemptCount + 1, + result.failure().map(failure -> failure.category().name()), + createdAt, + completedAt); + } + + /** + * Where a job ends when no further attempt will be made: completed only if a provider accepted + * it. + * + * @param submission the strongest submission outcome the job reached + * @return {@code COMPLETED} or {@code FAILED} + */ + public static RecipientDeliveryState terminalStateFor(SubmissionOutcome submission) { + return submission == SubmissionOutcome.CONFIRMED_ACCEPTED + ? RecipientDeliveryState.COMPLETED + : RecipientDeliveryState.FAILED; + } } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/TemplateRendererRegistry.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/TemplateRendererRegistry.java deleted file mode 100644 index d3ec66e9..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/TemplateRendererRegistry.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.dispatch; - -import dev.caskeleton.application.notification.platform.api.routing.Channel; -import dev.caskeleton.application.notification.platform.template.NotificationTemplateRenderer; - -/** Lookup of the renderer that owns a channel. */ -public interface TemplateRendererRegistry { - - /** Renderer for a channel, or a configuration failure when none is registered. */ - NotificationTemplateRenderer rendererFor(Channel channel); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/provider/ProviderCapabilities.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/provider/ProviderCapabilities.java index ff606ba9..5da0fec9 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/provider/ProviderCapabilities.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/provider/ProviderCapabilities.java @@ -37,4 +37,40 @@ public record ProviderCapabilities( throw new IllegalArgumentException("a batching provider must allow more than one item"); } } + + /** + * A provider that sends one message per call and offers nothing beyond the send. + * + *

    Both shipped families start here. Eleven positional arguments, eight of them booleans, was + * how a provider declared itself; a transposed pair of {@code false, true} compiled and quietly + * claimed a capability the provider does not have. Name the capabilities it adds instead. + * + * @param maxPayloadBytes the largest message the provider accepts + * @param maxTtl the longest time-to-live the provider honours + * @return the capabilities, every optional feature off and a batch size of one + */ + public static ProviderCapabilities dispatchOnly(long maxPayloadBytes, Duration maxTtl) { + return new ProviderCapabilities( + false, false, false, false, false, false, false, false, 1, maxPayloadBytes, maxTtl); + } + + /** + * The same capabilities, plus provider status callbacks. + * + * @return a copy that reports delivery events through a callback + */ + public ProviderCapabilities withStatusCallback() { + return new ProviderCapabilities( + batch, + providerIdempotency, + true, + statusQuery, + deliveryReceipt, + nativeScheduling, + nativeCancel, + collapse, + maxBatchSize, + maxPayloadBytes, + maxTtl); + } } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/template/NotificationTemplateRenderer.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/template/NotificationTemplateRenderer.java index 36a1d249..7e84384f 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/template/NotificationTemplateRenderer.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/template/NotificationTemplateRenderer.java @@ -1,13 +1,15 @@ package dev.caskeleton.application.notification.platform.template; -import dev.caskeleton.application.notification.platform.api.routing.Channel; - -/** Channel renderer SPI. Engine types stay inside the implementing adapter. */ +/** + * Template renderer SPI. Engine types stay inside the implementing adapter. + * + *

    One renderer serves every channel: the channel is part of the {@link RenderCommand}. It used + * to be one renderer per channel behind a lookup registry, but every channel got the same engine on + * purpose — two escaping policies for the same variable, or a content digest that depended on which + * channel rendered it, would be defects — so the lookup could only ever return the same rules. + */ public interface NotificationTemplateRenderer { - /** Channel this renderer produces content for. */ - Channel channel(); - /** Render deterministically; the same command must produce the same digest. */ RenderedNotificationContent render(RenderCommand command); } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/ProjectionMergeContractTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/ProjectionMergeContractTest.java index 3a8eb775..355843a0 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/ProjectionMergeContractTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/ProjectionMergeContractTest.java @@ -11,10 +11,8 @@ import org.junit.jupiter.api.Test; class ProjectionMergeContractTest { - private final StandardDeliveryProjector smsProjector = - new StandardDeliveryProjector(new ProviderId("twilio")); - private final StandardDeliveryProjector emailProjector = - new StandardDeliveryProjector(new ProviderId("ses")); + private final StandardDeliveryProjector smsProjector = new StandardDeliveryProjector(); + private final StandardDeliveryProjector emailProjector = new StandardDeliveryProjector(); @Test void sentAfterDeliveredDoesNotDowngrade() { diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/ProviderEventLateMatchTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/ProviderEventLateMatchTest.java index 6f76e228..9a57f838 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/ProviderEventLateMatchTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/ProviderEventLateMatchTest.java @@ -44,7 +44,7 @@ class ProviderEventLateMatchTest { private final ProviderEventProjectionService projection = new ProviderEventProjectionService( ledger, - providerId -> Optional.of(new DeliveredProjector()), + new DeliveredProjector(), resolver, projections, (ignoredAttempt, ignoredFacts) -> {}, @@ -235,11 +235,6 @@ class ProviderEventLateMatchTest { /** Marks the attempt delivered, which is enough to observe that projection ran. */ private static final class DeliveredProjector implements ProviderEventProjector { - @Override - public ProviderId providerId() { - return PROVIDER; - } - @Override public ProjectionResult project( DeliveryAttemptSnapshot attempt, ProviderEventRecord event, DeliveryProjection current) { diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorderTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorderTest.java index bfdb14ad..7903c15f 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorderTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorderTest.java @@ -34,6 +34,7 @@ import dev.caskeleton.application.notification.platform.callback.ProviderEventRe import dev.caskeleton.application.notification.platform.callback.ProviderEventRecordId; import dev.caskeleton.application.notification.platform.callback.ProviderEventSource; import dev.caskeleton.application.notification.platform.callback.ProviderRequestIdHash; +import dev.caskeleton.application.notification.platform.callback.StandardDeliveryProjector; import dev.caskeleton.application.notification.platform.callback.VerifiedProviderEvent; import dev.caskeleton.application.notification.platform.observation.NotificationMetricName; import dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence; @@ -250,10 +251,6 @@ class DispatchOutcomeRecorderTest { }; ProviderEventProjector delivered = new ProviderEventProjector() { - @Override - public ProviderId providerId() { - return new ProviderId("ses"); - } @Override public ProjectionResult project( @@ -267,7 +264,7 @@ class DispatchOutcomeRecorderTest { }; return new ProviderEventProjectionService( new NoopLedger(), - providerId -> Optional.of(delivered), + delivered, resolver, projections, (attempt, facts) -> {}, @@ -396,7 +393,7 @@ class DispatchOutcomeRecorderTest { NotificationSideEffectPort sideEffects = (attempt, facts) -> {}; return new ProviderEventProjectionService( ledger, - providerId -> Optional.empty(), + new StandardDeliveryProjector(), resolver, projections, sideEffects, diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchServiceTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchServiceTest.java index c2f5e739..21624c74 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchServiceTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchServiceTest.java @@ -28,6 +28,7 @@ import dev.caskeleton.application.notification.platform.policy.NotificationEligi import dev.caskeleton.application.notification.platform.policy.RetryBackoff; import dev.caskeleton.application.notification.platform.policy.RetryDecision; 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; import dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot; import dev.caskeleton.application.notification.platform.provider.ProviderRuntimeState; @@ -75,7 +76,7 @@ class NotificationDispatchServiceTest { new DeliveryAttemptFactory(new PlatformFakes.SequentialIds()), NotificationPlatformNoops.outcomeRecorder(attempts, recipients), gateway, - channel -> { + command -> { throw new AssertionError("renderer must not be reached for a missing recipient"); }, leases, @@ -118,7 +119,9 @@ class NotificationDispatchServiceTest { PlatformFakes.deduplication(Clock.fixed(NOW, ZoneOffset.UTC)), new PlatformFakes.RecordingMetrics(), Clock.fixed(NOW, ZoneOffset.UTC)); - var receipt = submissions.submit(PlatformFakes.plan("lease-loss", Map.of())); + var receipt = + new SubmitNotificationApplicationUseCase(submissions, transactions) + .handle(new SubmitNotificationCommand(PlatformFakes.plan("lease-loss", Map.of()))); RecipientDeliveryRecord recipient = requests.recipientsOf(new TenantId("tenant-a"), receipt.notificationId()).getFirst(); @@ -138,7 +141,7 @@ class NotificationDispatchServiceTest { new DeliveryAttemptFactory(new PlatformFakes.SequentialIds()), NotificationPlatformNoops.outcomeRecorder(attempts, recipients), gateway, - channel -> renderer(), + renderer(), leases, transactions, Clock.fixed(NOW, ZoneOffset.UTC), @@ -170,21 +173,16 @@ class NotificationDispatchServiceTest { NotificationDispatchService service = scenario.service( leases, - channel -> - new NotificationTemplateRenderer() { - @Override - public Channel channel() { - return Channel.EMAIL; - } + new NotificationTemplateRenderer() { - @Override - public RenderedNotificationContent render(RenderCommand command) { - throw new TemplateVariableValidationException( - NotificationFailureDescriptor.preDispatch( - NotificationFailureCode.TEMPLATE_VARIABLES_INVALID, - FailureCategory.TEMPLATE_FAILURE)); - } - }); + @Override + public RenderedNotificationContent render(RenderCommand command) { + throw new TemplateVariableValidationException( + NotificationFailureDescriptor.preDispatch( + NotificationFailureCode.TEMPLATE_VARIABLES_INVALID, + FailureCategory.TEMPLATE_FAILURE)); + } + }); // when service.dispatch(scenario.lease()); @@ -220,8 +218,7 @@ class NotificationDispatchServiceTest { // An operator redrive makes the delivery due now, ahead of its notBefore. scenario.recipients.transition( scenario.recipient.id(), RecipientDeliveryState.READY_TO_DISPATCH, Optional.of(NOW)); - NotificationDispatchService service = - scenario.service(new RecordingLeases(), channel -> renderer()); + NotificationDispatchService service = scenario.service(new RecordingLeases(), renderer()); // when service.dispatch(scenario.lease()); @@ -237,7 +234,7 @@ class NotificationDispatchServiceTest { Scenario scenario = new Scenario(PlatformFakes.plan("profile-gone", Map.of())); RecordingLeases leases = new RecordingLeases(); NotificationDispatchService service = - scenario.service(leases, channel -> renderer(), new ProfileGoneGateway(), 3); + scenario.service(leases, renderer(), new ProfileGoneGateway(), 3); // when service.dispatch(scenario.lease()); @@ -263,7 +260,7 @@ class NotificationDispatchServiceTest { Scenario scenario = new Scenario(PlatformFakes.plan("profile-gone-budget", Map.of())); RecordingLeases leases = new RecordingLeases(); NotificationDispatchService service = - scenario.service(leases, channel -> renderer(), new ProfileGoneGateway(), 0); + scenario.service(leases, renderer(), new ProfileGoneGateway(), 0); // when service.dispatch(scenario.lease()); @@ -297,8 +294,7 @@ class NotificationDispatchServiceTest { scenario.recipient.id(), RecipientDeliveryState.READY_TO_DISPATCH, Optional.of(NOW)); RecipientDeliveryRecord beforeDispatch = scenario.stored(); scenario.recipients.supersededLeases.add(scenario.lease()); - NotificationDispatchService service = - scenario.service(new RecordingLeases(), channel -> renderer()); + NotificationDispatchService service = scenario.service(new RecordingLeases(), renderer()); // when service.dispatch(scenario.lease()); @@ -339,8 +335,7 @@ class NotificationDispatchServiceTest { r.createdAt(), r.updatedAt())); scenario.recipients.supersededLeases.add(scenario.lease()); - NotificationDispatchService service = - scenario.service(new RecordingLeases(), channel -> renderer()); + NotificationDispatchService service = scenario.service(new RecordingLeases(), renderer()); // when service.dispatch(scenario.lease()); @@ -359,6 +354,7 @@ class NotificationDispatchServiceTest { private final RecipientDeliveryRecord recipient; private Scenario(NotificationPlan plan) { + PlatformFakes.RecordingTransactions transactions = new PlatformFakes.RecordingTransactions(); NotificationSubmissionService submissions = new NotificationSubmissionService( requests, @@ -368,12 +364,15 @@ class NotificationDispatchServiceTest { PlatformFakes.fingerprints(), new CanonicalNotificationPlanWriter( new PlatformFakes.SequentialIds(), PlatformFakes.routes(Channel.EMAIL)), - new PlatformFakes.RecordingTransactions(), + transactions, PlatformFakes.tenant("tenant-a"), PlatformFakes.deduplication(Clock.fixed(NOW, ZoneOffset.UTC)), new PlatformFakes.RecordingMetrics(), Clock.fixed(NOW, ZoneOffset.UTC)); - notificationId = submissions.submit(plan).notificationId(); + notificationId = + new SubmitNotificationApplicationUseCase(submissions, transactions) + .handle(new SubmitNotificationCommand(plan)) + .notificationId(); recipient = stored(); } @@ -388,7 +387,7 @@ class NotificationDispatchServiceTest { /** Dispatches through the real retry policy with no jitter, so the backoff is exact. */ private NotificationDispatchService service( RecipientLeaseStorePort leases, - TemplateRendererRegistry renderers, + NotificationTemplateRenderer renderer, ProviderDispatchGatewayPort gateway, int maxAdditionalAttempts) { return new NotificationDispatchService( @@ -405,7 +404,7 @@ class NotificationDispatchServiceTest { new DeliveryAttemptFactory(new PlatformFakes.SequentialIds()), NotificationPlatformNoops.outcomeRecorder(attempts, recipients), gateway, - renderers, + renderer, leases, new PlatformFakes.RecordingTransactions(), Clock.fixed(NOW, ZoneOffset.UTC), @@ -414,7 +413,7 @@ class NotificationDispatchServiceTest { } private NotificationDispatchService service( - RecipientLeaseStorePort leases, TemplateRendererRegistry renderers) { + RecipientLeaseStorePort leases, NotificationTemplateRenderer renderer) { return new NotificationDispatchService( requests, recipients, @@ -428,7 +427,7 @@ class NotificationDispatchServiceTest { new DeliveryAttemptFactory(new PlatformFakes.SequentialIds()), NotificationPlatformNoops.outcomeRecorder(attempts, recipients), new ProfileOnlyGateway(), - renderers, + renderer, leases, new PlatformFakes.RecordingTransactions(), Clock.fixed(NOW, ZoneOffset.UTC), @@ -460,10 +459,6 @@ class NotificationDispatchServiceTest { private static NotificationTemplateRenderer renderer() { return new NotificationTemplateRenderer() { - @Override - public Channel channel() { - return Channel.EMAIL; - } @Override public RenderedNotificationContent render(RenderCommand command) { diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java index 2416c62d..16fec4f0 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java @@ -14,6 +14,7 @@ import dev.caskeleton.application.notification.platform.callback.ProviderEventPr import dev.caskeleton.application.notification.platform.callback.ProviderEventRecord; import dev.caskeleton.application.notification.platform.callback.ProviderEventRecordId; import dev.caskeleton.application.notification.platform.callback.ProviderRequestIdHash; +import dev.caskeleton.application.notification.platform.callback.StandardDeliveryProjector; import dev.caskeleton.application.notification.platform.callback.VerifiedProviderEvent; import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort; import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; @@ -157,7 +158,7 @@ public final class NotificationPlatformNoops { NotificationSideEffectPort sideEffects = (attempt, facts) -> {}; return new ProviderEventProjectionService( ledger, - providerId -> Optional.empty(), + new StandardDeliveryProjector(), resolver, projections, sideEffects, diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionServiceTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionServiceTest.java index 6367f397..63cdb45f 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionServiceTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionServiceTest.java @@ -5,6 +5,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.application.notification.platform.api.CancelCommand; import dev.caskeleton.application.notification.platform.api.NotificationId; +import dev.caskeleton.application.notification.platform.api.NotificationPlan; +import dev.caskeleton.application.notification.platform.api.NotificationReceipt; import dev.caskeleton.application.notification.platform.api.RequestStatus; import dev.caskeleton.application.notification.platform.api.TenantId; import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; @@ -12,6 +14,8 @@ import dev.caskeleton.application.notification.platform.api.error.IdempotencyCon import dev.caskeleton.application.notification.platform.api.error.NotificationValidationException; import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.observation.NotificationMetricName; +import dev.caskeleton.application.notification.platform.port.in.ScheduleNotificationCommand; +import dev.caskeleton.application.notification.platform.port.in.SubmitNotificationCommand; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; @@ -55,9 +59,19 @@ class NotificationSubmissionServiceTest { metrics, CLOCK); + private NotificationReceipt submit(NotificationPlan plan) { + return new SubmitNotificationApplicationUseCase(service, transactions) + .handle(new SubmitNotificationCommand(plan)); + } + + private NotificationReceipt schedule(NotificationPlan plan, Instant scheduleAt) { + return new ScheduleNotificationApplicationUseCase(service, transactions) + .handle(new ScheduleNotificationCommand(plan, scheduleAt)); + } + @Test void aReceiptMeansTheRequestAndItsJobsAreDurable() { - var receipt = service.submit(PlatformFakes.plan("idem-1", Map.of("amount", "1000"))); + var receipt = submit(PlatformFakes.plan("idem-1", Map.of("amount", "1000"))); assertThat(requests.byId).containsKey(receipt.notificationId()); assertThat(requests.recipientsOf(new TenantId("tenant-a"), receipt.notificationId())) @@ -74,7 +88,7 @@ class NotificationSubmissionServiceTest { @Test void aScheduledRequestIsQueuedWithAFutureDueTimeRatherThanASecondState() { var scheduledFor = CLOCK.instant().plusSeconds(3600); - var receipt = service.schedule(PlatformFakes.plan("idem-scheduled", Map.of()), scheduledFor); + var receipt = schedule(PlatformFakes.plan("idem-scheduled", Map.of()), scheduledFor); assertThat(requests.byId.get(receipt.notificationId()).status()) .isEqualTo(RequestStatus.SCHEDULED); @@ -110,7 +124,7 @@ class NotificationSubmissionServiceTest { new dev.caskeleton.application.notification.platform.api.CorrelationId("corr-1"), Map.of()); - assertThatThrownBy(() -> service.schedule(plan, CLOCK.instant().plusSeconds(600))) + assertThatThrownBy(() -> schedule(plan, CLOCK.instant().plusSeconds(600))) .isInstanceOf(NotificationValidationException.class); assertThat(requests.byId).isEmpty(); } @@ -119,8 +133,8 @@ class NotificationSubmissionServiceTest { void repeatingTheSameRequestConvergesOnTheOriginalReceipt() { var plan = PlatformFakes.plan("idem-2", Map.of("amount", "1000")); - var first = service.submit(plan); - var second = service.submit(plan); + var first = submit(plan); + var second = submit(plan); assertThat(second.notificationId()).isEqualTo(first.notificationId()); assertThat(requests.byId).hasSize(1); @@ -130,23 +144,23 @@ class NotificationSubmissionServiceTest { @Test void thesameKeyWithDifferentContentIsAConflictRatherThanASilentReuse() { - service.submit(PlatformFakes.plan("idem-3", Map.of("amount", "1000"))); + submit(PlatformFakes.plan("idem-3", Map.of("amount", "1000"))); // Returning the earlier receipt here would confirm a notification whose content the caller // never sent — the exact failure the fingerprint exists to make impossible. - assertThatThrownBy(() -> service.submit(PlatformFakes.plan("idem-3", Map.of("amount", "9999")))) + assertThatThrownBy(() -> submit(PlatformFakes.plan("idem-3", Map.of("amount", "9999")))) .isInstanceOf(IdempotencyConflictException.class); } @Test void losingTheUniqueIndexRaceStillConvergesOnTheWinner() { var plan = PlatformFakes.plan("idem-4", Map.of("amount", "1000")); - var winner = service.submit(plan); + var winner = submit(plan); requests.failNextInsertAsDuplicate = true; // Two processes submitting the same key concurrently: the loser reads the winner's row rather // than surfacing a database error the caller cannot act on. - var loser = service.submit(plan); + var loser = submit(plan); assertThat(loser.notificationId()).isEqualTo(winner.notificationId()); } @@ -168,7 +182,12 @@ class NotificationSubmissionServiceTest { metrics, CLOCK); - assertThatThrownBy(() -> strict.submit(PlatformFakes.plan("idem-5", Map.of()))) + var strictSubmit = new SubmitNotificationApplicationUseCase(strict, transactions); + + assertThatThrownBy( + () -> + strictSubmit.handle( + new SubmitNotificationCommand(PlatformFakes.plan("idem-5", Map.of())))) .isInstanceOf(RuntimeException.class); // Accepting a version that cannot be rendered would only defer the failure to dispatch time, // where the caller is gone and the only signal is a stuck job. @@ -178,7 +197,7 @@ class NotificationSubmissionServiceTest { @Test void cancellationReportsExternalUncertaintyRatherThanClaimingTheMessageWasStopped() { - var receipt = service.submit(PlatformFakes.plan("idem-6", Map.of())); + var receipt = submit(PlatformFakes.plan("idem-6", Map.of())); var job = requests.recipientsOf(new TenantId("tenant-a"), receipt.notificationId()).get(0); requests.replace(withAmbiguousAttempt(job)); @@ -203,7 +222,7 @@ class NotificationSubmissionServiceTest { @Test void submissionMetricsCarryOnlyBoundedTags() { - service.submit(PlatformFakes.plan("idem-7", Map.of())); + submit(PlatformFakes.plan("idem-7", Map.of())); assertThat(metrics.counters).contains(NotificationMetricName.REQUESTED); assertThat(metrics.tags) @@ -263,8 +282,8 @@ class NotificationSubmissionServiceTest { java.time.Duration.ofMinutes(10), dev.caskeleton.application.notification.platform.api.DeduplicationAction.DROP); - var first = service.submit(planWithDedup("idem-dedup-1", spec)); - var second = service.submit(planWithDedup("idem-dedup-2", spec)); + var first = submit(planWithDedup("idem-dedup-1", spec)); + var second = submit(planWithDedup("idem-dedup-2", spec)); assertThat(first.willDeliver()).isTrue(); assertThat(second.willDeliver()) @@ -286,8 +305,8 @@ class NotificationSubmissionServiceTest { dev.caskeleton.application.notification.platform.api.DeduplicationAction .RETURN_EXISTING); - var first = service.submit(planWithDedup("idem-dedup-3", spec)); - var second = service.submit(planWithDedup("idem-dedup-4", spec)); + var first = submit(planWithDedup("idem-dedup-3", spec)); + var second = submit(planWithDedup("idem-dedup-4", spec)); assertThat(second.notificationId()) .as("the caller is told which notification already covers their request") @@ -313,9 +332,9 @@ class NotificationSubmissionServiceTest { java.time.Duration.ofMinutes(10), dev.caskeleton.application.notification.platform.api.DeduplicationAction.DROP); - service.submit(planWithDedup("idem-dedup-5", spec)); + submit(planWithDedup("idem-dedup-5", spec)); - assertThat(service.submit(planWithDedup("idem-dedup-6", otherKey)).willDeliver()).isTrue(); + assertThat(submit(planWithDedup("idem-dedup-6", otherKey)).willDeliver()).isTrue(); } @org.junit.jupiter.api.Test @@ -327,7 +346,7 @@ class NotificationSubmissionServiceTest { java.time.Duration.ofMinutes(10), dev.caskeleton.application.notification.platform.api.DeduplicationAction.DROP); - assertThatThrownBy(() -> service.submit(PlatformFakes.multiRecipientPlanWithDedup(spec))) + assertThatThrownBy(() -> submit(PlatformFakes.multiRecipientPlanWithDedup(spec))) .as("the window is keyed on one recipient identity; several recipients have no single one") .isInstanceOf(RuntimeException.class); } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/ProviderOutcomeClassifierTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/ProviderOutcomeClassifierTest.java new file mode 100644 index 00000000..cba9f316 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/ProviderOutcomeClassifierTest.java @@ -0,0 +1,65 @@ +package dev.caskeleton.application.notification.platform.dispatch; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; +import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; +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.ProviderUnavailableException; +import dev.caskeleton.application.notification.platform.provider.ProviderCallNotStartedException; +import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** Whether a provider call that threw could have transmitted the message. */ +class ProviderOutcomeClassifierTest { + + @Test + @DisplayName("전송이 시작되지 않았다고 어댑터가 알린 실패는 NOT_SUBMITTED다") + void aCallTheAdapterNeverStartedIsNotSubmitted() { + // when + ProviderSubmissionResult result = + ProviderOutcomeClassifier.fromException( + new ProviderCallNotStartedException( + NotificationFailureCode.PROVIDER_CONFIGURATION_INVALID, + FailureCategory.INVALID_PAYLOAD, + false, + "no credential")); + + // then + assertThat(result.submissionOutcome()).isEqualTo(SubmissionOutcome.NOT_SUBMITTED); + assertThat(result.confirmation()).isNotEqualTo(AttemptConfirmation.AMBIGUOUS); + } + + @Test + @DisplayName("발송 전 플랫폼 거절은 NOT_SUBMITTED다") + void aPreDispatchPlatformRefusalIsNotSubmitted() { + // when + ProviderSubmissionResult result = + ProviderOutcomeClassifier.fromException( + new ProviderUnavailableException( + NotificationFailureDescriptor.preDispatch( + NotificationFailureCode.PROVIDER_UNAVAILABLE, + FailureCategory.CAPACITY_REJECTED))); + + // then + assertThat(result.submissionOutcome()).isEqualTo(SubmissionOutcome.NOT_SUBMITTED); + assertThat(result.failure().orElseThrow().category()) + .isEqualTo(FailureCategory.CAPACITY_REJECTED); + } + + @Test + @DisplayName("분류되지 않은 예외는 이미 전송됐을 수 있으므로 AMBIGUOUS다") + void anUnclassifiedFailureIsAmbiguous() { + // when + ProviderSubmissionResult result = + ProviderOutcomeClassifier.fromException(new IllegalStateException("socket reset")); + + // then + assertThat(result.confirmation()).isEqualTo(AttemptConfirmation.AMBIGUOUS); + assertThat(result.failure().orElseThrow().category()) + .isEqualTo(FailureCategory.AMBIGUOUS_SUBMISSION); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/provider/ProviderSpiContractTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/provider/ProviderSpiContractTest.java index 7bac90b2..63a25604 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/provider/ProviderSpiContractTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/provider/ProviderSpiContractTest.java @@ -11,6 +11,7 @@ import dev.caskeleton.application.notification.platform.api.error.FailureCategor import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; import java.time.Duration; import java.util.Optional; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** @@ -144,6 +145,47 @@ class ProviderSpiContractTest { assertThat(capabilities.maxPayloadBytes()).isEqualTo(10_000L); } + @Test + @DisplayName("발송만 하는 provider의 capability는 선택 기능이 모두 꺼져 있고 callback만 이름으로 켠다") + void aDispatchOnlyProviderClaimsNothingAndAddsTheCallbackByName() { + // given + ProviderCapabilities dispatchOnly = + ProviderCapabilities.dispatchOnly(10_000_000L, Duration.ofDays(1)); + + // when + ProviderCapabilities withCallback = dispatchOnly.withStatusCallback(); + + // then + assertThat(dispatchOnly) + .isEqualTo( + new ProviderCapabilities( + false, + false, + false, + false, + false, + false, + false, + false, + 1, + 10_000_000L, + Duration.ofDays(1))); + assertThat(withCallback) + .isEqualTo( + new ProviderCapabilities( + false, + false, + true, + false, + false, + false, + false, + false, + 1, + 10_000_000L, + Duration.ofDays(1))); + } + private static ProviderFailure failure(boolean retryable) { return new ProviderFailure( NotificationFailureCode.PROVIDER_REJECTED, diff --git a/src/composition/notification-platform/README.md b/src/composition/notification-platform/README.md index a2bd3106..36a1f840 100644 --- a/src/composition/notification-platform/README.md +++ b/src/composition/notification-platform/README.md @@ -17,6 +17,8 @@ composition:notification-platform │ └─ NotificationCallbackConfiguration provider 콜백 수집 + ProviderCallbackIngressBridge ├─ config/module-defaults/notification.yml (설정 기본값, support 로더가 읽음) ├─ adapter:outbound:notification provider(SMTP·SES), 저장 외 런타임, NotificationPlatformAutoConfiguration + ├─ adapter:outbound:persistence-notification (runtimeOnly) 알림 entity·저장소·Flyway stream + ├─ adapter:outbound:persistence-jpa (runtimeOnly) DataSource·Flyway core·TransactionPort └─ adapter:inbound:web-notification POST /notifications, POST /notification-templates, POST /internal/notification/callbacks/{provider}/{profile} ``` @@ -25,15 +27,16 @@ composition:notification-platform (`afterName`). - 설정: `config/module-defaults/notification.yml`을 support의 `ModuleDefaultsEnvironmentPostProcessor`가 읽는다. 우선순위는 가장 낮다. 그래서 `application*.yml`, 환경 변수, 시스템 속성이 항상 이긴다. app-bootstrap은 이 파일을 모른다. -- 저장소: 요청·발송·ledger 테이블은 `adapter:outbound:persistence-jpa`에 있다. 그래서 - persistence-jpa 줄도 함께 넣어야 하고, `APP_PERSISTENCE_JPA_ENABLED=false`로 끄면 안 된다. +- 저장소: 요청·발송·ledger 테이블과 migration은 `adapter:outbound:persistence-notification`에 있고, + 그 테이블이 사는 관계형 플랫폼(DataSource, Flyway core stream, capability schema registry, + `TransactionPort`)은 `adapter:outbound:persistence-jpa`다. 이 모듈이 둘 다 `runtimeOnly`로 가져오므로 + (fileserver와 같은 한 줄 원칙) 따로 넣을 줄은 없다. `APP_PERSISTENCE_JPA_ENABLED=false`로 끄면 안 된다. ## 추가할 한 줄 ```groovy // app-bootstrap/build.gradle -runtimeOnly project(':adapter:outbound:persistence-jpa') // 알림 저장소 -runtimeOnly project(':composition:notification-platform') // 알림 +runtimeOnly project(':composition:notification-platform') // 알림 (저장소·JPA 플랫폼 포함) ``` 기본 조립에는 없다(`app-bootstrap/build.gradle`에 주석 처리된 줄로 있다). 이 줄을 지우면 use case @@ -52,7 +55,7 @@ runtimeOnly project(':composition:notification-platform') // 알림 | 언제 | 키 | | --- | --- | -| 항상 | persistence-jpa 줄과 그 연결 env(`APP_DATASOURCE_URL`, `APP_DATASOURCE_USERNAME`, `APP_DATASOURCE_PASSWORD`) | +| 항상 | 데이터베이스 연결 env(`APP_DATASOURCE_URL`, `APP_DATASOURCE_USERNAME`, `APP_DATASOURCE_PASSWORD`) | | 항상 (키 7종과 각 키 id, 32바이트 이상 base64, 서로 달라야 함) | `APP_NOTIFICATION_PLATFORM_{CONTACT_ENCRYPTION,CONTACT_LOOKUP_HMAC,CALLBACK_SIGNING,PROVIDER_CREDENTIAL,PAYLOAD_ENCRYPTION,PROVIDER_REQUEST_LOOKUP_HMAC,CALLBACK_FINGERPRINT_HMAC}_KEY`, 같은 이름 + `_ID` | | SMTP provider | `APP_NOTIFICATION_PLATFORM_SMTP_ENABLED=true`, `APP_NOTIFICATION_PLATFORM_SMTP_SENDER_IDENTITY`, `SPRING_MAIL_HOST`, `SPRING_MAIL_PORT`, `SPRING_MAIL_USERNAME`, `SPRING_MAIL_PASSWORD` | | SES provider | `APP_NOTIFICATION_PLATFORM_SES_ENABLED=true`, `APP_NOTIFICATION_PLATFORM_SES_SENDER_IDENTITY`, `APP_NOTIFICATION_PLATFORM_SES_ACCESS_KEY_ID`, `APP_NOTIFICATION_PLATFORM_SES_CREDENTIAL_KEY_ID`, `APP_NOTIFICATION_PLATFORM_SES_REGION` | diff --git a/src/composition/notification-platform/build.gradle b/src/composition/notification-platform/build.gradle index 049fbc49..732be3e8 100644 --- a/src/composition/notification-platform/build.gradle +++ b/src/composition/notification-platform/build.gradle @@ -18,6 +18,12 @@ dependencies { implementation project(':application-notification') implementation project(':adapter:outbound:notification') implementation project(':adapter:inbound:web-notification') + // The capability's tables and stores, and the relational platform they live in (DataSource, + // Flyway core stream, capability schema registry, TransactionPort). Runtime only: nothing here + // compiles against either, and one line in app-bootstrap selects the whole capability — the + // same shape as :composition:fileserver-platform (review 2026-09-24 NEW-11, S2-#1b). + runtimeOnly project(':adapter:outbound:persistence-notification') + runtimeOnly project(':adapter:outbound:persistence-jpa') implementation 'org.springframework.boot:spring-boot-autoconfigure' implementation 'org.springframework:spring-context' diff --git a/src/composition/notification-platform/gradle.lockfile b/src/composition/notification-platform/gradle.lockfile index 27e44dd1..0d9c7810 100644 --- a/src/composition/notification-platform/gradle.lockfile +++ b/src/composition/notification-platform/gradle.lockfile @@ -36,13 +36,17 @@ com.google.guava:guava:33.6.0-jre=checkstyle com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor +com.h2database:h2:2.4.240=runtimeClasspath,testRuntimeClasspath com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath com.networknt:json-schema-validator:3.0.2=runtimeClasspath,testRuntimeClasspath com.nimbusds:nimbus-jose-jwt:10.4=runtimeClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle +com.sun.istack:istack-commons-runtime:4.1.2=runtimeClasspath,testRuntimeClasspath com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath +com.zaxxer:HikariCP:7.0.2=runtimeClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle +commons-codec:commons-codec:1.19.0=runtimeClasspath,testRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle commons-io:commons-io:2.21.0=spotbugs commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -52,29 +56,34 @@ io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotatio io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-core:1.16.7=runtimeClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.projectreactor:reactor-core:3.8.7=runtimeClasspath,testRuntimeClasspath io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath io.swagger.core.v3:swagger-core-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath io.swagger.core.v3:swagger-models-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath jakarta.activation:jakarta.activation-api:2.1.4=runtimeClasspath,testCompileClasspath,testRuntimeClasspath jakarta.annotation:jakarta.annotation-api:3.0.0=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.inject:jakarta.inject-api:2.0.1=runtimeClasspath,testRuntimeClasspath jakarta.mail:jakarta.mail-api:2.1.5=runtimeClasspath,testRuntimeClasspath +jakarta.persistence:jakarta.persistence-api:3.2.0=runtimeClasspath,testRuntimeClasspath +jakarta.transaction:jakarta.transaction-api:2.0.1=runtimeClasspath,testRuntimeClasspath jakarta.validation:jakarta.validation-api:3.1.1=runtimeClasspath,testRuntimeClasspath jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +net.logstash.logback:logstash-logback-encoder:8.0=runtimeClasspath,testRuntimeClasspath net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs ognl:ognl:3.3.4=runtimeClasspath,testRuntimeClasspath -org.antlr:antlr4-runtime:4.13.2=checkstyle +org.antlr:antlr4-runtime:4.13.2=checkstyle,runtimeClasspath,testRuntimeClasspath org.apache.bcel:bcel:6.12.0=spotbugs org.apache.commons:commons-lang3:3.20.0=checkstyle,runtimeClasspath,spotbugs,testRuntimeClasspath org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle -org.apache.httpcomponents:httpclient:4.5.13=checkstyle -org.apache.httpcomponents:httpcore:4.4.16=checkstyle +org.apache.httpcomponents:httpclient:4.5.13=checkstyle,runtimeClasspath,testRuntimeClasspath +org.apache.httpcomponents:httpcore:4.4.16=checkstyle,runtimeClasspath,testRuntimeClasspath org.apache.logging.log4j:log4j-api:2.25.5=runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath org.apache.logging.log4j:log4j-core:2.25.5=spotbugs org.apache.logging.log4j:log4j-to-slf4j:2.25.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -87,9 +96,11 @@ org.apache.tomcat.embed:tomcat-embed-el:11.0.24=runtimeClasspath,testCompileClas org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.apache.xbean:xbean-reflect:3.7=checkstyle org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath +org.aspectj:aspectjweaver:1.9.25.1=runtimeClasspath,testRuntimeClasspath org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath org.attoparser:attoparser:2.0.7.RELEASE=runtimeClasspath,testRuntimeClasspath org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath +org.checkerframework:checker-qual:3.55.1=runtimeClasspath,testRuntimeClasspath org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle @@ -97,8 +108,15 @@ org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs org.eclipse.angus:angus-activation:2.0.3=runtimeClasspath,testRuntimeClasspath org.eclipse.angus:angus-mail:2.0.5=runtimeClasspath,testRuntimeClasspath +org.flywaydb:flyway-core:11.14.1=runtimeClasspath,testRuntimeClasspath +org.flywaydb:flyway-database-postgresql:11.14.1=runtimeClasspath,testRuntimeClasspath +org.glassfish.jaxb:jaxb-core:4.0.9=runtimeClasspath,testRuntimeClasspath +org.glassfish.jaxb:jaxb-runtime:4.0.9=runtimeClasspath,testRuntimeClasspath +org.glassfish.jaxb:txw2:4.0.9=runtimeClasspath,testRuntimeClasspath org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath +org.hibernate.models:hibernate-models:1.0.1=runtimeClasspath,testRuntimeClasspath +org.hibernate.orm:hibernate-core:7.2.24.Final=runtimeClasspath,testRuntimeClasspath org.hibernate.validator:hibernate-validator:9.0.1.Final=runtimeClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle org.javassist:javassist:3.29.0-GA=runtimeClasspath,testRuntimeClasspath @@ -130,6 +148,8 @@ org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.postgresql:postgresql:42.7.13=runtimeClasspath,testRuntimeClasspath +org.reactivestreams:reactive-streams:1.0.4=runtimeClasspath,testRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath org.slf4j:jul-to-slf4j:2.0.18=runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -142,16 +162,27 @@ org.springframework.boot:spring-boot-actuator-autoconfigure:4.0.8=runtimeClasspa org.springframework.boot:spring-boot-actuator:4.0.8=runtimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor +org.springframework.boot:spring-boot-data-commons:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-data-jpa:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-flyway:4.0.8=runtimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-health:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-hibernate:4.0.8=runtimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-http-converter:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-jackson:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jdbc:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jpa:4.0.8=runtimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-mail:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-persistence:4.0.8=runtimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-security-oauth2-resource-server:4.0.8=runtimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-security:4.0.8=runtimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-servlet:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-sql:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-data-jpa:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-flyway:4.0.8=runtimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-jackson:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jdbc:4.0.8=runtimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-json:4.0.8=runtimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-logging:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-mail:4.0.8=runtimeClasspath,testRuntimeClasspath @@ -168,11 +199,16 @@ org.springframework.boot:spring-boot-starter:4.0.8=runtimeClasspath,testCompileC org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-tomcat:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-transaction:4.0.8=runtimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-validation:4.0.8=runtimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-web-server:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-webmvc:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.data:spring-data-commons:4.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.data:spring-data-jpa:4.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.integration:spring-integration-core:7.0.6=runtimeClasspath,testRuntimeClasspath +org.springframework.integration:spring-integration-jdbc:7.0.6=runtimeClasspath,testRuntimeClasspath org.springframework.security:spring-security-config:7.0.7=runtimeClasspath,testRuntimeClasspath org.springframework.security:spring-security-core:7.0.7=runtimeClasspath,testRuntimeClasspath org.springframework.security:spring-security-crypto:7.0.7=runtimeClasspath,testRuntimeClasspath @@ -182,12 +218,17 @@ org.springframework.security:spring-security-oauth2-resource-server:7.0.7=runtim org.springframework.security:spring-security-web:7.0.7=runtimeClasspath,testRuntimeClasspath org.springframework.session:spring-session-core:4.0.5=runtimeClasspath,testRuntimeClasspath org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-aspects:7.0.9=runtimeClasspath,testRuntimeClasspath org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-context-support:7.0.9=runtimeClasspath,testRuntimeClasspath org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-jdbc:7.0.9=runtimeClasspath,testRuntimeClasspath +org.springframework:spring-messaging:7.0.9=runtimeClasspath,testRuntimeClasspath +org.springframework:spring-orm:7.0.9=runtimeClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-tx:7.0.9=runtimeClasspath,testRuntimeClasspath org.springframework:spring-web:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-webmvc:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.thymeleaf:thymeleaf:3.1.5.RELEASE=runtimeClasspath,testRuntimeClasspath @@ -195,6 +236,32 @@ org.unbescape:unbescape:1.1.6.RELEASE=runtimeClasspath,testRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath org.yaml:snakeyaml:2.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:annotations:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:apache-client:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:auth:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:aws-core:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:aws-json-protocol:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:checksums-spi:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:checksums:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:endpoints-spi:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth-aws-eventstream:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth-aws:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth-spi:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-client-spi:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:identity-spi:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:json-utils:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:metrics-spi:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:profiles:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:protocol-core:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:regions:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:retries-spi:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:retries:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:sdk-core:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:sesv2:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:third-party-jackson-core:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.awssdk:utils:2.30.0=runtimeClasspath,testRuntimeClasspath +software.amazon.eventstream:eventstream:1.0.1=runtimeClasspath,testRuntimeClasspath tools.jackson.core:jackson-core:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath tools.jackson.core:jackson-databind:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath tools.jackson:jackson-bom:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath diff --git a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java index 75aabc7d..2201f337 100644 --- a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java +++ b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java @@ -12,7 +12,7 @@ import dev.caskeleton.application.notification.platform.callback.DeliveryProject import dev.caskeleton.application.notification.platform.callback.NotificationSideEffectPort; import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService; -import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectorRegistry; +import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector; import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFactory; import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; import dev.caskeleton.application.notification.platform.dispatch.DispatchOutcomeRecorder; @@ -28,12 +28,12 @@ import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseS import dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService; import dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint; -import dev.caskeleton.application.notification.platform.dispatch.TemplateRendererRegistry; import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort; import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; import dev.caskeleton.application.notification.platform.policy.NotificationRetryPolicy; import dev.caskeleton.application.notification.platform.policy.RoutingDecisionEngine; import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort; +import dev.caskeleton.application.notification.platform.template.NotificationTemplateRenderer; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -62,7 +62,7 @@ class NotificationDeliveryConfiguration { DeliveryAttemptFactory attemptFactory, DispatchOutcomeRecorder recorder, ProviderDispatchGatewayPort gateway, - TemplateRendererRegistry renderers, + NotificationTemplateRenderer renderer, RecipientLeaseStorePort leases, TransactionPort transactions, Clock clock, @@ -77,7 +77,7 @@ class NotificationDeliveryConfiguration { attemptFactory, recorder, gateway, - renderers, + renderer, leases, transactions, clock, @@ -137,14 +137,14 @@ class NotificationDeliveryConfiguration { @Bean ProviderEventProjectionService providerEventProjectionService( ProviderEventLedger ledger, - ProviderEventProjectorRegistry projectors, + ProviderEventProjector projector, DeliveryAttemptResolverPort resolver, DeliveryProjectionStorePort projections, NotificationSideEffectPort sideEffects, TransactionPort transactions, NotificationMetricsPort metrics) { return new ProviderEventProjectionService( - ledger, projectors, resolver, projections, sideEffects, transactions, metrics); + ledger, projector, resolver, projections, sideEffects, transactions, metrics); } /** The N4 operator plane. */ diff --git a/src/config/architecture/modules.json b/src/config/architecture/modules.json index f07a0a8d..8d887c2e 100644 --- a/src/config/architecture/modules.json +++ b/src/config/architecture/modules.json @@ -64,7 +64,6 @@ "domain-core", "application-core", "shared-contract", - "application-notification", "adapter-outbound-support" ] }, @@ -77,6 +76,15 @@ "application-fileserver" ] }, + { + "id": "adapter-outbound-persistence-notification", + "gradle_path": ":adapter:outbound:persistence-notification", + "source_path": "src/adapter/outbound/persistence-notification", + "allowed_dependencies": [ + "application-core", + "application-notification" + ] + }, { "id": "adapter-outbound-persistence-mongo", "gradle_path": ":adapter:outbound:persistence-mongo", @@ -282,6 +290,8 @@ "application-core", "application-notification", "adapter-outbound-notification", + "adapter-outbound-persistence-notification", + "adapter-outbound-persistence-jpa", "adapter-inbound-web-notification" ] },