From 423a29c46f09aa4f2cd6f17410cbf3a6e60bfdb3 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Tue, 29 Sep 2026 12:30:01 +0900 Subject: [PATCH] =?UTF-8?q?review-followup=20Wave=203=20=EB=9D=BC=EC=9A=B4?= =?UTF-8?q?=EB=93=9C=202(P18):=20outbox=20canonical=20=ED=86=B5=EC=9D=BC,?= =?UTF-8?q?=20composition=20=EB=AA=A8=EB=93=88,=20legacy=20Kafka=20seam=20?= =?UTF-8?q?=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 결정 7: `LegacyOutboxAppendPort`·legacy 저장 모델·relay·Kafka R0 seam 삭제, 템플릿 JSON encoder(`JsonIntegrationEventEncoder`), durable operation·sample 이벤트가 `OutboxAppendPort` + encoder로, persistence-jpa V19(pre-canonical 미발행 row 거부) - 결정 3: outbox relay·멱등성 executor 조립을 `composition:outbox-relay`·`composition:idempotency`로, sample이 복사한 bootstrap 인프라를 `composition:service-runtime`으로(sample `SampleIdempotencyConfig` 복사본 삭제) - persistence-jpa outbox·멱등성 패키지 feature 기준 이동, messaging outbox·inbox leaf를 reliability / reliability-jdbc-postgresql로 - messaging outbox header를 jsonb로(P18-new-1 — `\`로 끝나는 값이 다음 header를 삼키던 결함) - 통합(충돌 22건): P25 A-10c(전략 선택 설정 삭제)를 service-runtime `DomainContextConfig`에 적용, P25 startup 예외 통합을 composition 설정 테스트에, P25 `CommandUseCase.handle` 이름을 PG 통합 테스트에, P15 `EventJson`은 호출자 0이 되어 삭제 - root CLAUDE.md의 legacy seam 문장 수정(P18-new-2) 검증: ./gradlew check architectureCheck verifyDependencyLocks verifyPublicPathSnapshot :app-bootstrap:verifyEnvKeys configContractCheck :app-bootstrap:integrationTest :sample-portfolio:integrationTest :sample-portfolio:systemTest persistence-jpa jpaPlatformContractTest·postgresql{Idempotency,OutboxAppendTransactional,OutboxConcurrentRelay,OutboxRowLifecycle}IntegrationTest :messaging:messaging-reliability-jdbc-postgresql:integrationTest --continue 통과(700 task) Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/integration-main.yml | 19 +- CLAUDE.md | 4 +- docs/architecture/jpa-adopter-api-surface.txt | 4 +- docs/architecture/jpa-api-surface.txt | 24 +- docs/capability-status.md | 24 + docs/messaging/configuration-reference.md | 20 +- docs/messaging/outbox-inbox.md | 6 +- docs/messaging/support-matrix.md | 6 +- docs/registries/env-keys.yaml | 35 +- .../W3-P18.md | 90 ++++ .../2026-09-25-review-followup-status.md | 45 +- docs/runbooks/outbox-publish-failed.md | 7 +- docs/study/postgresql-jpa-walkthrough.ko.md | 4 +- src/.env.example | 1 - src/README.md | 8 +- .../operation/DurableOperationController.java | 1 - .../DurableOperationControllerTest.java | 8 +- .../outbound/messaging-kafka/README.md | 32 +- .../outbound/messaging-kafka/build.gradle | 20 +- .../outbound/messaging-kafka/gradle.lockfile | 26 +- .../messaging/kafka/BrokerAddress.java | 108 ----- .../messaging/kafka/KafkaAdapterConfig.java | 32 -- .../messaging/kafka/KafkaAdapterSettings.java | 48 -- .../messaging/kafka/KafkaMessageBroker.java | 31 -- .../outbound/messaging/kafka/KafkaSender.java | 19 - .../kafka/KafkaSenderAutoConfiguration.java | 120 ----- ...cyKafkaMessagingRootAutoConfiguration.java | 21 - ...ot.autoconfigure.AutoConfiguration.imports | 1 - .../config/module-defaults/messaging.yml | 10 +- .../messaging/kafka/BrokerAddressTest.java | 120 ----- .../kafka/KafkaAdapterSettingsTest.java | 41 -- .../kafka/KafkaCapabilityActivationTest.java | 46 +- ...aSenderAutoConfigurationOwnershipTest.java | 18 - .../kafka/KafkaSenderInterruptionTest.java | 42 -- ...afkaAutoConfigurationRegistrationTest.java | 103 ----- src/adapter/outbound/messaging/CLAUDE.md | 27 +- src/adapter/outbound/messaging/README.md | 117 ++--- src/adapter/outbound/messaging/build.gradle | 5 - .../outbound/messaging/gradle.lockfile | 4 - .../outbound/messaging/MessagingConfig.java | 86 +--- .../outbound/messaging/MessagingSettings.java | 11 +- .../MessagingBridgeRootAutoConfiguration.java | 20 +- .../core/DisabledMessagePublisher.java | 17 - .../messaging/core/MessageBroker.java | 20 - .../messaging/core/MessagePublisher.java | 13 - .../messaging/core/OutboundMessage.java | 25 - .../core/OutboundMessagePublisher.java | 65 --- .../messaging/outbox/OutboxEnvelopeJson.java | 70 --- .../outbox/OutboxMessagePublishAdapter.java | 78 +--- .../messaging/MessagingConfigTest.java | 93 +--- ...ngPlatformBridgeAutoConfigurationTest.java | 72 +-- .../core/OutboundMessagePublisherTest.java | 175 ------- .../OutboxCanonicalPublishRoutingTest.java | 166 ------- .../OutboxMessagePublishAdapterTest.java | 330 +++++-------- .../outbound/persistence-jpa/CLAUDE.md | 18 +- .../outbound/persistence-jpa/README.md | 32 +- .../outbound/persistence-jpa/build.gradle | 6 +- .../PostgreSqlIdempotencyStoreConfig.java | 4 +- .../persistence/h2/H2PersistenceConfig.java | 3 +- .../{ => jpa}/IdempotencyReaper.java | 2 +- .../IdempotencyRecordJpaRepository.java | 4 +- .../entity/IdempotencyRecordEntity.java | 2 +- .../IdempotencyCapabilityGuard.java | 2 +- .../postgresql}/IdempotencyClaimGateway.java | 2 +- .../postgresql}/IdempotencyDigestPolicy.java | 2 +- .../postgresql}/IdempotencyRecordRow.java | 2 +- .../postgresql}/IdempotencyRowMapper.java | 2 +- .../postgresql}/IdempotencySchemaStream.java | 2 +- .../IdempotencyTransitionGateway.java | 2 +- .../PostgreSqlOwnerSafeIdempotencyStore.java | 2 +- .../outbox/CanonicalOutboxAppendAdapter.java | 105 ----- .../h2/H2OutboxClaimRepository.java | 24 +- .../{ => jpa}/OutboxClaimRepository.java | 4 +- .../{ => jpa}/OutboxEventJpaRepository.java | 4 +- .../outbox/{ => jpa}/OutboxReaper.java | 6 +- .../outbox/{ => jpa}/OutboxStoreAdapter.java | 146 +++--- .../{ => jpa}/entity/OutboxEventEntity.java | 38 +- .../PostgreSqlOutboxClaimRepository.java | 28 +- .../PostgreSqlPersistenceConfig.java | 3 +- .../module-defaults/persistence-jpa.yml | 8 +- .../V19__outbox_event_canonical_only.sql | 36 ++ ...rationSubmissionOutboxIntegrationTest.java | 30 +- ...ort.java => OutboxIntegrationSupport.java} | 17 +- .../PostgreSqlIdempotencyIntegrationTest.java | 2 +- ...oxAppendTransactionalIntegrationTest.java} | 22 +- ...boxClaimAndMaintenanceIntegrationTest.java | 140 +++++- ...OutboxConcurrentRelayIntegrationTest.java} | 37 +- ...SqlOutboxRowLifecycleIntegrationTest.java} | 116 ++--- .../CandidateAdapterCompositionTest.java | 2 +- .../persistence/JpaModuleBoundaryTest.java | 3 + .../PostgreSqlIdempotencyStoreConfigTest.java | 4 +- .../IdempotencyActivationContractTest.java | 2 +- .../{ => jpa}/IdempotencyReaperTest.java | 2 +- .../IdempotencyDigestPolicyTest.java | 2 +- .../OwnerSafeIdempotencyPreconditionTest.java | 2 +- ...icalOutboxAppendAdapterActivationTest.java | 64 --- .../CanonicalOutboxAppendAdapterTest.java | 143 ------ .../outbox/OutboxStoreAdapterTest.java | 401 ---------------- .../{ => outbox}/h2/H2ClaimSqlTest.java | 25 +- .../outbox/{ => jpa}/OutboxReaperTest.java | 2 +- .../{ => jpa}/OutboxReaperWiringTest.java | 2 +- .../outbox/jpa/OutboxStoreAdapterTest.java | 435 ++++++++++++++++++ .../OutboxSwitchWiringContractTest.java | 2 +- .../resources/db/applied-migrations.sha256 | 1 + src/adapter/outbound/support/CLAUDE.md | 5 + src/adapter/outbound/support/README.md | 26 ++ .../support/StrictSettingsBinder.java | 42 ++ .../support/messaging/CanonicalJson.java | 195 ++++++++ ...egrationEventEncoderAutoConfiguration.java | 31 ++ .../JsonIntegrationEventEncoder.java | 332 +++++++++++++ ...ot.autoconfigure.AutoConfiguration.imports | 1 + .../support/StrictSettingsBinderTest.java | 70 +++ ...tionEventEncoderAutoConfigurationTest.java | 47 ++ .../JsonIntegrationEventEncoderTest.java | 306 ++++++++++++ .../testkit.encoder-sample/v1.schema.json | 14 + src/app-bootstrap/CLAUDE.md | 13 +- src/app-bootstrap/README.md | 334 +------------- src/app-bootstrap/build.gradle | 15 +- .../ApplicationBoundaryArchitectureTest.java | 6 +- ...tartupFailureContractArchitectureTest.java | 2 +- .../TypeBoundaryArchitectureTest.java | 2 +- .../OutboundWithoutPermissionUseCase.java | 21 +- .../async/ScheduledJobOverlapPolicyTest.java | 3 +- .../FileserverCompositionIntegrationTest.java | 2 +- ...SqlIdempotencyProviderIntegrationTest.java | 4 +- ...leOperationCompositionIntegrationTest.java | 4 +- .../bootstrap/CaSkeletonApplication.java | 1 - .../operation/DurableOperationConfig.java | 25 +- ...anonicalTransportRequirementValidator.java | 61 --- .../autoconfigure/outbox/OutboxSettings.java | 78 ---- .../security/ManagementSecurityConfig.java | 40 -- .../main/resources/META-INF/spring.factories | 3 +- ...ot.autoconfigure.AutoConfiguration.imports | 3 - .../src/main/resources/application.yml | 1 - .../DefaultCompositionBootTest.java | 8 +- .../BootstrapClockAutoConfigurationTest.java | 11 - .../idempotency/IdempotencySettingsTest.java | 147 ------ ...tboxCanonicalTransportCompositionTest.java | 76 --- ...icalTransportRequirementValidatorTest.java | 59 --- .../outbox/OutboxSettingsTest.java | 122 ----- .../contract/ActuatorSecurityHttpTest.java | 9 +- ...lityAutoConfigurationReachabilityTest.java | 11 +- .../ConfigurationNamespaceContractTest.java | 6 +- .../DistributedTracingContractTest.java | 4 +- .../contract/MetricsAlertingContractTest.java | 4 +- .../TracingActivationContextTest.java | 5 +- .../MessagingAuthorityContractTest.java | 12 +- .../OperationalContractRuntimeTest.java | 2 +- .../startup/StartupOrderContractTest.java | 6 +- src/application-core/CLAUDE.md | 5 +- src/application-core/README.md | 23 +- .../operation/DurableOperationSubmitted.java | 23 + .../DurableOperationSubmittedContract.java | 85 ++++ .../operation/OperationCommand.java | 21 +- .../SubmitDurableOperationUseCase.java | 82 +++- .../outbox/CanonicalClaimedOutboxEvent.java | 46 -- .../outbox/ClaimedOutboxEvent.java | 48 +- .../outbox/LegacyOutboxAppendPort.java | 14 - .../application/outbox/NewOutboxEvent.java | 53 --- .../application/outbox/OutboxAppendPort.java | 8 +- .../application/outbox/OutboxEvent.java | 53 --- .../outbox/OutboxPayloadPolicy.java | 271 ----------- .../outbox/OutboxRelayFailureReport.java | 4 +- .../v1.schema.json | 24 + .../SubmitDurableOperationUseCaseTest.java | 77 ++-- .../ClaimedOutboxEventContractTest.java | 94 ++-- .../outbox/NewOutboxEventTest.java | 108 ----- .../outbox/OutboxAppendPortBoundaryTest.java | 21 +- .../outbox/OutboxPayloadPolicyTest.java | 139 ------ .../outbox/OutcomeAwareRelayTest.java | 14 +- ...PublishPendingOutboxEventsUseCaseTest.java | 81 +--- ...ryOutboxStoreLeaseFencingContractTest.java | 4 +- .../testkit/FakeIntegrationEventEncoder.java | 63 +++ .../outbox/testkit/InMemoryOutboxStore.java | 64 +-- ...ontract.java => OutboxAppendContract.java} | 46 +- .../outbox/testkit/OutboxEvents.java | 75 +++ .../testkit/OutboxLeaseFencingContract.java | 16 +- src/composition/idempotency/README.md | 93 ++++ src/composition/idempotency/build.gradle | 35 ++ src/composition/idempotency/gradle.lockfile | 199 ++++++++ .../IdempotencyAutoConfiguration.java} | 30 +- .../idempotency/IdempotencySettings.java | 26 +- ...ot.autoconfigure.AutoConfiguration.imports | 1 + .../config/module-defaults/idempotency.yml} | 12 +- .../IdempotencyAutoConfigurationTest.java} | 18 +- .../IdempotencyModuleDefaultsTest.java | 64 +++ .../idempotency/IdempotencySettingsTest.java | 189 ++++++++ src/composition/outbox-relay/README.md | 137 ++++++ src/composition/outbox-relay/build.gradle | 35 ++ src/composition/outbox-relay/gradle.lockfile | 157 +++++++ .../outbox/OutboxLeaderElectionToken.java | 2 +- .../composition}/outbox/OutboxMetrics.java | 2 +- .../outbox/OutboxRelayAutoConfiguration.java} | 35 +- .../outbox/OutboxRelayScheduler.java | 2 +- .../composition/outbox/OutboxSettings.java | 74 +++ ...ot.autoconfigure.AutoConfiguration.imports | 1 + .../OutboxRelayAutoConfigurationTest.java} | 45 +- .../OutboxRelaySchedulerLoggingTest.java | 2 +- .../outbox/OutboxSettingsTest.java | 102 ++++ src/composition/service-runtime/README.md | 248 ++++++++++ src/composition/service-runtime/build.gradle | 40 ++ .../service-runtime/gradle.lockfile | 185 ++++++++ .../runtime/context}/DomainContextConfig.java | 6 +- .../runtime/logging}/PrivacySettings.java | 2 +- .../logging/PseudonymizationConfig.java | 7 +- .../security/ManagementSecurityConfig.java | 67 +++ .../MetricsCardinalityMeterFilter.java | 2 +- .../metrics/MetricsContractConfig.java | 6 +- .../MetricsDistributionMeterFilter.java | 2 +- .../tracing/MicrometerSpanErrorRecorder.java | 2 +- .../runtime}/tracing/TracingConfig.java | 2 +- .../tracing/TracingSampleRateResolver.java | 2 +- ...acingSamplingEnvironmentPostProcessor.java | 2 +- .../tracing/TracingSamplingRateGauge.java | 2 +- .../runtime}/tracing/TracingSettings.java | 2 +- .../main/resources/META-INF/spring.factories | 2 + ...ot.autoconfigure.AutoConfiguration.imports | 5 + .../ServiceRuntimeRegistrationTest.java | 94 ++++ .../runtime/logging}/PrivacySettingsTest.java | 2 +- .../logging/PseudonymizationConfigTest.java | 2 +- .../MetricsCardinalityMeterFilterTest.java | 2 +- .../metrics/MetricsContractConfigTest.java | 2 +- .../MetricsDistributionMeterFilterTest.java | 2 +- .../MicrometerSpanErrorRecorderTest.java | 2 +- .../TracingSampleRateResolverTest.java | 2 +- ...gSamplingEnvironmentPostProcessorTest.java | 2 +- .../runtime}/tracing/TracingSettingsTest.java | 2 +- src/config/architecture/modules.json | 62 ++- .../runtime/compose-profile-contracts.json | 3 + src/messaging/CLAUDE.md | 41 +- .../build.gradle | 33 -- .../gradle.lockfile | 111 ----- .../reliability/OutboxRepository.java | 43 +- .../build.gradle | 12 +- .../gradle.lockfile | 0 .../messaging/inbox/InboxPostgresIT.java | 0 .../AdminOperationJournalPostgresIT.java | 0 .../messaging/outbox/OutboxPostgresIT.java | 107 +++-- .../messaging/inbox/JdbcInboxRepository.java | 0 .../outbox/JdbcAdminOperationJournal.java | 0 .../outbox/JdbcOutboxRepository.java | 254 ++-------- .../messaging/V1001__messaging_outbox.sql | 0 .../V1002__messaging_outbox_lease_fencing.sql | 0 ...003__messaging_admin_operation_journal.sql | 0 ...4__messaging_outbox_canonical_metadata.sql | 0 ...5__messaging_outbox_ordering_key_index.sql | 0 .../messaging/V1101__messaging_inbox.sql | 0 .../JdbcInboxTransactionRequirementTest.java | 0 .../JdbcOutboxTransactionRequirementTest.java | 0 .../messaging-reliability/build.gradle | 19 + .../messaging-reliability/gradle.lockfile | 89 ++++ .../messaging/inbox/IdempotentConsumer.java | 0 .../messaging/inbox/InboxCleanupJob.java | 0 .../messaging/inbox/InboxOutcome.java | 0 .../messaging/inbox/InboxRetentionPolicy.java | 0 .../inbox/TransactionalInboxHandler.java | 0 .../messaging/outbox/OutboxCleanupJob.java | 0 .../outbox/OutboxEnvelopeFactory.java | 0 .../messaging/outbox/OutboxProperties.java | 0 .../messaging/outbox/OutboxRelay.java | 2 +- .../messaging/outbox/OutboxRelayReport.java | 0 .../messaging/outbox/OutboxRelayWorker.java | 0 .../outbox/OutboxRetryScheduler.java | 0 .../inbox/IdempotentConsumerTest.java | 0 .../messaging/inbox/InboxOperationsTest.java | 0 .../outbox/OutboxEnvelopeFactoryTest.java | 0 .../outbox/OutboxOperationsTest.java | 19 +- .../messaging/outbox/OutboxRelayTest.java | 46 +- .../outbox/OutboxRelayWorkerTest.java | 0 .../build.gradle | 5 +- .../MessagingOutboxRelayLifecycleTest.java | 17 - src/sample-portfolio/CLAUDE.md | 8 +- src/sample-portfolio/README.md | 114 ++--- src/sample-portfolio/build.gradle | 9 + ...ampleIdempotencyReplayIntegrationTest.java | 8 +- .../application/event/EventJson.java | 49 -- .../event/PortfolioEventContract.java | 80 ++++ .../event/PortfolioEventContracts.java | 80 ++++ .../event/PortfolioEventOutbox.java | 107 +++++ .../event/PosterCreatedPayload.java | 11 + .../event/PosterEventPublisher.java | 79 +--- .../application/event/PosterIdPayload.java | 12 + .../event/PosterImageAttachedPayload.java | 12 + .../PosterImageAttachmentPreparedPayload.java | 16 + .../PosterImageAttachmentReadyPayload.java | 18 + .../PosterImagePublicationEventPublisher.java | 78 ++-- .../WorkLogReservedIntegrationEvent.java | 10 - ...WorkLogReservedIntegrationEventMapper.java | 46 -- .../worklog/CreateWorkLogUseCase.java | 65 +-- .../SampleApplicationUseCaseConfig.java | 84 +++- .../context/SampleDomainContextConfig.java | 20 - .../idempotency/SampleIdempotencyConfig.java | 47 -- .../logging/SamplePseudonymizationConfig.java | 25 - .../SampleManagementSecurityConfig.java | 10 +- .../metrics/SampleMetricsContractConfig.java | 89 ---- .../runtime/SampleSchedulingConfig.java | 24 + .../settings/SamplePrivacySettings.java | 33 -- .../SampleMicrometerSpanErrorRecorder.java | 33 -- .../tracing/SampleTracingConfig.java | 83 ---- .../SampleTracingSampleRateResolver.java | 51 -- ...acingSamplingEnvironmentPostProcessor.java | 38 -- .../tracing/SampleTracingSettings.java | 76 --- .../main/resources/META-INF/spring.factories | 2 - .../src/main/resources/application.yml | 6 +- .../messaging/poster.archived/v1.schema.json | 18 + .../messaging/poster.created/v1.schema.json | 23 + .../messaging/poster.deleted/v1.schema.json | 18 + .../poster.image-attached/v1.schema.json | 23 + .../v1.schema.json | 33 ++ .../v2.schema.json | 38 ++ .../messaging/poster.published/v1.schema.json | 18 + .../event/PortfolioEventContractsTest.java | 44 ++ .../event/PortfolioEventOutboxTest.java | 85 ++++ .../event/PosterEventPublisherTest.java | 60 ++- ...LogReservedConsumerDedupeContractTest.java | 73 ++- ...eservedIntegrationEventMapperJsonTest.java | 84 ---- ...LogReservedIntegrationEventMapperTest.java | 36 -- .../PosterImageAbortReconcileRaceTest.java | 9 +- .../PosterImagePublicationWorkflowTest.java | 17 +- .../worklog/CreateWorkLogOutboxTest.java | 124 ++--- .../worklog/WorkLogUseCasesTest.java | 16 +- .../WorkLogAuthorizationContractTest.java | 21 +- .../SamplePublicAccessSecurityConfigTest.java | 6 +- .../contract/OpenApiDriftContractTest.java | 6 +- .../web/date/DateHeaderContractTest.java | 6 +- .../web/filter/VirtualThreadMdcE2ETest.java | 3 +- .../web/openapi/OpenApiSnapshotTest.java | 6 +- src/shared-contract/README.md | 2 +- .../shared/concurrency/package-info.java | 4 +- 329 files changed, 6380 insertions(+), 6850 deletions(-) create mode 100644 docs/reviews/2026-09-25-review-followup-results/W3-P18.md delete mode 100644 src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/BrokerAddress.java delete mode 100644 src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaAdapterConfig.java delete mode 100644 src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaAdapterSettings.java delete mode 100644 src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaMessageBroker.java delete mode 100644 src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSender.java delete mode 100644 src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderAutoConfiguration.java delete mode 100644 src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/LegacyKafkaMessagingRootAutoConfiguration.java delete mode 100644 src/adapter/outbound/messaging-kafka/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports delete mode 100644 src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/BrokerAddressTest.java delete mode 100644 src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaAdapterSettingsTest.java delete mode 100644 src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderAutoConfigurationOwnershipTest.java delete mode 100644 src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderInterruptionTest.java delete mode 100644 src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/LegacyKafkaAutoConfigurationRegistrationTest.java delete mode 100644 src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/DisabledMessagePublisher.java delete mode 100644 src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/MessageBroker.java delete mode 100644 src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/MessagePublisher.java delete mode 100644 src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/OutboundMessage.java delete mode 100644 src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/OutboundMessagePublisher.java delete mode 100644 src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxEnvelopeJson.java delete mode 100644 src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/core/OutboundMessagePublisherTest.java delete mode 100644 src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxCanonicalPublishRoutingTest.java rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/{ => jpa}/IdempotencyReaper.java (95%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/{ => jpa}/IdempotencyRecordJpaRepository.java (81%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/{ => jpa}/entity/IdempotencyRecordEntity.java (99%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/{postgresql/idempotency => idempotency/postgresql}/IdempotencyCapabilityGuard.java (98%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/{postgresql/idempotency => idempotency/postgresql}/IdempotencyClaimGateway.java (98%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/{postgresql/idempotency => idempotency/postgresql}/IdempotencyDigestPolicy.java (97%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/{postgresql/idempotency => idempotency/postgresql}/IdempotencyRecordRow.java (94%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/{postgresql/idempotency => idempotency/postgresql}/IdempotencyRowMapper.java (98%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/{postgresql/idempotency => idempotency/postgresql}/IdempotencySchemaStream.java (98%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/{postgresql/idempotency => idempotency/postgresql}/IdempotencyTransitionGateway.java (98%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/{postgresql/idempotency => idempotency/postgresql}/PostgreSqlOwnerSafeIdempotencyStore.java (99%) delete mode 100644 src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapter.java rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/{ => outbox}/h2/H2OutboxClaimRepository.java (67%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/{ => jpa}/OutboxClaimRepository.java (81%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/{ => jpa}/OutboxEventJpaRepository.java (95%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/{ => jpa}/OutboxReaper.java (90%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/{ => jpa}/OutboxStoreAdapter.java (68%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/{ => jpa}/entity/OutboxEventEntity.java (90%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/{ => outbox}/postgresql/PostgreSqlOutboxClaimRepository.java (61%) create mode 100644 src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V19__outbox_event_canonical_only.sql rename src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/{LegacyOutboxIntegrationSupport.java => OutboxIntegrationSupport.java} (93%) rename src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/{PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest.java => PostgreSqlOutboxAppendTransactionalIntegrationTest.java} (70%) rename src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/{PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest.java => PostgreSqlOutboxConcurrentRelayIntegrationTest.java} (82%) rename src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/{PostgreSqlLegacyOutboxRowLifecycleIntegrationTest.java => PostgreSqlOutboxRowLifecycleIntegrationTest.java} (87%) rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/{ => jpa}/IdempotencyActivationContractTest.java (91%) rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/{ => jpa}/IdempotencyReaperTest.java (90%) rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/{postgresql/idempotency => idempotency/postgresql}/IdempotencyDigestPolicyTest.java (97%) rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/{postgresql/idempotency => idempotency/postgresql}/OwnerSafeIdempotencyPreconditionTest.java (98%) delete mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapterActivationTest.java delete mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapterTest.java delete mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapterTest.java rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/{ => outbox}/h2/H2ClaimSqlTest.java (91%) rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/{ => jpa}/OutboxReaperTest.java (96%) rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/{ => jpa}/OutboxReaperWiringTest.java (98%) create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapterTest.java rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/{ => jpa}/OutboxSwitchWiringContractTest.java (94%) create mode 100644 src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/CanonicalJson.java create mode 100644 src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/IntegrationEventEncoderAutoConfiguration.java create mode 100644 src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java create mode 100644 src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinderTest.java create mode 100644 src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/IntegrationEventEncoderAutoConfigurationTest.java create mode 100644 src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java create mode 100644 src/adapter/outbound/support/src/test/resources/contracts/messaging/testkit.encoder-sample/v1.schema.json delete mode 100644 src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidator.java delete mode 100644 src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettings.java delete mode 100644 src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/management/security/ManagementSecurityConfig.java delete mode 100644 src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettingsTest.java delete mode 100644 src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportCompositionTest.java delete mode 100644 src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidatorTest.java delete mode 100644 src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettingsTest.java rename src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/{autoconfigure/tracing => contract}/TracingActivationContextTest.java (94%) create mode 100644 src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmitted.java create mode 100644 src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmittedContract.java delete mode 100644 src/application-core/src/main/java/dev/caskeleton/application/outbox/CanonicalClaimedOutboxEvent.java delete mode 100644 src/application-core/src/main/java/dev/caskeleton/application/outbox/LegacyOutboxAppendPort.java delete mode 100644 src/application-core/src/main/java/dev/caskeleton/application/outbox/NewOutboxEvent.java delete mode 100644 src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxEvent.java delete mode 100644 src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPayloadPolicy.java create mode 100644 src/application-core/src/main/resources/contracts/messaging/durable-operation.submitted/v1.schema.json delete mode 100644 src/application-core/src/test/java/dev/caskeleton/application/outbox/NewOutboxEventTest.java delete mode 100644 src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxPayloadPolicyTest.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoder.java rename src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/{LegacyOutboxAppendContract.java => OutboxAppendContract.java} (57%) create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxEvents.java create mode 100644 src/composition/idempotency/README.md create mode 100644 src/composition/idempotency/build.gradle create mode 100644 src/composition/idempotency/gradle.lockfile rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java => composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfiguration.java} (70%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure => composition/idempotency/src/main/java/dev/caskeleton/composition}/idempotency/IdempotencySettings.java (80%) create mode 100644 src/composition/idempotency/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports rename src/{app-bootstrap/src/main/resources/config/capabilities.yml => composition/idempotency/src/main/resources/config/module-defaults/idempotency.yml} (55%) rename src/{app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderCompositionTest.java => composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfigurationTest.java} (88%) create mode 100644 src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencyModuleDefaultsTest.java create mode 100644 src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencySettingsTest.java create mode 100644 src/composition/outbox-relay/README.md create mode 100644 src/composition/outbox-relay/build.gradle create mode 100644 src/composition/outbox-relay/gradle.lockfile rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure => composition/outbox-relay/src/main/java/dev/caskeleton/composition}/outbox/OutboxLeaderElectionToken.java (92%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure => composition/outbox-relay/src/main/java/dev/caskeleton/composition}/outbox/OutboxMetrics.java (98%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfig.java => composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java} (73%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure => composition/outbox-relay/src/main/java/dev/caskeleton/composition}/outbox/OutboxRelayScheduler.java (97%) create mode 100644 src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxSettings.java create mode 100644 src/composition/outbox-relay/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports rename src/{app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfigTest.java => composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfigurationTest.java} (67%) rename src/{app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure => composition/outbox-relay/src/test/java/dev/caskeleton/composition}/outbox/OutboxRelaySchedulerLoggingTest.java (98%) create mode 100644 src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxSettingsTest.java create mode 100644 src/composition/service-runtime/README.md create mode 100644 src/composition/service-runtime/build.gradle create mode 100644 src/composition/service-runtime/gradle.lockfile rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency => composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/context}/DomainContextConfig.java (82%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings => composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/logging}/PrivacySettings.java (96%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap => composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime}/logging/PseudonymizationConfig.java (83%) create mode 100644 src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap => composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime}/metrics/MetricsCardinalityMeterFilter.java (94%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap => composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime}/metrics/MetricsContractConfig.java (93%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap => composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime}/metrics/MetricsDistributionMeterFilter.java (97%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure => composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime}/tracing/MicrometerSpanErrorRecorder.java (92%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure => composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime}/tracing/TracingConfig.java (98%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure => composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime}/tracing/TracingSampleRateResolver.java (97%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure => composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime}/tracing/TracingSamplingEnvironmentPostProcessor.java (97%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure => composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime}/tracing/TracingSamplingRateGauge.java (96%) rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure => composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime}/tracing/TracingSettings.java (98%) create mode 100644 src/composition/service-runtime/src/main/resources/META-INF/spring.factories create mode 100644 src/composition/service-runtime/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports create mode 100644 src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/ServiceRuntimeRegistrationTest.java rename src/{app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings => composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/logging}/PrivacySettingsTest.java (98%) rename src/{app-bootstrap/src/test/java/dev/caskeleton/bootstrap => composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime}/logging/PseudonymizationConfigTest.java (97%) rename src/{app-bootstrap/src/test/java/dev/caskeleton/bootstrap => composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime}/metrics/MetricsCardinalityMeterFilterTest.java (99%) rename src/{app-bootstrap/src/test/java/dev/caskeleton/bootstrap => composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime}/metrics/MetricsContractConfigTest.java (98%) rename src/{app-bootstrap/src/test/java/dev/caskeleton/bootstrap => composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime}/metrics/MetricsDistributionMeterFilterTest.java (99%) rename src/{app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure => composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime}/tracing/MicrometerSpanErrorRecorderTest.java (96%) rename src/{app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure => composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime}/tracing/TracingSampleRateResolverTest.java (98%) rename src/{app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure => composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime}/tracing/TracingSamplingEnvironmentPostProcessorTest.java (97%) rename src/{app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure => composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime}/tracing/TracingSettingsTest.java (99%) delete mode 100644 src/messaging/messaging-inbox-jdbc-postgresql/build.gradle delete mode 100644 src/messaging/messaging-outbox-jdbc-postgresql/gradle.lockfile rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/build.gradle (69%) rename src/messaging/{messaging-inbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/gradle.lockfile (100%) rename src/messaging/{messaging-inbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/integrationTest/java/dev/caskeleton/messaging/inbox/InboxPostgresIT.java (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/integrationTest/java/dev/caskeleton/messaging/outbox/AdminOperationJournalPostgresIT.java (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java (86%) rename src/messaging/{messaging-inbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/main/java/dev/caskeleton/messaging/inbox/JdbcInboxRepository.java (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/main/java/dev/caskeleton/messaging/outbox/JdbcAdminOperationJournal.java (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java (71%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/main/resources/db/migration/messaging/V1001__messaging_outbox.sql (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/main/resources/db/migration/messaging/V1002__messaging_outbox_lease_fencing.sql (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/main/resources/db/migration/messaging/V1003__messaging_admin_operation_journal.sql (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/main/resources/db/migration/messaging/V1004__messaging_outbox_canonical_metadata.sql (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/main/resources/db/migration/messaging/V1005__messaging_outbox_ordering_key_index.sql (100%) rename src/messaging/{messaging-inbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/main/resources/db/migration/messaging/V1101__messaging_inbox.sql (100%) rename src/messaging/{messaging-inbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/test/java/dev/caskeleton/messaging/inbox/JdbcInboxTransactionRequirementTest.java (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability-jdbc-postgresql}/src/test/java/dev/caskeleton/messaging/outbox/JdbcOutboxTransactionRequirementTest.java (100%) create mode 100644 src/messaging/messaging-reliability/build.gradle create mode 100644 src/messaging/messaging-reliability/gradle.lockfile rename src/messaging/{messaging-inbox-jdbc-postgresql => messaging-reliability}/src/main/java/dev/caskeleton/messaging/inbox/IdempotentConsumer.java (100%) rename src/messaging/{messaging-inbox-jdbc-postgresql => messaging-reliability}/src/main/java/dev/caskeleton/messaging/inbox/InboxCleanupJob.java (100%) rename src/messaging/{messaging-inbox-jdbc-postgresql => messaging-reliability}/src/main/java/dev/caskeleton/messaging/inbox/InboxOutcome.java (100%) rename src/messaging/{messaging-inbox-jdbc-postgresql => messaging-reliability}/src/main/java/dev/caskeleton/messaging/inbox/InboxRetentionPolicy.java (100%) rename src/messaging/{messaging-inbox-jdbc-postgresql => messaging-reliability}/src/main/java/dev/caskeleton/messaging/inbox/TransactionalInboxHandler.java (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability}/src/main/java/dev/caskeleton/messaging/outbox/OutboxCleanupJob.java (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability}/src/main/java/dev/caskeleton/messaging/outbox/OutboxEnvelopeFactory.java (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability}/src/main/java/dev/caskeleton/messaging/outbox/OutboxProperties.java (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability}/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelay.java (99%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability}/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelayReport.java (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability}/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelayWorker.java (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability}/src/main/java/dev/caskeleton/messaging/outbox/OutboxRetryScheduler.java (100%) rename src/messaging/{messaging-inbox-jdbc-postgresql => messaging-reliability}/src/test/java/dev/caskeleton/messaging/inbox/IdempotentConsumerTest.java (100%) rename src/messaging/{messaging-inbox-jdbc-postgresql => messaging-reliability}/src/test/java/dev/caskeleton/messaging/inbox/InboxOperationsTest.java (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability}/src/test/java/dev/caskeleton/messaging/outbox/OutboxEnvelopeFactoryTest.java (100%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability}/src/test/java/dev/caskeleton/messaging/outbox/OutboxOperationsTest.java (91%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability}/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayTest.java (95%) rename src/messaging/{messaging-outbox-jdbc-postgresql => messaging-reliability}/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayWorkerTest.java (100%) delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/EventJson.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContract.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContracts.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutbox.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterCreatedPayload.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterIdPayload.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachedPayload.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentPreparedPayload.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentReadyPayload.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEvent.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapper.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/context/SampleDomainContextConfig.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/logging/SamplePseudonymizationConfig.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/metrics/SampleMetricsContractConfig.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/runtime/SampleSchedulingConfig.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/settings/SamplePrivacySettings.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleMicrometerSpanErrorRecorder.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingConfig.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingSampleRateResolver.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingSamplingEnvironmentPostProcessor.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingSettings.java delete mode 100644 src/sample-portfolio/src/main/resources/META-INF/spring.factories create mode 100644 src/sample-portfolio/src/main/resources/contracts/messaging/poster.archived/v1.schema.json create mode 100644 src/sample-portfolio/src/main/resources/contracts/messaging/poster.created/v1.schema.json create mode 100644 src/sample-portfolio/src/main/resources/contracts/messaging/poster.deleted/v1.schema.json create mode 100644 src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attached/v1.schema.json create mode 100644 src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attachment-prepared/v1.schema.json create mode 100644 src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attachment-ready/v2.schema.json create mode 100644 src/sample-portfolio/src/main/resources/contracts/messaging/poster.published/v1.schema.json create mode 100644 src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContractsTest.java create mode 100644 src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutboxTest.java delete mode 100644 src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperJsonTest.java delete mode 100644 src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperTest.java diff --git a/.github/workflows/integration-main.yml b/.github/workflows/integration-main.yml index 4d0e91df..004633b3 100644 --- a/.github/workflows/integration-main.yml +++ b/.github/workflows/integration-main.yml @@ -276,12 +276,9 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - uses: ./.github/actions/setup-gradle-java - - name: Inbox PostgreSQL contract + - name: Messaging outbox, inbox and admin-journal PostgreSQL contracts working-directory: src - run: ./gradlew :messaging:messaging-inbox-jdbc-postgresql:integrationTest --stacktrace - - name: Outbox PostgreSQL contract - working-directory: src - run: ./gradlew :messaging:messaging-outbox-jdbc-postgresql:integrationTest --stacktrace + run: ./gradlew :messaging:messaging-reliability-jdbc-postgresql:integrationTest --stacktrace - name: Messaging starter Kafka round trip working-directory: src run: ./gradlew :messaging:messaging-spring-boot-starter:integrationTest --stacktrace @@ -309,15 +306,15 @@ jobs: - name: Integer lock migration compatibility working-directory: src run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlIntLockMigrationCompatibilityIntegrationTest --stacktrace - - name: Legacy outbox transactional append + - name: Outbox transactional append working-directory: src - run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlLegacyOutboxAppendTransactionalIntegrationTest --stacktrace - - name: Legacy outbox concurrent relay + run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlOutboxAppendTransactionalIntegrationTest --stacktrace + - name: Outbox concurrent relay working-directory: src - run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlLegacyOutboxConcurrentRelayIntegrationTest --stacktrace - - name: Legacy outbox row lifecycle + run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlOutboxConcurrentRelayIntegrationTest --stacktrace + - name: Outbox row lifecycle working-directory: src - run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlLegacyOutboxRowLifecycleIntegrationTest --stacktrace + run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlOutboxRowLifecycleIntegrationTest --stacktrace # The optional gRPC platform build declares one strict INTEGRATION lane — # `grpc-operation-ledger-jpa:integrationTest`, which certifies the atomic diff --git a/CLAUDE.md b/CLAUDE.md index 20d388ca..de0b8f00 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -74,8 +74,8 @@ own `*-api` leaves are its ports, its broker leaves are its adapters, its starte root — and the messaging module review (`docs/reviews/2026-08-14-messaging-module-code-review.md` MSG-023 §6.2) chose that layout deliberately over folding it into `adapter:outbound:*`. This application reaches it through the application-owned anti-corruption bridge in -`adapter:outbound:messaging` (MSG-015). The canonical bridge exists; legacy outbox/realtime cutover -still has explicitly documented seams in `src/messaging/CLAUDE.md`. +`adapter:outbound:messaging` (MSG-015). The canonical bridge is the only path: the legacy outbox +append port and the legacy Kafka publishing seam were deleted (owner decision 7). Never infer an individual leaf's Gradle path, allowed dependency, or test command from this table. Read its `gradle_path` and `allowed_dependencies` from `src/config/architecture/modules.json`; runtime diff --git a/docs/architecture/jpa-adopter-api-surface.txt b/docs/architecture/jpa-adopter-api-surface.txt index 559f33a5..1cc052e2 100644 --- a/docs/architecture/jpa-adopter-api-surface.txt +++ b/docs/architecture/jpa-adopter-api-surface.txt @@ -12,8 +12,8 @@ dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy -dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository -dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlOutboxClaimRepository +dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository +dev.caskeleton.adapter.outbound.persistence.outbox.postgresql.PostgreSqlOutboxClaimRepository dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlPersistenceConfig dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlStateErrorMapping dev.caskeleton.adapter.outbound.persistence.security.DatabasePrivilegeReport diff --git a/docs/architecture/jpa-api-surface.txt b/docs/architecture/jpa-api-surface.txt index 891b9908..a1ccd83c 100644 --- a/docs/architecture/jpa-api-surface.txt +++ b/docs/architecture/jpa-api-surface.txt @@ -79,7 +79,6 @@ dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping -dev.caskeleton.adapter.outbound.persistence.h2.H2OutboxClaimRepository dev.caskeleton.adapter.outbound.persistence.h2.H2PersistenceConfig dev.caskeleton.adapter.outbound.persistence.h2.H2SqlStateErrorMapping dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy @@ -100,9 +99,11 @@ dev.caskeleton.adapter.outbound.persistence.hibernate.stateless.HibernateStatele dev.caskeleton.adapter.outbound.persistence.hibernate.stateless.StatelessRowCapExceededException dev.caskeleton.adapter.outbound.persistence.hibernate.stateless.StatelessWorkName dev.caskeleton.adapter.outbound.persistence.hibernate.stateless.StatelessWorkResult -dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyReaper -dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyRecordJpaRepository -dev.caskeleton.adapter.outbound.persistence.idempotency.entity.IdempotencyRecordEntity +dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyReaper +dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyRecordJpaRepository +dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.entity.IdempotencyRecordEntity +dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.IdempotencySchemaStream +dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlOwnerSafeIdempotencyStore dev.caskeleton.adapter.outbound.persistence.liveevent.JpaLiveEventReplayAdapter dev.caskeleton.adapter.outbound.persistence.liveevent.LiveEventJpaRepository dev.caskeleton.adapter.outbound.persistence.liveevent.entity.LiveEventEntity @@ -165,12 +166,13 @@ dev.caskeleton.adapter.outbound.persistence.observation.SqlDiagnosticRedactor dev.caskeleton.adapter.outbound.persistence.operation.DurableOperationJpaRepository dev.caskeleton.adapter.outbound.persistence.operation.DurableOperationStoreAdapter dev.caskeleton.adapter.outbound.persistence.operation.entity.DurableOperationEntity -dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository -dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository -dev.caskeleton.adapter.outbound.persistence.outbox.OutboxReaper -dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter -dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity -dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlOutboxClaimRepository +dev.caskeleton.adapter.outbound.persistence.outbox.h2.H2OutboxClaimRepository +dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository +dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository +dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxReaper +dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter +dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity +dev.caskeleton.adapter.outbound.persistence.outbox.postgresql.PostgreSqlOutboxClaimRepository dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlPersistenceConfig dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlStateErrorMapping dev.caskeleton.adapter.outbound.persistence.postgresql.array.PostgreSqlArraySupport @@ -188,8 +190,6 @@ dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlException dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlFailureClassifier dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlServerErrorFields dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlState -dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.IdempotencySchemaStream -dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.PostgreSqlOwnerSafeIdempotencyStore dev.caskeleton.adapter.outbound.persistence.postgresql.json.JsonDocument dev.caskeleton.adapter.outbound.persistence.postgresql.json.JsonDocumentCodec dev.caskeleton.adapter.outbound.persistence.postgresql.json.JsonPathName diff --git a/docs/capability-status.md b/docs/capability-status.md index 4410cd30..7f662bea 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -422,3 +422,27 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap | `GraphQlRequestEnvelopeValidator`·`GraphQlHttpRequestEnvelope` + `GraphQlRequestEnvelopeValidatorTest` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/` | `4fb7943b` | 요청 경로에서 도달 불가 (J-10d) | | `MigrationFailedException`·`ProfileMismatchException`·`RequiredAdapterDisabledException`·`StartupValidationException` | `src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/` | `f2857840^`(= `b7187e1b`) | 역할 없는 subclass (S6-#13) | | `ExternalRequestUrlResolver`의 forwarded 파싱 + env `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES` | `src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolver.java` | `d54909c4` | 컨테이너(RemoteIpValve)와 다른 두 번째 신뢰 판단 (I-5b) | +| `LegacyOutboxAppendPort` | `src/application-core/src/main/java/dev/caskeleton/application/outbox/LegacyOutboxAppendPort.java` | `6d27356e` | canonical `OutboxAppendPort`로 통일(결정 7) | +| legacy outbox 모델 `NewOutboxEvent`, `OutboxEvent`, `CanonicalClaimedOutboxEvent`, `OutboxPayloadPolicy` (+ `NewOutboxEventTest`, `OutboxPayloadPolicyTest`) | `src/application-core/src/main/java/dev/caskeleton/application/outbox/` | `6d27356e` | append 모델이 `ValidatedIntegrationEvent` 하나. `ClaimedOutboxEvent`는 sealed 합집합이 아니라 canonical record | +| `LegacyOutboxAppendContract` | `src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/LegacyOutboxAppendContract.java` | `6d27356e` | `OutboxAppendContract`로 대체 | +| `CanonicalOutboxAppendAdapter` (+ Activation·단위 테스트) | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapter.java` | `6d27356e` | `OutboxStoreAdapter`가 `OutboxAppendPort`를 직접 구현(트랜잭션 guard 포함) | +| `OutboxEventEntity.payload`·`idempotencyKey` 접근자, claim SQL의 legacy CASE | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/entity/OutboxEventEntity.java`, `PostgreSqlOutboxClaimRepository`, `H2OutboxClaimRepository` | `6d27356e` | canonical 컬럼만 읽고 씀. 컬럼은 V19에서 nullable로 두고 migration은 수정하지 않음 | +| `OutboxCanonicalTransportRequirementValidator` (+ Validator/Composition 테스트) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidator.java` | `6d27356e` | 켜고 끌 canonical 플래그가 없어짐 | +| 설정 키 `ca-skeleton.outbox.canonical-transport-enabled` / env `APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED` | `persistence-jpa.yml`, `docs/registries/env-keys.yaml`, `src/.env.example` | `6d27356e` | 같음 | +| messaging `core/*`: `MessageBroker`, `MessagePublisher`, `OutboundMessage`, `OutboundMessagePublisher`, `DisabledMessagePublisher` (+ `OutboundMessagePublisherTest`) | `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/` | `6d27356e` | legacy 발행 경로 삭제. relay는 bridge(`IntegrationEventPublishPort`)만 씀 | +| `OutboxEnvelopeJson` (+ `OutboxCanonicalPublishRoutingTest`) | `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxEnvelopeJson.java` | `6d27356e` | envelope은 encoder가 한 번 만들고 bytes 그대로 전달 | +| legacy Kafka seam: `KafkaSender`, `KafkaSenderAutoConfiguration`, `KafkaMessageBroker`, `KafkaAdapterConfig`, `KafkaAdapterSettings`, `BrokerAddress`, `LegacyKafkaMessagingRootAutoConfiguration`, `AutoConfiguration.imports` (+ 테스트 5개) | `src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/` | `6d27356e` | TLS/SASL 없는 두 번째 producer(X1-#1f, NEW-4a). leaf는 코드 없는 capability 묶음으로 유지 | +| `messaging.yml`의 `kafka.brokers` | `src/adapter/outbound/messaging-kafka/src/main/resources/config/module-defaults/messaging.yml` | `6d27356e` | seam 설정 | +| `WorkLogReservedIntegrationEvent`, `WorkLogReservedIntegrationEventMapper` (+ Mapper 테스트 2개) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/` | `6d27356e` | `PortfolioEventOutbox` + 계약 `portfolio.worklog.reserved` v1로 대체 | +| `SampleIdempotencyConfig` (executor 복사본) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java` | `6d27356e` | `composition:idempotency` 사용. Clock·스케줄링만 `SampleSchedulingConfig`로 | +| app-bootstrap `config/capabilities.yml` (이동) | `src/app-bootstrap/src/main/resources/config/capabilities.yml` | `6d27356e` | `composition/idempotency/.../config/module-defaults/idempotency.yml`로 이동 | +| app-bootstrap outbox 조립 `OutboxConfig`·`OutboxSettings`·`OutboxMetrics`·`OutboxRelayScheduler`·`OutboxLeaderElectionToken` (이동) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/` | `6d27356e` | `composition:outbox-relay`로 이동 | +| app-bootstrap 멱등성 조립 `IdempotencyProviderSelectionConfig`·`IdempotencySettings` (이동) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/` | `6d27356e` | `composition:idempotency`로 이동 | +| app-bootstrap runtime 배선 tracing 6개, metrics 3개, `DomainContextConfig/Settings`, `PseudonymizationConfig`, `PrivacySettings`, `ManagementSecurityConfig` (이동) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/{autoconfigure/tracing,metrics,concurrency,logging,settings,management/security}/` | `6d27356e` | `composition:service-runtime`으로 이동 | +| sample bootstrap 복사본: `SampleTracingConfig`, `SampleTracingSettings`, `SampleTracingSampleRateResolver`(`staging` 분기), `SampleTracingSamplingEnvironmentPostProcessor`, `SampleMicrometerSpanErrorRecorder`, `SampleMetricsContractConfig`, `SampleDomainContextConfig`, `SamplePseudonymizationConfig`, `SamplePrivacySettings`, `META-INF/spring.factories` | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/{tracing,metrics,context,logging,settings}/` | `6d27356e` | 원본과 갈라진 복사본(S6-#7). 공용 모듈 사용 | +| messaging `OutboxRepository.leaseBatch`, 4인자 `claimBatch`, 3인자 `markAmbiguous` | `src/messaging/messaging-reliability-api/src/main/java/dev/caskeleton/messaging/reliability/OutboxRepository.java` | `6d27356e` | main 호출 0. fencing 없는 claim/쓰기 표면(S7-#8) | +| `JdbcOutboxRepository`의 LEASE SQL·`leaseBatch`·`*Unfenced` 4개·`update` helper·손 JSON(`toJson`/`fromJson`/`escape`/`unescape`) | `src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java` | `6d27356e` | 호출 0. 손 JSON reader는 결함(P18-new-1). jsonb 함수로 대체 | +| leaf `messaging-outbox-jdbc-postgresql`, `messaging-inbox-jdbc-postgresql` (코드는 이동) | `src/messaging/messaging-outbox-jdbc-postgresql`, `src/messaging/messaging-inbox-jdbc-postgresql` | `6d27356e` | `messaging-reliability` + `messaging-reliability-jdbc-postgresql`로 재분할(S7-#5b) | +| 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`를 직접 만든다 | diff --git a/docs/messaging/configuration-reference.md b/docs/messaging/configuration-reference.md index 2dd4be8f..0f87d731 100644 --- a/docs/messaging/configuration-reference.md +++ b/docs/messaging/configuration-reference.md @@ -21,20 +21,16 @@ Application의 canonical integration event를 platform publish pipeline으로 producing-service identity다. 값이 없으면 `IntegrationEventPublishPort` bridge 자체를 만들지 않는다. `spring.application.name`이나 -현재 process 이름으로 추론하지 않는다. 기존 legacy `OutboxEvent`/realtime 경로는 별도 cutover가 -끝날 때까지 `app.messaging.broker` 경로를 유지한다. +현재 process 이름으로 추론하지 않는다. 모든 발행(outbox relay 포함)이 이 bridge를 지나므로 messaging +모듈이 켜진 상태에서 값이 없으면 기동이 거부된다. -## Outbox canonical transport-only cutover +## Outbox -`APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED` / `ca-skeleton.outbox.canonical-transport-enabled`은 -기존 `outbox_event` writer/claim/status authority를 유지한 채 canonical row의 **transport만** platform -publish path로 보내는 compatibility gate다. 기본값은 `false`이며 두 번째 relay를 만들지 않는다. - -`true`일 때는 `OutboxAppendPort`가 `ValidatedIntegrationEvent`의 exact envelope bytes와 canonical -metadata를 기존 outbox row에 저장하고, claim된 canonical row는 `IntegrationEventPublishPort`로 간다. -legacy row는 계속 `MessageBroker`를 사용한다. 따라서 mixed-row compatibility 기간에는 relay가 켜져 -있다면 `app.messaging.broker`도 계속 필요하며, canonical path를 위해 `IntegrationEventPublishPort`도 -추가로 필요하다. legacy backlog가 0이라는 별도 증거 없이 broker 요구를 제거하지 않는다. +outbox는 canonical 하나다(2026-09-28). use case가 `IntegrationEventEncoderPort`로 만든 +`ValidatedIntegrationEvent`를 `OutboxAppendPort`로 append하고, relay는 claim한 row의 exact envelope +bytes를 `IntegrationEventPublishPort`로 보낸다. 예전의 `ca-skeleton.outbox.canonical-transport-enabled` +gate와 legacy `MessageBroker → KafkaSender` 경로는 삭제됐다. 발행할 contract의 logical destination마다 +아래 destination profile을 선언한다(템플릿의 durable operation event는 `durable-operations`). ## Destination profile diff --git a/docs/messaging/outbox-inbox.md b/docs/messaging/outbox-inbox.md index fede443b..d71c30fc 100644 --- a/docs/messaging/outbox-inbox.md +++ b/docs/messaging/outbox-inbox.md @@ -21,8 +21,8 @@ Flyway version `1000..1999`를 예약해서 애플리케이션의 일반적인 classpath:db/migration/messaging ``` -현재 순서는 `V1001..V1005`(outbox/admin)와 `V1101`(inbox)이다. starter 테스트가 두 JDBC -모듈을 실제 combined classpath로 올려 version 중복과 예약 대역 이탈을 검사한다. 개별 DDL의 +현재 순서는 `V1001..V1005`(outbox/admin)와 `V1101`(inbox)이고, 모두 +`messaging-reliability-jdbc-postgresql`에 있다. starter 테스트가 그 모듈을 실제 combined classpath로 올려 version 중복과 예약 대역 이탈을 검사한다. 개별 DDL의 의미와 전환 순서는 [migration-guide.md](migration-guide.md)를 따른다. ## Outbox @@ -39,7 +39,7 @@ COMMIT; ### relay ```text -leaseBatch(100, 30s) -- lease로 다중 relay 인스턴스 안전 +claimBatch(owner, 100, 30s, now, maxAttempts) -- owner + fencing token으로 다중 relay 인스턴스 안전 → publish (messageId 그대로) → CONFIRMED → markPublished → AMBIGUOUS → markAmbiguous (같은 messageId로 재시도 가능) diff --git a/docs/messaging/support-matrix.md b/docs/messaging/support-matrix.md index 84c9647f..bd3164cd 100644 --- a/docs/messaging/support-matrix.md +++ b/docs/messaging/support-matrix.md @@ -17,8 +17,10 @@ > `BrokerFailureMatrix.shipped()` 하드코딩이 아니라 레인이 낸 증거(`BrokerCertificationEvidence`)에서 > 나온다. 증거가 없는 조합은 `NOT_COVERED`다 (MSG-014). -> **모듈 이름과 런타임 편입.** `messaging-outbox-jdbc-postgresql` / `messaging-inbox-jdbc-postgresql`은 -> 이전에 `-jpa`로 불렸다. 구현은 Spring JDBC이고 SQL은 PostgreSQL 전용(`?::jsonb`, +> **모듈 이름과 런타임 편입.** 관계형 신뢰성 구현은 `messaging-reliability-jdbc-postgresql`, +> 그 port만 보는 relay·consumer 로직은 `messaging-reliability`다(2026-09-28에 +> `messaging-outbox-jdbc-postgresql` / `messaging-inbox-jdbc-postgresql`을 이렇게 나눴다). 그 전에는 +> `-jpa`로 불렸다. 구현은 Spring JDBC이고 SQL은 PostgreSQL 전용(`jsonb`, > `FOR UPDATE SKIP LOCKED`, `ON CONFLICT`, `TIMESTAMPTZ`)이므로, 그 이름은 쓰지 않는 기술을 > 광고하고 vendor 중립 port(`messaging-reliability-api`)의 위치를 가렸다 (MSG-023). > diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 6d6ed884..3529a148 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -2913,8 +2913,9 @@ env_keys: - name: APP_MESSAGING_BROKER # source: messaging multi-broker redesign 2026-06-16 — single active broker selection - # (app.messaging.broker=); blank = messaging disabled. Replaces the former - # Kafka-binary APP_MESSAGING_KAFKA_ENABLED. Adding a broker is new files only. + # (app.messaging.broker=), read by the vendored messaging platform. Replaces the + # former Kafka-binary APP_MESSAGING_KAFKA_ENABLED. The application bridge no longer reads it: + # the legacy KafkaSender seam that did was removed with the canonical outbox (2026-09-28). type: string # The Kafka module's config/module-defaults/messaging.yml defaults it to kafka, the only registered broker. default: kafka @@ -2931,11 +2932,14 @@ env_keys: # source: canonical messaging platform bridge 2026-09-18 # Explicit logical producing-service identity for IntegrationEventPublishPort. # Blank/absent = canonical platform bridge is not exposed; identity is never inferred. + # Every publication, the outbox relay's included, goes through that bridge, so with the + # messaging module present and on a blank value refuses startup (2026-09-28 canonical outbox). type: string default: null allowed_values: null classification: public-config required: false + required_when: APP_MESSAGING_ENABLED=true reload_policy: restart-only owner_branch: feature-integration-adapter-templates validation: none @@ -2945,9 +2949,9 @@ env_keys: - name: APP_MESSAGING_KAFKA_BROKERS # source: feature-domain-event-outbox-contract — "Kafka는 optional integration adapter" # (broker 활성화 시 endpoint 필요) - # Also feeds app.messaging.brokers.kafka.bootstrap-servers (the messaging platform's Kafka - # transport) through the Kafka module's config/module-defaults/messaging.yml, so one key - # addresses both paths. spring.kafka.bootstrap-servers is not read. + # Feeds app.messaging.brokers.kafka.bootstrap-servers (the messaging platform's Kafka + # transport) through the Kafka module's config/module-defaults/messaging.yml. + # spring.kafka.bootstrap-servers is not read. type: csv_list default: null allowed_values: null @@ -4185,26 +4189,11 @@ env_keys: validation: boolean compatibility_impact: behavior-change required_test: adapter-contract:outbox-capability-disabled-safe - - name: APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED - # source: MSG-015 transport-only cutover 2026-09-18 - # Enables canonical outbox rows/platform transport without switching publication authority. - type: boolean - default: false - allowed_values: - - "true" - - "false" - classification: public-config - required: false - reload_policy: restart-only - owner_branch: feature-integration-adapter-templates - validation: boolean - compatibility_impact: additive - required_test: app-bootstrap:outbox-canonical-transport-gate - - name: APP_OUTBOX_RELAY_ENABLED # source: five-adapter-runtime-remediation §6.3 MSG-INT-001 — starts the relay scheduler. - # Requires APP_OUTBOX_ENABLED, APP_PERSISTENCE_JPA_ENABLED and APP_MESSAGING_ENABLED with a - # broker; the shipped default was true beside a blank broker, which refused every startup. + # Requires APP_OUTBOX_ENABLED, APP_PERSISTENCE_JPA_ENABLED and APP_MESSAGING_ENABLED with + # APP_MESSAGING_PRODUCER_ID; the shipped default was true beside a blank broker, which refused + # every startup. type: boolean default: false allowed_values: [true, false] diff --git a/docs/reviews/2026-09-25-review-followup-results/W3-P18.md b/docs/reviews/2026-09-25-review-followup-results/W3-P18.md new file mode 100644 index 00000000..a8d07641 --- /dev/null +++ b/docs/reviews/2026-09-25-review-followup-results/W3-P18.md @@ -0,0 +1,90 @@ +# W3-P18 — outbox canonical 통일 + `composition:*` + legacy Kafka seam 삭제 + +- worktree: `/home/donghyeon/workspace/chat-gpt-container/codebase/clean-architecture-backend-template/.claude/worktrees/agent-aabba563c6ef6bf7d` +- 브랜치: `worktree-agent-aabba563c6ef6bf7d` (기준 `016597ac`) +- 커밋(순서대로): + - `6268c494` P18 D: outbox를 canonical 하나로 통일하고 legacy Kafka 발행 경로 삭제 + - `a053ae89` P18 W3: outbox relay·멱등성 executor 조립을 composition 모듈로 이동 + - `910ab7ab` P18 W3: persistence-jpa outbox·멱등성 패키지를 feature 기준으로 이동 + - `165e0499` P18 W3: messaging outbox 죽은 표면 삭제와 header JSON을 jsonb로 + - `2ddd210a` P18 W3: sample 복사 bootstrap 인프라를 composition:service-runtime 공용 모듈로 + - `e1dafd00` P18 W3: messaging outbox·inbox leaf를 reliability(stdlib)와 reliability-jdbc-postgresql로 재분할 +- W1·W2 커밋은 따로 없다. W1 행 3개와 W2 행 2개는 D 커밋(`6268c494`)의 삭제와 sample 이전으로 닫혔다. +- 추가한 migration 버전: persistence-jpa `V19__outbox_event_canonical_only.sql`. `applied-migrations.sha256`에 한 줄을 더했다: `a0306e5b0fbcaf43984d256362dc4244aec57a0ce5031e4f5263be3762fe1caf postgresql/V19__outbox_event_canonical_only.sql`. 이미 적용된 migration은 고치지 않았다. messaging의 `V1001..V1005`·`V1101`은 내용을 바꾸지 않고 `messaging-reliability-jdbc-postgresql`로 옮기기만 했다. classpath 위치 `db/migration/messaging`도 같다. +- registry 변경: + - 추가: `composition-outbox-relay`, `composition-idempotency`, `composition-service-runtime`, `messaging-reliability`, `messaging-reliability-jdbc-postgresql`. + - 삭제: `messaging-outbox-jdbc-postgresql`, `messaging-inbox-jdbc-postgresql`. + - `adapter-outbound-messaging-kafka`는 registry에 남겼다. 코드가 없는 capability 묶음으로, bridge와 `messaging-spring-boot-starter-kafka`를 `runtimeOnly`로 싣는다. 한 줄 선택(`runtimeOnly project(':adapter:outbound:messaging-kafka')`)을 그대로 쓰기 위해서다. +- env 키 변경: + - `APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED` 삭제. + - `APP_MESSAGING_PRODUCER_ID`를 `required_when: APP_MESSAGING_ENABLED=true`로 바꿨다. + - `env-keys.yaml`, `.env.example`, `compose-profile-contracts.json`을 함께 고쳤다. +- 설정 prefix는 바꾸지 않았다(3-B 몫). +- `docs/capability-status.md`는 고치지 않았다. 아래 "제거된 코드" 표를 오케스트레이터가 옮겨 적어야 한다. + +## 행 결과 +| ID | 결과 | 근거 | +|---|---|---| +| X1-지도-Kafka producer | 해당 없음(코드 삭제) | **삭제:** legacy seam producer(`KafkaSenderAutoConfiguration`·`KafkaSender`·`LegacyKafkaMessagingRootAutoConfiguration`)를 `6268c494`에서 지웠다.
**남은 producer:** platform 하나다. `KafkaSecurityConfigurer`로 TLS/SASL을 적용한다: `src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaMessagingAutoConfiguration.java:188` `config.putAll(producerSecurity(...))`, `:216`.
**같은 결함 없음:** `MessagingSecuredBrokerQualificationTest`가 PASS다 — `aPublishIsConfirmedByAPrivateCaBrokerThatRequiresSaslAsTheProviderUser`, `aPublishIsConfirmedByAPrivateCaBrokerThatRequiresAClientCertificate`, `:messaging:messaging-spring-boot-starter:integrationTest` 3/3. | +| X1-#1f | 해당 없음(코드 삭제) | 위와 같다. 보안 블록을 추가할 대상인 `KafkaAdapterSettings`·`kafkaSeamProducer`가 `6268c494`에서 삭제됐다. canonical 경로의 producer는 `KafkaMessagingAutoConfiguration.java:188`에서 보안 profile을 적용하고, `MessagingSecuredBrokerQualificationTest` 2/2가 PASS다. | +| NEW-4a | 해당 없음(코드 삭제) | **삭제:** 항상 PLAINTEXT인 seam producer(`KafkaSenderAutoConfiguration.java:62-80`)와 그것을 켜던 `LegacyKafkaMessagingRootAutoConfiguration`이 `6268c494`에서 삭제됐다. messaging-kafka의 `AutoConfiguration.imports`도 삭제했다.
**남은 producer:** platform producer 하나다(`KafkaMessagingAutoConfiguration.java:188`, `:216`). 보안 profile이 없는데 broker가 TLS를 요구하면 기동을 거부하는 규칙도 그 경로에 그대로 있다.
**테스트:** `KafkaCapabilityActivationTest`는 leaf가 bridge+starter 묶음이 된 것에 맞게 갱신했고 PASS다. | +| S6-lead-3 | 완료 | **이전:** sample 3곳(`CreateWorkLogUseCase`, `PosterEventPublisher`, `PosterImagePublicationEventPublisher`)을 `PortfolioEventOutbox`로 옮겼다(`src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutbox.java:44`). 이 클래스는 `OutboxAppendPort`와 `IntegrationEventEncoderPort`를 쓴다.
**계약 등록:** `PortfolioEventContracts`가 계약 8개(poster 7 + `portfolio.worklog.reserved` v1)와 schema hash를 등록한다.
**삭제:** `LegacyOutboxAppendPort`.
**테스트:** `PortfolioEventOutboxTest`, `PortfolioEventContractsTest`, `CreateWorkLogOutboxTest`, `PosterEventPublisherTest`, `WorkLogReservedConsumerDedupeContractTest` PASS. `:sample-portfolio:test` 289, integrationTest 49, systemTest 3, webSystemTest 5 모두 PASS. | +| S7-lead-3 | 해당 없음(코드 삭제) | R0 경로(`LegacyKafkaMessagingRootAutoConfiguration`·`KafkaSender`·`KafkaSenderAutoConfiguration`·`KafkaMessageBroker`)를 `6268c494`에서 삭제했다. 남은 Kafka producer는 platform `KafkaMessagingTransport` 하나다. | +| X1-지도-Outbox | 완료 | **append 포트:** `OutboxAppendPort` 하나다(`src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAppendPort.java:15`). `LegacyOutboxAppendPort`는 삭제했다.
**구현:** `OutboxStoreAdapter implements OutboxAppendPort, OutboxStorePort`(`src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java:48`). `CanonicalOutboxAppendAdapter`는 여기로 합쳤다.
**X1-#1c guard:** `append` 첫 줄의 `requireTransaction("append")`(`:65`)다.
**relay 조립:** `composition:outbox-relay`에 있다(`src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java:53`).
**테스트:** `OutboxAppendContract`(application-core testFixtures)를 fake와 adapter가 공유한다. PostgreSQL lane `postgresqlOutboxAppendTransactionalIntegrationTest` 2, `postgresqlOutboxConcurrentRelayIntegrationTest` 4, `postgresqlOutboxRowLifecycleIntegrationTest` 10 PASS. | +| X1-#1b | 완료 | **소비자 4곳 이전:** `SubmitDurableOperationUseCase`(`src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java:72`, 계약 `DurableOperationSubmittedContract`)와 sample 3곳이 `OutboxAppendPort`를 쓴다.
**encoder:** 템플릿 encoder `JsonIntegrationEventEncoder`(`src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java:47`)와 `IntegrationEventEncoderAutoConfiguration`.
**테스트:** `JsonIntegrationEventEncoderTest`, `IntegrationEventEncoderAutoConfigurationTest`, `DurableOperationSubmissionOutboxIntegrationTest`(실제 encoder) PASS. | +| X1-#1i | 완료 | **이동:** `OutboxConfig`→`OutboxRelayAutoConfiguration`, 그리고 `OutboxSettings`·`OutboxMetrics`·`OutboxRelayScheduler`·`OutboxLeaderElectionToken`을 `src/composition/outbox-relay`로 옮겼다(`a053ae89`).
**삭제:** `OutboxCanonicalTransportRequirementValidator`는 옮기지 않고 삭제했다. 켜고 끌 canonical 플래그가 더는 없다.
**연결:** app-bootstrap은 `runtimeOnly project(':composition:outbox-relay')` 한 줄로 받는다.
**테스트:** `OutboxRelayAutoConfigurationTest`(`aMisspeltOutboxKeyFailsStartupInsteadOfLeavingTheDefaultInForce` 포함), `OutboxRelaySchedulerLoggingTest` PASS. | +| S1-#2b / S2-#4b | 완료 | **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. | +| S2-lead-1 | 완료 | 포트 버전이 하나로 줄었다: `OutboxAppendPort`(append)와 `OutboxStorePort`(claim/완료). 근거는 S1-#2b와 같다. | +| S7-#8 | 완료 | **삭제:** `OutboxRepository`의 `leaseBatch`, 4인자 `claimBatch`, 3인자 `markAmbiguous`(`src/messaging/messaging-reliability-api/src/main/java/dev/caskeleton/messaging/reliability/OutboxRepository.java:43`, `:57`만 남음). `JdbcOutboxRepository`의 LEASE SQL, `*Unfenced` 4개, `update` helper, 손으로 쓴 JSON(`toJson`/`fromJson`/`escape`/`unescape`).
**header 저장:** `jsonb_object(?::text[])`로 쓰고 `jsonb_each_text`로 읽는다(`src/messaging/messaging-reliability-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java:59`, `:77-78`).
**TDD:** `OutboxPostgresIT.aHeaderValueEndingInABackslashRoundTripsWithoutSwallowingTheNextHeader`(`OutboxPostgresIT.java:612`)가 먼저 FAIL했다("map entries not expected: x-path=C:\exports\"") → 수정 후 PASS. integrationTest 36/36.
**그대로 둔 것:** purge 오버로드(1차 M-6)는 손대지 않았다. | +| S4-lead-4b | 완료 | **삭제:** `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. | +| NEW-2a | 완료 | X1-#1i와 같다. 조립은 `src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java:43-53`에 있고, app-bootstrap `AutoConfiguration.imports`에서 outbox 줄을 뺐다. | +| NEW-2b | 완료 | **이동:** `IdempotencyProviderSelectionConfig`→`IdempotencyAutoConfiguration`(`src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfiguration.java:38`, executor 생성 `:58`).
**설정:** `IdempotencySettings.bind`는 `StrictSettingsBinder.bindExcept`로 strict 바인딩한다. `config/module-defaults/idempotency.yml`로 옮겼다(예전 `capabilities.yml`).
**sample:** `SampleIdempotencyConfig`를 삭제했다. Clock·`@EnableScheduling`만 `SampleSchedulingConfig`에 남겼다.
**테스트:** `IdempotencySettingsTest`(strict), `IdempotencyAutoConfigurationTest`, `IdempotencyModuleDefaultsTest`, `StrictSettingsBinderTest`, `SampleIdempotencyReplayIntegrationTest` PASS. | +| G-11b | 완료 | NEW-2b와 같다. `modules.json`에 `composition-idempotency`(edge application-core, adapter-outbound-support)를 등록했다. app-bootstrap과 sample이 `runtimeOnly project(':composition:idempotency')`를 쓴다. | +| X1-#2b | 완료 | executor 생성은 한 곳이다: `IdempotencyAutoConfiguration.java:58`. main에 `new IdempotencyExecutor`는 여기뿐이다. web testFixtures의 fault fixture는 테스트용이다. provider는 store bean만 기여한다. | +| S1-lead-3 | 완료 | NEW-2b와 같다. | +| X1-지도-요청 멱등성 | 완료 | 조립이 한 곳이다(`composition:idempotency`). 두 root가 같은 모듈을 쓴다. | +| S6-#7 | 완료 | **새 leaf `composition:service-runtime`**(`dev.caskeleton.composition.runtime`, edge application-core, shared-contract, adapter-outbound-support, adapter-outbound-identifier):
- 원본을 app-bootstrap에서 옮겼다: `tracing`(TracingConfig 외 5), `metrics`(MetricsContractConfig+filter 2), `context`(DomainContextConfig/Settings), `logging`(PseudonymizationConfig, PrivacySettings), `management/security`(ManagementSecurityConfig).
- 모두 이 모듈의 `AutoConfiguration.imports`로, sampling bridge는 `spring.factories`로 등록한다.
- app-bootstrap과 sample이 `runtimeOnly project(':composition:service-runtime')`를 쓴다.
**sample:** 복사본 10개와 `spring.factories`를 삭제했다. 원본을 쓰므로 `staging=0.10` 분기도 사라졌다.
**sample actuator chain:** 복사본이 아니라 공개 데모라는 샘플만의 결정이라 남겼다. bean 이름을 `actuatorSecurityFilterChain`으로 바꿔 공용 chain이 물러나게 했다(`ConditionalOnMissingBean(name)`).
**테스트:** `ServiceRuntimeRegistrationTest` 4개(신규), 옮긴 테스트 9 클래스 — `:composition:service-runtime:test` 86 PASS. `ActuatorSecurityHttpTest`, `DefaultCompositionBootTest`, `StartupOrderContractTest`, `ConfigurationNamespaceContractTest` 갱신 후 PASS. | +| S7-#5b | 완료 | **`messaging-reliability`**(stdlib: `OutboxRelay`·`OutboxRelayWorker`·`OutboxRetryScheduler`·`OutboxEnvelopeFactory`·`OutboxCleanupJob`·`OutboxProperties`·`OutboxRelayReport`, `IdempotentConsumer`·`TransactionalInboxHandler`·`InboxCleanupJob`·`InboxOutcome`·`InboxRetentionPolicy`).
**`messaging-reliability-jdbc-postgresql`**(`JdbcOutboxRepository`, `JdbcInboxRepository`, `JdbcAdminOperationJournal`, migration `V1001..V1005`·`V1101`, PG IT 3개).
**영향:** 옛 두 leaf는 삭제했다. 패키지명은 그대로라 starter 코드는 바뀌지 않았다. CI lane `integration-main.yml`을 새 경로로 바꿨다.
**테스트:** `:messaging:messaging-reliability:test` 47, `:messaging:messaging-reliability-jdbc-postgresql:test` 8, integrationTest 36, starter test 87, integrationTest 3 PASS. | +| S2-#9b | 완료 | 이동만 했다(`910ab7ab`). 새 패키지는 `persistence/outbox/{jpa(+entity),postgresql,h2}`, `persistence/idempotency/{jpa(+entity),postgresql}`다. JPA API surface는 `updateJpaApiSurface -PapproveJpaApiSurfaceChange`로 다시 승인했다. `JpaModuleBoundaryTest`에 autoconfigure→idempotency edge를 기록했다. `verifyJpaApiSurface`·`verifyJpaReadinessRegistry` PASS. | + +## 제거된 코드 +| 대상 | 경로 | 마지막으로 존재한 커밋 | 이유 | +|---|---|---|---| +| `LegacyOutboxAppendPort` | `src/application-core/src/main/java/dev/caskeleton/application/outbox/LegacyOutboxAppendPort.java` | `6d27356e` | canonical `OutboxAppendPort`로 통일(결정 7) | +| legacy outbox 모델 `NewOutboxEvent`, `OutboxEvent`, `CanonicalClaimedOutboxEvent`, `OutboxPayloadPolicy` (+ `NewOutboxEventTest`, `OutboxPayloadPolicyTest`) | `src/application-core/src/main/java/dev/caskeleton/application/outbox/` | `6d27356e` | append 모델이 `ValidatedIntegrationEvent` 하나. `ClaimedOutboxEvent`는 sealed 합집합이 아니라 canonical record | +| `LegacyOutboxAppendContract` | `src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/LegacyOutboxAppendContract.java` | `6d27356e` | `OutboxAppendContract`로 대체 | +| `CanonicalOutboxAppendAdapter` (+ Activation·단위 테스트) | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapter.java` | `6d27356e` | `OutboxStoreAdapter`가 `OutboxAppendPort`를 직접 구현(트랜잭션 guard 포함) | +| `OutboxEventEntity.payload`·`idempotencyKey` 접근자, claim SQL의 legacy CASE | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/entity/OutboxEventEntity.java`, `PostgreSqlOutboxClaimRepository`, `H2OutboxClaimRepository` | `6d27356e` | canonical 컬럼만 읽고 씀. 컬럼은 V19에서 nullable로 두고 migration은 수정하지 않음 | +| `OutboxCanonicalTransportRequirementValidator` (+ Validator/Composition 테스트) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidator.java` | `6d27356e` | 켜고 끌 canonical 플래그가 없어짐 | +| 설정 키 `ca-skeleton.outbox.canonical-transport-enabled` / env `APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED` | `persistence-jpa.yml`, `docs/registries/env-keys.yaml`, `src/.env.example` | `6d27356e` | 같음 | +| messaging `core/*`: `MessageBroker`, `MessagePublisher`, `OutboundMessage`, `OutboundMessagePublisher`, `DisabledMessagePublisher` (+ `OutboundMessagePublisherTest`) | `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/` | `6d27356e` | legacy 발행 경로 삭제. relay는 bridge(`IntegrationEventPublishPort`)만 씀 | +| `OutboxEnvelopeJson` (+ `OutboxCanonicalPublishRoutingTest`) | `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxEnvelopeJson.java` | `6d27356e` | envelope은 encoder가 한 번 만들고 bytes 그대로 전달 | +| legacy Kafka seam: `KafkaSender`, `KafkaSenderAutoConfiguration`, `KafkaMessageBroker`, `KafkaAdapterConfig`, `KafkaAdapterSettings`, `BrokerAddress`, `LegacyKafkaMessagingRootAutoConfiguration`, `AutoConfiguration.imports` (+ 테스트 5개) | `src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/` | `6d27356e` | TLS/SASL 없는 두 번째 producer(X1-#1f, NEW-4a). leaf는 코드 없는 capability 묶음으로 유지 | +| `messaging.yml`의 `kafka.brokers` | `src/adapter/outbound/messaging-kafka/src/main/resources/config/module-defaults/messaging.yml` | `6d27356e` | seam 설정 | +| `WorkLogReservedIntegrationEvent`, `WorkLogReservedIntegrationEventMapper` (+ Mapper 테스트 2개) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/` | `6d27356e` | `PortfolioEventOutbox` + 계약 `portfolio.worklog.reserved` v1로 대체 | +| `SampleIdempotencyConfig` (executor 복사본) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java` | `6d27356e` | `composition:idempotency` 사용. Clock·스케줄링만 `SampleSchedulingConfig`로 | +| app-bootstrap `config/capabilities.yml` (이동) | `src/app-bootstrap/src/main/resources/config/capabilities.yml` | `6d27356e` | `composition/idempotency/.../config/module-defaults/idempotency.yml`로 이동 | +| app-bootstrap outbox 조립 `OutboxConfig`·`OutboxSettings`·`OutboxMetrics`·`OutboxRelayScheduler`·`OutboxLeaderElectionToken` (이동) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/` | `6d27356e` | `composition:outbox-relay`로 이동 | +| app-bootstrap 멱등성 조립 `IdempotencyProviderSelectionConfig`·`IdempotencySettings` (이동) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/` | `6d27356e` | `composition:idempotency`로 이동 | +| app-bootstrap runtime 배선 tracing 6개, metrics 3개, `DomainContextConfig/Settings`, `PseudonymizationConfig`, `PrivacySettings`, `ManagementSecurityConfig` (이동) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/{autoconfigure/tracing,metrics,concurrency,logging,settings,management/security}/` | `6d27356e` | `composition:service-runtime`으로 이동 | +| sample bootstrap 복사본: `SampleTracingConfig`, `SampleTracingSettings`, `SampleTracingSampleRateResolver`(`staging` 분기), `SampleTracingSamplingEnvironmentPostProcessor`, `SampleMicrometerSpanErrorRecorder`, `SampleMetricsContractConfig`, `SampleDomainContextConfig`, `SamplePseudonymizationConfig`, `SamplePrivacySettings`, `META-INF/spring.factories` | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/{tracing,metrics,context,logging,settings}/` | `6d27356e` | 원본과 갈라진 복사본(S6-#7). 공용 모듈 사용 | +| messaging `OutboxRepository.leaseBatch`, 4인자 `claimBatch`, 3인자 `markAmbiguous` | `src/messaging/messaging-reliability-api/src/main/java/dev/caskeleton/messaging/reliability/OutboxRepository.java` | `6d27356e` | main 호출 0. fencing 없는 claim/쓰기 표면(S7-#8) | +| `JdbcOutboxRepository`의 LEASE SQL·`leaseBatch`·`*Unfenced` 4개·`update` helper·손 JSON(`toJson`/`fromJson`/`escape`/`unescape`) | `src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java` | `6d27356e` | 호출 0. 손 JSON reader는 결함(P18-new-1). jsonb 함수로 대체 | +| leaf `messaging-outbox-jdbc-postgresql`, `messaging-inbox-jdbc-postgresql` (코드는 이동) | `src/messaging/messaging-outbox-jdbc-postgresql`, `src/messaging/messaging-inbox-jdbc-postgresql` | `6d27356e` | `messaging-reliability` + `messaging-reliability-jdbc-postgresql`로 재분할(S7-#5b) | +| application-core 테스트 `malformedReportData` | `src/application-core/src/test/java/dev/caskeleton/application/outbox/` (relay 테스트) | `6d27356e` | blank aggregate id를 가진 claim이 canonical 모델에서 만들어질 수 없음 | + +## 새로 발견한 결함 +- **P18-new-1** (고침): header를 두 방향이 다르게 escape했다. + - 위치: `src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java`, 손으로 쓴 JSON reader(삭제 전 `:608-680`). + - 증상: escape된 backslash 뒤의 따옴표를 escape된 따옴표로 읽었다. 그래서 `\`로 끝나는 header 값이 다음 header를 삼키거나 값 끝에 `"`가 붙어 돌아왔다. + - 수정: PostgreSQL `jsonb_object(text[])`로 쓰고 `jsonb_each_text`로 읽는다(`165e0499`, 현재 `messaging-reliability-jdbc-postgresql/.../JdbcOutboxRepository.java:59`, `:77-78`). + - TDD: `OutboxPostgresIT.aHeaderValueEndingInABackslashRoundTripsWithoutSwallowingTheNextHeader`가 먼저 FAIL했고(`map entries not expected: x-path=C:\exports\"`), 수정 후 PASS. +- **P18-new-2** (안 고침): root `CLAUDE.md`의 문장 하나가 사실과 다르다. + - 위치: "Module families" 절, "The canonical bridge exists; legacy outbox/realtime cutover still has explicitly documented seams in `src/messaging/CLAUDE.md`". + - 이유: 이번 묶음에서 cutover가 끝났고, `src/messaging/CLAUDE.md`에는 남은 seam 기록이 없다. + - root 정책 문서(AGENTS.md 요약)라 손대지 않았다. 문장 삭제나 수정이 필요하다. +- **P18-new-3** (고침, 설계 노트): actuator chain의 켜짐 조건이 바뀌었다. + - 예전: app-bootstrap의 scan되는 `@Configuration`이었다. web security를 끈 좁은 slice에서도 `HttpSecurity`를 요구했다. + - 지금: auto-configuration이 되면서 `@ConditionalOnBean(HttpSecurity)` + `before = ServletWebSecurity/ManagementWebSecurity` 조건이 붙었다(`src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java`). + - 앞으로의 동작: web security를 직접 켜지 않고 Boot의 자동 `@EnableWebSecurity`에만 기대는 조립은 이 chain 대신 Boot 기본 actuator chain(health 개방, 나머지 인증)을 받는다. 두 shipped root는 web adapter `SecurityConfig`(highest precedence)나 자기 chain으로 영향이 없다. + - `ActuatorSecurityHttpTest` slice는 `@EnableWebSecurity`를 명시하도록 고쳤다. diff --git a/docs/reviews/2026-09-25-review-followup-status.md b/docs/reviews/2026-09-25-review-followup-status.md index f57d70f4..67f201a8 100644 --- a/docs/reviews/2026-09-25-review-followup-status.md +++ b/docs/reviews/2026-09-25-review-followup-status.md @@ -374,7 +374,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | G-10a | Consider | SCRIPT ACL probe가 `return {1}`이라 스크립트 내부 명령(`TIME`/`HSET`/`PEXPIRE`/`DEL`) 권한 부족을 기동 때 못 잡음 | 완료 | Wave 1–2 P6 (fcddab7e·Wave 2 커밋): `RedisSemanticScriptAclProbe.java:29-38`: probe key에서 `TIME`→`HSET`→`PEXPIRE`→`HGET`→`DEL`을 실행하고 읽은 값이 쓴 값과 같을 때만 `{1}`. `anAccountDeniedACommandTheScriptsCallFailsStartup`[HSET/PEXPIRE/HGET/DEL] FAIL→PASS. 실제 Redis standalone·cluster에서 `LiveRedisSemanticScriptAclProbeTest` 2건 PASS. 테스트 ACL `+time`은 NEW-5a(W1)에서 추가 | - | probe 스크립트를 probeKey에 `TIME`·`HSET`·`PEXPIRE`·`HGET`·`DEL`을 실제 실행하는 것으로 교체하고, 테스트 ACL에 `+time` 추가 | | G-10b | Consider | `redisRequired`가 REGULAR lane만 probe → ADVANCED 자격 증명이 깨져도 readiness UP | 완료 | Wave 1–2 P6 (fcddab7e·Wave 2 커밋): `RedisCorrectnessRoles.java:71` `anyScriptRoleSelected`(idempotency/rate-limit/lease), `RedisSdkAutoConfiguration.java:296`: 스크립트 role이 선택되면 `redisRequired`가 SCRIPT lane에서 `SCRIPT LOAD`+`EVALSHA`(`return 1`, key `:probe:{health}:script`)도 확인(`RedisHealthContributor.java:92`). 실제 Redis `LiveRedisCompositionTest.aBrokenAdvancedAccountTakesRequiredRedisDown` FAIL(`expected: DOWN but was: UP`)→PASS, `aWorkingAdvancedAccountKeepsRequiredRedisUp` PASS. 단위 `RedisHealthContributorTest.aScriptLaneItsAccountCannotRunIsUnreachable` PASS | - | script capability가 선택되면 required contributor가 SCRIPT lane에서 등록 스크립트 EVALSHA로 probe | | G-11a | Consider | application executor를 adapter leaf에서 조립하고 provider마다 lease·codec 적용이 다름 | 완료 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java:32-55`(`IdempotencySettings` 하나로 한 번 조립), `src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisIdempotencyConfig.java:31-35`(store만 제공). 「제거된 코드」 행 228. 테스트 `IdempotencyProviderCompositionTest.redisComposesOneExecutorOverTheRedisStoreAlone`. 커밋 `6d27356e` | - | - | -| G-11b | Consider | 소유자 결정: 멱등성 executor 조립을 별도 `composition:*` 모듈로 이동 — 아직 app-bootstrap에 있고 sample이 두 번째 executor를 조립 | 남음 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java:28-55`, `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java:39`. `src/composition/`에는 fileserver·notification만 있음 | W3 | `composition:idempotency` leaf를 `modules.json`에 등록하고 `IdempotencyProviderSelectionConfig`·`IdempotencySettings`를 옮긴 뒤 app-bootstrap·sample이 그 leaf를 쓰게 하고 `SampleIdempotencyConfig` 삭제 | +| G-11b | Consider | 소유자 결정: 멱등성 executor 조립을 별도 `composition:*` 모듈로 이동 — 아직 app-bootstrap에 있고 sample이 두 번째 executor를 조립 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): NEW-2b와 같다. `modules.json`에 `composition-idempotency`(edge application-core, adapter-outbound-support)를 등록했다. app-bootstrap과 sample이 `runtimeOnly project(':composition:idempotency')`를 쓴다. | - | `composition:idempotency` leaf를 `modules.json`에 등록하고 `IdempotencyProviderSelectionConfig`·`IdempotencySettings`를 옮긴 뒤 app-bootstrap·sample이 그 leaf를 쓰게 하고 `SampleIdempotencyConfig` 삭제 | | G-12a | Nit | `app-bootstrap/CLAUDE.md`가 없는 `autoconfigure/redis/RedisCapabilityConfig`·`RedisKeys`를 가리킴 | 완료 | `src/app-bootstrap/CLAUDE.md:92,102`가 `cache-redis`의 `capability/RedisCapabilityConfig`·`capability/RedisKeys`를 가리킴(두 파일 존재). 커밋 `6d27356e` | - | - | | G-12b | Nit | `cache-redis/CLAUDE.md`의 Boot 버전 "4.0.0" 틀림 | 남음 | `src/adapter/outbound/cache-redis/CLAUDE.md:8`(실제 `src/gradle/libs.versions.toml:84` `4.0.8`). `:11` package root `…outbound.cache`는 실제 `…cache.redis`의 상위라 부정확 | W5 | `:8` 버전 줄 삭제(버전은 루트 CLAUDE.md가 소유)하고 `:11`을 `dev.caskeleton.adapter.outbound.cache.redis`로 수정 | | G-12c | Nit | `src/README.md`가 orphaned key `APP_CACHE_REDIS_ENABLED`·`APP_CACHE_REDIS_CLIENT_MODE`를 동작하는 키처럼 설명 | 남음 | `src/README.md:312-317`(`CLIENT_MODE`가 managed/external을 고른다고 서술). `docs/registries/env-keys.yaml:2445-2480` `deprecated_orphaned: true`, Java 읽는 곳 0(sample yml `src/sample-portfolio/src/main/resources/application.yml:257-258`만 바인딩) | W5 | `src/README.md:312-313,316-317` 두 항목 삭제 | @@ -682,8 +682,8 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | ID | 심각도 | 요약 | 상태 | 근거 | Wave | 수정 방향 | |---|---|---|---|---|---|---| -| X1-지도-Outbox | 권고 | Outbox 저장 모델 3개·append 포트 4개·relay 3개 → 앱 1벌(v1 + fencing), messaging outbox 유지 | 남음 | V2 전부·Debezium 삭제(`docs/capability-status.md:130,175-179`), v1 + `V17__outbox_event_lease_fencing.sql`로 1벌(커밋 `6d27356e`). 남은 것: append 포트 2개(`LegacyOutboxAppendPort`, `OutboxAppendPort`), `CanonicalOutboxAppendAdapter` guard 없음, relay 조립이 app-bootstrap | W3 | X1-#1b(결정) 뒤 append 포트 1개만 남기고, X1-#1c guard 추가, X1-#1i로 relay 조립을 `composition:outbox-relay`로 이동 | -| X1-지도-요청 멱등성 | 권고 | 계약 2개·store 3개·executor 조립 3곳·inbound ledger 3개 → V2 정본, 조립 1곳 | 남음 | v1 삭제·V2 개명, websocket·graphql ledger 삭제(`docs/capability-status.md:226-232`). `new IdempotencyExecutor` 2곳: `IdempotencyProviderSelectionConfig.java:48`, sample `SampleIdempotencyConfig.java:39` | W3 | X1-#2b대로 `composition:idempotency` 신설 후 두 곳을 모듈 하나로 | +| X1-지도-Outbox | 권고 | Outbox 저장 모델 3개·append 포트 4개·relay 3개 → 앱 1벌(v1 + fencing), messaging outbox 유지 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **append 포트:** `OutboxAppendPort` 하나다(`src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAppendPort.java:15`). `LegacyOutboxAppendPort`는 삭제했다.
**구현:** `OutboxStoreAdapter implements OutboxAppendPort, OutboxStorePort`(`src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java:48`). `CanonicalOutboxAppendAdapter`는 여기로 합쳤다.
**X1-#1c guard:** `append` 첫 줄의 `requireTransaction("append")`(`:65`)다.
**relay 조립:** `composition:outbox-relay`에 있다(`src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java:53`).
**테스트:** `OutboxAppendContract`(application-core testFixtures)를 fake와 adapter가 공유한다. PostgreSQL lane `postgresqlOutboxAppendTransactionalIntegrationTest` 2, `postgresqlOutboxConcurrentRelayIntegrationTest` 4, `postgresqlOutboxRowLifecycleIntegrationTest` 10 PASS. | - | X1-#1b(결정) 뒤 append 포트 1개만 남기고, X1-#1c guard 추가, X1-#1i로 relay 조립을 `composition:outbox-relay`로 이동 | +| X1-지도-요청 멱등성 | 권고 | 계약 2개·store 3개·executor 조립 3곳·inbound ledger 3개 → V2 정본, 조립 1곳 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): 조립이 한 곳이다(`composition:idempotency`). 두 root가 같은 모듈을 쓴다. | - | X1-#2b대로 `composition:idempotency` 신설 후 두 곳을 모듈 하나로 | | X1-지도-자연키 생성-또는-반환 | 권고 | durable operation을 notification 방식(`ON CONFLICT`)으로, upsert executor 삭제 (= E-2) | 완료 | `DurableOperationJpaRepository.java:48` `ON CONFLICT … DO NOTHING`, `DurableOperationStoreAdapter.java:46-58` 삽입 후 재조회, upsert 실행기 7종 삭제(`docs/capability-status.md:158`), 커밋 `6d27356e` | - | - | | X1-지도-Inbox / 소비자 dedup | 권고 | app-core inbox 삭제, 나머지(messaging inbox·notification ledger) 유지 | 완료 | `application/inbox/`·`PostgreSqlSameStoreInboxAdapter` 삭제(`docs/capability-status.md:155`), mongo change stream dedup 삭제(`:151`); application-core 패키지 목록에 `inbox` 없음, 커밋 `6d27356e` | - | - | | X1-지도-lock / lease / fencing | 권고 | 미사용 포트·claim executor 삭제, fencing은 contract kit로 | 남음 | claim executor·`CacheRefreshCoordinationPort`·`LeaseWatchdog` 삭제(`docs/capability-status.md:152-153,157`). 남은 포트 2개 모두 비즈니스 소비자 0: `DistributedLockPort`(참조는 `StartupSafetyValidator.java:51` 존재 검사뿐), `DistributedLeasePort`(참조 0) | W3 | 결정(2026-09-25): lock·lease 유지, 쓰지 않는 claim executor만 삭제, fencing은 계약 테스트로 | @@ -691,20 +691,20 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | X1-지도-Backoff 계산식 | 권고 | 10개, "full jitter" 뜻 3가지 → shared-contract `Backoff` | 남음 | 앱 쪽 3개 남음(`OutboxBackoffPolicy.java:63-68`, `ExponentialFullJitterBackoff.java:78`, `RetryBackoff.java:42`), JPA 2개 삭제 | W3 | X1-#9 | | X1-지도-Rate limit | 권고 | web 전용 병렬 타입 세트 삭제 (= I-8 일부) | 완료 | `WebRateLimiter`·web `RateLimitDecision`·`RateLimitFailurePolicy`·`WebMvcThrottleFilter` 삭제(`docs/capability-status.md:99`); 남은 경로 `RateLimitWebConfig.java:22` → `EdgeRateLimitTransportBridge` → shared `EdgeRateLimitPort`, 커밋 `6d27356e` | - | - | | X1-지도-Admission / in-flight | 권고 | 유지하되 gRPC check-then-increment는 `Semaphore`로 (= N-5) | 완료 | Wave 1–2 P5 (fcddab7e·Wave 2 커밋): N-5a와 같은 수정. `Semaphore` 대신 한 락: in-flight와 queued 두 카운터를 한 결정에서 함께 봐야 해서 semaphore 두 개로는 원자적으로 안 된다. `GrpcAdmissionController.java:52`, `GrpcAdmissionControllerTest` | - | X1-#10a | -| X1-지도-Kafka producer | 권고 | legacy seam·platform 2개, 둘 다 TLS/SASL 없음 → outbox 정리에 포함 | 남음 | platform producer는 Wave 1(1-4)에서 보안 적용. legacy `KafkaSenderAutoConfiguration.java:60-80` `kafkaSeamProducer`에 `security.protocol`·SASL·SSL 설정 없음 | W1 | X1-#1f | +| X1-지도-Kafka producer | 권고 | legacy seam·platform 2개, 둘 다 TLS/SASL 없음 → outbox 정리에 포함 | 해당 없음(코드 삭제) | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **삭제:** legacy seam producer(`KafkaSenderAutoConfiguration`·`KafkaSender`·`LegacyKafkaMessagingRootAutoConfiguration`)를 `6268c494`에서 지웠다.
**남은 producer:** platform 하나다. `KafkaSecurityConfigurer`로 TLS/SASL을 적용한다: `src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaMessagingAutoConfiguration.java:188` `config.putAll(producerSecurity(...))`, `:216`.
**같은 결함 없음:** `MessagingSecuredBrokerQualificationTest`가 PASS다 — `aPublishIsConfirmedByAPrivateCaBrokerThatRequiresSaslAsTheProviderUser`, `aPublishIsConfirmedByAPrivateCaBrokerThatRequiresAClientCertificate`, `:messaging:messaging-spring-boot-starter:integrationTest` 3/3. | - | X1-#1f | | X1-지도-파일 control plane / canonical JSON | 권고 | 소비자 0인 `FilePublicationPort` plane 삭제, parser 3개 → 1개 | 완료 | publication R1/R2 31개·`FilePublicationPort`·`FileExportPort` 삭제(`docs/capability-status.md:76-77`), 남은 직접 파서 `objectstorage/control/CanonicalJsonReader.java` 1개, 커밋 `6d27356e` | - | - | | X1-지도-readiness / evidence / API-surface / moduleboundary | 권고 | 카드 스키마·검증기·API-surface gate·moduleboundary 여러 벌 → 하나로 | 남음 | Wave 3 W3-P16 (Wave 3 라운드 1 커밋): 완료: JPA readiness·evidence → persistence-jpa 테스트(manifest 폐기), API surface 구현 하나. 남은 "messaging 카드 검증은 messaging leaf로": `MessagingCapabilityRegistryContractTest`는 `config/messaging/*.yaml`을 snakeyaml로 읽는데 `adapter:outbound:messaging`은 모든 configuration(테스트 포함)에서 YAML·Jackson 2를 exclude+reject한다("Jackson 3 only and YAML-free"). 옮기려면 카드 파일을 JSON으로 바꾸거나 test 설정만 예외로 둘지 정해야 함. 승인자: 저장소 소유자 결정 필요
결정 29·31(2026-09-28): 보류 해제 → 남음, 빌드 잔여 묶음 P27 | W3 | 결정(2026-09-25): O3 — JPA readiness·evidence는 persistence-jpa 테스트로(manifest 폐기), messaging 카드 검증은 messaging leaf로 | | X1-지도-테스트 fake / contract kit | 권고 | 같은 포트 fake가 모듈마다 따로 → 포트 소유 leaf testFixtures에 contract kit | 남음 | `TransactionPort` fake 21 → 10, kit 4개(DurableOperation·OutboxLeaseFencing·GrpcOperationLedger·sample WorkLogRepository) | W4 | X1-#3a~#3d | | X1-#1a | Required | Outbox V2 삭제 + v1 claim에 owner+token fencing 이식 | 완료 | `persistence-jpa/.../db/migration/postgresql/V17__outbox_event_lease_fencing.sql`, `OutboxStoreAdapter.java:102-123`(markPublished·markFailed·markDead가 `lease.owner()`·`lease.token()` 조건부 UPDATE), V2 코드·`jpa/outbox-storage`·`jpa/outbox-polling` 삭제(`docs/capability-status.md:175-179`), 커밋 `6d27356e` | - | - | -| X1-#1b | Required | append 포트를 `OutboxAppendPort` 하나로, legacy는 cutover 후 삭제 | 남음 | `OutboxAppendPort` main 소비자 0(구현 `CanonicalOutboxAppendAdapter`뿐). `LegacyOutboxAppendPort` 소비자 4곳: `SubmitDurableOperationUseCase.java:56`, sample `PosterEventPublisher.java:25`·`PosterImagePublicationEventPublisher.java:12`·`CreateWorkLogUseCase.java:42`. canonical 경로는 `IntegrationEventEncoderPort` 구현이 필요한데 템플릿은 주지 않음(`src/messaging/CLAUDE.md:83-89`, main 구현 0) | W3 | 결정(2026-09-25): canonical 통일(S1-#2b와 같은 작업) | +| X1-#1b | Required | append 포트를 `OutboxAppendPort` 하나로, legacy는 cutover 후 삭제 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **소비자 4곳 이전:** `SubmitDurableOperationUseCase`(`src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java:72`, 계약 `DurableOperationSubmittedContract`)와 sample 3곳이 `OutboxAppendPort`를 쓴다.
**encoder:** 템플릿 encoder `JsonIntegrationEventEncoder`(`src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java:47`)와 `IntegrationEventEncoderAutoConfiguration`.
**테스트:** `JsonIntegrationEventEncoderTest`, `IntegrationEventEncoderAutoConfigurationTest`, `DurableOperationSubmissionOutboxIntegrationTest`(실제 encoder) PASS. | - | 결정(2026-09-25): canonical 통일(S1-#2b와 같은 작업) | | X1-#1c | Required | `CanonicalOutboxAppendAdapter`에 caller 트랜잭션 guard 없음 (= E-3) | 남음 | `CanonicalOutboxAppendAdapter.java:36-75` `append`가 트랜잭션 확인 없이 `repository.save` | W3 | X1-#4 helper를 `append` 첫 줄에서 호출(1곳) + 트랜잭션 없이 부르면 거부되는 테스트 | | X1-#1d | Required | canonical 이벤트가 v1 claim을 타며 aggregate 순서·tenant 범위를 잃음 (= E-5) | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): E-5a·E-5b와 같은 변경 — canonical row claim 순서를 tenant·type·id + sequence·index로(PostgreSQL·H2 SQL), migration V18 index | - | X1-#1b에서 canonical 경로를 남기면: canonical row(`contract_id IS NOT NULL`) gate를 `(tenant_scope, aggregate_type, aggregate_id)` + `(aggregate_sequence, event_index)` 순서로, `H2OutboxClaimRepository`도 동일 | -| X1-#1f | Required | legacy Kafka producer에 TLS/SASL 없음 (Critical #8 = M-2와 같은 문제) | 남음 | `adapter/outbound/messaging-kafka/.../KafkaSenderAutoConfiguration.java:60-80` producer config에 bootstrap·serializer·acks·timeout만 | W1 | `KafkaAdapterSettings`에 security 블록(protocol·SASL·truststore) 추가 후 `kafkaSeamProducer` config에 반영, 또는 X1-#1b 결정으로 seam 자체 삭제 | +| X1-#1f | Required | legacy Kafka producer에 TLS/SASL 없음 (Critical #8 = M-2와 같은 문제) | 해당 없음(코드 삭제) | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): 위와 같다. 보안 블록을 추가할 대상인 `KafkaAdapterSettings`·`kafkaSeamProducer`가 `6268c494`에서 삭제됐다. canonical 경로의 producer는 `KafkaMessagingAutoConfiguration.java:188`에서 보안 profile을 적용하고, `MessagingSecuredBrokerQualificationTest` 2/2가 PASS다. | - | `KafkaAdapterSettings`에 security 블록(protocol·SASL·truststore) 추가 후 `kafkaSeamProducer` config에 반영, 또는 X1-#1b 결정으로 seam 자체 삭제 | | X1-#1g | Required | `src/messaging/CLAUDE.md`에 "앱은 `messaging_outbox`를 쓰지 않는다" 명시 | 남음 | `grep -n messaging_outbox src/messaging/CLAUDE.md` → 0건 | W5 | `src/messaging/CLAUDE.md` MSG-015 절(:60-89)에 한 줄 추가 | | X1-#1h | Required | fencing 시나리오를 contract kit로 fake·실제 adapter 양쪽에서 실행 | 완료 | testFixtures `OutboxLeaseFencingContract`를 `InMemoryOutboxStoreLeaseFencingContractTest.java:9`와 `PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest.java:45`가 상속, 커밋 `6d27356e` | - | - | -| X1-#1i | 권고 | outbox relay 조립이 app-bootstrap에 남음(소유자 결정: `composition:*`로 이동) | 남음 | `app-bootstrap/.../autoconfigure/outbox/OutboxConfig.java:44-118`이 `PublishPendingOutboxEventsUseCase`·`OutboxRelayScheduler` 생성, `AutoConfiguration.imports:2`. persistence-jpa로는 `AdapterBoundaryArchitectureTest.java:207` `PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES` 때문에 못 옮김 | W3 | 새 leaf `composition:outbox-relay`(edge: application-core, adapter-outbound-support) 등록, `OutboxConfig`·`OutboxSettings`·`OutboxRelayScheduler`·`OutboxMetrics`·`OutboxLeaderElectionToken`·`OutboxCanonicalTransportRequirementValidator` 6개 + 테스트 5개 이동, app-bootstrap은 `runtimeOnly` 한 줄 | +| X1-#1i | 권고 | outbox relay 조립이 app-bootstrap에 남음(소유자 결정: `composition:*`로 이동) | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **이동:** `OutboxConfig`→`OutboxRelayAutoConfiguration`, 그리고 `OutboxSettings`·`OutboxMetrics`·`OutboxRelayScheduler`·`OutboxLeaderElectionToken`을 `src/composition/outbox-relay`로 옮겼다(`a053ae89`).
**삭제:** `OutboxCanonicalTransportRequirementValidator`는 옮기지 않고 삭제했다. 켜고 끌 canonical 플래그가 더는 없다.
**연결:** app-bootstrap은 `runtimeOnly project(':composition:outbox-relay')` 한 줄로 받는다.
**테스트:** `OutboxRelayAutoConfigurationTest`(`aMisspeltOutboxKeyFailsStartupInsteadOfLeavingTheDefaultInForce` 포함), `OutboxRelaySchedulerLoggingTest` PASS. | - | 새 leaf `composition:outbox-relay`(edge: application-core, adapter-outbound-support) 등록, `OutboxConfig`·`OutboxSettings`·`OutboxRelayScheduler`·`OutboxMetrics`·`OutboxLeaderElectionToken`·`OutboxCanonicalTransportRequirementValidator` 6개 + 테스트 5개 이동, app-bootstrap은 `runtimeOnly` 한 줄 | | X1-#2a | Required | 멱등성 V2를 정본으로, v1 삭제, 이름에서 `V2` 제거, sample을 V2로 | 완료 | `application/idempotency/IdempotencyExecutor.java`·`IdempotencyStorePort.java`(V2 개명), v1 모델·JPA v1 store·bootstrap v1 조립 삭제(`docs/capability-status.md:226-229`), sample `PublishPosterImageUseCase`가 `IdempotencyExecutor` 사용. v1 완료 기록 결함(= A-8)도 함께 소멸. 커밋 `6d27356e` | - | - | -| X1-#2b | Required | executor 조립 1곳, provider는 store bean만 (= G-11 일부) | 남음 | Redis·PG provider는 store만 기여(`RedisIdempotencyConfig`·`PostgreSqlIdempotencyStoreConfig`에 executor 생성 0). executor 생성 2곳: `IdempotencyProviderSelectionConfig.java:48`, sample `SampleIdempotencyConfig.java:39`(같은 키·기본값을 `Binder`로 복사) | W3 | 새 leaf `composition:idempotency`(edge: application-core, adapter-outbound-support)로 `IdempotencyProviderSelectionConfig`·`IdempotencySettings` + 테스트 2개 이동, app-bootstrap·sample 둘 다 `runtimeOnly`; `SampleIdempotencyConfig`는 executor bean 삭제(Clock·`@EnableScheduling`만 유지) | +| X1-#2b | Required | executor 조립 1곳, provider는 store bean만 (= G-11 일부) | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): executor 생성은 한 곳이다: `IdempotencyAutoConfiguration.java:58`. main에 `new IdempotencyExecutor`는 여기뿐이다. web testFixtures의 fault fixture는 테스트용이다. provider는 store bean만 기여한다. | - | 새 leaf `composition:idempotency`(edge: application-core, adapter-outbound-support)로 `IdempotencyProviderSelectionConfig`·`IdempotencySettings` + 테스트 2개 이동, app-bootstrap·sample 둘 다 `runtimeOnly`; `SampleIdempotencyConfig`는 executor bean 삭제(Clock·`@EnableScheduling`만 유지) | | X1-#2c | Required | websocket `CommittedResultLedger`(inbound가 가진 저장 SPI) 삭제 | 완료 | websocket command ledger 일체 삭제(`docs/capability-status.md:230`), websocket main 참조 0, 커밋 `6d27356e` | - | - | | X1-#2e | Required | `DurableOperationStoreAdapter`를 `ON CONFLICT` 방식으로, upsert executor 삭제 (= E-2) | 완료 | X1-지도-자연키 행과 같은 근거(`DurableOperationJpaRepository.java:48`, `docs/capability-status.md:158`), 커밋 `6d27356e` | - | - | | X1-#3a | Required | `TransactionPort` fake를 application-core testFixtures 1개로 | 남음 | testFixtures `DirectTransactionPort` 생김(사용 14파일), sample 6개는 0으로. 남은 자체 fake 10개: application-core test 4(`SubmitDurableOperationUseCaseTest`, `OutcomeAwareRelayTest`, `PublishPendingOutboxEventsUseCaseTest`, `TransactionPortTest`), application-notification 4(`PlatformFakes`, `AdminOperationExecutorTest`, `CallbackIngestionAtomicityTest`, `ProviderEventLateMatchTest`), application-fileserver `DirectTransactions`, composition `FileserverAssemblyFixture` (측정: 테스트 source set에서 `git grep -E "implements (\w+\.)*TransactionPort\b\|new (\w+\.)*TransactionPort\(\)"`) | W4 | 그냥 실행만 하는 fake는 `DirectTransactionPort`로 교체(application-notification·application-fileserver·composition에 application-core testFixtures 의존 추가), 호출 기록이 필요한 outbox relay fake만 유지 | @@ -774,7 +774,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): |---|---|---|---|---|---|---| | S1-#1 | Required | 멱등성 엔진 2세대 공존, V2는 호출자 0 (= X1-#2, A-8) | 완료 | `6d27356e`: v1 삭제(「제거된 코드」 멱등성 v1 모델·JPA v1 store·bootstrap 조립 행), V2가 이름 없이 `application-core/.../idempotency/IdempotencyExecutor.java`로 정본. 조립은 `app-bootstrap/.../idempotency/IdempotencyProviderSelectionConfig.java:36-55` 한 곳(store 개수 검사 포함), provider는 store만(`cache-redis/.../capability/RedisIdempotencyConfig.java:51`) | - | - | | S1-#2a | Required | outbox V2 append·폴링 포트, `OutboxV2RetryPolicy` (= X1-#1, A-3) | 해당 없음(코드 삭제) | 「제거된 코드」 "application-core outbox V2 포트·유스케이스 17종" 행. `application-core/.../outbox/`에 V2 파일 0, 폴링 `OutboxStorePort` 1개·retry `OutboxBackoffPolicy` 1개만 남음 | - | - | -| S1-#2b / S2-#4b | Required | append 포트 2개(legacy·canonical)가 같은 `outbox_event`에 공존, `ClaimedOutboxEvent` sealed 합집합 유지 (= X1-#1) | 남음 | `application-core/.../outbox/LegacyOutboxAppendPort.java:11`(sample 4곳 + `SubmitDurableOperationUseCase` 사용), `OutboxAppendPort.java:13`(main 호출자 0, 구현 `CanonicalOutboxAppendAdapter`뿐), `ClaimedOutboxEvent.java:11` `permits OutboxEvent, CanonicalClaimedOutboxEvent`
S2-#4b: `persistence-jpa/.../outbox/entity/OutboxEventEntity.java` public 62개, `outbox/OutboxStoreAdapter.java`(legacy) + `CanonicalOutboxAppendAdapter.java:28` | W3 | 결정(2026-09-25): canonical 통일 — 템플릿 JSON encoder 제공, `LegacyOutboxAppendPort` 소비자 4곳 이전 후 legacy 포트·legacy Kafka 발행 경로 삭제
S2-#4b: 결정(2026-09-25): canonical 통일 → legacy adapter·컬럼 접근자 삭제(적용된 migration 유지) | +| 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` 정적 메서드로 분리 | @@ -803,7 +803,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S1-#20 | Nit | notification `dispatch/` 패키지에 여러 기능 | 남음 | `application-notification/.../platform/dispatch/` 46파일 3,855줄(제출·템플릿 게시·`ContactPoint*`·reconciliation 포함) | W5 | `submission/`, `dispatch/`, `reconciliation/`로 이동, `ContactPoint*`는 `contact/`로 | | S1-lead-1 | 권고 | messaging 자체 outbox/inbox와 app-core outbox/inbox가 같은 패턴 3~4벌 | 완료 | app-core inbox 삭제(「제거된 코드」 same-store inbox 행), outbox V2 삭제. 남은 2벌(app outbox + vendored `messaging_outbox`)은 D2 결정(`docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md:104` "messaging platform outbox는 vendored라 유지") | - | - | | S1-lead-2 | 권고 | UUID 생성기 제각각 | 남음 | notification 자체 `adapter/outbound/notification/.../dispatch/UuidV7Generator.java`, fileserver `RandomUploadIdentifierFactory`(v4), sample `Uuid*IdFactory`(uuid-creator v7) | W3 | notification `UuidV7Generator`를 sample이 쓰는 uuid-creator로 대체(v7 생성 1벌), fileserver v4는 유지 | -| S1-lead-3 | 권고 | 멱등성 executor 조립 위치 (= G-11) | 남음 | adapter 조립은 사라졌으나(`RedisIdempotencyConfig.java:51` store만) 조립이 `app-bootstrap/.../idempotency/IdempotencyProviderSelectionConfig.java:48`에 있음. 소유자 결정은 별도 `composition:*` 모듈 | W3 | `IdempotencyProviderSelectionConfig`·`IdempotencySettings`를 새 `composition:idempotency`(가칭) 모듈로 이동, registry 등록 | +| S1-lead-3 | 권고 | 멱등성 executor 조립 위치 (= G-11) | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): NEW-2b와 같다. | - | `IdempotencyProviderSelectionConfig`·`IdempotencySettings`를 새 `composition:idempotency`(가칭) 모듈로 이동, registry 등록 | | S1-lead-4 | 권고 | `Local*Gateway`가 `LocalBlockingContentStore`로 넘기기만 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `b4fe7c8b`. `LocalBlockingContentStore`가 `DownloadContentPort`·`ZeroCopyDownloadPort`를 직접 구현(`platform/local/LocalBlockingContentStore.java:47`), `LocalDownloadContentGateway`·`LocalZeroCopyDownloadGateway`와 bean 2개 삭제. `LocalCleanupContentGateway`는 `purgeQuarantined`를 orphan scan에 넘기는 두 협력자 조합이라 위임 전용이 아니어서 유지. `LocalStorageGatewayContractTest` PASS | - | 위임만 하는 3개는 `LocalBlockingContentStore`가 해당 gateway 인터페이스를 직접 구현, 로직 있는 Copy/Upload는 유지 | | 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` 전이표에서 파라미터로 넘기거나, 두 목록이 같은지 단언하는 테스트 추가 | @@ -821,7 +821,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | 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-#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별로 흩어짐 | 남음 | outbox: `outbox/`, `outbox/entity/`, `postgresql/PostgreSqlOutboxClaimRepository.java`, `h2/H2OutboxClaimRepository.java`; 멱등성: `idempotency/`, `postgresql/idempotency/`, migration `jpa/idempotency` + `postgresql/V1,V10` | W3 | feature 기준 패키지(`outbox/{jpa,postgresql,h2}`, `idempotency/{jpa,postgresql}`)로 이동만 | +| 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` 행 | - | - | @@ -830,7 +830,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | 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`도 삭제) | - | - | | S2-#14d | Nit | `JpaAdapterComponentsConfig`가 classpath 밖 leaf로 `{@link}` | 완료 | `persistence-jpa/.../config/JpaAdapterComponentsConfig.java:36`이 `{@code FileserverJpaPersistenceConfig}`로 변경(`208077fd`에서는 `{@link`) | - | - | -| S2-lead-1 | 권고 | app-core 포트 버전이 #4의 원인 | 남음 | V2 포트는 삭제됐으나 `OutboxAppendPort`/`LegacyOutboxAppendPort` 2개 남음(S1-#2b 근거와 같음). 멱등성은 `IdempotencyStorePort` 하나 | W3 | 결정(2026-09-25): canonical 통일(S1-#2b와 같은 작업) | +| S2-lead-1 | 권고 | app-core 포트 버전이 #4의 원인 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): 포트 버전이 하나로 줄었다: `OutboxAppendPort`(append)와 `OutboxStorePort`(claim/완료). 근거는 S1-#2b와 같다. | - | 결정(2026-09-25): canonical 통일(S1-#2b와 같은 작업) | | S2-lead-2 | 권고 | 멱등성 claim 판정표가 Redis·PG에 따로 (= X1-#3) | 남음 | Redis 판정은 Lua 안(`cache-redis/.../idempotency/IdempotencyScripts.java`) + 응답 매핑 `RedisIdempotencyStoreAdapter.java:135-157`, PG는 `postgresql/idempotency/IdempotencyClaimGateway.java`. 공통 계약 테스트 없음(`application-core/src/testFixtures/.../idempotency/testkit/`에 `InMemoryIdempotencyStore`만) | W4 | application-core testFixtures에 `IdempotencyStoreContract` 추가, InMemory·Redis·PG adapter가 모두 상속 | | S2-lead-3 | 권고 | 서명 cursor codec 여러 벌 (= X2 P1-4) | 남음 | web `CursorCodec`·`HmacWebCursorCodec` 삭제(「제거된 코드」 서명 커서 코덱·2세대 페이지네이션 행). 남은 3벌: `persistence-jpa/.../api/query/SignedJsonCursorCodec.java`, `persistence-mongo/.../query/pagination/MongoKeysetCursorCodec.java`, `graphql/.../pagination/HmacGraphQlCursorCodec.java` | W3 | X2 P1-4대로 서명은 inbound 한 계층, persistence는 typed keyset만(jpa·mongo codec 삭제 또는 서명 제거) | | S2-lead-4 | 권고 | persistence 실패 예외 계층 3벌 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): `JpaPersistenceExceptionCodeTest.aJpaFailureCarriesTheOperationalCodeOfItsCategory` 16건 FAIL(`Expecting actual throwable to be an instance of: PersistenceFailureException`)→PASS. `persistence-jpa/.../api/error/JpaPersistenceException.java:22`(상속), `:59`(`FailureCategory`→`DB_*`; 직렬화 후에도 `errorCode()`가 category에서 계산). 대응 코드가 없던 2개는 `DB_OPTIMISTIC_CONFLICT`(CONFLICT/409/false)·`DB_COMPLETION_UNKNOWN`(DATA_INTEGRITY/500/false) 신설, SCHEMA_MISMATCH·DATA_CORRUPTION·ENTITY_NOT_FOUND·UNKNOWN은 이전 catch-all과 같은 `INTERNAL_ERROR`. `LockFailureClassificationContractTest`의 REGISTRY-GAP-1("optimistic 코드 없음") 고정 테스트를 `anOptimisticLockConflictIsANonRetryableConflict`로 승격. testFixtures에 `:shared-contract` 추가(mongo는 edge 없어 유지) | - | `JpaPersistenceException`이 `PersistenceFailureException`을 상속해 inbound가 한 계층만 매핑(mongo는 edge 없어 유지) | @@ -907,7 +907,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | 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-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` | 남음 | `src/adapter/outbound/messaging-kafka` main 371줄(`LegacyKafkaMessagingRootAutoConfiguration`, `KafkaSender`, `KafkaMessageBroker`). legacy outbox가 `OutboxMessagePublishAdapter` → `MessageBroker`로 이 경로를 씀. `src/messaging/CLAUDE.md:75-78`에 MSG-015 cutover가 끝나지 않았다고 적혀 있음 | W3 | legacy `OutboxEvent`에 canonical metadata를 채우는 migration 후 relay를 bridge로 바꾸고 `adapter:outbound:messaging-kafka`와 `core/MessageBroker` 계열 삭제 | +| 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 참조 | | 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` 하나 | - | - | @@ -976,7 +976,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S6-#5 | Required | fileserver가 build에서 빠졌는데 스위치·설정이 root에 남음 | 완료 | `dependencyPolicy` 없음, 한 줄 선택(`src/app-bootstrap/build.gradle:152`), 설정은 모듈 소유(`CS:37`, `CS:234`), `MasterSwitch.FILESERVER*` 삭제(`CS:78`), composition 자체 imports(`src/composition/fileserver-platform/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`), `6d27356e` | - | - | | S6-#6a | Required | 멱등성 설정 binder 3개·yml 2개, PG provider 하드코딩 (= X1-#2) | 완료 | settings record 하나 `IdempotencySettings`(`BS/autoconfigure/idempotency/IdempotencySettings.java:24-34`, prefix `ca-skeleton.capabilities.idempotency`), `config/idempotency.yml`·`IdempotencyProviderSettings`·`PostgreSqlIdempotencyProviderConfig` 삭제(`CS:228`), `APP_IDEMPOTENCY_TTL` 한 키(`src/app-bootstrap/src/main/resources/config/capabilities.yml:14`) | - | - | | S6-#6b | Required | `APP_RATE_LIMIT_DEFAULT_POLICY_ID`가 두 키에 바인딩 | 완료 | Wave 1–2 P6 (fcddab7e·Wave 2 커밋): 두 키 모두 읽히고 있었다(web `EdgeRateLimitTransportSettings`가 `app.rate-limit.*`, cache-redis `RedisRateLimitConfig`가 `ca-skeleton.capabilities.rate-limit.default-policy-id`). 소유자 결정 16(`app.*` 통일)에 맞춰 `app.rate-limit.default-policy-id` 하나만 남김: `cache-redis.yml:65` 줄과 `RedisCapabilitySettings.RateLimit.defaultPolicyId` 삭제, `RedisRateLimitConfig.java:34,60`이 `app.rate-limit.default-policy-id`로 검증. env 키 `APP_RATE_LIMIT_DEFAULT_POLICY_ID`는 그대로(`env-keys.yaml`·`.env.example` 변경 없음). `RedisCapabilityCompositionTest.aDefaultPolicyTheLimiterDoesNotHaveIsRefusedAtStartup` FAIL(`Expecting actual not to be null`)→PASS | - | 읽는 쪽 하나만 남기고 다른 키 삭제(sample의 `ca-skeleton.rate-limit.*`는 1차 L-11) | -| S6-#7 | Required | sample이 bootstrap 인프라를 복사, 이미 갈라짐 | 남음 | `SP/bootstrap/{tracing,idempotency,settings,logging,metrics,context,management}` 525줄. `SampleTracingSampleRateResolver.java:23` `"staging" -> 0.10`, `SampleIdempotencyConfig.java:15` "stand-in", `SamplePseudonymizationConfig.java:12` "Sample-local copy" | W3 | 소유자 결정대로 멱등성 executor·outbox relay 조립을 `composition:*` 모듈로 옮겨 두 root가 함께 쓰고, tracing·logging·metrics·context·management는 공용 library leaf로(registry edge 추가), staging 분기 삭제 | +| S6-#7 | Required | sample이 bootstrap 인프라를 복사, 이미 갈라짐 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **새 leaf `composition:service-runtime`**(`dev.caskeleton.composition.runtime`, edge application-core, shared-contract, adapter-outbound-support, adapter-outbound-identifier):
- 원본을 app-bootstrap에서 옮겼다: `tracing`(TracingConfig 외 5), `metrics`(MetricsContractConfig+filter 2), `context`(DomainContextConfig/Settings), `logging`(PseudonymizationConfig, PrivacySettings), `management/security`(ManagementSecurityConfig).
- 모두 이 모듈의 `AutoConfiguration.imports`로, sampling bridge는 `spring.factories`로 등록한다.
- app-bootstrap과 sample이 `runtimeOnly project(':composition:service-runtime')`를 쓴다.
**sample:** 복사본 10개와 `spring.factories`를 삭제했다. 원본을 쓰므로 `staging=0.10` 분기도 사라졌다.
**sample actuator chain:** 복사본이 아니라 공개 데모라는 샘플만의 결정이라 남겼다. bean 이름을 `actuatorSecurityFilterChain`으로 바꿔 공용 chain이 물러나게 했다(`ConditionalOnMissingBean(name)`).
**테스트:** `ServiceRuntimeRegistrationTest` 4개(신규), 옮긴 테스트 9 클래스 — `:composition:service-runtime:test` 86 PASS. `ActuatorSecurityHttpTest`, `DefaultCompositionBootTest`, `StartupOrderContractTest`, `ConfigurationNamespaceContractTest` 갱신 후 PASS. | - | 소유자 결정대로 멱등성 executor·outbox relay 조립을 `composition:*` 모듈로 옮겨 두 root가 함께 쓰고, tracing·logging·metrics·context·management는 공용 library leaf로(registry edge 추가), staging 분기 삭제 | | S6-#8 | Required | sample root가 다른 leaf 패키지를 넓게 scan | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `SamplePortfolioApplication`: `@ComponentScan("dev.caskeleton.sample")`·`@ConfigurationPropertiesScan("dev.caskeleton.sample")`, 제외는 `WebSecurityAutoConfiguration` 하나(`SamplePortfolioApplication.java:31-32`). web·objectstorage는 각 auto-config로. `SamplePublicAccessSecurityConfigTest.sampleCompositionRootExcludesOnlyTheWebSecurityRoot`·`sampleCompositionRootScansOnlyTheSamplePackage`(옛 exclude-filter 단언 대체). sample `test`·`integrationTest` 51·`systemTest` 3·`webSystemTest` 5 PASS | - | scan을 `dev.caskeleton.sample`로 좁히고 web·identifier·objectstorage는 각 leaf auto-config로 받기(보안 설정 2개는 exclude/property로 끔) | | S6-#9 | Required | sample `application.yml` 중 읽는 코드 없는 블록 | 남음 | 326줄 중 약 101줄: `src/sample-portfolio/src/main/resources/application.yml:150-177`(capabilities.cache), `:180-181`(bootstrap), `:210-226`(logging), `:255-279`(app.cache.redis), `:280-283`(messaging), `:284-288`(notification), `:289-308`(outbound.http). sample classpath에 해당 binder 없음(`src/sample-portfolio/build.gradle:48-83`) | W5 | 해당 블록 삭제 | | S6-#10a | Consider | sample 대표 예제가 poster-image에 묻힘, 패키지 종류별·기능별 혼재 | 남음 | poster 관련 main 약 5.9k줄 vs WorkLog 약 2.2k줄. `SP/application/`에 `command/query/event/port/exception`과 `poster/posterimage/worklog` 공존
Wave 3 W3-P25: 미완 — 이유: 기능별 패키지 재배치와 poster-image 별도 sample 모듈 분리는 sample 전체 파일 이동(+`modules.json` leaf 등록)이라, 동시에 도는 P18(sample outbox·멱등성·`PosterEventPublisher`)·P24(object storage)와 같은 파일을 대량으로 겹친다. 통합 뒤 단독 작업으로 넘김. 이번 묶음에서 legacy 모드 삭제(S6-#10b)로 poster 표면은 줄었다 | W3 | 기능별 패키지로 정리, poster-image는 objectstorage 검증용 별도 sample 모듈로 이동 | @@ -1002,7 +1002,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S6-G3 | 권고 | capability 하나 켜는 표면이 큼(outbox 스위치 5개, yml 19개) | 완료 | bootstrap yml 19개 1,388줄 → 9개 655줄. Outbox+relay = build 줄 2개 + `APP_OUTBOX_ENABLED`·`APP_OUTBOX_RELAY_ENABLED`(`CS:35`), 검증 클래스 1개(`OutboxCanonicalTransportRequirementValidator`); Redis 연결 env는 `src/adapter/outbound/cache-redis/README.md:50`에 문서화 | - | - | | S6-lead-1 | 권고 | gRPC 서버 스택 2개, 둘 다 조립 안 됨 (= X1-#10) | 완료 | `adapter:inbound:grpc`는 자기 imports(`GrpcServerConfig`)로 한 줄 선택(`CS:42`), 플랫폼 `grpc:*`는 별도 build `src/optional-platforms`(`CS:41`). 두 스택 공존은 X1-#10에서 의도로 수용 | - | - | | S6-lead-2 | 권고 | 인라인 `TransactionPort` fake가 저장소 전체에 (= X1-#3) | 남음 | 인라인 fake 24 → 10개 파일: application-core 4(`TransactionPortTest` 포함), application-notification 4, `application-fileserver/.../testkit/DirectTransactions.java`, `composition/fileserver-platform/.../FileserverAssemblyFixture.java`. `DirectTransactionPort` 사용 12개 파일 | W4 | 계약 자체를 검증하는 `TransactionPortTest` 외 9개를 `DirectTransactionPort`로 교체 | -| S6-lead-3 | 권고 | 복사용 예제 `CreateWorkLogUseCase`가 `LegacyOutboxAppendPort` 사용 (= X1-#1 append 포트) | 남음 | `SP/application/worklog/CreateWorkLogUseCase.java:7`; canonical `OutboxAppendPort`(`src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAppendPort.java:13`) 존재, legacy 포트 Javadoc은 "cutover 창 동안만"(`LegacyOutboxAppendPort.java:3-9`)
Wave 1–2 P1: 미완 — 이유: sample을 `OutboxAppendPort`로 옮기려면 `ValidatedIntegrationEvent`를 만들 encoder가 있어야 하는데 템플릿에 없다(`IntegrationEventEncoderPort` 구현 0). 결정 7(템플릿 JSON encoder 제공 + legacy 포트 삭제)이 Wave 3 3-C 작업. sample의 legacy 포트 사용처 3곳(`CreateWorkLogUseCase`, `PosterEventPublisher`, `PosterImagePublicationEventPublisher`) | W2 | 예제를 `OutboxAppendPort` + `ValidatedIntegrationEvent`로 옮기고 MSG-015 cutover 후 legacy 포트 삭제 | +| S6-lead-3 | 권고 | 복사용 예제 `CreateWorkLogUseCase`가 `LegacyOutboxAppendPort` 사용 (= X1-#1 append 포트) | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **이전:** sample 3곳(`CreateWorkLogUseCase`, `PosterEventPublisher`, `PosterImagePublicationEventPublisher`)을 `PortfolioEventOutbox`로 옮겼다(`src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutbox.java:44`). 이 클래스는 `OutboxAppendPort`와 `IntegrationEventEncoderPort`를 쓴다.
**계약 등록:** `PortfolioEventContracts`가 계약 8개(poster 7 + `portfolio.worklog.reserved` v1)와 schema hash를 등록한다.
**삭제:** `LegacyOutboxAppendPort`.
**테스트:** `PortfolioEventOutboxTest`, `PortfolioEventContractsTest`, `CreateWorkLogOutboxTest`, `PosterEventPublisherTest`, `WorkLogReservedConsumerDedupeContractTest` PASS. `:sample-portfolio:test` 289, integrationTest 49, systemTest 3, webSystemTest 5 모두 PASS. | - | 예제를 `OutboxAppendPort` + `ValidatedIntegrationEvent`로 옮기고 MSG-015 cutover 후 legacy 포트 삭제 | | S6-lead-4 | 권고 | `CS` WIRED=yes vs `dependencyPolicy` 모순, `MasterSwitch`가 없는 capability 나열 | 해당 없음(코드 삭제) | `dependencyPolicy`·`MasterSwitch` 삭제(`CS:248`), WIRED 정의를 "선택하면 조립됨"으로 재정의(`CS:11`, `CS:37`) | - | - | | S6-lead-5 | 권고 | `DefaultUploadApplicationService` 생성자 14개 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `f2ff284a`. `DefaultUploadApplicationService` 생성자(`upload/DefaultUploadApplicationService.java:76`) 14개 → 10개: `UploadStores(metadata, sessions, cleanupQueue)`·`UploadPolicies(access, filenames, upload)` record | - | 정책 3개(access·filename·upload)와 저장소 2개를 record로 묶거나 업로드 단계별 서비스로 분해 | | S7-#1a | Required | 선택 불가·SDK 없는 messaging leaf(experimental 4, rabbit 2)와 Debezium | 해당 없음(코드 삭제) | `CS:124-130` | - | - | @@ -1012,12 +1012,12 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S7-#3 | Required | grpc 18 leaf를 9 leaf로 | 완료 | Wave 3 W3-P17 (Wave 3 라운드 1 커밋): `e2397d2f`. registry의 `optional-grpc` leaf 18 → 9: `grpc-core-api`, `grpc-runtime`(policy+server+client+discovery+admin), `grpc-contract`(proto-contract+codegen 자리), `grpc-observability`, `grpc-operation-ledger-jpa`, `grpc-spring-boot-starter`, `grpc-testkit`, `grpc-advanced`(bootstrap+edition+streaming+resilience+diagnostics), `grpc-advanced-compat`. 패키지 이름은 그대로(import 변경 없음). settings는 registry 구동(`OptionalArchitectureRegistrySettingsPlugin`)이라 `src/optional-platforms/settings.gradle` 변경 불필요, build-logic 무변경. 새 edge 없음, 미사용 edge 삭제: grpc-client의 io.grpc(leaf 합병으로 소멸), codegen→proto-contract, edition→core-api/proto-contract/bootstrap, testkit→proto-contract/codegen. starter·grpc-advanced·compat는 grpc-runtime의 versionless io.grpc api를 받으므로 `ca.grpc-platform-module`(gRPC BOM)로 전환 — 새 leaf로 lockfile을 재생성할 때 BOM 없이 `Could not find io.grpc:grpc-api:.`로 실패해서다(기존 lockfile 값과 동일하게 해석됨). `GrpcPackageOwnershipTest` leaf 목록 갱신. lockfile은 `-p optional-platforms resolveAndLockAll --write-locks`로 재생성 | - | policy+server+client+discovery+admin → `grpc-runtime`, proto-contract+codegen → `grpc-contract`, advanced 5개 → `grpc-advanced`, 미사용 edge 삭제 | | S7-#4 | Required | gate·guard·catalog 같은 governance를 운영 코드로 (≈ N-9) | 완료 | Wave 1–2 P5 (fcddab7e·Wave 2 커밋): 삭제 커밋 `9b296c7c`(P5 D). 상수 gate·guard·catalog·invariant·testkit·문자열 ArchUnit 흉내 삭제(아래 「제거된 코드」). 전부 main 호출자 0이었다. `GrpcRawApiImportRule`·`GrpcApplicationBoundaryRules`는 자기 테스트의 합성 입력만 검사하고 저장소 코드를 검사하지 않아서 테스트로 옮기지 않고 삭제했다(inbound→outbound 규칙은 app-bootstrap ArchUnit `INBOUND_ADAPTERS_DO_NOT_DEPEND_ON_OUTBOUND_ADAPTERS`가 이미 검사). `GrpcResolverSafetyPolicy`는 상수 메서드 2개만 삭제. starter의 항상 통과하던 advanced 격리 검사도 함께 제거 `src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java:41`. 문서 갱신: `src/grpc/CLAUDE.md`, `src/grpc-advanced/CLAUDE.md`, `docs/runbooks/grpc-advanced-capabilities.md`, `docs/compatibility/grpc-advanced-support-matrix.md` | - | 상수 gate·catalog·invariant·testkit 삭제, import 규칙은 ArchUnit 테스트로 | | S7-#5a | Required | `messaging-outbox-jdbc-postgresql`의 Debezium 4개 | 해당 없음(코드 삭제) | `CS:130` | - | - | -| S7-#5b | Required | 한 leaf가 relay 로직·PG repository·admin journal을 함께 가짐 | 남음 | `src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/`: relay 7클래스 877줄, `JdbcOutboxRepository` 721줄, `JdbcAdminOperationJournal` 326줄; Spring JDBC import 파일 2개. inbox는 6개 중 5개가 stdlib | W3 | `messaging-reliability`(stdlib relay·inbox 로직) + `messaging-reliability-jdbc-postgresql`(Jdbc 3종)으로 재분할 | +| S7-#5b | Required | 한 leaf가 relay 로직·PG repository·admin journal을 함께 가짐 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **`messaging-reliability`**(stdlib: `OutboxRelay`·`OutboxRelayWorker`·`OutboxRetryScheduler`·`OutboxEnvelopeFactory`·`OutboxCleanupJob`·`OutboxProperties`·`OutboxRelayReport`, `IdempotentConsumer`·`TransactionalInboxHandler`·`InboxCleanupJob`·`InboxOutcome`·`InboxRetentionPolicy`).
**`messaging-reliability-jdbc-postgresql`**(`JdbcOutboxRepository`, `JdbcInboxRepository`, `JdbcAdminOperationJournal`, migration `V1001..V1005`·`V1101`, PG IT 3개).
**영향:** 옛 두 leaf는 삭제했다. 패키지명은 그대로라 starter 코드는 바뀌지 않았다. CI lane `integration-main.yml`을 새 경로로 바꿨다.
**테스트:** `:messaging:messaging-reliability:test` 47, `:messaging:messaging-reliability-jdbc-postgresql:test` 8, integrationTest 36, starter test 87, integrationTest 3 PASS. | - | `messaging-reliability`(stdlib relay·inbox 로직) + `messaging-reliability-jdbc-postgresql`(Jdbc 3종)으로 재분할 | | S7-#6a | Required | `PublishResult` 7인자 생성자 직접 호출 | 남음 | 11파일 28회 → 5파일 8회(`KafkaMessagingTransport` 1, `KafkaPublishFailureClassifier` 2, `KafkaPublishMapper` 1, `DefaultMessagePublisher` 2, `MS/PublishResults.java` 2). `PublishResult.java:30`에 정적 factory 없음 | W3 | `PublishResult.rejected/ambiguous/confirmed` 정적 factory 추가 후 8곳 교체 | | S7-#6b | Required | `PublishEvidence.ambiguous()`를 두고 직접 생성 | 남음 | `MS/PublishResults.java:43-47,57-59` `new PublishEvidence(true, MAY_HAVE_BEEN_TRANSMITTED, false, NONE)` 2회 | W3 | `PublishEvidence.ambiguous()` 사용 | | S7-#6c | Required | `rejectedLocally` 4벌, `PulsarPreSendRejection`·`NatsPreSendRejection` 중복 | 해당 없음(코드 삭제) | rabbit·pulsar·nats 삭제(`CS:124-129`), 남은 것은 `KafkaMessagingTransport.java:200` 1개 | - | - | | S7-#7 | Required | envelope ↔ canonical header 변환 3벌 | 해당 없음(코드 삭제) | Rabbit mapper·Debezium router 삭제(`CS:128,130`). 남은 Kafka `KafkaHeaderMapper`(쓰기)·`KafkaDeliveryMapper`(읽기) 한 쌍, `RESERVED_HEADER_FORGED`는 `KafkaHeaderMapper.java:92` 한 곳 | - | - | -| S7-#8 | Consider | outbox port·repository 죽은 표면 | 남음 | `OutboxRepository.java:36` `leaseBatch`(main 호출 0), 4인자 `claimBatch`(`:47`)·3인자 `markAmbiguous`(`:69`)(relay는 `:58`·`:72` 오버로드만 사용), `JdbcOutboxRepository.java:426-455` `*Unfenced` 4개(호출 0), 손 JSON `:608-680` | W3 | 메서드 7개 삭제, header JSON은 Jackson 또는 `jsonb_each_text` (purge 오버로드는 1차 M-6) | +| S7-#8 | Consider | outbox port·repository 죽은 표면 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **삭제:** `OutboxRepository`의 `leaseBatch`, 4인자 `claimBatch`, 3인자 `markAmbiguous`(`src/messaging/messaging-reliability-api/src/main/java/dev/caskeleton/messaging/reliability/OutboxRepository.java:43`, `:57`만 남음). `JdbcOutboxRepository`의 LEASE SQL, `*Unfenced` 4개, `update` helper, 손으로 쓴 JSON(`toJson`/`fromJson`/`escape`/`unescape`).
**header 저장:** `jsonb_object(?::text[])`로 쓰고 `jsonb_each_text`로 읽는다(`src/messaging/messaging-reliability-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java:59`, `:77-78`).
**TDD:** `OutboxPostgresIT.aHeaderValueEndingInABackslashRoundTripsWithoutSwallowingTheNextHeader`(`OutboxPostgresIT.java:612`)가 먼저 FAIL했다("map entries not expected: x-path=C:\exports\"") → 수정 후 PASS. integrationTest 36/36.
**그대로 둔 것:** purge 오버로드(1차 M-6)는 손대지 않았다. | - | 메서드 7개 삭제, header JSON은 Jackson 또는 `jsonb_each_text` (purge 오버로드는 1차 M-6) | | S7-#9a | Consider | starter 550줄 god config | 남음 | `MS/MessagingCoreAutoConfiguration.java` 549줄, `@Bean` 28 | W3 | config/validation, publish pipeline, observability 세 configuration으로 분리 | | S7-#9b | Consider | broker 중립 core starter에 broker 전용 필드 union | 남음 | Rabbit 필드는 삭제(`CS:235`), `MS/BrokerSettings.java:32-44`에 Kafka 전용 필드(`bootstrapServers`, `enableIdempotence`, `acks` 등) 남음 | W3 | Kafka 필드는 starter-kafka가 자기 settings record로 바인딩 | | S7-#9c | Consider | 외부 사용 0인 Blocking/Reactive/Batch facade와 `reactor-core` api 노출 | 남음 | `MS/Default{Blocking,Reactive,Batch}MessagePublisher.java`, `MS/ReactiveMessagePublisher.java`(합계 398줄) starter 밖 main 참조 0; `src/messaging/messaging-spring-boot-starter/build.gradle:46` `api 'io.projectreactor:reactor-core'` | W3 | facade 삭제(또는 reactor `compileOnly`) | @@ -1033,7 +1033,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S7-#16c | Nit | `KafkaConsumerRegistrar.dispatch` 긴 메서드 | 남음 | `KafkaConsumerRegistrar.java:264-354`(약 90줄) | W5 | S7-#2 결정 후: 유지면 분해, 삭제면 소멸 | | S7-lead-1 | 권고 | outbox relay 3개 (= X1-#1) | 완료 | V2 relay 삭제(`CS:175`), 앱 relay는 `PublishPendingOutboxEventsUseCase` 하나(`BS/autoconfigure/outbox/OutboxConfig.java:86`). messaging `OutboxRelay`는 vendored 제품 기능으로 `@ConditionalOnBean(OutboxRepository)`(`MS/MessagingReliabilityAutoConfiguration.java:81`)이고 main에 `JdbcOutboxRepository` 생성 0이라 앱 조립에 들어오지 않음, `6d27356e` | - | - | | S7-lead-2 | 권고 | 멱등성 저장소 3개(앱, grpc ledger, messaging inbox) (= X1-#2) | 남음 | 셋 다 존재. messaging inbox는 소비자 dedup이고 family 규칙상 앱 계약 사용 불가(`CLAUDE.md:65`); grpc ledger도 앱 edge 없음(`MJ:606`, allowed `grpc-core-api`만) → 분리는 구조상 의도. 그러나 root `CLAUDE.md:59-67` family 표에 `grpc:*`·`grpc-advanced:*` 행이 없어 이 예외가 문서에 없음 | W5 | family 표에 gRPC 플랫폼을 messaging과 같은 vendored 예외(자체 ledger, optional build)로 한 줄 추가 | -| S7-lead-3 | 권고 | Kafka producer 경로 2개 (= X1 표 Kafka producer) | 남음 | R0 `LegacyKafkaMessagingRootAutoConfiguration`·`KafkaSender`·`KafkaSenderAutoConfiguration`(`src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/`) vs 플랫폼 `KafkaMessagingTransport`; `CS:32` "legacy `KafkaSender` seam and the vendored platform"
Wave 1–2 P1: 미완 — 이유: = X1 표 Kafka producer(legacy `KafkaSender` R0 경로). 결정 7로 Wave 3 3-C에서 경로째 삭제. 이번 묶음 지시대로 legacy seam은 손대지 않음 | W2 | MSG-015 cutover(S6-lead-3과 함께) 후 R0 `KafkaSender` 경로 삭제 | +| S7-lead-3 | 권고 | Kafka producer 경로 2개 (= X1 표 Kafka producer) | 해당 없음(코드 삭제) | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): R0 경로(`LegacyKafkaMessagingRootAutoConfiguration`·`KafkaSender`·`KafkaSenderAutoConfiguration`·`KafkaMessageBroker`)를 `6268c494`에서 삭제했다. 남은 Kafka producer는 platform `KafkaMessagingTransport` 하나다. | - | MSG-015 cutover(S6-lead-3과 함께) 후 R0 `KafkaSender` 경로 삭제 | | S7-lead-4 | 권고 | lease/claimBatch 구현 여러 벌 (= X1-#6) | 남음 | persistence-jpa 안에 owner+token lease 2벌: outbox(`OutboxStoreAdapter.java:79-90`, `OutboxEventJpaRepository.java:34,47`)와 알림(`RecipientDeliveryJpaRepository.java:85-175`, `JpaRecipientLeaseStore`). outbox는 계약 kit `OutboxLeaseFencingContract`(application-core testFixtures)가 있으나 `RecipientLeaseStorePort`는 PG 통합 테스트 1개뿐. messaging `OutboxRepository.claimBatch`는 vendored라 별개 | W4 | SQL은 테이블별 유지(X1-#6), application-notification testFixtures에 `RecipientLeaseFencingContract`를 만들어 fake와 JPA store가 함께 상속 | | S7-lead-5 | 권고 | messaging 기본 off 처리 두 곳(sentinel vs starter switch) | 해당 없음(코드 삭제) | `DisabledMessagingSentinelAutoConfiguration` 삭제(`CS:240`), 끄는 키는 모듈 `app.messaging.enabled` 하나(`CS:32`) | - | - | @@ -1053,10 +1053,10 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): |---|---|---|---|---|---|---| | NEW-1a | Consider | compose smoke가 lane이 실제로 켠 기능·DB 벤더를 확인하지 않는다. `expectedSwitchesOn`·`expectedPersistenceVendor`를 읽는 코드가 없다(스크립트·정적 검사기 모두). | 완료 | Wave 1–2 P13 (fcddab7e·Wave 2 커밋): 방식: Spring Boot `management.info.env.enabled=true`(`src/app-bootstrap/src/main/resources/config/observability.yml:86-94`, `info.*` 트리만 노출, env 전체 아님)와, 각 capability 모듈이 자기 설정 파일에 `info.capabilities..enabled: ${<스위치 키>:}`을 싣는다. JPA는 `vendor: ${ca-skeleton.persistence.vendor:postgresql}`도 싣는다(vendor=postgresql이면 `JpaDataSourceProfileValidator`가 실제 DB가 PostgreSQL인지 기동 때 확인하므로 선택자=실제 DB). Java 코드 추가 없음, capability 모듈 8개의 yml만 추가: `persistence-jpa.yml`, `persistence-mongo/config/mongo.yml`, `messaging-kafka/.../messaging.yml`, `notification-platform/.../notification.yml`, `graphql/config/graphql.yml`, `cache-redis.yml`, `fileserver-platform/.../fileserver.yml`, `httpclient.yml`. 계약 재정의: `expectedSwitchesOn`(property 키) → `expectedCapabilitiesOn`(info 이름), 최상위 `capabilities` 카탈로그(8개) 추가, `$activationComment`/`$vendorComment` 갱신(`src/config/runtime/compose-profile-contracts.json:741-752`). smoke: `scripts/run-compose-runtime-smoke.sh:434-468` — health 응답 뒤 `/actuator/info`를 받아 ①보고된 capability 이름 집합 = 카탈로그(모듈 누락·info 꺼짐 검출, all-off lane이 빈 목록끼리 비교하는 헛검사가 안 되게) ②enabled=true 집합 = `expectedCapabilitiesOn` ③JPA가 켜졌으면 `vendor`, 아니면 `none` = `expectedPersistenceVendor`. 정적 검사 `scripts/verify-compose-profile-contracts.sh:133-146`(check 6): 카탈로그 밖 이름, JPA 켜짐/꺼짐과 맞지 않는 vendor를 거부. 실제 실행(Docker, qualification 이미지): 재현 — off-local이 persistence-jpa를 기대하도록 바꾼 계약에서 HEAD의 smoke는 `all 1 blocking lanes passed`(결함), 새 smoke는 `off-local: the application reports [] on, the contract expects [persistence-jpa]`로 FAIL. 실제 계약: `--lane off-local` passed(8개 모두 `enabled:"false"`), `--lane local-jpa` passed(`persistence-jpa {enabled:"true",vendor:"postgresql"}`), `--lane off-prod` passed. `--lane local-redis`는 info 검사(`redis enabled:"true"`)를 통과한 뒤 기존 3c 기동 로그 검사에서 실패(P13-new-2). 정적 검사: 실제 계약 18 lane 전부 match, 깨진 사본(카탈로그 밖 이름·JPA 켜짐+vendor none)은 두 lane FAIL. 한계: objectstorage·websocket·gRPC는 모든 lane에서 꺼지고 info에 보고하지 않는다(예전 activation endpoint도 보고하지 않던 셋). `ConfigurationNamespaceContractTest`의 허용 root에 프레임워크 namespace `info` 추가(`app-bootstrap/src/test/.../ConfigurationNamespaceContractTest.java:57-74`). | - | 결정(2026-09-25): smoke가 lane이 켠 capability·DB 벤더를 health component(또는 info)로 확인, 계약 필드를 그 값에 맞춰 재정의 | | NEW-1b | Required | 새 CI 잡이 GitHub에서 한 번도 돌지 않았다. 18개 lane을 실제로 돌린 증거가 없다. | 남음 | 브랜치에 upstream이 없고(`git status -sb` → `## refactor/review-followup`), `6d27356e`를 포함한 원격 브랜치도 없다(`git branch -r --contains` 결과 비어 있음). 새로 추가된 잡은 `.github/workflows/build-logic.yml:30-41`(included build 테스트), `.github/workflows/integration-main.yml:64`(`main-check`), `:85`(`configuration-cache`), `:130`(`jpa-candidate-evidence`)이다. compose 잡은 `integration-main.yml:374-387`에 있고 `push: main`·nightly·dispatch에서만 돈다(`:33-40`). 계약 lane은 18개다(`jq '.lanes\|length'`). lane은 `COMPOSITION=qualification` 이미지로 돈다(`run-compose-runtime-smoke.sh:34`, `src/Dockerfile:70-77`). | W4 | 로컬에서 돌리려면 docker, docker compose 2.24.4 이상(`compose-profile-contracts.json`의 `minimumComposeVersion`), jq, openssl(TLS lane의 인증서 생성, `:183-211`)이 필요하다. 명령은 `bash scripts/run-compose-runtime-smoke.sh --matrix src/config/runtime/compose-profile-contracts.json`이고, 이미지는 스크립트가 `docker compose build app`으로 만든다(`:366`). 스크립트의 도구 사전 검사(`:75-77`)에 `openssl`을 추가한다. 브랜치를 push해서 `workflow_dispatch`로 `integration-main`·`build-logic`을 한 번 돌리고 그 결과를 증거로 남긴다. | -| NEW-2a | Consider | outbox relay 조립이 app-bootstrap에 있다. | 남음 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfig.java:44-120`. 조건: `@AutoConfiguration(afterName=PersistenceJpaAutoConfiguration, MessagingBridgeRootAutoConfiguration)`, `@ConditionalOnProperty(ca-skeleton.outbox.enabled=true)`, `@ConditionalOnBean(OutboxStorePort)`, `@EnableScheduling`. 빈: `outboxCanonicalTransportRequirementValidator`, `outboxRelayScheduler`(`relay-enabled` 기본 true + `@ConditionalOnBean(OutboxMessagePublishPort)`), `outboxRandomGenerator`, `outboxLeaderElection`, `outboxMetrics`. 같은 패키지에 `OutboxSettings`·`OutboxMetrics`·`OutboxRelayScheduler`·`OutboxLeaderElectionToken`·`OutboxCanonicalTransportRequirementValidator`가 있다. 등록은 `src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports:2`. persistence-jpa로 옮기지 못하는 이유는 `AdapterBoundaryArchitectureTest.java:207-227` 때문이다. 이 규칙은 `adapter.outbound.persistence..` 패키지가 `*UseCase`를 참조하는 것을 막는데, `OutboxConfig`는 `PublishPendingOutboxEventsUseCase`를 직접 만든다(:85). | W3 | 새 leaf `:composition:outbox-relay`(패키지 `dev.caskeleton.composition.outbox`)를 만들고 위 6개 클래스와 테스트(`OutboxConfigTest`·`OutboxSettingsTest`·`OutboxRelaySchedulerLoggingTest`·`OutboxCanonicalTransport*Test`)를 옮긴다. 자세한 내용은 아래 메모. | -| NEW-2b | Consider | 멱등성 executor 조립이 app-bootstrap에 있고, sample이 검증 없는 복사본을 따로 가진다. | 남음 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java:28-56`: `@AutoConfiguration`, 빈은 `idempotencyExecutor` 하나다(`@ConditionalOnExpression(provider != disabled)`). store가 정확히 1개가 아니면 기동 실패한다(:39-47). 설정은 `IdempotencySettings.java:24-67`에 있고 lease·TTL 상한과 codec·revision을 검증한다. sample 복사본 `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java:21-47`과의 차이는 셋이다. ① `Binder`로 직접 읽어서 상한·양수 검증이 없다(:38-45). ② store를 1개로 가정한다(`IdempotencyStorePort store` 직접 주입). ③ `Clock` 빈과 `@EnableScheduling`을 함께 들고 있다(:22,:27-30). | W3 | 새 leaf `:composition:idempotency`로 `IdempotencyProviderSelectionConfig`·`IdempotencySettings`와 테스트(`IdempotencyProviderCompositionTest`·`IdempotencySettingsTest`)를 옮긴다. sample은 `runtimeOnly project(':composition:idempotency')`를 쓰고 `SampleIdempotencyConfig`에서는 executor 빈을 지운다(Clock·scheduling만 남긴다). modules.json의 `sample-portfolio.allowed_dependencies`에 `composition-idempotency`를 추가한다. | +| NEW-2a | Consider | outbox relay 조립이 app-bootstrap에 있다. | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): X1-#1i와 같다. 조립은 `src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java:43-53`에 있고, app-bootstrap `AutoConfiguration.imports`에서 outbox 줄을 뺐다. | - | 새 leaf `:composition:outbox-relay`(패키지 `dev.caskeleton.composition.outbox`)를 만들고 위 6개 클래스와 테스트(`OutboxConfigTest`·`OutboxSettingsTest`·`OutboxRelaySchedulerLoggingTest`·`OutboxCanonicalTransport*Test`)를 옮긴다. 자세한 내용은 아래 메모. | +| NEW-2b | Consider | 멱등성 executor 조립이 app-bootstrap에 있고, sample이 검증 없는 복사본을 따로 가진다. | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **이동:** `IdempotencyProviderSelectionConfig`→`IdempotencyAutoConfiguration`(`src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfiguration.java:38`, executor 생성 `:58`).
**설정:** `IdempotencySettings.bind`는 `StrictSettingsBinder.bindExcept`로 strict 바인딩한다. `config/module-defaults/idempotency.yml`로 옮겼다(예전 `capabilities.yml`).
**sample:** `SampleIdempotencyConfig`를 삭제했다. Clock·`@EnableScheduling`만 `SampleSchedulingConfig`에 남겼다.
**테스트:** `IdempotencySettingsTest`(strict), `IdempotencyAutoConfigurationTest`, `IdempotencyModuleDefaultsTest`, `StrictSettingsBinderTest`, `SampleIdempotencyReplayIntegrationTest` PASS. | - | 새 leaf `:composition:idempotency`로 `IdempotencyProviderSelectionConfig`·`IdempotencySettings`와 테스트(`IdempotencyProviderCompositionTest`·`IdempotencySettingsTest`)를 옮긴다. sample은 `runtimeOnly project(':composition:idempotency')`를 쓰고 `SampleIdempotencyConfig`에서는 executor 빈을 지운다(Clock·scheduling만 남긴다). modules.json의 `sample-portfolio.allowed_dependencies`에 `composition-idempotency`를 추가한다. | | NEW-3 | Required | fileserver 보상 트랜잭션의 30초 타임아웃이 사라졌다. 지금은 `inNew` 경로 전체에 타임아웃이 없다. | 완료 | Wave 1–2 P4 (fcddab7e·Wave 2 커밋): C-3d와 같은 수정·테스트. `SpringTransactionPort.java:62` | - | 가장 작은 변경은 `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionPort.java`의 `requiresNewTemplate`에 `setTimeout(30)`을 거는 것이다(상수 1개). 이러면 보상·outbox·audit용 REQUIRES_NEW의 옛 동작이 돌아온다. 전 트랜잭션에 상한을 원하면 대신 `persistence-jpa.yml` module-defaults에 `spring.transaction.default-timeout: 30s`를 둔다. 테스트는 `SpringTransactionPort` 단위 테스트에서 inNew template의 timeout 값을 단언한다. | -| NEW-4a | Required | Kafka legacy seam producer에 보안 설정이 전혀 없다(항상 PLAINTEXT). | 남음 | `src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderAutoConfiguration.java:62-80`: bootstrap·serializer·acks·timeout만 넣는다. `security.protocol`·SASL·SSL 키가 없다. messaging-kafka 모듈을 고르면 `LegacyKafkaMessagingRootAutoConfiguration`(imports 1행)로 항상 켜진다. 반면 platform producer는 `KafkaSecurityConfigurer`를 적용한다(`KafkaMessagingAutoConfiguration.java:234-235`). | W1 | seam producer도 같은 보안 profile을 쓰게 한다. `KafkaMessagingAutoConfiguration.producerSecurity(...)`를 재사용 가능한 static으로 빼거나 `KafkaSecurityConfigurer` 결과를 주입받아 `config.putAll(...)`한다. 보안 profile이 없고 broker가 TLS·auth를 요구하면 기동을 실패시킨다(platform 쪽 `:200-211`과 같은 규칙). 장기적으로는 seam을 platform transport로 합쳐 producer를 하나로 줄인다. | +| NEW-4a | Required | Kafka legacy seam producer에 보안 설정이 전혀 없다(항상 PLAINTEXT). | 해당 없음(코드 삭제) | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **삭제:** 항상 PLAINTEXT인 seam producer(`KafkaSenderAutoConfiguration.java:62-80`)와 그것을 켜던 `LegacyKafkaMessagingRootAutoConfiguration`이 `6268c494`에서 삭제됐다. messaging-kafka의 `AutoConfiguration.imports`도 삭제했다.
**남은 producer:** platform producer 하나다(`KafkaMessagingAutoConfiguration.java:188`, `:216`). 보안 profile이 없는데 broker가 TLS를 요구하면 기동을 거부하는 규칙도 그 경로에 그대로 있다.
**테스트:** `KafkaCapabilityActivationTest`는 leaf가 bridge+starter 묶음이 된 것에 맞게 갱신했고 PASS다. | - | seam producer도 같은 보안 profile을 쓰게 한다. `KafkaMessagingAutoConfiguration.producerSecurity(...)`를 재사용 가능한 static으로 빼거나 `KafkaSecurityConfigurer` 결과를 주입받아 `config.putAll(...)`한다. 보안 profile이 없고 broker가 TLS·auth를 요구하면 기동을 실패시킨다(platform 쪽 `:200-211`과 같은 규칙). 장기적으로는 seam을 platform transport로 합쳐 producer를 하나로 줄인다. | | NEW-4b | Required | Kafka TLS 자료(truststore/keystore) 설정 키가 없다. `MUTUAL_TLS`를 설정 값으로는 받지만 실제로 동작하지 않는다. | 완료 | Wave 1–2 P1 (fcddab7e·Wave 2 커밋): M-2e 행과 같은 수정·테스트 | - | `BrokerSettings`(messaging-spring-boot-starter)에 `trust-store-location/password/type`, `key-store-location/password/type`을 추가하거나 Spring Boot SSL bundle 이름(`ssl-bundle`)을 받는다. `KafkaSecurityConfigurer`가 `ssl.truststore.*`·`ssl.keystore.*`(또는 PEM `ssl.*.certificates`)를 채운다. keystore가 없는 `MUTUAL_TLS`는 컴파일 단계에서 거부한다. 구현하지 않을 거면 `MessagingConfigurationCompiler.java:258`에서 `MUTUAL_TLS`를 뺀다. | | NEW-4c | Consider | platform producer가 broker 주소를 `spring.kafka.bootstrap-servers`에서만 읽고, 선언된 broker의 `bootstrap-servers`는 검증만 한 뒤 쓰지 않는다. | 완료 | Wave 1–2 P1 (fcddab7e·Wave 2 커밋): M-2b 행과 같은 수정·테스트 | - | 주소 출처를 하나로 정한다. 추천은 compiled broker(`CompiledMessagingConfiguration`의 kafka broker `bootstrapServers()`)를 쓰고, 없을 때만 `spring.kafka.bootstrap-servers`로 fallback하는 것이다. 둘 다 있는데 값이 다르면 기동을 실패시킨다. 테스트는 `producerConfig(...)`에 두 값을 다르게 주고 결과를 단언한다. | | NEW-4d | Required | credential rotation이 Kafka producer에 반영되지 않는다. | 완료 | Wave 1–2 P1 (fcddab7e·Wave 2 커밋): M-2f 행과 같은 수정·테스트 | - | Kafka 방식으로 해결한다. `sasl.client.callback.handler.class`에 `CredentialRuntimeRegistry`를 조회하는 handler를 넣고 JAAS에는 username만 둔다. 이러면 재인증(broker `connections.max.reauth.ms`) 때마다 새 비밀번호를 쓴다. 다른 방법은 registry의 generation 변화에 맞춰 producer를 교체하고 transport generation을 올리는 것이다. Javadoc(:17-21)은 실제 동작에 맞춘다. | @@ -1201,3 +1201,6 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검 | P25-new-1 | 발견 | `TomcatWebSocketAbuseIT` shutdown 테스트가 부하 중 `20.0006s < 20s`로 한 번 실패, 재실행 4회 통과(타이밍 의존). | 남음 | Wave 3 P25 결과 파일 | W4 | 시간 경계 단언을 결정적 신호로 | | P25-new-2 | 발견 | legacy upload 삭제 뒤 `PosterEventPublisher.publishImageAttached`·`PosterImageAttached` 호출자 0(= P24-new-2). | 남음 | Wave 3 P25 결과 파일 | W3 | P24-new-2와 함께(P28) | | P25-new-3 | 발견 | sample `local` 프로필이 기본값과 같은 `object-storage.enabled=false`만 남김. | 남음 | Wave 3 P25 결과 파일 | W5 | 불필요한 설정 삭제 또는 이유 주석 | +| 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에 켜짐 조건 명시 | diff --git a/docs/runbooks/outbox-publish-failed.md b/docs/runbooks/outbox-publish-failed.md index 84d847c4..8975e2f7 100644 --- a/docs/runbooks/outbox-publish-failed.md +++ b/docs/runbooks/outbox-publish-failed.md @@ -31,8 +31,11 @@ status: stub - relay 스케줄러는 발행 포트(`OutboxMessagePublishPort`, messaging bridge가 제공)가 있을 때만 생긴다. messaging을 고르지 않은 배포에서는 relay가 없고 PENDING row가 그대로 남는다(MSG-024의 "DEAD까지 소진"은 대역 publisher가 있던 때의 이야기다). messaging 모듈이 켜져 있는데 - `APP_MESSAGING_BROKER`가 공백이면 기동이 거부된다(messaging `MessagingConfig`, messaging platform - `MessagingProviderSelection`) — broker를 설정하거나 messaging을 끈다. + `APP_MESSAGING_PRODUCER_ID`가 공백이면(messaging `MessagingConfig`) 또는 `APP_MESSAGING_BROKER`가 + 공백이면(messaging platform `MessagingProviderSelection`) 기동이 거부된다 — 값을 설정하거나 + messaging을 끈다. + - 발행이 `REJECTED_*`로 바로 DEAD가 된다면 event의 logical destination(`app.messaging.destinations`)이 + 선언돼 있는지부터 본다. - 기동은 했는데 실패가 쌓인다면 broker는 설정돼 있고 도달이 안 되는 것이다 — endpoint부터 본다. 3. `outbox.pending.size` status 분포 확인 (FAILED 누적 vs PENDING 누적) diff --git a/docs/study/postgresql-jpa-walkthrough.ko.md b/docs/study/postgresql-jpa-walkthrough.ko.md index 1dc5aa3f..f0cc4186 100644 --- a/docs/study/postgresql-jpa-walkthrough.ko.md +++ b/docs/study/postgresql-jpa-walkthrough.ko.md @@ -59,8 +59,8 @@ PostgreSQL과 직접 관련된 레지스트리 leaf는 세 개다. | leaf | 성격 | |---|---| | `adapter-outbound-persistence-jpa` | 이 글의 주인공. JPA + PostgreSQL 어댑터이자 "관계형 퍼시스턴스 플랫폼" | -| `messaging-outbox-jdbc-postgresql` | vendored messaging 제품의 outbox 구현 (별개 계보) | -| `messaging-inbox-jdbc-postgresql` | 같음 | +| `messaging-reliability-jdbc-postgresql` | vendored messaging 제품의 outbox·inbox 저장소 구현 (별개 계보) | +| `messaging-reliability` | 같은 제품의 relay·consumer 로직 (stdlib) | messaging 쪽 두 개는 **이 애플리케이션의 레이어가 아니라 vendored 라이브러리**라서 계보가 완전히 다르다. 루트 `CLAUDE.md`가 그 예외를 명시적으로 적어 두고 있고, 이 글은 diff --git a/src/.env.example b/src/.env.example index ef922a77..f30773b7 100644 --- a/src/.env.example +++ b/src/.env.example @@ -295,7 +295,6 @@ APP_WEBSOCKET_BROADCAST_DESTINATION=/topic/events APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY=10000 APP_OUTBOX_ENABLED=false APP_OUTBOX_RELAY_ENABLED=false -APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED=false APP_NOTIFICATION_PLATFORM_ENABLED=true APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE=ko-KR APP_NOTIFICATION_PLATFORM_MODE=SERVING diff --git a/src/README.md b/src/README.md index d7434c35..d4d0f743 100644 --- a/src/README.md +++ b/src/README.md @@ -263,7 +263,7 @@ Kafka 없이 기동합니다. 나머지 기능은 `app-bootstrap/build.gradle` |---|---|---|---| | JPA/PostgreSQL (Flyway·outbox store·JDBC 멱등성·분산 락) | `runtimeOnly project(':adapter:outbound:persistence-jpa')` | `APP_DATASOURCE_URL`, `APP_DATASOURCE_USERNAME`, `APP_DATASOURCE_PASSWORD` | `APP_PERSISTENCE_JPA_ENABLED` | | Redis (cache·rate limit·lease·멱등성) | `runtimeOnly project(':adapter:outbound:cache-redis')` | `APP_REDIS_MODE`, `APP_REDIS_NODES`, `APP_REDIS_NAMESPACE_*`, `APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE`, 쓰는 역할의 선택자(`APP_CACHE_CANONICAL_DEFAULT_PROVIDER`, `APP_RATE_LIMIT_PROVIDER`, `APP_LEASE_PROVIDER`, `APP_IDEMPOTENCY_PROVIDER=redis`) | `APP_REDIS_ENABLED` | -| Kafka 발행 | `runtimeOnly project(':adapter:outbound:messaging-kafka')` | `APP_MESSAGING_KAFKA_BROKERS` (canonical 이벤트를 보내면 `APP_MESSAGING_PRODUCER_ID`) | `APP_MESSAGING_ENABLED` | +| Kafka 발행 | `runtimeOnly project(':adapter:outbound:messaging-kafka')` | `APP_MESSAGING_KAFKA_BROKERS`, `APP_MESSAGING_PRODUCER_ID` | `APP_MESSAGING_ENABLED` | | Mongo | `runtimeOnly project(':adapter:outbound:persistence-mongo')` | `APP_PERSISTENCE_MONGO_ACTIVE_PROFILE`, `SPRING_MONGODB_URI`(또는 profile의 `uri-secret`) | `APP_PERSISTENCE_MONGO_ENABLED` | | GraphQL | `runtimeOnly project(':adapter:inbound:graphql')` | `APP_GRAPHQL_DEPLOYMENT_MODE` (local→`LOCAL`, dev→`DEV`, prod→`PRODUCTION_*`) | `APP_GRAPHQL_ENABLED` | | 외부 HTTP 호출 | `runtimeOnly project(':adapter:outbound:httpclient')` | client 하나 이상: `APP_HTTPCLIENT_CLIENTS_0_*` (`docs/httpclient/env-fields.yaml`) | `APP_HTTPCLIENT_ENABLED` | @@ -325,9 +325,9 @@ Kafka·Redis는 위 "기능 추가 = 한 줄 + env" 표의 한 줄로 고릅니 - **`APP_MESSAGING_BROKER`** — 활성 메시지 브로커 id. Kafka 모듈의 설정 기본값이 `kafka`(등록된 유일한 broker)라 보통 비워 두지 않습니다. 빈 값을 주면 기동이 거부되면서 이 키 이름을 지목합니다. 이 키를 비워도 메시징이 꺼지지는 않습니다 — 끄는 것은 `APP_MESSAGING_ENABLED=false`입니다. -- **`APP_MESSAGING_KAFKA_BROKERS`** — `host:port` CSV. Kafka 모듈을 고르면 필수. legacy seam과 - messaging platform의 Kafka transport(`app.messaging.brokers.kafka.bootstrap-servers`)가 같은 값을 - 씁니다. `spring.kafka.bootstrap-servers`는 읽지 않습니다. +- **`APP_MESSAGING_KAFKA_BROKERS`** — `host:port` CSV. Kafka 모듈을 고르면 필수. messaging + platform의 Kafka transport(`app.messaging.brokers.kafka.bootstrap-servers`)가 이 값을 씁니다. + `spring.kafka.bootstrap-servers`는 읽지 않습니다. - **`APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED`** — Slack webhook R0 provider enable flag. notification 플랫폼이 켜졌을 때 어떤 provider를 쓸지 고르는 값입니다. - **`APP_NOTIFICATION_GOOGLE_EMAIL_ENABLED`** — Google Email R0 provider enable flag. 위와 같습니다. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java index e3435515..2ea90e57 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java @@ -87,7 +87,6 @@ public class DurableOperationController { null, RequestFingerprint.ofSha256(payload.getBytes(StandardCharsets.UTF_8)), payload, - OperationCommand.SUBMITTED_EVENT_TYPE, OperationCommand.DEFAULT_TIME_TO_LIVE)); URI location = ServletUriComponentsBuilder.fromCurrentRequestUri() diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java index a6ddbb4e..f9088af9 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java @@ -12,9 +12,10 @@ import com.jayway.jsonpath.JsonPath; import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; +import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.operation.CancelDurableOperationUseCase; +import dev.caskeleton.application.operation.DurableOperationSubmittedContract; import dev.caskeleton.application.operation.GetDurableOperationUseCase; -import dev.caskeleton.application.operation.OperationCommand; import dev.caskeleton.application.operation.SubmitDurableOperationUseCase; import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStore; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; @@ -60,7 +61,8 @@ class DurableOperationControllerTest { void setUp() { DurableOperationController controller = new DurableOperationController( - new SubmitDurableOperationUseCase(operations, outbox, transactions, clock), + new SubmitDurableOperationUseCase( + operations, outbox, new FakeIntegrationEventEncoder(), transactions, clock), new GetDurableOperationUseCase(operations, transactions, clock), new CancelDurableOperationUseCase(operations, transactions, clock)); mvc = @@ -121,7 +123,7 @@ class DurableOperationControllerTest { // then assertThat(outbox.oldestUnpublishedAgeSecondsByEventType(clock.instant())) - .containsOnlyKeys(OperationCommand.SUBMITTED_EVENT_TYPE); + .containsOnlyKeys(DurableOperationSubmittedContract.CONTRACT_ID.value()); } @Test diff --git a/src/adapter/outbound/messaging-kafka/README.md b/src/adapter/outbound/messaging-kafka/README.md index 8e04d3a3..0fce818a 100644 --- a/src/adapter/outbound/messaging-kafka/README.md +++ b/src/adapter/outbound/messaging-kafka/README.md @@ -2,35 +2,40 @@ - Module ID: `adapter-outbound-messaging-kafka` - Gradle path: `:adapter:outbound:messaging-kafka` -- Package: `dev.caskeleton.adapter.outbound.messaging.kafka` +- Package: `dev.caskeleton.adapter.outbound.messaging.kafka` (테스트만 있다) - 테스트: `./gradlew :adapter:outbound:messaging-kafka:test --console=plain` ## 제공하는 것 이 모듈 하나를 붙이면 Kafka 발행이 들어온다. 유스케이스는 application-core 포트만 호출한다. +이 leaf에는 코드가 없다. 선택 한 줄과 설정 기본값을 묶는 capability 단위다. ``` adapter:outbound:messaging-kafka - ├─ LegacyKafkaMessagingRootAutoConfiguration KafkaSender seam + KafkaMessageBroker ├─ config/module-defaults/messaging.yml (설정 기본값, support 로더가 읽음) - ├─ adapter:outbound:messaging MessagePublisher, OutboxMessagePublishPort, + ├─ adapter:outbound:messaging OutboxMessagePublishPort, │ IntegrationEventPublishPort bridge └─ messaging:messaging-spring-boot-starter-kafka messaging platform + Kafka transport ``` | 포트 (application-core) | 구현 | | --- | --- | -| `OutboxMessagePublishPort` | legacy outbox row → `KafkaMessageBroker`, canonical row → `IntegrationEventPublishPort` | -| `IntegrationEventPublishPort` | platform `EncodedMessagePublisher` (`APP_MESSAGING_PRODUCER_ID`가 있을 때만) | +| `OutboxMessagePublishPort` | claim된 row의 validated event → `IntegrationEventPublishPort` | +| `IntegrationEventPublishPort` | platform `EncodedMessagePublisher` | | `OutboxRelayFailureReportPort` | 구조화 로그 | - 켜기와 끄기: 모듈이 있으면 켜진다. `APP_MESSAGING_ENABLED=false`로만 끈다. 끄면 messaging bean, Kafka producer, 스레드가 하나도 생기지 않는다. -- 설정: `config/module-defaults/messaging.yml`을 support의 `ModuleDefaultsEnvironmentPostProcessor`가 읽는다. 우선순위가 가장 낮아서 `application*.yml`, - 환경 변수, 시스템 속성이 항상 이긴다. app-bootstrap은 이 파일을 모른다. -- broker 주소 하나(`APP_MESSAGING_KAFKA_BROKERS`)가 legacy seam(`app.messaging.kafka.brokers`)과 - platform transport(`app.messaging.brokers.kafka.bootstrap-servers`) 양쪽에 들어간다. - `spring.kafka.bootstrap-servers`는 읽지 않는다. 논리 broker 이름은 `kafka` 하나다. +- 설정: `config/module-defaults/messaging.yml`을 support의 `ModuleDefaultsEnvironmentPostProcessor`가 + 읽는다. 우선순위가 가장 낮아서 `application*.yml`, 환경 변수, 시스템 속성이 항상 이긴다. + app-bootstrap은 이 파일을 모른다. +- broker 주소는 `APP_MESSAGING_KAFKA_BROKERS` 하나(`app.messaging.brokers.kafka.bootstrap-servers`). + `spring.kafka.bootstrap-servers`는 읽지 않는다. 논리 broker 이름은 `kafka` 하나다. Kafka 연결의 + TLS·SASL은 platform의 broker profile이 소유한다(`docs/messaging/configuration-reference.md`). +- 발행 경로는 하나다. 옛 `KafkaSender` seam(TLS/SASL 없는 R0 producer)은 outbox를 canonical로 + 통일하면서 삭제했다(2026-09-28). +- 발행할 event의 contract마다 destination을 선언해야 한다(`app.messaging.destinations.`). 템플릿의 durable operation event는 `durable-operations`로 간다. ## 추가할 한 줄 @@ -48,8 +53,9 @@ runtimeOnly project(':adapter:outbound:messaging-kafka') // Kafka 발행 | 언제 | 키 | | --- | --- | | 항상 | `APP_MESSAGING_KAFKA_BROKERS` (CSV `host:port`). 비어 있으면 기동이 실패한다 | -| canonical integration event를 보낼 때 | `APP_MESSAGING_PRODUCER_ID` (배포와 무관한 논리적 서비스 이름) | +| 항상 | `APP_MESSAGING_PRODUCER_ID` (배포와 무관한 논리적 서비스 이름). 비어 있으면 기동이 실패한다 — 모든 발행이 canonical bridge를 지난다 | | 끌 때 | `APP_MESSAGING_ENABLED=false` | -`APP_MESSAGING_BROKER`는 기본값이 `kafka`다. 등록된 broker가 Kafka 하나라 바꿀 일이 없다. -destination·broker profile·보안 설정은 `docs/messaging/configuration-reference.md`. +`APP_MESSAGING_BROKER`는 platform이 쓸 broker 선택값이고 기본값이 `kafka`다. 등록된 broker가 Kafka +하나라 바꿀 일이 없다. destination·broker profile·보안 설정은 +`docs/messaging/configuration-reference.md`. diff --git a/src/adapter/outbound/messaging-kafka/build.gradle b/src/adapter/outbound/messaging-kafka/build.gradle index ea1bd4e9..fc7eafed 100644 --- a/src/adapter/outbound/messaging-kafka/build.gradle +++ b/src/adapter/outbound/messaging-kafka/build.gradle @@ -7,9 +7,11 @@ plugins { // // runtimeOnly project(':adapter:outbound:messaging-kafka') // -// That line brings the broker-neutral application bridge (adapter:outbound:messaging), the legacy -// KafkaSender seam in this leaf, the vendored messaging platform with its Kafka transport, and the -// capability's settings (config/module-defaults/messaging.yml). Deleting it removes all of them. +// That line brings the broker-neutral application bridge (adapter:outbound:messaging), the vendored +// messaging platform with its Kafka transport, and the capability's settings +// (config/module-defaults/messaging.yml). Deleting it removes all of them. The leaf has no code of +// its own: it is the selection, not an adapter. Its one test boots the capability the way an +// application gets it. // Every project shares the group dev.caskeleton, and the vendored transport is also named // messaging-kafka (:messaging:messaging-kafka). Same group and name is the same module to Gradle, @@ -24,16 +26,14 @@ base { } dependencies { - implementation project(':adapter:outbound:messaging') - implementation 'org.apache.kafka:kafka-clients' - - implementation 'org.springframework.boot:spring-boot-autoconfigure' - - // The platform publisher behind the canonical IntegrationEventPublishPort bridge. Runtime only: - // this leaf names none of its types; the bridge reaches it through EncodedMessagePublisher. + // Runtime only: this leaf names none of their types. The bridge publishes the application's + // canonical events through the platform's EncodedMessagePublisher, which the Kafka starter + // provides. + runtimeOnly project(':adapter:outbound:messaging') runtimeOnly project(':messaging:messaging-spring-boot-starter-kafka') // The activation test boots the whole capability and names the ports it must produce. + testImplementation project(':adapter:outbound:messaging') testImplementation project(':application-core') testImplementation project(':messaging:messaging-schema-api') } diff --git a/src/adapter/outbound/messaging-kafka/gradle.lockfile b/src/adapter/outbound/messaging-kafka/gradle.lockfile index 7eb9ad07..64aa98cd 100644 --- a/src/adapter/outbound/messaging-kafka/gradle.lockfile +++ b/src/adapter/outbound/messaging-kafka/gradle.lockfile @@ -38,13 +38,13 @@ com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspat 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 +commons-logging:commons-logging:1.3.6=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-commons:1.16.7=runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-core:1.16.7=runtimeClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.projectreactor:reactor-core:3.8.7=runtimeClasspath,testRuntimeClasspath jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath jakarta.annotation:jakarta.annotation-api:3.0.0=runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -63,7 +63,7 @@ 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.kafka:kafka-clients:4.1.2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.kafka:kafka-clients:4.1.2=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 @@ -86,7 +86,7 @@ org.dom4j:dom4j:2.2.0=spotbugs org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,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 @@ -120,7 +120,7 @@ org.slf4j:slf4j-api:2.0.18=runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileCl org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle 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-autoconfigure:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-jackson:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -142,12 +142,12 @@ org.springframework.boot:spring-boot-tomcat:4.0.8=testCompileClasspath,testRunti 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:spring-aop: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.boot:spring-boot:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-aop:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-beans:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-context:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-jdbc:7.0.9=runtimeClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-tx:7.0.9=runtimeClasspath,testRuntimeClasspath @@ -160,4 +160,4 @@ org.yaml:snakeyaml:2.5=testCompileClasspath,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 -empty= +empty=compileClasspath diff --git a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/BrokerAddress.java b/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/BrokerAddress.java deleted file mode 100644 index d69dd6cf..00000000 --- a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/BrokerAddress.java +++ /dev/null @@ -1,108 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.kafka; - -import java.util.Objects; - -/** - * One broker endpoint, parsed rather than pattern-matched. - * - *

The regular expression it replaces accepted several things that are not addresses. It ran - * against the trimmed value but the untrimmed original was what got stored, so {@code " - * kafka:9092"} passed validation and was then handed to the client with its leading space. {@code - * \\d{1,5}} accepts {@code 0} and {@code 99999}, neither of which is a port. And {@code [^:\\s]+} - * cannot express a bracketed IPv6 literal at all, so {@code [::1]:9092} — the only correct way to - * write an IPv6 endpoint — was rejected while {@code ::1:9092} was accepted and is ambiguous. - * - * @param host the host, without brackets for an IPv6 literal - * @param port the port, between 1 and 65535 - * @param ipv6Literal whether the host was written as a bracketed IPv6 literal - */ -public record BrokerAddress(String host, int port, boolean ipv6Literal) { - - private static final int MIN_PORT = 1; - private static final int MAX_PORT = 65_535; - - /** Validates the parsed components. */ - public BrokerAddress { - Objects.requireNonNull(host, "host must not be null"); - if (host.isBlank()) { - throw new IllegalArgumentException("broker host must not be blank"); - } - if (port < MIN_PORT || port > MAX_PORT) { - throw new IllegalArgumentException("broker port " + port + " is outside 1..65535"); - } - } - - /** - * Parses one {@code host:port} entry. - * - * @param raw the configured entry, possibly with surrounding whitespace - * @return the canonical address - * @throws IllegalArgumentException naming what is wrong with the entry - */ - public static BrokerAddress parse(String raw) { - if (raw == null || raw.isBlank()) { - throw new IllegalArgumentException("a broker entry must not be blank"); - } - String entry = raw.trim(); - if (entry.startsWith("[")) { - int closing = entry.indexOf(']'); - if (closing < 0 || closing + 1 >= entry.length() || entry.charAt(closing + 1) != ':') { - throw new IllegalArgumentException( - "broker entry '" + entry + "' is a bracketed host without a ':port' after the bracket"); - } - String host = entry.substring(1, closing); - if (host.isBlank()) { - throw new IllegalArgumentException("broker entry '" + entry + "' has an empty host"); - } - return new BrokerAddress(host, parsePort(entry, entry.substring(closing + 2)), true); - } - int separator = entry.lastIndexOf(':'); - if (separator < 0) { - throw new IllegalArgumentException("broker entry '" + entry + "' is not host:port"); - } - String host = entry.substring(0, separator); - if (host.isBlank() || host.indexOf(':') >= 0) { - // A bare IPv6 literal reaches here: it contains colons, and which one separates the port is - // not decidable. Brackets are how the ambiguity is resolved, so require them. - throw new IllegalArgumentException( - "broker entry '" - + entry - + "' is not host:port; write an IPv6 address in brackets, as [::1]:9092"); - } - if (host.chars().anyMatch(Character::isWhitespace)) { - throw new IllegalArgumentException( - "broker entry '" + entry + "' has whitespace inside the host"); - } - return new BrokerAddress(host, parsePort(entry, entry.substring(separator + 1)), false); - } - - private static int parsePort(String entry, String port) { - if (port.isEmpty() || !port.chars().allMatch(Character::isDigit)) { - throw new IllegalArgumentException( - "broker entry '" + entry + "' does not end in a numeric port"); - } - int parsed; - try { - parsed = Integer.parseInt(port); - } catch (NumberFormatException tooLong) { - throw new IllegalArgumentException( - "broker entry '" + entry + "' has a port outside 1..65535", tooLong); - } - if (parsed < MIN_PORT || parsed > MAX_PORT) { - // Reported here rather than in the constructor so the message names the offending entry: an - // operator reading "port 0 is invalid" against a list of nine brokers learns nothing. - throw new IllegalArgumentException( - "broker entry '" + entry + "' has port " + parsed + ", outside 1..65535"); - } - return parsed; - } - - /** - * The canonical {@code host:port} form, which is what the client is given. - * - * @return the canonical text - */ - public String canonical() { - return ipv6Literal ? "[" + host + "]:" + port : host + ":" + port; - } -} diff --git a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaAdapterConfig.java b/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaAdapterConfig.java deleted file mode 100644 index dc1b351a..00000000 --- a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaAdapterConfig.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.kafka; - -import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Layer 1 gating for the Kafka broker template: registers the Kafka {@link MessageBroker} only when - * {@code app.messaging.broker=kafka}. The central {@code MessagingConfig} binds both messaging - * ports onto it. - * - *

Needs a project-supplied {@link KafkaSender} bean (the integration seam) and a non-empty - * {@code app.messaging.kafka.brokers}. Adding another broker is a new config like this one — this - * file never changes. - */ -@Configuration -@EnableConfigurationProperties(KafkaAdapterSettings.class) -public class KafkaAdapterConfig { - - @Bean - @ConditionalOnProperty(name = "app.messaging.broker", havingValue = "kafka") - public MessageBroker kafkaMessageBroker(KafkaSender sender, KafkaAdapterSettings settings) { - if (settings.brokers().isEmpty()) { - throw new IllegalStateException( - "app.messaging.broker=kafka requires a non-empty app.messaging.kafka.brokers " - + "(CSV of host:port)"); - } - return new KafkaMessageBroker(sender); - } -} diff --git a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaAdapterSettings.java b/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaAdapterSettings.java deleted file mode 100644 index 82a49359..00000000 --- a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaAdapterSettings.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.kafka; - -import java.util.List; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * Kafka broker tuning bound from {@code app.messaging.kafka.*}. - * - *

Each entry is parsed into a {@link BrokerAddress} and stored in its canonical form. The - * previous binding validated the trimmed value with a regular expression and then stored the - * untrimmed original, so a configured {@code " kafka:9092"} passed the check and reached the client - * with its leading space; the same expression accepted port {@code 0} and port {@code 99999}, and - * could not express a bracketed IPv6 literal. - * - *

The "Kafka selected implies brokers required" cross-field rule stays in {@code - * KafkaAdapterConfig}, so an empty list is still valid at bind time. - * - * @param brokers CSV of {@code host:port} broker endpoints, canonicalised - */ -@ConfigurationProperties(prefix = "app.messaging.kafka") -public record KafkaAdapterSettings(List brokers) { - - /** Parses and canonicalises every configured entry. */ - public KafkaAdapterSettings { - List configured = (brokers == null) ? List.of() : List.copyOf(brokers); - brokers = - configured.stream() - .map( - entry -> { - try { - return BrokerAddress.parse(entry).canonical(); - } catch (IllegalArgumentException invalid) { - throw new IllegalArgumentException( - "APP_MESSAGING_KAFKA_BROKERS " + invalid.getMessage(), invalid); - } - }) - .toList(); - } - - /** - * The parsed addresses, for callers that need the components rather than the text. - * - * @return one address per configured entry - */ - public List addresses() { - return brokers.stream().map(BrokerAddress::parse).toList(); - } -} diff --git a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaMessageBroker.java b/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaMessageBroker.java deleted file mode 100644 index 0fc70bd3..00000000 --- a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaMessageBroker.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.kafka; - -import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; -import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage; - -/** - * Kafka contribution of the {@link MessageBroker} SPI (brokerId {@code "kafka"}). Delegates the raw - * send to the project-supplied {@link KafkaSender} seam; the fail-open (general) and fail-closed - * (outbox) policies are applied by the binding decorators in the messaging package, not here — so - * this class carries no policy and no Kafka SDK. - */ -public class KafkaMessageBroker implements MessageBroker { - - private static final String BROKER_ID = "kafka"; - - private final KafkaSender sender; - - public KafkaMessageBroker(KafkaSender sender) { - this.sender = sender; - } - - @Override - public String brokerId() { - return BROKER_ID; - } - - @Override - public void send(OutboundMessage message) throws Exception { - sender.send(message); - } -} diff --git a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSender.java b/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSender.java deleted file mode 100644 index dbb031d2..00000000 --- a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSender.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.kafka; - -import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage; - -/** - * Integration seam the forking project implements to bind the Kafka template to a real producer. - * The skeleton carries no Kafka SDK dependency — it is added by the project that enables Kafka. A - * send failure may throw; the binding decorator applies the failure policy. - */ -@FunctionalInterface -public interface KafkaSender { - - /** - * Sends a message to the broker. May throw on any transport/broker failure. - * - * @throws Exception on any send failure (caught and handled fail-open by the publisher) - */ - void send(OutboundMessage message) throws Exception; -} diff --git a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderAutoConfiguration.java b/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderAutoConfiguration.java deleted file mode 100644 index 3b81ade8..00000000 --- a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderAutoConfiguration.java +++ /dev/null @@ -1,120 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.kafka; - -import java.time.Duration; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.Producer; -import org.apache.kafka.clients.producer.ProducerConfig; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.common.serialization.StringSerializer; -import org.springframework.beans.factory.annotation.Qualifier; -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; - -/** - * The adapter-owned broker bridge behind {@link KafkaSender} (MSG-INT-003). - * - *

{@code KafkaSender} is documented as an integration seam for a forking project, and the - * skeleton supplied no implementation of it — only a test fake. So selecting {@code - * app.messaging.broker=kafka} against a healthy broker failed startup on a missing bean, and the - * messaging capability had no way to reach a broker in any deployment. A seam with no production - * implementation anywhere is indistinguishable from an unimplemented feature. - * - *

It stays a seam and is owned by the outbound messaging adapter. The bean backs off entirely to - * anything a forking project defines, and it is registered only when Kafka is the selected broker — - * so a deployment with messaging off, or on a different broker, carries no producer, no connection - * and no background sender thread. - * - *

{@code kafka-clients} rather than {@code spring-kafka}: the seam takes one already-serialized - * message and returns nothing, so a listener container, a converter stack and a template would all - * be unused weight on the classpath of every deployment. - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnProperty(name = "app.messaging.broker", havingValue = "kafka") -public class KafkaSenderAutoConfiguration { - - /** - * The producer, configured so a send that returns has actually been accepted. - * - *

{@code acks=all} with idempotence, because the seam's contract is that a normal return means - * the broker took the message. A producer with {@code acks=1} returns before replication and a - * non-idempotent one can duplicate on internal retry; either would make a successful return mean - * less than the callers of this seam assume. - * - *

Named and conditioned by name, not by type. The messaging platform's own {@code - * KafkaMessagingAutoConfiguration} declares a {@code Producer} bean too — a {@code - * Producer} for its transport, against a different switch — and the two shipped - * together the moment the platform facade joined the runtime classpath. Sharing the method name - * {@code messagingKafkaProducer} made the context refuse to start with a {@code - * BeanDefinitionOverrideException}, and a type-scoped {@code @ConditionalOnMissingBean} would - * have been worse: whichever configuration lost the race would leave its own stack without a - * producer while the other stack's, with incompatible serializers, sat in its place. - * - * @param settings the broker addresses, already validated as non-empty when Kafka is selected - * @return the producer, closed on context shutdown - */ - @Bean(name = "kafkaSeamProducer", destroyMethod = "close") - @ConditionalOnMissingBean(name = "kafkaSeamProducer") - public Producer kafkaSeamProducer(KafkaAdapterSettings settings) { - Map config = new HashMap<>(); - config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, String.join(",", settings.brokers())); - config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); - config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); - config.put(ProducerConfig.ACKS_CONFIG, "all"); - config.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true); - // Bounded, so a broker that stops answering surfaces as a failed send rather than as a caller - // blocked for the default two minutes inside a dispatch worker. - // - // All three are stated, not two of three. Kafka enforces - // delivery.timeout.ms >= linger.ms + request.timeout.ms and refuses to construct the producer - // otherwise; setting only the delivery timeout left request.timeout.ms at its default and the - // sum came out exactly equal, which the check rejects. - config.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, 10_000); - config.put(ProducerConfig.LINGER_MS_CONFIG, 0); - config.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, 15_000); - config.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 30_000); - return new KafkaProducer<>(config); - } - - /** - * The seam itself. - * - *

Waits for the broker's acknowledgement rather than returning on enqueue. {@code - * Producer.send} is asynchronous and returns a future the moment the record is buffered, so a - * fire-and-forget implementation would satisfy the seam's signature while reporting success for a - * message the broker never saw — and the publisher above it applies a failure policy it would - * then never be given the chance to apply. - * - * @param producer the configured producer - * @return the sender - */ - @Bean - @ConditionalOnMissingBean(KafkaSender.class) - public KafkaSender kafkaSender( - @Qualifier("kafkaSeamProducer") Producer producer) { - Duration ackTimeout = Duration.ofSeconds(30); - return message -> { - try { - producer - .send( - new ProducerRecord<>( - message.topic(), - // An empty key means "no key" to Kafka, which is round-robin partitioning. The - // seam models an absent key as the empty string, and passing that through as a - // literal key would put every unkeyed message on one partition. - message.key().isEmpty() ? null : message.key(), - message.payload())) - .get(ackTimeout.toMillis(), TimeUnit.MILLISECONDS); - } catch (InterruptedException interrupted) { - // Future.get cleared the flag when it threw, and the callers above catch Exception. Without - // restoring it, a relay being shut down kept waiting out every remaining row's timeout. - Thread.currentThread().interrupt(); - throw interrupted; - } - }; - } -} diff --git a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/LegacyKafkaMessagingRootAutoConfiguration.java b/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/LegacyKafkaMessagingRootAutoConfiguration.java deleted file mode 100644 index 6cddad81..00000000 --- a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/LegacyKafkaMessagingRootAutoConfiguration.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.kafka; - -import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Import; - -/** - * Build-time Kafka capability for the legacy R0 messaging seam. - * - *

The broker-neutral messaging bridge no longer imports Kafka classes. An application that still - * needs the R0 Kafka seam must deliberately add this leaf; only then can the Kafka producer/client - * enter its runtime graph. Present means on; {@code app.messaging.enabled=false} turns it off. - */ -@AutoConfiguration -@ConditionalOnProperty( - prefix = "app.messaging", - name = "enabled", - havingValue = "true", - matchIfMissing = true) -@Import({KafkaSenderAutoConfiguration.class, KafkaAdapterConfig.class}) -public class LegacyKafkaMessagingRootAutoConfiguration {} diff --git a/src/adapter/outbound/messaging-kafka/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/outbound/messaging-kafka/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports deleted file mode 100644 index b9b6bc19..00000000 --- a/src/adapter/outbound/messaging-kafka/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ /dev/null @@ -1 +0,0 @@ -dev.caskeleton.adapter.outbound.messaging.kafka.LegacyKafkaMessagingRootAutoConfiguration diff --git a/src/adapter/outbound/messaging-kafka/src/main/resources/config/module-defaults/messaging.yml b/src/adapter/outbound/messaging-kafka/src/main/resources/config/module-defaults/messaging.yml index f095acce..ce8b6d8a 100644 --- a/src/adapter/outbound/messaging-kafka/src/main/resources/config/module-defaults/messaging.yml +++ b/src/adapter/outbound/messaging-kafka/src/main/resources/config/module-defaults/messaging.yml @@ -7,10 +7,11 @@ app: messaging: # true | false — 모듈이 있으면 켜진다. false 로만 끈다. enabled: ${APP_MESSAGING_ENABLED:true} - # 이 모듈을 고른 서비스는 Kafka 를 쓴다. 등록된 broker 는 kafka 하나다. + # messaging platform 이 쓸 broker. 등록된 broker 는 kafka 하나다. broker: ${APP_MESSAGING_BROKER:kafka} - # canonical IntegrationEventPublishPort bridge 의 producer id. 비어 있으면 bridge 가 없다. - # host/pod/process 이름에서 추측하지 않는다. + # canonical IntegrationEventPublishPort bridge 의 producer id. 모든 발행(outbox relay 포함)이 이 + # bridge 를 지나므로 켜진 상태에서 비어 있으면 기동이 실패한다. host/pod/process 이름에서 추측하지 + # 않는다. producer-id: ${APP_MESSAGING_PRODUCER_ID:} # messaging platform 의 Kafka transport 가 연결하는 broker. 논리 이름은 kafka 하나다. # 비어 있으면 기동이 실패한다(app.messaging.brokers.kafka.bootstrap-servers). @@ -18,9 +19,6 @@ app: kafka: type: kafka bootstrap-servers: ${APP_MESSAGING_KAFKA_BROKERS:} - kafka: - # CSV host:port. 같은 주소를 legacy KafkaSender seam 에도 준다. - brokers: ${APP_MESSAGING_KAFKA_BROKERS:} # /actuator/info 에 싣는 이 모듈의 상태(management.info.env). compose smoke 가 lane 이 실제로 켠 # capability 를 이 값으로 확인한다. 위 스위치를 해석한 값이고, 기본값은 messaging root diff --git a/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/BrokerAddressTest.java b/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/BrokerAddressTest.java deleted file mode 100644 index cbe75d14..00000000 --- a/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/BrokerAddressTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.kafka; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * What counts as a broker endpoint. - * - *

The regular expression that decided this ran against the trimmed value and then stored the - * untrimmed original, accepted port 0 and port 99999, and could not express a bracketed IPv6 - * literal at all — so the only correct way to write an IPv6 endpoint was rejected while an - * ambiguous one was accepted. - */ -class BrokerAddressTest { - - @Test - @DisplayName("an ordinary endpoint parses and canonicalises") - void anOrdinaryEndpointParses() { - BrokerAddress address = BrokerAddress.parse("kafka-1.internal:9092"); - - assertThat(address.host()).isEqualTo("kafka-1.internal"); - assertThat(address.port()).isEqualTo(9092); - assertThat(address.canonical()).isEqualTo("kafka-1.internal:9092"); - } - - @Test - @DisplayName("surrounding whitespace is removed rather than validated away and kept") - void surroundingWhitespaceIsRemoved() { - assertThat(new KafkaAdapterSettings(List.of(" kafka:9092 ")).brokers()) - .as("the old binding validated the trimmed value and stored the untrimmed one") - .containsExactly("kafka:9092"); - } - - @Test - @DisplayName("whitespace inside the host is refused") - void whitespaceInsideTheHostIsRefused() { - assertThatThrownBy(() -> BrokerAddress.parse("kaf ka:9092")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("whitespace"); - } - - @Test - @DisplayName("the port range is 1 to 65535") - void thePortRangeIsOneToSixtyFiveThousand() { - assertThatCode(() -> BrokerAddress.parse("kafka:1")).doesNotThrowAnyException(); - assertThatCode(() -> BrokerAddress.parse("kafka:65535")).doesNotThrowAnyException(); - - assertThatThrownBy(() -> BrokerAddress.parse("kafka:0")) - .as("port 0 asks the operating system to choose, which a client cannot connect to") - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> BrokerAddress.parse("kafka:65536")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> BrokerAddress.parse("kafka:99999")) - .as("the five-digit pattern accepted this") - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a bracketed IPv6 literal is accepted and stays bracketed") - void aBracketedIpv6LiteralIsAccepted() { - BrokerAddress address = BrokerAddress.parse("[2001:db8::1]:9092"); - - assertThat(address.host()).isEqualTo("2001:db8::1"); - assertThat(address.port()).isEqualTo(9092); - assertThat(address.ipv6Literal()).isTrue(); - assertThat(address.canonical()).isEqualTo("[2001:db8::1]:9092"); - } - - @Test - @DisplayName("a bare IPv6 literal is refused because it is ambiguous") - void aBareIpv6LiteralIsRefused() { - assertThatThrownBy(() -> BrokerAddress.parse("2001:db8::1:9092")) - .as("which colon separates the port is not decidable, so brackets are required") - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("[::1]:9092"); - } - - @Test - @DisplayName("a bracketed host with no port is refused") - void aBracketedHostWithNoPortIsRefused() { - assertThatThrownBy(() -> BrokerAddress.parse("[2001:db8::1]")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> BrokerAddress.parse("[2001:db8::1]9092")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("an entry with no port at all is refused") - void anEntryWithNoPortIsRefused() { - assertThatThrownBy(() -> BrokerAddress.parse("kafka")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("host:port"); - assertThatThrownBy(() -> BrokerAddress.parse("kafka:")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> BrokerAddress.parse("kafka:http")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> BrokerAddress.parse(":9092")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("the settings binding reports which entry is wrong") - void theSettingsBindingReportsWhichEntryIsWrong() { - assertThatThrownBy(() -> new KafkaAdapterSettings(List.of("kafka-1:9092", "kafka-2:0"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("APP_MESSAGING_KAFKA_BROKERS") - .hasMessageContaining("kafka-2:0"); - } - - @Test - @DisplayName("an absent broker list is empty, not a failure") - void anAbsentBrokerListIsEmpty() { - assertThat(new KafkaAdapterSettings(null).brokers()).isEmpty(); - } -} diff --git a/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaAdapterSettingsTest.java b/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaAdapterSettingsTest.java deleted file mode 100644 index e563e3e3..00000000 --- a/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaAdapterSettingsTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.kafka; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.Test; - -class KafkaAdapterSettingsTest { - - @Test - void emptyOrNullBrokersIsTolerated() { - // bound globally via @ConfigurationPropertiesScan even when Kafka is not the active - // broker — an empty list must bind cleanly (the "required" guard lives in the config). - assertThat(new KafkaAdapterSettings((List) null).brokers()).isEmpty(); - assertThat(new KafkaAdapterSettings(List.of()).brokers()).isEmpty(); - } - - @Test - void rejectsABrokerThatIsNotHostPort() { - assertThatThrownBy(() -> new KafkaAdapterSettings(List.of("not-a-broker"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("host:port"); - } - - @Test - void acceptsCsvOfHostPortBrokers() { - KafkaAdapterSettings settings = - new KafkaAdapterSettings(List.of("broker-1:9092", "broker-2:9092")); - assertThat(settings.brokers()).containsExactly("broker-1:9092", "broker-2:9092"); - } - - @Test - void brokersListIsDefensivelyCopied() { - List mutable = new ArrayList<>(List.of("broker-1:9092")); - KafkaAdapterSettings settings = new KafkaAdapterSettings(mutable); - mutable.add("broker-2:9092"); - assertThat(settings.brokers()).containsExactly("broker-1:9092"); - } -} diff --git a/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaCapabilityActivationTest.java b/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaCapabilityActivationTest.java index 319225f7..0f7b5ae5 100644 --- a/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaCapabilityActivationTest.java +++ b/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaCapabilityActivationTest.java @@ -1,17 +1,14 @@ package dev.caskeleton.adapter.outbound.messaging.kafka; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; -import dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher; -import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; -import dev.caskeleton.adapter.outbound.messaging.core.MessagePublisher; -import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessagePublisher; import dev.caskeleton.adapter.outbound.messaging.outbox.OutboxMessagePublishAdapter; import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.messaging.schema.EncodedMessagePublisher; import java.util.Arrays; +import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -28,30 +25,38 @@ import org.springframework.context.annotation.Configuration; class KafkaCapabilityActivationTest { @Test - void presentModuleIsOnAndPublishesThroughKafka() { - // given — only the broker address; everything else is the module's own default + void presentModulePublishesEveryOutboxRowThroughTheCanonicalPlatformBridge() { + // given — the broker address and the producer identity; everything else is the module's default try (ConfigurableApplicationContext context = start("--APP_MESSAGING_KAFKA_BROKERS=localhost:1", "--APP_MESSAGING_PRODUCER_ID=orders")) { // then - assertThat(context.getBean(MessageBroker.class)).isInstanceOf(KafkaMessageBroker.class); - assertThat(context.getBean(MessagePublisher.class)) - .isInstanceOf(OutboundMessagePublisher.class); - assertThat(context.getBean(OutboxMessagePublishPort.class)) - .isInstanceOf(OutboxMessagePublishAdapter.class); - assertThat(context.getBeanNamesForType(EncodedMessagePublisher.class)).hasSize(1); - assertThat(context.getBeanNamesForType(IntegrationEventPublishPort.class)).hasSize(1); + assertThat( + List.of( + context.getBean(OutboxMessagePublishPort.class).getClass(), + context.getBeanNamesForType(EncodedMessagePublisher.class).length, + context.getBeanNamesForType(IntegrationEventPublishPort.class).length)) + .containsExactly(OutboxMessagePublishAdapter.class, 1, 1); } } @Test void presentModuleWithoutABrokerAddressRefusesToStart() { - assertThatThrownBy(() -> start().close()) - .satisfiesAnyOf( - failure -> - assertThat(failure) - .hasStackTraceContaining("app.messaging.brokers.kafka.bootstrap-servers"), - failure -> assertThat(failure).hasStackTraceContaining("app.messaging.kafka.brokers")); + // when + Throwable thrown = catchThrowable(() -> start("--APP_MESSAGING_PRODUCER_ID=orders").close()); + + // then + assertThat(thrown).hasStackTraceContaining("app.messaging.brokers.kafka.bootstrap-servers"); + } + + @Test + void presentModuleWithoutAProducerIdRefusesToStartBecauseNothingCouldPublish() { + // when + Throwable thrown = + catchThrowable(() -> start("--APP_MESSAGING_KAFKA_BROKERS=localhost:1").close()); + + // then + assertThat(thrown).hasStackTraceContaining("no IntegrationEventPublishPort exists"); } @Test @@ -68,7 +73,6 @@ class KafkaCapabilityActivationTest { || name.startsWith("dev.caskeleton.adapter.outbound.messaging.") || name.startsWith("org.apache.kafka."))) .isEmpty(); - assertThat(context.getBeanNamesForType(DisabledMessagePublisher.class)).isEmpty(); } } diff --git a/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderAutoConfigurationOwnershipTest.java b/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderAutoConfigurationOwnershipTest.java deleted file mode 100644 index ed67183c..00000000 --- a/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderAutoConfigurationOwnershipTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.kafka; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import org.junit.jupiter.api.Test; -import org.springframework.context.annotation.Import; - -class KafkaSenderAutoConfigurationOwnershipTest { - @Test - void kafkaCapabilityRootOwnsTheProductionKafkaSenderInsideTheAdapter() { - Import imports = LegacyKafkaMessagingRootAutoConfiguration.class.getAnnotation(Import.class); - - assertThat(imports).isNotNull(); - assertThat(Arrays.asList(imports.value())) - .contains(KafkaSenderAutoConfiguration.class, KafkaAdapterConfig.class); - } -} diff --git a/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderInterruptionTest.java b/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderInterruptionTest.java deleted file mode 100644 index 16ec4b11..00000000 --- a/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderInterruptionTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.kafka; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; - -import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage; -import org.apache.kafka.clients.producer.MockProducer; -import org.apache.kafka.common.serialization.StringSerializer; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -class KafkaSenderInterruptionTest { - - @AfterEach - void clearInterrupt() { - Thread.interrupted(); - } - - /** - * An interrupted wait for the broker's acknowledgement leaves the thread interrupted. - * - *

{@code Future.get} clears the flag when it throws, and the callers above this seam catch - * {@code Exception}. So the interrupt that was meant to stop a relay during shutdown vanished, - * and the relay spent up to thirty seconds on every remaining row. - */ - @Test - void anInterruptedAcknowledgementWaitRethrowsWithTheInterruptFlagRestored() { - // given - KafkaSender sender = - new KafkaSenderAutoConfiguration() - .kafkaSender( - new MockProducer<>(false, null, new StringSerializer(), new StringSerializer())); - Thread.currentThread().interrupt(); - - // when - Throwable thrown = catchThrowable(() -> sender.send(new OutboundMessage("topic", "k", "v"))); - - // then - assertThat(new Object[] {thrown.getClass(), Thread.currentThread().isInterrupted()}) - .containsExactly(InterruptedException.class, true); - } -} diff --git a/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/LegacyKafkaAutoConfigurationRegistrationTest.java b/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/LegacyKafkaAutoConfigurationRegistrationTest.java deleted file mode 100644 index c20ba121..00000000 --- a/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/LegacyKafkaAutoConfigurationRegistrationTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.kafka; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; -import java.io.UncheckedIOException; -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.core.annotation.AnnotatedElementUtils; - -/** - * This leaf's auto-configurations are registered, not merely annotated. - * - *

Spring Boot needs two independent things before an auto-configuration runs: the annotation on - * the class, and a line naming it in {@code META-INF/spring/...AutoConfiguration.imports}. Tests - * that build a context with {@code AutoConfigurations.of(...)} supply the second one themselves, so - * they stay green for a capability that is present in no running application — which is exactly how - * several capabilities in this repository came to be assembled by nothing. - * - *

So this reads the registration file the jar actually ships and asserts both directions: every - * class this leaf means to register is named in it, and every name in it resolves to a class that - * carries {@code @AutoConfiguration}. A rename, a move or a deleted line fails here rather than in - * a deployment that starts and quietly does less than it says. - */ -class LegacyKafkaAutoConfigurationRegistrationTest { - - private static final String IMPORTS_RESOURCE = - "META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports"; - - /** The auto-configurations this leaf publishes. */ - private static final List PUBLISHED_ROOTS = - List.of( - "dev.caskeleton.adapter.outbound.messaging.kafka.LegacyKafkaMessagingRootAutoConfiguration"); - - @Test - @DisplayName("the shipped registration file names every root this leaf publishes") - void theShippedRegistrationFileNamesEveryRoot() { - assertThat(registeredNames()) - .as("the registration lines this leaf's own jar ships") - .containsAll(PUBLISHED_ROOTS); - } - - @Test - @DisplayName("every registered name resolves to a real Boot auto-configuration") - void everyRegisteredNameResolvesToAnAutoConfiguration() { - for (String name : registeredNames()) { - Class registered; - try { - registered = - Class.forName( - name, false, LegacyKafkaAutoConfigurationRegistrationTest.class.getClassLoader()); - } catch (ClassNotFoundException missing) { - throw new AssertionError( - IMPORTS_RESOURCE + " registers " + name + ", which does not exist", missing); - } - assertThat(AnnotatedElementUtils.hasAnnotation(registered, AutoConfiguration.class)) - .as("%s is registered but is not annotated @AutoConfiguration", name) - .isTrue(); - } - } - - /** - * The registration lines this leaf's own resource declares. - * - *

Read from this leaf's source tree rather than from the classpath. {@code - * ClassLoader#getResources} returns every registration file on the test runtime classpath — - * Spring Boot's, springdoc's, and every dependency leaf's — so asserting over that set tests - * other people's modules and fails on their conditional classes. The file below is the one this - * leaf packages, which is the thing this contract is about. - */ - private static List registeredNames() { - Path resource = leafRoot().resolve("src/main/resources/" + IMPORTS_RESOURCE); - assertThat(Files.isRegularFile(resource)).as("%s", resource).isTrue(); - List names; - try { - names = - Files.readAllLines(resource, StandardCharsets.UTF_8).stream() - .map(String::strip) - .filter(line -> !line.isEmpty() && !line.startsWith("#")) - .toList(); - } catch (IOException failure) { - throw new UncheckedIOException("cannot read " + resource, failure); - } - assertThat(names).as("%s registers nothing", resource).isNotEmpty(); - return names; - } - - /** The nearest directory above the test's working directory that ships a registration file. */ - private static Path leafRoot() { - for (Path path = Path.of("").toAbsolutePath(); path != null; path = path.getParent()) { - if (Files.isRegularFile(path.resolve("src/main/resources/" + IMPORTS_RESOURCE))) { - return path; - } - } - throw new IllegalStateException( - "no leaf shipping " + IMPORTS_RESOURCE + " found above " + Path.of("").toAbsolutePath()); - } -} diff --git a/src/adapter/outbound/messaging/CLAUDE.md b/src/adapter/outbound/messaging/CLAUDE.md index 6819c1fd..f7f0bba6 100644 --- a/src/adapter/outbound/messaging/CLAUDE.md +++ b/src/adapter/outbound/messaging/CLAUDE.md @@ -26,23 +26,24 @@ Package root: `dev.caskeleton.adapter.outbound.messaging`. - The canonical platform bridge may depend only on `messaging-core-api` and `messaging-schema-api`; do not import `messaging-runtime-core`, transport SPI implementations, or broker SDK types under `platformbridge/`. -- `KafkaSender` / `MessageBroker` are transitional legacy R0 seams for `OutboxEvent` and realtime - compatibility only. Do not route new canonical integration-event publication through them. +- There is one publication path: `OutboxMessagePublishAdapter` → `IntegrationEventPublishPort` → + the platform bridge. The legacy `KafkaSender` / `MessageBroker` R0 seam and the fail-open + `MessagePublisher` were removed with the canonical outbox (2026-09-28); do not reintroduce a + second path. - Canonical producer identity is explicit `app.messaging.producer-id`; never derive it from - `spring.application.name`, host, pod, or process identity. -- The template ships no `IntegrationEventEncoderPort` implementation. The R1 contract compiler, - binding compiler, JSON Schema envelope encoder and capability card registry (`contract/`, - `destination/`, `envelope/`, `config/`) and the durable realtime fan-out adapter (`realtime/`) - were removed on 2026-09-25 (see `docs/capability-status.md`); an adopter that turns on canonical - transport provides its own encoder. + `spring.application.name`, host, pod, or process identity. With the module on and no bridge, + startup is refused — the relay would have nothing to publish through. +- The template's `IntegrationEventEncoderPort` (`JsonIntegrationEventEncoder`) lives in + `adapter:outbound:support`, not here: a use case encodes before it appends, in compositions that + may not carry this module. The R1 contract/binding compilers and JSON Schema envelope encoder were + removed on 2026-09-25 (see `docs/capability-status.md`). - No JSON Schema engine (NetworkNT) here. The evidence manifest schema check moved to build-tools (`VerifyMessagingEvidenceTask`). - Do not hide use-case sequencing or business routing policy in broker adapters. -- `OutboxMessagePublishAdapter` is mapping/send-only and emits no dependency log. The confirmed - FAILED/DEAD transition owns the one canonical ERROR; only the general fail-open publisher keeps - `FailOpenDependencyLogger`. +- `OutboxMessagePublishAdapter` is delegate-only and emits no dependency log. The confirmed + FAILED/DEAD transition owns the one canonical ERROR. ## Tests -Use unit/contract tests with fake broker senders. No real network or broker is used in focused tests; -settings records receive binding/validation tests when configuration changes. +Use unit/contract tests with a fake canonical publisher. No real network or broker is used in +focused tests; settings records receive binding/validation tests when configuration changes. diff --git a/src/adapter/outbound/messaging/README.md b/src/adapter/outbound/messaging/README.md index 8678c3fe..9d54608f 100644 --- a/src/adapter/outbound/messaging/README.md +++ b/src/adapter/outbound/messaging/README.md @@ -1,9 +1,8 @@ # adapter:outbound:messaging — 설계 결정 참조 -메시징(broker publish + outbox) 아웃바운드 어댑터 모듈. 패키지 루트: -`dev.caskeleton.adapter.outbound.messaging`. `:adapter:outbound:support` 에 의존해 공유 -correlation / fail-open 의존성 로깅을 일반 publisher에서 재사용한다. outbox relay 실패는 이 -모듈이 별도의 typed report adapter로 구조화한다. +메시징(broker publish + outbox relay 발행) 아웃바운드 어댑터 모듈. 패키지 루트: +`dev.caskeleton.adapter.outbound.messaging`. outbox relay 실패는 이 모듈이 별도의 typed report +adapter로 구조화한다. 허용/금지 의존 정책은 `src/config/architecture/modules.json`과 이 모듈의 [CLAUDE.md](CLAUDE.md)가 소유한다. 이 문서는 코드 주석에서 덜어낸 **설계 결정의 근거**를 모아둔 @@ -11,110 +10,70 @@ correlation / fail-open 의존성 로깅을 일반 publisher에서 재사용한 ## 모듈 개요 -application-core의 legacy 포트(`MessagePublisher` / `OutboxMessagePublishPort`)와 canonical -`IntegrationEventPublishPort` 뒤에 두는 **선택형** 연동 어댑터다. 서비스는 이 모듈을 직접 고르지 않고 +application-core의 `OutboxMessagePublishPort`와 canonical `IntegrationEventPublishPort` 뒤에 두는 +**선택형** 연동 어댑터다. 서비스는 이 모듈을 직접 고르지 않고 `runtimeOnly project(':adapter:outbound:messaging-kafka')` 한 줄로 받는다(추가할 한 줄·env 키는 [messaging-kafka README](../messaging-kafka/README.md)). 모듈이 있으면 켜지고 -`app.messaging.enabled=false`로만 끈다. broker가 없을 때의 legacy 바인딩은 `Disabled*` 구현으로 -fail-fast 한다(Layer 3). +`app.messaging.enabled=false`로만 끈다. -canonical path는 `platformbridge/PlatformIntegrationEventPublishAdapter`가 -`EncodedMessagePublisher`에 위임한다. 이 path는 broker SDK나 transport SPI를 직접 보지 않는다. -`KafkaSender`/`MessageBroker`는 metadata가 부족한 legacy `OutboxEvent`/realtime 경로의 transitional -R0 seam으로만 남아 있고, legacy storage/relay cutover와 함께 제거한다. +발행 경로는 하나다. -## Legacy 두 포트와 canonical platform bridge +`OutboxMessagePublishPort → OutboxMessagePublishAdapter → IntegrationEventPublishPort → +PlatformIntegrationEventPublishAdapter → EncodedMessagePublisher` -`MessagingConfig`는 legacy 두 messaging 포트를 단일 활성 `MessageBroker` 위에 조립한다. 이 경로는 -기존 `OutboxEvent`/realtime compatibility를 위해 남아 있다. +bridge는 broker SDK나 transport SPI를 직접 보지 않는다. legacy `KafkaSender`/`MessageBroker` R0 +seam과 그 위의 `MessagePublisher`·`OutboxEnvelopeJson`은 outbox를 canonical 하나로 통일하면서 +삭제했다(2026-09-28, 소유자 결정 7). -canonical `IntegrationEventPublishPort`는 별도 경로다. +## canonical platform bridge -`IntegrationEventPublishPort → PlatformIntegrationEventPublishAdapter → EncodedMessagePublisher` +`IntegrationEventPublishPort`는 `app.messaging.producer-id`가 명시되고 platform publisher bean이 +있을 때만 생성된다. exact `ValidatedIntegrationEvent.envelopeBytes()`를 보존하고 platform의 중앙 +publish pipeline을 탄다. producer id는 host/pod/process 이름에서 추측하지 않는다. -`app.messaging.producer-id`가 명시되고 platform publisher bean이 있을 때만 생성된다. exact -`ValidatedIntegrationEvent.envelopeBytes()`를 보존하고 platform의 중앙 publish pipeline을 탄다. - -MSG-015 transport-only 단계에서는 legacy relay authority도 이 bridge를 사용할 수 있다. -`OutboxMessagePublishAdapter`가 claim subtype으로 경로를 분리해서 legacy `OutboxEvent`는 기존 -`MessageBroker`, `CanonicalClaimedOutboxEvent`는 `IntegrationEventPublishPort`만 호출한다. 한 row가 두 -transport로 fallback/dual-publish되지 않는다. mixed-row 기간에는 old backlog를 보존하기 위해 legacy -broker requirement도 유지한다. - -## broker 선택 검증 - -`app.messaging.broker` 가 설정됐는데 `MessageBroker` 빈이 없으면 startup 을 명시적 메시지로 -실패시킨다(조용한 no-op 아님). settings 와 활성 빈의 `brokerId()` 불일치도 startup 실패다. +`OutboxMessagePublishAdapter`는 claim된 row의 validated event를 그대로 bridge에 넘기고 platform의 +네 가지 결과(CONFIRMED·AMBIGUOUS·REJECTED_BEFORE_SEND·REJECTED_AFTER_BROKER)를 relay에 돌려준다. +다시 직렬화하지 않는다. ## outbox 발행 포트에는 대역이 없다 `OutboxMessagePublishPort`의 대역(항상 던지는 publisher)은 두지 않는다. 대역도 bean이므로 relay 스케줄러의 조건을 채우고, relay는 모든 PENDING 행을 그 대역에 실패시켜 DEAD로 소진한다. 그래서 -모듈이 있고 켜져 있는데 broker가 비어 있고 canonical transport도 없으면 startup을 거부한다. -`DisabledMessagePublisher`(일반 발행기의 fail-fast 대역)는 남아 있다 — relay가 쓰지 않는다. +모듈이 있고 켜져 있는데 `IntegrationEventPublishPort`가 없으면(producer id가 비었거나 platform +transport가 없으면) startup을 거부한다. -## OutboxEnvelopeJson — 손수 짠 JSON - -이 모듈은 `jackson-databind` 를 classpath 에 두지 않아(스켈레톤을 가볍게 유지) outbox envelope -직렬화는 의존성 없는 손수 짠 JSON 이다. - -## MessagePublisher vs OutboxMessagePublishPort - -`MessagePublisher` 는 fail-open 어댑터-로컬 발행기로, 발행 실패를 correlationId 와 함께 -로깅하고 삼켜(→ `:adapter:outbound:support` 의 `FailOpenDependencyLogger`) outbox/retry 로 -위임하므로 core 5xx 가 되지 않는다. 내구성 있는 전달이 필요하면 `OutboxMessagePublishPort` 를 -쓴다. `OutboxMessagePublishAdapter`는 envelope mapping + broker send만 수행하며 runtime 예외를 -그대로 전파하고 checked 예외는 cause를 보존해 감싼다. 성공 DEBUG나 실패 WARN을 남기지 않는다. -반환 타입을 void 로 둬 broker SDK 타입이 어댑터 밖으로 새지 않는다(B7). - -## Legacy R0 characterization - -현재 `KafkaSender.send(...)`와 `MessageBroker.send(...)`의 정상 void 반환은 호출이 예외 없이 -끝났다는 뜻일 뿐 broker acknowledgement 증거가 아니다. relay는 이 정상 반환 뒤 legacy -`PUBLISHED`를 기록한다. sender 예외는 fail-closed outbox 경로에서 전파되어 relay의 -`FAILED/DEAD` 전이를 유발한다. - -broker 설정이 blank면 `MessagePublisher`는 `DisabledMessagePublisher`에 바인딩되고, canonical -transport도 없으면 startup이 실패한다. broker를 선택했지만 project-supplied sender가 없거나 선택 -ID와 활성 `MessageBroker.brokerId()`가 다르면 startup이 실패한다. +## 중복 가능 구간 publisher 정상 반환 뒤 DB mark가 실패하면 row는 `IN_FLIGHT`에 남아 timeout reclaim 후 같은 -event가 다시 publish될 수 있다. 현재 consumer/inbox가 없으므로 이 duplicate 가능 구간을 -중복 안전 전달로 표현하지 않는다. 또한 legacy FIFO gate는 `occurred_at`의 strict less-than 비교만 -사용하므로 동일 aggregate의 timestamp 동률 row는 서로를 gate하지 않는다. +event가 다시 publish될 수 있다. 같은 event id로 다시 나가므로 consumer는 event id로 중복을 걸러야 +한다. 같은 aggregate의 row는 `(aggregate_sequence, event_index)` 순서로 하나씩 풀린다. ## OutboxRelayFailureReport 구조화 ERROR -`MessagingConfig`는 broker 활성 여부와 무관하게 정확히 하나의 -`Slf4jOutboxRelayFailureReportAdapter`를 등록한다. broker 설정이 blank면 안전한 -`dependency_name=disabled`를 쓴다. 이 adapter는 confirmed FAILED/DEAD report 하나를 SLF4J 2 fluent +`MessagingConfig`는 정확히 하나의 `Slf4jOutboxRelayFailureReportAdapter`를 등록한다. +`dependency_name`은 platform이 쓰는 broker 선택값(`app.messaging.broker`, 기본 `kafka`)이고, 비어 +있으면 `messaging-platform`이다. 이 adapter는 confirmed FAILED/DEAD report 하나를 SLF4J 2 fluent ERROR 하나로 렌더링한다. 공통 field는 `error.code`, `error.category`, `dependency_name`, `dependency_type=messaging`, `outcome`, `event_id`, `event_type`, `aggregate_id`, `correlation_id`, `attempt_count`, `runbook_link`다. retry report만 `next_attempt_at`을 추가한다. -payload/idempotency key/envelope/exception-derived field는 받거나 렌더링하지 않고 cause만 throwable로 -붙인다. logging 내부 `RuntimeException`은 adapter와 use case 양쪽에서 방어하므로 persisted -FAILED/DEAD outcome을 바꾸지 않는다. +payload/envelope/exception-derived field는 받거나 렌더링하지 않는다. logging 내부 +`RuntimeException`은 adapter와 use case 양쪽에서 방어하므로 persisted FAILED/DEAD outcome을 바꾸지 +않는다. -## 제거된 R1 encoder 체인 (2026-09-25) +## encoder는 이 모듈에 없다 -`contract`·`destination`·`config`(로컬 contract/binding 컴파일러, capability card registry), -`envelope`(결정적 JSON Schema envelope encoder, `LocalJsonSchemaRegistry`, pin한 Draft 2020-12 -meta-schema), `realtime`(durable fan-out adapter)은 조립하는 곳이 없어 삭제했다. 복구 경로는 -`docs/capability-status.md`의 제거 표에 있다. 그 결과 NetworkNT는 이 leaf의 production 의존성이 -아니다. - -`IntegrationEventEncoderPort`는 adopter 확장 지점으로 남는다. 템플릿은 구현체를 주지 않으므로 -`ca-skeleton.outbox.canonical-transport-enabled=true`를 켜는 adopter가 encoder bean을 직접 제공한다. +템플릿의 `IntegrationEventEncoderPort` 구현(`JsonIntegrationEventEncoder`)은 +`adapter:outbound:support`에 있다. use case가 append 전에 encode하므로 outbox를 쓰는 모든 조립에 +있어야 하고, 이 모듈은 발행 쪽에만 있다. 옛 R1 encoder 체인(`contract`·`destination`·`config`· +`envelope`·`realtime`)은 2026-09-25에 삭제됐고 복구 경로는 `docs/capability-status.md` 제거 표에 +있다. 공통 build evidence manifest 검증은 build-tools로 옮겼다. 루트 `verifyMessagingContracts` (`VerifyMessagingEvidenceTask`)가 application-core·shared-contract 두 qualification 레인 결과로 `build/messaging-evidence/contracts-schema/manifest.json`을 쓰고, 쓴 바이트를 바로 common schema로 -검증한다(common schema 자체도 Draft 2020-12 meta-schema 검증을 먼저 통과해야 한다). 이 leaf는 그 -검증에 관여하지 않는다. +검증한다. 이 leaf는 그 검증에 관여하지 않는다. canonical path는 platform `PublishResult`의 confirmation/transmission evidence를 application -`OutboxPublishOutcome`으로 명시적으로 변환한다. production legacy relay가 아직 `OutboxEvent`를 읽기 -때문에 R2 durable outbox storage/relay cutover는 남아 있고, `KafkaSender`/legacy broker selection은 그 -R0 compatibility path에서만 authority를 유지한다. +`OutboxPublishOutcome`으로 명시적으로 변환한다. diff --git a/src/adapter/outbound/messaging/build.gradle b/src/adapter/outbound/messaging/build.gradle index 87b19e28..a1fa876e 100644 --- a/src/adapter/outbound/messaging/build.gradle +++ b/src/adapter/outbound/messaging/build.gradle @@ -14,11 +14,6 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-json' implementation 'org.slf4j:slf4j-api' - // Test-only: the Kafka broker template, for the broker-selection cases. Without the platform - // starter it pulls at runtime — this leaf's tests use a same-named stand-in for the platform root. - testImplementation(project(':adapter:outbound:messaging-kafka')) { - exclude group: 'dev.caskeleton', module: 'messaging-spring-boot-starter-kafka' - } // Test-only: MessagingEvidenceSchemaValidatorTest holds the common evidence schema to Draft 2020-12. testImplementation libs.json.schema.validator } diff --git a/src/adapter/outbound/messaging/gradle.lockfile b/src/adapter/outbound/messaging/gradle.lockfile index 4b9ffb4f..de2704ed 100644 --- a/src/adapter/outbound/messaging/gradle.lockfile +++ b/src/adapter/outbound/messaging/gradle.lockfile @@ -1,7 +1,6 @@ # 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. -at.yawk.lz4:lz4-java:1.10.1=testRuntimeClasspath 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 @@ -9,7 +8,6 @@ com.ethlo.time:itu:1.14.0=testCompileClasspath,testRuntimeClasspath com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor -com.github.luben:zstd-jni:1.5.6-10=testRuntimeClasspath 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 @@ -63,7 +61,6 @@ 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.kafka:kafka-clients:4.1.2=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 @@ -147,7 +144,6 @@ org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,te org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath -org.xerial.snappy:snappy-java:1.1.10.7=testRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath tools.jackson.core:jackson-core:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfig.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfig.java index 8475ae35..f2b3f624 100644 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfig.java +++ b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfig.java @@ -1,12 +1,7 @@ package dev.caskeleton.adapter.outbound.messaging; -import dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher; -import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; -import dev.caskeleton.adapter.outbound.messaging.core.MessagePublisher; -import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessagePublisher; import dev.caskeleton.adapter.outbound.messaging.outbox.OutboxMessagePublishAdapter; import dev.caskeleton.adapter.outbound.messaging.outbox.Slf4jOutboxRelayFailureReportAdapter; -import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger; import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort; @@ -17,82 +12,43 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * Assembles both messaging ports onto the single active {@link MessageBroker} (the cache - * central-assembly pattern). A broker is contributed as a - * {@code @ConditionalOnProperty(app.messaging.broker=)}-gated bean, at most one active — adding - * a broker is new files only and this config never changes. A broker that is set but that no bean - * contributes fails startup. + * Binds the outbox relay's publish port to the canonical platform bridge. * *

The outbox publish port has no stand-in. A stand-in that throws on every call would still * satisfy the relay scheduler's bean condition, and the relay would exhaust every PENDING row to - * DEAD against it. So a present-and-enabled bridge with a blank broker and no canonical transport - * is refused at startup: the module is here, so messaging was wanted, and nothing can publish. + * DEAD against it. So a present-and-enabled bridge that cannot publish — no platform publisher, or + * no {@code app.messaging.producer-id} — is refused at startup: the module is here, so messaging + * was wanted, and nothing can publish. */ @Configuration @EnableConfigurationProperties(MessagingSettings.class) public class MessagingConfig { - @Bean - public MessagePublisher messagePublisher( - ObjectProvider brokerProvider, - MessagingSettings settings, - FailOpenDependencyLogger dependencyLogger) { - MessageBroker active = resolveBroker(brokerProvider, settings); - return (active == null) - ? new DisabledMessagePublisher() - : new OutboundMessagePublisher(active, dependencyLogger); - } + /** The {@code dependency_name} the relay's failure log carries when no broker is named. */ + static final String DEPENDENCY_NAME = "messaging-platform"; @Bean public OutboxMessagePublishPort outboxMessagePublishPort( - ObjectProvider brokerProvider, - ObjectProvider canonicalPublisherProvider, - MessagingSettings settings, - @Value("${ca-skeleton.outbox.canonical-transport-enabled:false}") - boolean canonicalTransportEnabled) { - MessageBroker active = resolveBroker(brokerProvider, settings); + ObjectProvider canonicalPublisherProvider) { IntegrationEventPublishPort canonicalPublisher = canonicalPublisherProvider.getIfAvailable(); - if (active == null && canonicalPublisher == null) { + if (canonicalPublisher == null) { throw new IllegalStateException( - "app.messaging.enabled is on but app.messaging.broker is blank and no canonical transport" - + " is configured, so nothing can publish outbox rows — select a broker (the" - + " messaging-kafka module defaults it to kafka), set app.messaging.producer-id for the" - + " canonical transport, or set app.messaging.enabled=false"); + "app.messaging.enabled is on but no IntegrationEventPublishPort exists, so nothing can" + + " publish outbox rows — set app.messaging.producer-id and select a messaging" + + " transport (the messaging-kafka module), or set app.messaging.enabled=false"); } - return new OutboxMessagePublishAdapter( - java.util.Optional.ofNullable(active), - java.util.Optional.ofNullable(canonicalPublisher), - canonicalTransportEnabled); + return new OutboxMessagePublishAdapter(canonicalPublisher); } - /** Always available, including when broker publication is disabled. */ + /** + * Always available while the bridge is on. The log names the broker the platform was told to use + * ({@code app.messaging.broker}, the platform's selector), so the relay's failure lines keep the + * {@code dependency_name} an alert already matches on. + */ @Bean - public OutboxRelayFailureReportPort outboxRelayFailureReportPort(MessagingSettings settings) { - String dependencyName = settings.broker().isBlank() ? "disabled" : settings.broker(); - return new Slf4jOutboxRelayFailureReportAdapter(dependencyName); - } - - private static MessageBroker resolveBroker( - ObjectProvider brokerProvider, MessagingSettings settings) { - if (settings.broker().isBlank()) { - return null; - } - MessageBroker active = brokerProvider.getIfAvailable(); - if (active == null) { - throw new IllegalStateException( - "app.messaging.broker=" - + settings.broker() - + " but no MessageBroker bean contributes that id — enable the broker template" - + " (supply its client seam) or unset app.messaging.broker"); - } - if (!settings.broker().equals(active.brokerId())) { - throw new IllegalStateException( - "app.messaging.broker=" - + settings.broker() - + " but the active MessageBroker reports brokerId '" - + active.brokerId() - + "'"); - } - return active; + public OutboxRelayFailureReportPort outboxRelayFailureReportPort( + @Value("${app.messaging.broker:}") String broker) { + return new Slf4jOutboxRelayFailureReportAdapter( + broker.isBlank() ? DEPENDENCY_NAME : broker.trim()); } } diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingSettings.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingSettings.java index a1d6ec26..8e06e28c 100644 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingSettings.java +++ b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingSettings.java @@ -1,24 +1,17 @@ package dev.caskeleton.adapter.outbound.messaging; -import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; import org.springframework.boot.context.properties.ConfigurationProperties; /** - * Messaging template selection. {@code app.messaging.broker=} chooses the single active - * {@link MessageBroker} (e.g. {@code kafka}). Blank means no legacy broker: the generic publisher - * is the fail-fast {@code DisabledMessagePublisher}, and startup is refused unless the canonical - * transport can publish outbox rows instead. + * The application bridge's own setting under {@code app.messaging}. * - * @param broker the active legacy broker id, matched against {@link MessageBroker#brokerId()}; - * blank means the legacy broker template is disabled * @param producerId the explicit logical producing-service identity used by the canonical platform * bridge; blank means that bridge is not exposed */ @ConfigurationProperties(prefix = "app.messaging") -public record MessagingSettings(String broker, String producerId) { +public record MessagingSettings(String producerId) { public MessagingSettings { - broker = (broker == null) ? "" : broker.trim(); producerId = (producerId == null) ? "" : producerId.trim(); } } diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingBridgeRootAutoConfiguration.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingBridgeRootAutoConfiguration.java index 716bbcc6..0de7505c 100644 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingBridgeRootAutoConfiguration.java +++ b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingBridgeRootAutoConfiguration.java @@ -3,7 +3,6 @@ package dev.caskeleton.adapter.outbound.messaging.autoconfigure; import dev.caskeleton.adapter.outbound.messaging.MessagingConfig; import dev.caskeleton.adapter.outbound.messaging.MessagingSettings; import dev.caskeleton.adapter.outbound.messaging.platformbridge.PlatformIntegrationEventPublishAdapter; -import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger; import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; import dev.caskeleton.messaging.schema.EncodedMessagePublisher; import org.springframework.boot.autoconfigure.AutoConfiguration; @@ -23,11 +22,9 @@ import org.springframework.util.StringUtils; /** * The one place that decides whether this application publishes to a broker. * - *

Before this, whether {@code app.messaging.broker} was blank was the de-facto switch. That is a - * selector doing a switch's job, and it reads badly in both directions: a blank broker with the - * relay enabled took down startup, while a deployment that wanted no messaging at all still - * assembled settings and publishers. Broker-specific client configuration is now a build-time - * capability leaf; this root remains broker-neutral and only binds ports to a contributed broker. + *

The broker itself is a build-time choice: a transport leaf (messaging-kafka) brings the + * vendored platform and its transport, and this root stays broker-neutral — it binds the + * application's ports to the platform's pre-encoded publish path and nothing else. * *

On when present: an application that selected a messaging leaf wants messaging, so a missing * {@code app.messaging.enabled} means on and only an explicit {@code false} turns it off. @@ -43,17 +40,6 @@ import org.springframework.util.StringUtils; @Import(MessagingConfig.class) public class MessagingBridgeRootAutoConfiguration { - /** - * The shared fail-open logger the publisher needs, so the module works wherever it is present - * rather than only where a composition root's component scan happens to reach {@code - * adapter.support}. Backs off to the one that scan registers. - */ - @Bean - @ConditionalOnMissingBean - FailOpenDependencyLogger failOpenDependencyLogger() { - return new FailOpenDependencyLogger(); - } - /** * Connects canonical application integration events to the central messaging platform. * diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/DisabledMessagePublisher.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/DisabledMessagePublisher.java deleted file mode 100644 index 27f9b011..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/DisabledMessagePublisher.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.core; - -import dev.caskeleton.shared.error.AdapterDisabledException; - -/** - * Fail-fast {@link MessagePublisher} binding when no broker is active ({@code app.messaging.broker} - * unset — the default). Any publish throws {@link AdapterDisabledException} — never a silent no-op - * (mirrors the cache router's unbound fail-fast). Broker-agnostic; the outbox counterpart is {@code - * DisabledOutboxMessagePublisher}. - */ -public class DisabledMessagePublisher implements MessagePublisher { - - @Override - public void publish(OutboundMessage message) { - throw new AdapterDisabledException("messaging"); - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/MessageBroker.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/MessageBroker.java deleted file mode 100644 index 049377a9..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/MessageBroker.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.core; - -/** - * SPI a forking project contributes to bind the messaging template to a real broker. The active - * broker is selected by {@code app.messaging.broker=}. The skeleton carries no broker SDK - * — it is supplied by the project that selects the broker. - */ -public interface MessageBroker { - - /** Stable broker identifier matched against {@code app.messaging.broker}. */ - String brokerId(); - - /** - * Sends a message to the broker. May throw on any transport/broker failure; the binding decorator - * applies the fail-open (general) or fail-closed (outbox) policy. - * - * @throws Exception on any send failure (handled by the binding decorator) - */ - void send(OutboundMessage message) throws Exception; -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/MessagePublisher.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/MessagePublisher.java deleted file mode 100644 index 2d75a791..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/MessagePublisher.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.core; - -/** - * Adapter-local fire-and-forget (fail-open) publishing port for the optional adapter template. Not - * use-case-facing ({@code adapter-outbound} type, so application-core cannot hold it) — a use case - * that needs durable delivery uses the application-core {@code OutboxMessagePublishPort}. The - * active binding is selected by {@code app.messaging.broker}. The {@code void} return keeps broker - * SDK types from escaping the adapter (B7). - */ -public interface MessagePublisher { - - void publish(OutboundMessage message); -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/OutboundMessage.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/OutboundMessage.java deleted file mode 100644 index 7ed18c3c..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/OutboundMessage.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.core; - -import java.util.Objects; - -/** - * Transport-neutral message a {@link MessagePublisher} emits. Carries only the routing key family - * ({@code topic}, partition {@code key}) and an already-serialized {@code payload} string — it - * deliberately does NOT depend on any broker SDK type, so the messaging port stays - * template-portable across Kafka and any future broker. - * - * @param topic logical destination / topic - * @param key partition / ordering key (may be empty, never null) - * @param payload serialized message body (the producer is responsible for serialization) - */ -public record OutboundMessage(String topic, String key, String payload) { - - public OutboundMessage { - Objects.requireNonNull(topic, "topic"); - Objects.requireNonNull(key, "key"); - Objects.requireNonNull(payload, "payload"); - if (topic.isBlank()) { - throw new IllegalArgumentException("topic must not be blank"); - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/OutboundMessagePublisher.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/OutboundMessagePublisher.java deleted file mode 100644 index 3f919e87..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/OutboundMessagePublisher.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.core; - -import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger; - -/** - * General {@link MessagePublisher} binding (fail-open). Delegates to the active {@link - * MessageBroker}; on failure it logs with the correlation id and swallows — a broker outage must - * never turn a core use case into a 5xx (durable delivery is delegated to the outbox/retry path). - * The fail-closed counterpart is {@code OutboxMessagePublishAdapter}. - * - *

Broker-agnostic: the same decorator serves any {@link MessageBroker}, so adding a broker never - * touches this class. - */ -public class OutboundMessagePublisher implements MessagePublisher { - - private static final String DEPENDENCY_TYPE = "messaging"; - - private final MessageBroker broker; - private final FailOpenDependencyLogger dependencyLogger; - - public OutboundMessagePublisher(MessageBroker broker, FailOpenDependencyLogger dependencyLogger) { - this.broker = broker; - this.dependencyLogger = dependencyLogger; - } - - @Override - public void publish(OutboundMessage message) { - // The send and the observation are separate steps because they used to share a try block: a - // logger that threw after a successful send was caught by the same catch and reported as a - // publish failure. The broker had accepted the message; the only thing that failed was the - // record of it, and the two must not be confusable. - boolean sent = false; - try { - broker.send(message); - sent = true; - } catch (Exception ex) { - // fail-open: observe with correlationId, delegate durability to outbox/retry, - // do NOT propagate — the core use case must still succeed. The failure is swallowed, the - // interrupt is not: a thread being stopped must still see it after this returns. - if (ex instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } - observeQuietly( - () -> dependencyLogger.logFailure(broker.brokerId(), DEPENDENCY_TYPE, "publish", ex)); - } - if (sent) { - observeQuietly( - () -> dependencyLogger.logSuccess(broker.brokerId(), DEPENDENCY_TYPE, "publish")); - } - } - - /** - * Runs an observation, absorbing whatever it throws. - * - *

Diagnostics are non-authoritative. An appender that is out of disk must not change what the - * caller believes about the broker. - */ - private static void observeQuietly(Runnable observation) { - try { - observation.run(); - } catch (RuntimeException ignored) { - // Nothing to report it to: the reporter is what failed. - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxEnvelopeJson.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxEnvelopeJson.java deleted file mode 100644 index 3fb1c2c5..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxEnvelopeJson.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.outbox; - -import dev.caskeleton.application.outbox.OutboxEvent; - -/** - * Hand-rolled, dependency-free JSON serialiser for the outbox envelope (no Jackson — the module - * deliberately keeps {@code jackson-databind} off its classpath). - * - *

{@link OutboxEvent#payload()} MUST already be a valid serialised JSON value; it is inserted - * verbatim (no escaping) — serialisation policy is owned by the {@code schema-serialization} - * branch, this class only assembles the envelope. All other string fields go through {@link - * #escape(String)}. - */ -public final class OutboxEnvelopeJson { - - private OutboxEnvelopeJson() {} - - public static String toJson(OutboxEvent event) { - return "{" - + "\"eventId\":\"" - + escape(event.eventId()) - + "\"," - + "\"eventType\":\"" - + escape(event.eventType()) - + "\"," - + "\"aggregateId\":\"" - + escape(event.aggregateId()) - + "\"," - + "\"occurredAt\":\"" - + escape(event.occurredAt().toString()) - + "\"," - + "\"correlationId\":\"" - + escape(event.correlationId()) - + "\"," - + "\"idempotencyKey\":\"" - + escape(event.idempotencyKey()) - + "\"," - + "\"payload\":" - + event.payload() - + "}"; - } - - /** Escapes a string for a JSON string literal (RFC 8259 §7). */ - static String escape(String value) { - StringBuilder sb = new StringBuilder(value.length() + 4); - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - if (c == '\\') { - sb.append("\\\\"); - } else if (c == '"') { - sb.append("\\\""); - } else if (c == '\b') { - sb.append("\\b"); - } else if (c == '\t') { - sb.append("\\t"); - } else if (c == '\n') { - sb.append("\\n"); - } else if (c == '\f') { - sb.append("\\f"); - } else if (c == '\r') { - sb.append("\\r"); - } else if (c < 0x20) { - sb.append(String.format("\\u%04x", (int) c)); - } else { - sb.append(c); - } - } - return sb.toString(); - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapter.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapter.java index d11eb983..91528ef2 100644 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapter.java +++ b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapter.java @@ -1,56 +1,28 @@ package dev.caskeleton.adapter.outbound.messaging.outbox; -import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; -import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage; import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; -import dev.caskeleton.application.outbox.CanonicalClaimedOutboxEvent; import dev.caskeleton.application.outbox.ClaimedOutboxEvent; -import dev.caskeleton.application.outbox.OutboxEvent; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.application.outbox.OutboxPublishAmbiguousException; import dev.caskeleton.application.outbox.OutboxPublishOutcome; import dev.caskeleton.application.outbox.OutboxPublishRefusedException; -import dev.caskeleton.shared.error.AdapterDisabledException; import java.util.Objects; -import java.util.Optional; /** - * Transport-only cutover router for the legacy outbox relay authority. + * The relay's publish port: a claimed row's validated event, delegated unchanged to the canonical + * {@link IntegrationEventPublishPort}. * - *

Legacy rows are rendered through the existing {@link MessageBroker} path. Canonical rows carry - * an already validated event and are delegated unchanged to {@link IntegrationEventPublishPort}. A - * row never falls back across branches when its required transport is absent. + *

The event is the one the append validated, restored from its exact envelope bytes; nothing + * here re-renders it. The platform's four-valued outcome is passed through, so the relay can tell a + * possibly-stored message (ambiguous) from a refused one. */ public final class OutboxMessagePublishAdapter implements OutboxMessagePublishPort { - private final Optional broker; - private final Optional canonicalPublisher; - private final boolean canonicalTransportEnabled; + private final IntegrationEventPublishPort canonicalPublisher; - public OutboxMessagePublishAdapter(MessageBroker broker) { - this( - Optional.of(Objects.requireNonNull(broker, "broker must not be null")), - Optional.empty(), - false); - } - - public OutboxMessagePublishAdapter( - Optional broker, Optional canonicalPublisher) { - this(broker, canonicalPublisher, true); - } - - public OutboxMessagePublishAdapter( - Optional broker, - Optional canonicalPublisher, - boolean canonicalTransportEnabled) { - this.broker = Objects.requireNonNull(broker, "broker Optional must not be null"); + public OutboxMessagePublishAdapter(IntegrationEventPublishPort canonicalPublisher) { this.canonicalPublisher = - Objects.requireNonNull(canonicalPublisher, "canonicalPublisher Optional must not be null"); - this.canonicalTransportEnabled = canonicalTransportEnabled; - if (broker.isEmpty() && canonicalPublisher.isEmpty()) { - throw new IllegalArgumentException( - "at least one outbox publication transport must be present"); - } + Objects.requireNonNull(canonicalPublisher, "canonicalPublisher must not be null"); } @Override @@ -68,38 +40,6 @@ public final class OutboxMessagePublishAdapter implements OutboxMessagePublishPo @Override public OutboxPublishOutcome publishForOutcome(ClaimedOutboxEvent event) { Objects.requireNonNull(event, "event must not be null"); - if (event instanceof CanonicalClaimedOutboxEvent canonical) { - if (!canonicalTransportEnabled) { - throw new AdapterDisabledException("messaging canonical platform transport"); - } - IntegrationEventPublishPort publisher = - canonicalPublisher.orElseThrow( - () -> new AdapterDisabledException("messaging canonical platform")); - return publisher.publish(canonical.event()).toCompletableFuture().join(); - } - if (event instanceof OutboxEvent legacy) { - return publishLegacy(legacy); - } - throw new IllegalStateException("unsupported claimed outbox event type: " + event.getClass()); - } - - private OutboxPublishOutcome publishLegacy(OutboxEvent event) { - MessageBroker activeBroker = - broker.orElseThrow(() -> new AdapterDisabledException("messaging legacy broker")); - String envelope = OutboxEnvelopeJson.toJson(event); - OutboundMessage message = new OutboundMessage(event.eventType(), event.aggregateId(), envelope); - try { - activeBroker.send(message); - return OutboxPublishOutcome.CONFIRMED; - } catch (Exception unknownOutcome) { - // The legacy MessageBroker seam exposes no transmission evidence. Once send() throws, this - // adapter cannot prove that zero bytes reached the broker, so calling it a refusal risks - // losing an event that was accepted before the acknowledgement path failed. An interrupt is - // kept, so a relay being shut down stops instead of moving on to the next row. - if (unknownOutcome instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } - return OutboxPublishOutcome.AMBIGUOUS; - } + return canonicalPublisher.publish(event.event()).toCompletableFuture().join(); } } diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfigTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfigTest.java index 08a92156..54ea4f2d 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfigTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfigTest.java @@ -1,95 +1,42 @@ package dev.caskeleton.adapter.outbound.messaging; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher; -import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; -import dev.caskeleton.adapter.outbound.messaging.kafka.KafkaAdapterConfig; -import dev.caskeleton.adapter.outbound.messaging.kafka.KafkaSender; -import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger; +import dev.caskeleton.adapter.outbound.messaging.outbox.OutboxMessagePublishAdapter; +import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; +import dev.caskeleton.application.outbox.OutboxMessagePublishPort; +import dev.caskeleton.application.outbox.OutboxPublishOutcome; +import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.test.context.runner.ApplicationContextRunner; class MessagingConfigTest { private final ApplicationContextRunner runner = - new ApplicationContextRunner() - .withBean(FailOpenDependencyLogger.class, FailOpenDependencyLogger::new) - .withUserConfiguration(MessagingConfig.class); + new ApplicationContextRunner().withUserConfiguration(MessagingConfig.class); @Test - void blankBrokerWithoutCanonicalTransportIsRefusedRatherThanStoodIn() { + void noCanonicalPublisherIsRefusedRatherThanStoodIn() { // A stand-in outbox publisher would satisfy the relay scheduler's bean condition and drain - // every - // PENDING row to DEAD. With nothing to publish to, the bridge refuses startup instead. - runner - .withPropertyValues("app.messaging.broker=") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(rootCause(context.getStartupFailure())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("app.messaging.broker is blank") - .hasMessageContaining("app.messaging.enabled=false"); - }); + // every PENDING row to DEAD. With nothing to publish to, the bridge refuses startup instead. + runner.run( + context -> + assertThat(rootCause(context.getStartupFailure())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no IntegrationEventPublishPort exists") + .hasMessageContaining("app.messaging.producer-id")); } @Test - void selectedKafkaBrokerWithoutProjectSenderFailsStartupCharacterization() { + void theOutboxPublishPortDelegatesToTheCanonicalPublisher() { runner - .withUserConfiguration(KafkaAdapterConfig.class) - .withPropertyValues( - "app.messaging.broker=kafka", "app.messaging.kafka.brokers=localhost:9092") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(rootCause(context.getStartupFailure())) - .isInstanceOf(NoSuchBeanDefinitionException.class) - .hasMessageContaining(KafkaSender.class.getName()); - }); - } - - @Test - void selectedBrokerIdMismatchFailsStartupCharacterization() { - runner - .withBean(MessageBroker.class, () -> brokerReporting("other")) - .withPropertyValues("app.messaging.broker=kafka") + .withBean( + IntegrationEventPublishPort.class, + () -> event -> CompletableFuture.completedFuture(OutboxPublishOutcome.CONFIRMED)) .run( context -> - assertThat(context) - .hasFailed() - .getFailure() - .hasRootCauseMessage( - "app.messaging.broker=kafka but the active MessageBroker reports brokerId" - + " 'other'")); - } - - @Test - void theDisabledPublisherFailsFastNamingMessaging() { - assertThatThrownBy( - () -> - new DisabledMessagePublisher() - .publish( - new dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage( - "t", "k", "p"))) - .isInstanceOf(dev.caskeleton.shared.error.AdapterDisabledException.class) - .extracting("adapterName") - .isEqualTo("messaging"); - } - - private static MessageBroker brokerReporting(String brokerId) { - return new MessageBroker() { - @Override - public String brokerId() { - return brokerId; - } - - @Override - public void send( - dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage ignoredMessage) {} - }; + assertThat(context.getBean(OutboxMessagePublishPort.class)) + .isInstanceOf(OutboxMessagePublishAdapter.class)); } private static Throwable rootCause(Throwable failure) { diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingPlatformBridgeAutoConfigurationTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingPlatformBridgeAutoConfigurationTest.java index 16177167..c56aef1b 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingPlatformBridgeAutoConfigurationTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingPlatformBridgeAutoConfigurationTest.java @@ -3,9 +3,6 @@ package dev.caskeleton.adapter.outbound.messaging.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.messaging.MessagingSettings; -import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; -import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage; -import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger; import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.messaging.schema.EncodedMessagePublisher; @@ -20,25 +17,26 @@ class MessagingPlatformBridgeAutoConfigurationTest { private final ApplicationContextRunner runner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MessagingBridgeRootAutoConfiguration.class)) - .withBean(FailOpenDependencyLogger.class, FailOpenDependencyLogger::new) .withBean( EncodedMessagePublisher.class, () -> (destination, message, options) -> { throw new AssertionError("publisher is not invoked while wiring the bridge"); }) - .withBean(MessageBroker.class, MessagingPlatformBridgeAutoConfigurationTest::testBroker) - .withPropertyValues("app.messaging.enabled=true", "app.messaging.broker=test"); + .withPropertyValues("app.messaging.enabled=true"); @Test void explicitProducerIdCreatesOneCanonicalPublishBridge() { runner .withPropertyValues("app.messaging.producer-id=portfolio-service") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(IntegrationEventPublishPort.class); - }); + .run(context -> assertThat(context).hasSingleBean(IntegrationEventPublishPort.class)); + } + + @Test + void explicitProducerIdGivesTheRelayItsPublishPort() { + runner + .withPropertyValues("app.messaging.producer-id=portfolio-service") + .run(context -> assertThat(context).hasSingleBean(OutboxMessagePublishPort.class)); } @Test @@ -51,7 +49,6 @@ class MessagingPlatformBridgeAutoConfigurationTest { MessagingBridgeRootAutoConfiguration.class, dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration .class)) - .withBean(FailOpenDependencyLogger.class, FailOpenDependencyLogger::new) .withPropertyValues( "app.messaging.enabled=true", "app.messaging.producer-id=portfolio-service"); @@ -59,28 +56,23 @@ class MessagingPlatformBridgeAutoConfigurationTest { assembled.run(context -> assertThat(context).hasSingleBean(IntegrationEventPublishPort.class)); } + /** + * The shipped yml always defines the key ({@code ${APP_MESSAGING_PRODUCER_ID:}}), so the property + * is present and blank whenever the operator has not set it. Blank means no bridge is built — the + * identity is never guessed — and with no bridge nothing can publish, so a module that is present + * and on refuses to start rather than leave the relay without a transport. + */ @ParameterizedTest @ValueSource(strings = {"", " "}) - void blankProducerIdLeavesTheBridgeOutWithoutFailingStartup(String producerId) { - // The shipped yml always defines the key (`${APP_MESSAGING_PRODUCER_ID:}`), so the property is - // present and blank whenever the operator has not set it. + void blankProducerIdRefusesStartupInsteadOfInventingAnIdentity(String producerId) { runner .withPropertyValues("app.messaging.producer-id=" + producerId) .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(IntegrationEventPublishPort.class); - }); - } - - @Test - void presentWithoutTheSwitchIsOn() { - new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MessagingBridgeRootAutoConfiguration.class)) - .withBean(FailOpenDependencyLogger.class, FailOpenDependencyLogger::new) - .withBean(MessageBroker.class, MessagingPlatformBridgeAutoConfigurationTest::testBroker) - .withPropertyValues("app.messaging.broker=test") - .run(context -> assertThat(context).hasSingleBean(OutboxMessagePublishPort.class)); + context -> + assertThat(context) + .getFailure() + .rootCause() + .hasMessageContaining("no IntegrationEventPublishPort exists")); } @Test @@ -94,26 +86,4 @@ class MessagingPlatformBridgeAutoConfigurationTest { assertThat(context).doesNotHaveBean(OutboxMessagePublishPort.class); }); } - - @Test - void missingProducerIdDoesNotInventCanonicalPublisherIdentity() { - runner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(IntegrationEventPublishPort.class); - }); - } - - /** A selected broker, so the bridge has something to publish outbox rows to. */ - private static MessageBroker testBroker() { - return new MessageBroker() { - @Override - public String brokerId() { - return "test"; - } - - @Override - public void send(OutboundMessage message) {} - }; - } } diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/core/OutboundMessagePublisherTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/core/OutboundMessagePublisherTest.java deleted file mode 100644 index 779557cd..00000000 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/core/OutboundMessagePublisherTest.java +++ /dev/null @@ -1,175 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.core; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.read.ListAppender; -import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger; -import dev.caskeleton.adapter.outbound.support.OutboundCorrelation; -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; - -/** - * General {@link OutboundMessagePublisher} = fail-open: delegates to the active {@link - * MessageBroker}; a broker failure is logged with the correlation id and swallowed (never - * propagated). Broker-agnostic — a fake broker stands in for any real broker. - */ -class OutboundMessagePublisherTest { - - private ch.qos.logback.classic.Logger logbackLogger; - private ListAppender appender; - private FailOpenDependencyLogger dependencyLogger; - - @BeforeEach - void setUp() { - logbackLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("test.messaging"); - appender = new ListAppender<>(); - appender.start(); - logbackLogger.addAppender(appender); - logbackLogger.setLevel(Level.DEBUG); - dependencyLogger = new FailOpenDependencyLogger(logbackLogger); - } - - @AfterEach - void tearDown() { - logbackLogger.detachAppender(appender); - MDC.clear(); - } - - /** Fake broker (brokerId "kafka") capturing sends, optionally failing. */ - private static final class FakeBroker implements MessageBroker { - final List sent = new ArrayList<>(); - private final RuntimeException failure; - - FakeBroker() { - this.failure = null; - } - - FakeBroker(RuntimeException failure) { - this.failure = failure; - } - - @Override - public String brokerId() { - return "kafka"; - } - - @Override - public void send(OutboundMessage message) { - if (failure != null) { - throw failure; - } - sent.add(message); - } - } - - @Test - void publishDelegatesToTheActiveBrokerOnSuccess() { - FakeBroker broker = new FakeBroker(); - OutboundMessagePublisher publisher = new OutboundMessagePublisher(broker, dependencyLogger); - OutboundMessage message = new OutboundMessage("worklog-events", "wl-1", "{}"); - - publisher.publish(message); - - assertThat(broker.sent).containsExactly(message); - } - - @Test - void publishFailureIsFailOpenAndNeverThrows() { - FakeBroker broker = new FakeBroker(new IllegalStateException("broker unavailable")); - OutboundMessagePublisher publisher = new OutboundMessagePublisher(broker, dependencyLogger); - - // fail-open: a broker outage must not propagate to the core use case. - assertThatCode(() -> publisher.publish(new OutboundMessage("t", "k", "p"))) - .doesNotThrowAnyException(); - } - - /** - * Fail-open swallows the failure, not the interrupt: a thread being stopped must still see that - * it is being stopped after the publish returns. - */ - @Test - void anInterruptedSendIsSwallowedWithTheInterruptFlagKept() { - // given - MessageBroker interruptedBroker = - new MessageBroker() { - @Override - public String brokerId() { - return "kafka"; - } - - @Override - public void send(OutboundMessage message) throws InterruptedException { - throw new InterruptedException("shutting down"); - } - }; - OutboundMessagePublisher publisher = - new OutboundMessagePublisher(interruptedBroker, dependencyLogger); - - // when - publisher.publish(new OutboundMessage("t", "k", "p")); - - // then - assertThat(Thread.interrupted()).isTrue(); - } - - @Test - void publishFailureLogCarriesCorrelationIdAndBrokerId() { - MDC.put(OutboundCorrelation.MDC_KEY, "corr-msg-1"); - FakeBroker broker = new FakeBroker(new IllegalStateException("broker unavailable")); - OutboundMessagePublisher publisher = new OutboundMessagePublisher(broker, dependencyLogger); - - publisher.publish(new OutboundMessage("t", "k", "p")); - - ILoggingEvent event = - appender.list.stream().filter(e -> e.getLevel() == Level.WARN).findFirst().orElseThrow(); - assertThat(event.getFormattedMessage()) - .contains("correlation_id=\"corr-msg-1\"") - .contains("dependency_name=\"kafka\"") - .contains("dependency_type=\"messaging\"") - .contains("operation=\"publish\""); - } - - @org.junit.jupiter.api.DisplayName( - "a logger failure after a confirmed send is not a publish failure") - @Test - void aLoggerFailureAfterAConfirmedSendIsNotAPublishFailure() { - // The send and the success log used to share one try block, so a logger that threw after the - // broker had accepted the message was caught by the failure branch and recorded as a publish - // failure. The broker's outcome and the record of it are different facts. - FakeBroker broker = new FakeBroker(); - org.slf4j.Logger throwingLogger = - (org.slf4j.Logger) - java.lang.reflect.Proxy.newProxyInstance( - getClass().getClassLoader(), - new Class[] {org.slf4j.Logger.class}, - (proxy, method, args) -> { - if (method.getName().equals("debug")) { - throw new IllegalStateException("the appender is out of disk"); - } - if (method.getReturnType() == boolean.class) { - return true; - } - if (method.getReturnType() == String.class) { - return "test.messaging"; - } - return null; - }); - - OutboundMessagePublisher publisher = - new OutboundMessagePublisher(broker, new FailOpenDependencyLogger(throwingLogger)); - OutboundMessage message = new OutboundMessage("worklog-events", "wl-1", "{}"); - - assertThatCode(() -> publisher.publish(message)).doesNotThrowAnyException(); - assertThat(broker.sent) - .as("the message reached the broker; only the record of it failed") - .containsExactly(message); - } -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxCanonicalPublishRoutingTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxCanonicalPublishRoutingTest.java deleted file mode 100644 index eeac704c..00000000 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxCanonicalPublishRoutingTest.java +++ /dev/null @@ -1,166 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.outbox; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; -import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage; -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; -import dev.caskeleton.application.messaging.event.AggregateIdentity; -import dev.caskeleton.application.messaging.event.AggregateOrder; -import dev.caskeleton.application.messaging.event.EventId; -import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; -import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import dev.caskeleton.application.outbox.CanonicalClaimedOutboxEvent; -import dev.caskeleton.application.outbox.OutboxEvent; -import dev.caskeleton.application.outbox.OutboxEventStatus; -import dev.caskeleton.application.outbox.OutboxPublishOutcome; -import dev.caskeleton.shared.error.AdapterDisabledException; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import org.junit.jupiter.api.Test; - -class OutboxCanonicalPublishRoutingTest { - - @Test - void canonicalClaimUsesOnlyCanonicalPublisherAndPreservesExactEvent() { - RecordingBroker broker = new RecordingBroker(); - RecordingCanonicalPublisher canonical = new RecordingCanonicalPublisher(); - canonical.result = OutboxPublishOutcome.AMBIGUOUS; - OutboxMessagePublishAdapter adapter = - new OutboxMessagePublishAdapter(Optional.of(broker), Optional.of(canonical)); - CanonicalClaimedOutboxEvent claim = - new CanonicalClaimedOutboxEvent(canonicalEvent(), OutboxEventStatus.IN_FLIGHT, 1); - - OutboxPublishOutcome outcome = adapter.publishForOutcome(claim); - - assertThat(outcome).isEqualTo(OutboxPublishOutcome.AMBIGUOUS); - assertThat(canonical.events).containsExactly(claim.event()); - assertThat(broker.sent).isEmpty(); - assertThat(canonical.events.getFirst().envelopeBytes()) - .containsExactly(claim.event().envelopeBytes()); - } - - @Test - void legacyClaimUsesOnlyLegacyBroker() { - RecordingBroker broker = new RecordingBroker(); - RecordingCanonicalPublisher canonical = new RecordingCanonicalPublisher(); - OutboxMessagePublishAdapter adapter = - new OutboxMessagePublishAdapter(Optional.of(broker), Optional.of(canonical)); - - OutboxPublishOutcome outcome = adapter.publishForOutcome(legacyEvent()); - - assertThat(outcome).isEqualTo(OutboxPublishOutcome.CONFIRMED); - assertThat(broker.sent).hasSize(1); - assertThat(canonical.events).isEmpty(); - } - - @Test - void disabledCanonicalTransportRejectsCanonicalClaimEvenWhenPublisherExists() { - RecordingBroker broker = new RecordingBroker(); - RecordingCanonicalPublisher canonical = new RecordingCanonicalPublisher(); - OutboxMessagePublishAdapter adapter = - new OutboxMessagePublishAdapter(Optional.of(broker), Optional.of(canonical), false); - - assertThatThrownBy( - () -> - adapter.publishForOutcome( - new CanonicalClaimedOutboxEvent( - canonicalEvent(), OutboxEventStatus.IN_FLIGHT, 1))) - .isInstanceOf(AdapterDisabledException.class) - .hasMessageContaining("canonical"); - - assertThat(canonical.events).isEmpty(); - assertThat(broker.sent).isEmpty(); - } - - @Test - void missingBranchDependencyFailsClosedWithoutFallingAcrossTransports() { - OutboxMessagePublishAdapter canonicalOnly = - new OutboxMessagePublishAdapter( - Optional.empty(), Optional.of(new RecordingCanonicalPublisher())); - OutboxMessagePublishAdapter legacyOnly = - new OutboxMessagePublishAdapter(Optional.of(new RecordingBroker()), Optional.empty()); - - assertThatThrownBy(() -> canonicalOnly.publishForOutcome(legacyEvent())) - .isInstanceOf(AdapterDisabledException.class); - assertThatThrownBy( - () -> - legacyOnly.publishForOutcome( - new CanonicalClaimedOutboxEvent( - canonicalEvent(), OutboxEventStatus.IN_FLIGHT, 1))) - .isInstanceOf(AdapterDisabledException.class); - } - - private static OutboxEvent legacyEvent() { - return new OutboxEvent( - "legacy-1", - "LegacyEvent", - "aggregate-1", - "{}", - Instant.parse("2026-09-18T03:00:00Z"), - "corr-1", - "legacy-1", - OutboxEventStatus.IN_FLIGHT, - 1); - } - - private static ValidatedIntegrationEvent canonicalEvent() { - String partition = "a".repeat(64); - byte[] envelope = "{\"wire\":\"exact\"}".getBytes(StandardCharsets.UTF_8); - Sha256 zero = new Sha256(new byte[32]); - return new ValidatedIntegrationEvent( - new EventId("01994e11-4d88-7000-8000-000000000001"), - new ContractId("portfolio.worklog.reserved"), - 1, - 3, - new LogicalDestinationId("portfolio-domain-events"), - new AggregateIdentity("tenant-a", "worklog", "worklog-42"), - new AggregateOrder(17, 2), - Instant.parse("2026-09-18T03:00:00Z"), - "corr-1", - Optional.empty(), - partition, - partition.getBytes(StandardCharsets.US_ASCII), - envelope, - "application/json", - zero, - Sha256.of(envelope), - zero, - zero, - "catalog-r1", - "binding-r1"); - } - - private static final class RecordingBroker implements MessageBroker { - private final List sent = new ArrayList<>(); - - @Override - public String brokerId() { - return "kafka"; - } - - @Override - public void send(OutboundMessage message) { - sent.add(message); - } - } - - private static final class RecordingCanonicalPublisher implements IntegrationEventPublishPort { - private final List events = new ArrayList<>(); - private OutboxPublishOutcome result = OutboxPublishOutcome.CONFIRMED; - - @Override - public java.util.concurrent.CompletionStage publish( - ValidatedIntegrationEvent event) { - events.add(event); - return CompletableFuture.completedFuture(result); - } - } -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapterTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapterTest.java index 30ecccc9..f415114d 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapterTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapterTest.java @@ -1,245 +1,123 @@ package dev.caskeleton.adapter.outbound.messaging.outbox; 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 ch.qos.logback.classic.Level; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.read.ListAppender; -import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; -import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage; -import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger; -import dev.caskeleton.application.outbox.OutboxEvent; +import dev.caskeleton.application.messaging.contract.ContractId; +import dev.caskeleton.application.messaging.contract.LogicalDestinationId; +import dev.caskeleton.application.messaging.contract.Sha256; +import dev.caskeleton.application.messaging.event.AggregateIdentity; +import dev.caskeleton.application.messaging.event.AggregateOrder; +import dev.caskeleton.application.messaging.event.EventId; +import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.outbox.ClaimedOutboxEvent; import dev.caskeleton.application.outbox.OutboxEventStatus; -import java.io.IOException; +import dev.caskeleton.application.outbox.OutboxPublishAmbiguousException; +import dev.caskeleton.application.outbox.OutboxPublishOutcome; +import dev.caskeleton.application.outbox.OutboxPublishRefusedException; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -import org.junit.jupiter.api.Nested; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; import org.junit.jupiter.api.Test; -import org.slf4j.LoggerFactory; -/** - * Broker-agnostic outbox publish adapter (fail-closed). Covers: - * - *

    - *
  • Success — correct OutboundMessage (topic=eventType, key=aggregateId, payload=envelope JSON) - * sent to the active broker. - *
  • Fail-closed — broker failure is propagated without duplicate dependency logs; checked - * exceptions are wrapped. - *
  • Envelope JSON fields and escaping. - *
- */ class OutboxMessagePublishAdapterTest { - /** Fake broker (brokerId "kafka") capturing sends, optionally failing with a given throwable. */ - private static final class FakeBroker implements MessageBroker { - final List sent = new ArrayList<>(); - private final Exception failure; + private final RecordingCanonicalPublisher canonical = new RecordingCanonicalPublisher(); + private final OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(canonical); - FakeBroker() { - this.failure = null; - } + @Test + void aClaimedRowIsPublishedAsTheExactValidatedEventItCarries() { + // given + ClaimedOutboxEvent claim = claim(); - FakeBroker(Exception failure) { - this.failure = failure; - } + // when + adapter.publishForOutcome(claim); + + // then + assertThat(canonical.events).containsExactly(claim.event()); + } + + @Test + void thePlatformOutcomeIsPassedThroughUnchanged() { + // given + canonical.result = OutboxPublishOutcome.REJECTED_AFTER_BROKER; + + // when + OutboxPublishOutcome outcome = adapter.publishForOutcome(claim()); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_AFTER_BROKER); + } + + @Test + void anAmbiguousPublishThrowsTheAmbiguousSignalFromTheThrowingMethod() { + // given + canonical.result = OutboxPublishOutcome.AMBIGUOUS; + + // when + Throwable thrown = catchThrowable(() -> adapter.publish(claim())); + + // then + assertThat(thrown).isInstanceOf(OutboxPublishAmbiguousException.class); + } + + @Test + void aRefusedPublishThrowsTheRefusalWithItsOutcome() { + // given + canonical.result = OutboxPublishOutcome.REJECTED_BEFORE_SEND; + + // when + Throwable thrown = catchThrowable(() -> adapter.publish(claim())); + + // then + assertThat(thrown) + .isInstanceOf(OutboxPublishRefusedException.class) + .extracting("outcome") + .isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND); + } + + private static ClaimedOutboxEvent claim() { + String partition = "a".repeat(64); + byte[] envelope = "{\"wire\":\"exact\"}".getBytes(StandardCharsets.UTF_8); + Sha256 zero = new Sha256(new byte[32]); + ValidatedIntegrationEvent event = + new ValidatedIntegrationEvent( + new EventId("01994e11-4d88-7000-8000-000000000001"), + new ContractId("portfolio.worklog.reserved"), + 1, + 1, + new LogicalDestinationId("portfolio-domain-events"), + new AggregateIdentity("tenant-a", "worklog", "worklog-42"), + new AggregateOrder(17, 2), + Instant.parse("2026-09-18T03:00:00Z"), + "corr-1", + Optional.empty(), + partition, + partition.getBytes(StandardCharsets.US_ASCII), + envelope, + "application/json", + zero, + Sha256.of(envelope), + zero, + zero, + "catalog-r1", + "binding-r1"); + return new ClaimedOutboxEvent(event, OutboxEventStatus.IN_FLIGHT, 1); + } + + private static final class RecordingCanonicalPublisher implements IntegrationEventPublishPort { + private final List events = new ArrayList<>(); + private OutboxPublishOutcome result = OutboxPublishOutcome.CONFIRMED; @Override - public String brokerId() { - return "kafka"; - } - - @Override - public void send(OutboundMessage message) throws Exception { - if (failure != null) { - throw failure; - } - sent.add(message); - } - } - - private OutboxEvent sampleEvent() { - return new OutboxEvent( - "evt-01", - "WorkLogReserved", - "wl-agg-1", - "{\"workLogId\":\"wl-01\"}", - Instant.parse("2024-01-02T03:04:05Z"), - "corr-abc", - "idem-xyz", - OutboxEventStatus.IN_FLIGHT, - 1); - } - - @Nested - class SuccessPath { - - @Test - void legacyVoidSenderNormalReturnCompletesWithoutBrokerConfirmationCharacterization() { - FakeBroker broker = new FakeBroker(); - OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker); - - adapter.publish(sampleEvent()); - - assertThat(broker.sent).hasSize(1); - OutboundMessage sent = broker.sent.get(0); - assertThat(sent.topic()).isEqualTo("WorkLogReserved"); - assertThat(sent.key()).isEqualTo("wl-agg-1"); - } - - @Test - void publishEnvelopeContainsAllFields() { - FakeBroker broker = new FakeBroker(); - OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker); - - adapter.publish(sampleEvent()); - - String payload = broker.sent.get(0).payload(); - assertThat(payload).contains("\"eventId\""); - assertThat(payload).contains("\"eventType\""); - assertThat(payload).contains("\"aggregateId\""); - assertThat(payload).contains("\"occurredAt\""); - assertThat(payload).contains("\"correlationId\""); - assertThat(payload).contains("\"idempotencyKey\""); - assertThat(payload).contains("\"payload\""); - } - - @Test - void publishEnvelopeFieldValuesMatchEvent() { - FakeBroker broker = new FakeBroker(); - OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker); - - adapter.publish(sampleEvent()); - - String payload = broker.sent.get(0).payload(); - assertThat(payload).contains("\"evt-01\""); - assertThat(payload).contains("\"WorkLogReserved\""); - assertThat(payload).contains("\"wl-agg-1\""); - assertThat(payload).contains("2024-01-02T03:04:05Z"); - assertThat(payload).contains("\"corr-abc\""); - assertThat(payload).contains("\"idem-xyz\""); - assertThat(payload).contains("{\"workLogId\":\"wl-01\"}"); - } - } - - @Nested - class FailClosedPath { - - @Test - void senderFailureIsTypedAsAmbiguousWhenTheLegacySeamHasNoTransmissionEvidence() { - FakeBroker broker = new FakeBroker(new IllegalStateException("broker down")); - OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker); - - assertThatThrownBy(() -> adapter.publish(sampleEvent())) - .isInstanceOf(dev.caskeleton.application.outbox.OutboxPublishAmbiguousException.class); - assertThat(adapter.publishForOutcome(sampleEvent())) - .isEqualTo(dev.caskeleton.application.outbox.OutboxPublishOutcome.AMBIGUOUS); - } - - @Test - void publishFailureEmitsNoDuplicateDependencyLog() { - ch.qos.logback.classic.Logger dependencyLogger = - (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(FailOpenDependencyLogger.class); - ListAppender appender = new ListAppender<>(); - appender.start(); - dependencyLogger.addAppender(appender); - dependencyLogger.setLevel(Level.DEBUG); - FakeBroker broker = new FakeBroker(new IllegalStateException("broker unavailable")); - OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker); - - try { - adapter.publish(sampleEvent()); - } catch (RuntimeException ignored) { - // expected - } finally { - dependencyLogger.detachAppender(appender); - appender.stop(); - } - - assertThat(appender.list).isEmpty(); - } - - @Test - void checkedNetworkFailureIsAlsoAmbiguousRatherThanAnUntypedRuntimeException() { - FakeBroker broker = new FakeBroker(new IOException("network error")); - OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker); - - assertThatThrownBy(() -> adapter.publish(sampleEvent())) - .isInstanceOf(dev.caskeleton.application.outbox.OutboxPublishAmbiguousException.class); - } - - /** - * A relay stopped mid-send stays stopped. - * - *

The interrupt was consumed by the catch that turns a failed send into AMBIGUOUS, so a - * relay being shut down went on to the next row and waited out that row's acknowledgement - * timeout too. - */ - @Test - void anInterruptedSendKeepsTheRelayThreadInterrupted() { - // given - FakeBroker broker = new FakeBroker(new InterruptedException("shutting down")); - OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker); - - // when - adapter.publishForOutcome(sampleEvent()); - - // then - assertThat(Thread.interrupted()).isTrue(); - } - - @Test - void adapterStateContainsOnlyTheTwoTransportReferencesAndCanonicalGate() { - assertThat( - Arrays.stream(OutboxMessagePublishAdapter.class.getDeclaredFields()) - .map(field -> field.getName())) - .containsExactlyInAnyOrder("broker", "canonicalPublisher", "canonicalTransportEnabled"); - } - } - - @Nested - class JsonEscape { - - @Test - void envelopeEscapesDoubleQuotesInStringFields() { - OutboxEvent eventWithQuote = - new OutboxEvent( - "evt-02", - "Has\"Quote", - "agg-1", - "{}", - Instant.parse("2024-01-01T00:00:00Z"), - "corr-1", - "idem-1", - OutboxEventStatus.IN_FLIGHT, - 1); - FakeBroker broker = new FakeBroker(); - new OutboxMessagePublishAdapter(broker).publish(eventWithQuote); - - assertThat(broker.sent.get(0).payload()).contains("Has\\\"Quote"); - } - - @Test - void envelopeInsertsPayloadRawWithoutDoubleEncoding() { - OutboxEvent event = - new OutboxEvent( - "evt-05", - "SomeEvent", - "agg-2", - "{\"nested\":{\"a\":1}}", - Instant.parse("2024-01-01T00:00:00Z"), - "corr-2", - "idem-2", - OutboxEventStatus.IN_FLIGHT, - 1); - FakeBroker broker = new FakeBroker(); - new OutboxMessagePublishAdapter(broker).publish(event); - - String payload = broker.sent.get(0).payload(); - assertThat(payload).contains("{\"nested\":{\"a\":1}}"); - assertThat(payload).doesNotContain("\"{\\\"nested\\\""); + public CompletionStage publish(ValidatedIntegrationEvent event) { + events.add(event); + return CompletableFuture.completedFuture(result); } } } diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index 5c48dc1e..8efb45f1 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -66,7 +66,7 @@ to `spring.autoconfigure.exclude`, so no DataSource, pool, EntityManagerFactory The same split applies to owner-safe PostgreSQL idempotency: this leaf constructs the concrete PostgreSQL store behind `IdempotencyStorePort` (`PostgreSqlIdempotencyStoreConfig`, active only with -`ca-skeleton.capabilities.idempotency.provider=postgresql`), while app-bootstrap owns provider +`ca-skeleton.capabilities.idempotency.provider=postgresql`), while `composition:idempotency` owns provider selection, TTL/lease/codec policy, executor construction, and exclusivity validation. With that provider the leaf also applies the `db/migration/jpa/core` + `db/migration/jpa/idempotency` Flyway streams and activates the capability registry row at startup (`IdempotencySchemaStream`, skipped @@ -79,8 +79,8 @@ Everything that only makes sense with a relational store therefore lives here an module: migration startup sequencing, resolved datasource/version validation, OSIV/DDL/pool/TLS/vendor safety, the sanitized management endpoint/report (`startup`), the metered multi-instance lock (`lock`), the readiness `db` contribution and the shipped settings -(`config/module-defaults/persistence-jpa.yml`). Use-case assembly does not: the outbox relay stays in -app-bootstrap because a driven adapter must not construct or call a use case. The leaf must have +(`config/module-defaults/persistence-jpa.yml`). Use-case assembly does not: the outbox relay is +`composition:outbox-relay` because a driven adapter must not construct or call a use case. The leaf must have zero imports from `dev.caskeleton.bootstrap`; startup failures go through `adapter:outbound:support` (`support.startup`), and new composition helpers stay package-private so `verifyJpaApiSurface` does not grow by wiring accident. @@ -126,7 +126,10 @@ nobody tested. - Spring Data repositories. - Persistence mappers. - Repository adapter implementations. -- Outbox transport-only compatibility: raw `NewOutboxEvent` append belongs only to `LegacyOutboxAppendPort`; canonical `OutboxAppendPort` persists `ValidatedIntegrationEvent` exact bytes. Partial canonical metadata must fail closed. +- Outbox append: one model. `OutboxStoreAdapter` implements `OutboxAppendPort` and persists a + `ValidatedIntegrationEvent`'s exact envelope bytes and hashes; a claim restores the same event + from them. A row without complete canonical metadata is unreadable and goes to DEAD, never + published by guess. `V19` refuses unpublished pre-canonical rows. - Outbox relay fencing: `claimBatch` records the claiming relay (`lease_owner`) and increments `lease_token` under the claim's row lock (`V17`); `markPublished`/`markFailed`/`markDead` are one conditional UPDATE on `event_id` + `IN_FLIGHT` + owner + token and return `APPLIED`/`STALE`. A @@ -137,7 +140,7 @@ nobody tested. - Audit-metadata base + actor seam (`audit/AuditableEntity`, `audit/AuditContextPort`, `audit/DomainContextAuditContextPort`) — see "Persistence auditing contract" below. - Vendor SPI extension points shared by all RDBMS vendors: - - `outbox/OutboxClaimRepository` — vendor module implements claim strategy (e.g. FOR UPDATE SKIP LOCKED). + - `outbox/jpa/OutboxClaimRepository` — vendor module implements claim strategy (e.g. FOR UPDATE SKIP LOCKED); the implementations sit beside it in `outbox/postgresql` and `outbox/h2`. - `failure/SqlStateErrorMapping` — vendor module contributes vendor-specific SQLState rows. ## Vendor selection @@ -150,6 +153,11 @@ two SPI beans (outbox claim, SQLState mapping): | PostgreSQL | `.postgresql` | `ca-skeleton.persistence.vendor=postgresql` (also the default) | Flyway, `db/migration/postgresql` | | H2 | `.h2` | `ca-skeleton.persistence.vendor=h2` | Hibernate `ddl-auto`, entities only | +The outbox and idempotency features keep their pieces together, by feature and then by vendor: +`outbox/{jpa,postgresql,h2}` and `idempotency/{jpa,postgresql}`. The vendor configurations above still +decide which claim repository is registered. None of those feature classes imports a driver type, so +`PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL` still holds with them outside `.postgresql`. + `config/PersistenceVendorSettings` binds the selector to an enum, so an unknown value fails at startup instead of loading neither composition and surfacing as a missing `OutboxClaimRepository`. The profiles state the choice: `application-local.yml`, `application-dev.yml` and diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index 94650578..8ebfb9ce 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -61,7 +61,7 @@ sample-portfolio가 제공). | 스위치·vendor | `APP_PERSISTENCE_JPA_ENABLED`(기본 true), `APP_PERSISTENCE_VENDOR`(`postgresql`\|`h2`), `APP_FLYWAY_ENABLED`, `APP_MIGRATION_ON_STARTUP` | | 풀 | `APP_DATASOURCE_POOL_MAX_SIZE`, `APP_DATASOURCE_POOL_MIN_IDLE`, `APP_DATASOURCE_CONNECTION_TIMEOUT`, `APP_DATASOURCE_POOL_IDLE_TIMEOUT`, `APP_DATASOURCE_POOL_MAX_LIFETIME` | | JPA | `APP_DATASOURCE_DDL_AUTO`, `APP_DATASOURCE_SHOW_SQL`, `APP_DATASOURCE_FORMAT_SQL`, `APP_DATASOURCE_OPEN_IN_VIEW`, `APP_JPA_HIBERNATE_*` | -| 선택 기능 | `APP_OUTBOX_ENABLED`, `APP_OUTBOX_RELAY_ENABLED`, `APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED`, `APP_MULTI_INSTANCE_ENABLED`(합성 루트 소유, 락 provider 선택), `APP_IDEMPOTENCY_PROVIDER=postgresql`, `APP_REALTIME_REPLAY_ENABLED`, `APP_REALTIME_REPLAY_RETENTION` | +| 선택 기능 | `APP_OUTBOX_ENABLED`, `APP_OUTBOX_RELAY_ENABLED`, `APP_MULTI_INSTANCE_ENABLED`(합성 루트 소유, 락 provider 선택), `APP_IDEMPOTENCY_PROVIDER=postgresql`, `APP_REALTIME_REPLAY_ENABLED`, `APP_REALTIME_REPLAY_RETENTION` | ## 라이브러리 API — 서비스의 어댑터 leaf에서 `implementation`으로 받아 직접 호출 @@ -223,18 +223,19 @@ failure translation contract 다. 여기서는 SPI 구조와 fallback 근거만 ## outbox — `OutboxStoreAdapter` 외 -스키마는 Flyway(`V3__outbox_event.sql`)가 소유하고, MSG-015 transport-only cutover를 위한 -`V13__outbox_canonical_transport_compatibility.sql`이 기존 row를 깨지 않으면서 canonical metadata와 -exact `BYTEA envelope_bytes`를 additive하게 확장한다. +스키마는 Flyway(`V3__outbox_event.sql`)가 소유하고, `V13__outbox_canonical_transport_compatibility.sql`이 +canonical metadata와 exact `BYTEA envelope_bytes`를 더했다. append 모델은 canonical 하나다(2026-09-28, +소유자 결정 7): `OutboxStoreAdapter`가 `OutboxAppendPort`(`ValidatedIntegrationEvent`)와 +`OutboxStorePort`를 함께 구현하고, `ca-skeleton.outbox.enabled=true`일 때만 존재한다. row는 validated +event의 exact envelope bytes와 hash를 저장하고, claim은 그 bytes로 같은 event를 복원한다 +(`ClaimedOutboxEvent`). `event_type`·`aggregate_id`·`correlation_id`는 claim gate와 metrics query를 +위해 contract id·aggregate id·correlation id를 한 번 더 적는다. -append 경계도 명시적으로 분리된다. `LegacyOutboxAppendPort`는 기존 `NewOutboxEvent` compatibility -producer 전용이고, `OutboxAppendPort`는 `ValidatedIntegrationEvent`만 받는다. -`CanonicalOutboxAppendAdapter`는 `ca-skeleton.outbox.enabled=true`와 -`canonical-transport-enabled=true`가 모두 만족될 때만 존재하며 exact bytes를 저장한다. legacy 필수 -컬럼에는 rollback window용 UTF-8 compatibility projection을 같이 기록한다. - -claim 시 canonical column이 전부 null이면 legacy `OutboxEvent`, 전부 존재하면 -`CanonicalClaimedOutboxEvent`로 매핑한다. 일부만 존재하는 row는 legacy로 강등하지 않고 fail-closed한다. +`V19__outbox_event_canonical_only.sql`은 pre-canonical row가 더 없다는 것을 DB에 적는다: envelope 없는 +미발행 row가 남아 있으면 migration이 실패하고(이전 릴리스로 relay를 비우거나 손으로 정리한 뒤 +다시 적용한다), 이후로는 `PUBLISHED`가 아닌 row에 canonical metadata가 반드시 있다 +(`ck_outbox_event_canonical_unless_published`). pre-canonical `payload`·`idempotency_key` 컬럼은 +nullable로 남고 아무것도 쓰거나 읽지 않는다 — 이전 릴리스로 되돌릴 때를 위해 지우지 않았다. ### 트랜잭션 경계 계약 - **append**: 호출자의 `TransactionPort.inWrite()` 경계 안에서 호출되어야 하며, 내부에서 새 @@ -260,12 +261,11 @@ FIFO gate 의 "같은 aggregate"와 "앞선 row": 이고, 순서는 `(aggregate_sequence, event_index)` 다. 그래서 `occurred_at` 이 같은 이벤트도 한 번에 하나씩 나가고, 다른 tenant·type 의 DEAD row 가 같은 `aggregate_id` 를 막지 않는다. 인덱스는 `V18` 의 `ix_outbox_event_unpublished_aggregate_order`. -- legacy row 가 끼면 예전처럼 `aggregate_id` + `occurred_at <` 로 비교한다(같은 `occurred_at` 의 - legacy row 는 함께 claim된다 — `equalTimestampRowsAreClaimedTogetherLegacyFifoLimitationCharacterization`). +- gate 가 비교하는 row 는 전부 canonical 이다: V19 가 envelope 없는 미발행 row 를 거부한다. -읽을 수 없는 row(부분 canonical metadata, compatibility projection 불일치 등)는 claim 에서 DEAD 로 +읽을 수 없는 row(envelope 없음, 부분 metadata, 저장된 hash 와 bytes 불일치 등)는 claim 에서 DEAD 로 옮기고 배치에서 뺀다. 예전에는 예외로 claim transaction 전체가 롤백되고 다음 claim 이 같은 row 를 -다시 먼저 골라 relay 가 영구히 멈췄다. legacy 로 낮춰 발행하지 않으므로 fail-closed 는 유지된다. +다시 먼저 골라 relay 가 영구히 멈췄다. 추측해서 발행하지 않으므로 fail-closed 는 유지된다. eligible row(I3/I4/I6): - `PENDING` — `next_attempt_at <= now`(insert 시 즉시 eligible) diff --git a/src/adapter/outbound/persistence-jpa/build.gradle b/src/adapter/outbound/persistence-jpa/build.gradle index b816ec11..c9242d0d 100644 --- a/src/adapter/outbound/persistence-jpa/build.gradle +++ b/src/adapter/outbound/persistence-jpa/build.gradle @@ -153,9 +153,9 @@ def readinessLanes = [ postgresqlAggregateIntegrationTest : ['PostgreSqlAggregateIntegrationTest'], postgresqlQueryIntegrationTest : ['PostgreSqlQueryIntegrationTest'], postgresqlIdempotencyIntegrationTest : ['PostgreSqlIdempotencyIntegrationTest'], - postgresqlLegacyOutboxAppendTransactionalIntegrationTest: ['PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest'], - postgresqlLegacyOutboxConcurrentRelayIntegrationTest : ['PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest'], - postgresqlLegacyOutboxRowLifecycleIntegrationTest : ['PostgreSqlLegacyOutboxRowLifecycleIntegrationTest'], + postgresqlOutboxAppendTransactionalIntegrationTest : ['PostgreSqlOutboxAppendTransactionalIntegrationTest'], + postgresqlOutboxConcurrentRelayIntegrationTest : ['PostgreSqlOutboxConcurrentRelayIntegrationTest'], + postgresqlOutboxRowLifecycleIntegrationTest : ['PostgreSqlOutboxRowLifecycleIntegrationTest'], postgresqlFileserverMigrationIntegrationTest : ['PostgreSqlFileserverMigrationIntegrationTest'], postgresqlFileserverMetadataIntegrationTest : ['PostgreSqlFileserverMetadataStoreIntegrationTest'], postgresqlFileserverReclamationIntegrationTest : ['PostgreSqlFileserverReclamationIntegrationTest'], diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfig.java index 9a72bb76..1dca8fd0 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfig.java @@ -1,7 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.autoconfigure; -import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.IdempotencySchemaStream; -import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.PostgreSqlOwnerSafeIdempotencyStore; +import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.IdempotencySchemaStream; +import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlOwnerSafeIdempotencyStore; import dev.caskeleton.application.idempotency.IdempotencyStorePort; import javax.sql.DataSource; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2PersistenceConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2PersistenceConfig.java index 27146084..04447856 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2PersistenceConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2PersistenceConfig.java @@ -3,7 +3,8 @@ package dev.caskeleton.adapter.outbound.persistence.h2; import dev.caskeleton.adapter.outbound.persistence.config.PersistenceJpaConfig; import dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings; import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.h2.H2OutboxClaimRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository; import jakarta.persistence.EntityManager; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyReaper.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyReaper.java similarity index 95% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyReaper.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyReaper.java index 7adb7609..759379c0 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyReaper.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyReaper.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa; import java.time.Clock; import org.slf4j.Logger; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyRecordJpaRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyRecordJpaRepository.java similarity index 81% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyRecordJpaRepository.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyRecordJpaRepository.java index df7c0dc2..0c0288da 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyRecordJpaRepository.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyRecordJpaRepository.java @@ -1,6 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa; -import dev.caskeleton.adapter.outbound.persistence.idempotency.entity.IdempotencyRecordEntity; +import dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.entity.IdempotencyRecordEntity; import java.time.Instant; import java.util.UUID; import org.springframework.data.jpa.repository.JpaRepository; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/entity/IdempotencyRecordEntity.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/entity/IdempotencyRecordEntity.java similarity index 99% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/entity/IdempotencyRecordEntity.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/entity/IdempotencyRecordEntity.java index 8ef66aaa..e88f247b 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/entity/IdempotencyRecordEntity.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/entity/IdempotencyRecordEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.idempotency.entity; +package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyCapabilityGuard.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyCapabilityGuard.java similarity index 98% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyCapabilityGuard.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyCapabilityGuard.java index f574bd96..9bc0427e 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyCapabilityGuard.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyCapabilityGuard.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; import java.util.Objects; import javax.sql.DataSource; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyClaimGateway.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyClaimGateway.java similarity index 98% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyClaimGateway.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyClaimGateway.java index 1121b2b9..7884d1d0 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyClaimGateway.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyClaimGateway.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; import java.util.Objects; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyDigestPolicy.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java similarity index 97% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyDigestPolicy.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java index f1c5a225..5754cad9 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyDigestPolicy.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRecordRow.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyRecordRow.java similarity index 94% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRecordRow.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyRecordRow.java index 2010aa1f..d3ba48e1 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRecordRow.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyRecordRow.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; import dev.caskeleton.application.idempotency.IdempotencyState; import java.time.Instant; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRowMapper.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyRowMapper.java similarity index 98% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRowMapper.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyRowMapper.java index 78e67adc..6279e7de 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRowMapper.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyRowMapper.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; import dev.caskeleton.application.idempotency.IdempotencyState; import java.sql.ResultSet; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencySchemaStream.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencySchemaStream.java similarity index 98% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencySchemaStream.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencySchemaStream.java index ff06258b..f2b0f6fe 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencySchemaStream.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencySchemaStream.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; import java.util.Objects; import javax.sql.DataSource; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyTransitionGateway.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyTransitionGateway.java similarity index 98% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyTransitionGateway.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyTransitionGateway.java index 3f5df002..736169f0 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyTransitionGateway.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyTransitionGateway.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; import dev.caskeleton.application.idempotency.IdempotencyOwner; import java.time.Duration; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/PostgreSqlOwnerSafeIdempotencyStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlOwnerSafeIdempotencyStore.java similarity index 99% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/PostgreSqlOwnerSafeIdempotencyStore.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlOwnerSafeIdempotencyStore.java index 497808b5..a16c145f 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/PostgreSqlOwnerSafeIdempotencyStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlOwnerSafeIdempotencyStore.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt; import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapter.java deleted file mode 100644 index 61ad1ba5..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapter.java +++ /dev/null @@ -1,105 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.outbox; - -import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity; -import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import dev.caskeleton.application.outbox.OutboxAppendPort; -import dev.caskeleton.application.outbox.OutboxEventStatus; -import java.nio.ByteBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Objects; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** - * Canonical append path for the transport-only outbox cutover. - * - *

The existing {@code outbox_event} row remains the durable authority. Canonical metadata and - * exact envelope bytes are stored additively while legacy required columns receive a reversible - * compatibility projection. This adapter never opens its own transaction. - */ -@Repository -@ConditionalOnProperty( - prefix = "ca-skeleton.outbox", - name = {"enabled", "canonical-transport-enabled"}, - havingValue = "true") -final class CanonicalOutboxAppendAdapter implements OutboxAppendPort { - - private final OutboxEventJpaRepository repository; - - CanonicalOutboxAppendAdapter(OutboxEventJpaRepository repository) { - this.repository = Objects.requireNonNull(repository, "repository must not be null"); - } - - @Override - public void append(ValidatedIntegrationEvent event) { - // Outside a caller transaction the row commits on its own, apart from the business write it - // announces — the dual write the outbox exists to prevent. - if (!TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException("outbox append requires an active caller transaction"); - } - Objects.requireNonNull(event, "event must not be null"); - byte[] envelopeBytes = event.envelopeBytes(); - String compatibilityPayload = strictUtf8(envelopeBytes); - - OutboxEventEntity entity = new OutboxEventEntity(); - - // Legacy compatibility projection retained while the v1 relay owns the row lifecycle. - entity.setEventId(event.eventId().value()); - entity.setAggregateId(event.aggregate().aggregateId()); - entity.setEventType(event.contractId().value()); - entity.setPayload(compatibilityPayload); - entity.setOccurredAt(event.occurredAt()); - entity.setStatus(OutboxEventStatus.PENDING.name()); - entity.setAttemptCount(0); - entity.setNextAttemptAt(event.occurredAt()); - entity.setCorrelationId(event.correlationId()); - entity.setIdempotencyKey(event.eventId().value()); - - // Canonical authority for the new platform transport branch. - entity.setContractId(event.contractId().value()); - entity.setEnvelopeVersion(event.envelopeVersion()); - entity.setPayloadVersion(event.payloadVersion()); - entity.setLogicalDestination(event.logicalDestinationId().value()); - entity.setTenantScope(event.aggregate().tenantScope()); - entity.setAggregateType(event.aggregate().aggregateType()); - entity.setAggregateSequence(event.order().sequence()); - entity.setEventIndex(event.order().eventIndex()); - entity.setPartitionKey(event.partitionKeyText()); - entity.setEnvelopeBytes(envelopeBytes); - entity.setContentType(event.contentType()); - entity.setSchemaSetHash(event.schemaSetHash().toString()); - entity.setEnvelopeSha256(event.envelopeSha256().toString()); - entity.setEnvelopeSchemaHash(event.envelopeSchemaHash().toString()); - entity.setPayloadSchemaHash(event.payloadSchemaHash().toString()); - entity.setContractCatalogRevision(event.contractCatalogRevision()); - entity.setDestinationBindingRevision(event.destinationBindingRevision()); - entity.setCausationId(event.causationId().orElse(null)); - - repository.save(entity); - } - - private static String strictUtf8(byte[] bytes) { - try { - String decoded = - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(bytes)) - .toString(); - if (!Arrays.equals(decoded.getBytes(StandardCharsets.UTF_8), bytes)) { - throw new IllegalArgumentException( - "canonical envelope must round-trip as exact UTF-8 for the legacy compatibility projection"); - } - return decoded; - } catch (CharacterCodingException exception) { - throw new IllegalArgumentException( - "canonical envelope must be valid UTF-8 for the legacy compatibility projection", - exception); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2OutboxClaimRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/h2/H2OutboxClaimRepository.java similarity index 67% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2OutboxClaimRepository.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/h2/H2OutboxClaimRepository.java index 4d07f5ee..46b02409 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2OutboxClaimRepository.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/h2/H2OutboxClaimRepository.java @@ -1,7 +1,7 @@ -package dev.caskeleton.adapter.outbound.persistence.h2; +package dev.caskeleton.adapter.outbound.persistence.outbox.h2; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository; -import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; import jakarta.persistence.EntityManager; import java.time.Instant; import java.util.List; @@ -28,17 +28,13 @@ public final class H2OutboxClaimRepository implements OutboxClaimRepository { AND o.status IN ('PENDING', 'FAILED', 'IN_FLIGHT') AND NOT EXISTS ( SELECT 1 FROM outbox_event p - WHERE p.aggregate_id = o.aggregate_id - AND p.status <> 'PUBLISHED' - AND CASE - WHEN o.contract_id IS NOT NULL AND p.contract_id IS NOT NULL THEN - p.tenant_scope = o.tenant_scope - AND p.aggregate_type = o.aggregate_type - AND (p.aggregate_sequence < o.aggregate_sequence - OR (p.aggregate_sequence = o.aggregate_sequence - AND p.event_index < o.event_index)) - ELSE p.occurred_at < o.occurred_at - END + WHERE p.aggregate_id = o.aggregate_id + AND p.tenant_scope = o.tenant_scope + AND p.aggregate_type = o.aggregate_type + AND p.status <> 'PUBLISHED' + AND (p.aggregate_sequence < o.aggregate_sequence + OR (p.aggregate_sequence = o.aggregate_sequence + AND p.event_index < o.event_index)) ) ORDER BY o.occurred_at ASC, o.aggregate_sequence ASC, o.event_index ASC LIMIT :limit diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxClaimRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxClaimRepository.java similarity index 81% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxClaimRepository.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxClaimRepository.java index f23515ac..278346e8 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxClaimRepository.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxClaimRepository.java @@ -1,6 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.outbox; +package dev.caskeleton.adapter.outbound.persistence.outbox.jpa; -import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; import java.time.Instant; import java.util.List; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxEventJpaRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java similarity index 95% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxEventJpaRepository.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java index 4b2637c2..c323e644 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxEventJpaRepository.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java @@ -1,6 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.outbox; +package dev.caskeleton.adapter.outbound.persistence.outbox.jpa; -import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; import java.time.Instant; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxReaper.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxReaper.java similarity index 90% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxReaper.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxReaper.java index 71de2bdc..6cb1b57c 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxReaper.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxReaper.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.outbox; +package dev.caskeleton.adapter.outbound.persistence.outbox.jpa; import java.time.Clock; import java.time.Duration; @@ -31,8 +31,8 @@ public class OutboxReaper { private final Clock clock; private final Duration retention; - // @Value is acceptable for this single reaper-local value; canonical settings live in - // app-bootstrap OutboxSettings / application.yml. + // @Value is acceptable for this single reaper-local value; the settings are declared and + // validated once, in composition:outbox-relay OutboxSettings. public OutboxReaper( OutboxEventJpaRepository repository, Clock clock, diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java similarity index 68% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapter.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java index 6807f1f4..708bed94 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapter.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java @@ -1,6 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.outbox; +package dev.caskeleton.adapter.outbound.persistence.outbox.jpa; -import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; import dev.caskeleton.application.messaging.contract.Sha256; @@ -8,18 +8,12 @@ import dev.caskeleton.application.messaging.event.AggregateIdentity; import dev.caskeleton.application.messaging.event.AggregateOrder; import dev.caskeleton.application.messaging.event.EventId; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import dev.caskeleton.application.outbox.CanonicalClaimedOutboxEvent; import dev.caskeleton.application.outbox.ClaimedOutboxEvent; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.OutboxCompletion; -import dev.caskeleton.application.outbox.OutboxEvent; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; import dev.caskeleton.application.outbox.OutboxStorePort; -import java.nio.ByteBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; @@ -29,6 +23,7 @@ import java.util.HashMap; import java.util.HexFormat; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,15 +32,20 @@ import org.springframework.stereotype.Repository; import org.springframework.transaction.support.TransactionSynchronizationManager; /** - * JPA-backed {@link LegacyOutboxAppendPort} + {@link OutboxStorePort}. {@link #append} and the - * claim/mark operations run inside the caller's {@code TransactionPort.inWrite()} boundary and - * declare no {@code @Transactional} of their own; {@link #claimBatch} delegates the vendor claim to - * {@link OutboxClaimRepository}. See README "outbox" for the append/claim/no-@Transactional - * contracts. + * JPA-backed {@link OutboxAppendPort} + {@link OutboxStorePort}. {@link #append} and the claim/mark + * operations run inside the caller's {@code TransactionPort.inWrite()} boundary and declare no + * {@code @Transactional} of their own; {@link #claimBatch} delegates the vendor claim to {@link + * OutboxClaimRepository}. See README "outbox" for the append/claim/no-@Transactional contracts. + * + *

A row stores the exact envelope bytes and hashes of the {@link ValidatedIntegrationEvent} it + * was appended with, and a claim restores that event from them, so the relay publishes the bytes + * that were validated. The {@code event_type}, {@code aggregate_id} and {@code correlation_id} + * columns repeat the contract id, aggregate id and correlation id for the claim gate and the + * metrics queries. */ @Repository @ConditionalOnProperty(prefix = "ca-skeleton.outbox", name = "enabled", havingValue = "true") -public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePort { +public class OutboxStoreAdapter implements OutboxAppendPort, OutboxStorePort { private static final Logger log = LoggerFactory.getLogger(OutboxStoreAdapter.class); @@ -59,20 +59,40 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo } @Override - public void append(NewOutboxEvent event) { + public void append(ValidatedIntegrationEvent event) { + // Outside a caller transaction the row commits on its own, apart from the business write it + // announces — the dual write the outbox exists to prevent. requireTransaction("append"); + Objects.requireNonNull(event, "event must not be null"); + OutboxEventEntity entity = new OutboxEventEntity(); - entity.setEventId(event.eventId()); - entity.setAggregateId(event.aggregateId()); - entity.setEventType(event.eventType()); - entity.setPayload(event.payload()); + entity.setEventId(event.eventId().value()); + entity.setAggregateId(event.aggregate().aggregateId()); + entity.setEventType(event.contractId().value()); entity.setOccurredAt(event.occurredAt()); entity.setStatus(OutboxEventStatus.PENDING.name()); entity.setAttemptCount(0); // PENDING: nextAttemptAt = occurredAt so the relay can claim immediately. entity.setNextAttemptAt(event.occurredAt()); entity.setCorrelationId(event.correlationId()); - entity.setIdempotencyKey(event.idempotencyKey()); + entity.setContractId(event.contractId().value()); + entity.setEnvelopeVersion(event.envelopeVersion()); + entity.setPayloadVersion(event.payloadVersion()); + entity.setLogicalDestination(event.logicalDestinationId().value()); + entity.setTenantScope(event.aggregate().tenantScope()); + entity.setAggregateType(event.aggregate().aggregateType()); + entity.setAggregateSequence(event.order().sequence()); + entity.setEventIndex(event.order().eventIndex()); + entity.setPartitionKey(event.partitionKeyText()); + entity.setEnvelopeBytes(event.envelopeBytes()); + entity.setContentType(event.contentType()); + entity.setSchemaSetHash(event.schemaSetHash().toString()); + entity.setEnvelopeSha256(event.envelopeSha256().toString()); + entity.setEnvelopeSchemaHash(event.envelopeSchemaHash().toString()); + entity.setPayloadSchemaHash(event.payloadSchemaHash().toString()); + entity.setContractCatalogRevision(event.contractCatalogRevision()); + entity.setDestinationBindingRevision(event.destinationBindingRevision()); + entity.setCausationId(event.causationId().orElse(null)); repository.save(entity); } @@ -82,8 +102,8 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo * *

A row that cannot be read as an event is moved to DEAD and left out of the batch. Throwing * instead rolled the whole claim back, and the next claim selected the same row first again, so - * one bad row stopped the relay for good. DEAD is fail-closed: the row is never published or - * downgraded to a legacy claim, and it waits for the DEAD-row runbook like any other. + * one bad row stopped the relay for good. DEAD is fail-closed: the row is never published, and it + * waits for the DEAD-row runbook like any other. */ @Override public List claimBatch( @@ -176,40 +196,19 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo return result; } + /** + * Restores the appended event. A row without its envelope — written by the pre-canonical + * generation, or damaged — is unreadable, and so is one whose stored hash is not the hash of its + * bytes: {@link ValidatedIntegrationEvent} recomputes it, so a row cannot vouch for itself. + */ private static ClaimedOutboxEvent toClaimedOutboxEvent(OutboxEventEntity entity) { - if (!hasAnyCanonicalMetadata(entity)) { - return toLegacyOutboxEvent(entity); - } if (!hasCompleteCanonicalMetadata(entity)) { throw new IllegalStateException( - "outbox row contains partial canonical metadata for eventId=" + entity.getEventId()); + "outbox row eventId=" + + entity.getEventId() + + " carries no complete canonical envelope; the pre-canonical relay that read such" + + " rows is gone"); } - return toCanonicalOutboxEvent(entity); - } - - private static OutboxEvent toLegacyOutboxEvent(OutboxEventEntity entity) { - return new OutboxEvent( - entity.getEventId(), - entity.getEventType(), - entity.getAggregateId(), - entity.getPayload(), - entity.getOccurredAt(), - entity.getCorrelationId(), - entity.getIdempotencyKey(), - OutboxEventStatus.valueOf(entity.getStatus()), - entity.getAttemptCount()); - } - - private static CanonicalClaimedOutboxEvent toCanonicalOutboxEvent(OutboxEventEntity entity) { - byte[] envelopeBytes = entity.getEnvelopeBytes(); - String compatibilityPayload = strictUtf8(envelopeBytes, entity.getEventId()); - if (!entity.getEventType().equals(entity.getContractId()) - || !entity.getIdempotencyKey().equals(entity.getEventId()) - || !entity.getPayload().equals(compatibilityPayload)) { - throw new IllegalStateException( - "canonical outbox compatibility projection mismatch for eventId=" + entity.getEventId()); - } - try { ValidatedIntegrationEvent event = new ValidatedIntegrationEvent( @@ -226,7 +225,7 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo Optional.ofNullable(entity.getCausationId()), entity.getPartitionKey(), entity.getPartitionKey().getBytes(StandardCharsets.US_ASCII), - envelopeBytes, + entity.getEnvelopeBytes(), entity.getContentType(), digest(entity.getSchemaSetHash(), "schema_set_hash", entity.getEventId()), digest(entity.getEnvelopeSha256(), "envelope_sha256", entity.getEventId()), @@ -234,7 +233,7 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo digest(entity.getPayloadSchemaHash(), "payload_schema_hash", entity.getEventId()), entity.getContractCatalogRevision(), entity.getDestinationBindingRevision()); - return new CanonicalClaimedOutboxEvent( + return new ClaimedOutboxEvent( event, OutboxEventStatus.valueOf(entity.getStatus()), entity.getAttemptCount()); } catch (IllegalArgumentException exception) { throw new IllegalStateException( @@ -242,27 +241,6 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo } } - private static boolean hasAnyCanonicalMetadata(OutboxEventEntity entity) { - return entity.getContractId() != null - || entity.getEnvelopeVersion() != null - || entity.getPayloadVersion() != null - || entity.getLogicalDestination() != null - || entity.getTenantScope() != null - || entity.getAggregateType() != null - || entity.getAggregateSequence() != null - || entity.getEventIndex() != null - || entity.getPartitionKey() != null - || entity.getEnvelopeBytes() != null - || entity.getContentType() != null - || entity.getSchemaSetHash() != null - || entity.getEnvelopeSha256() != null - || entity.getEnvelopeSchemaHash() != null - || entity.getPayloadSchemaHash() != null - || entity.getContractCatalogRevision() != null - || entity.getDestinationBindingRevision() != null - || entity.getCausationId() != null; - } - private static boolean hasCompleteCanonicalMetadata(OutboxEventEntity entity) { return entity.getContractId() != null && entity.getEnvelopeVersion() != null @@ -288,21 +266,7 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo return new Sha256(HexFormat.of().parseHex(hex)); } catch (IllegalArgumentException exception) { throw new IllegalArgumentException( - "invalid " + field + " for canonical outbox eventId=" + eventId, exception); - } - } - - private static String strictUtf8(byte[] bytes, String eventId) { - try { - return StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(bytes)) - .toString(); - } catch (CharacterCodingException exception) { - throw new IllegalStateException( - "canonical outbox envelope is not valid UTF-8 for eventId=" + eventId, exception); + "invalid " + field + " for outbox eventId=" + eventId, exception); } } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/entity/OutboxEventEntity.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxEventEntity.java similarity index 90% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/entity/OutboxEventEntity.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxEventEntity.java index d3a58a61..6b932a6c 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/entity/OutboxEventEntity.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxEventEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.outbox.entity; +package dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -8,16 +8,15 @@ import jakarta.persistence.PostPersist; import jakarta.persistence.Table; import jakarta.persistence.Transient; import java.time.Instant; -import org.hibernate.annotations.JdbcTypeCode; -import org.hibernate.type.SqlTypes; import org.springframework.data.domain.Persistable; /** * JPA row for the {@code outbox_event} table; schema owned by Flyway ({@code V3__outbox_event.sql} * + additive canonical metadata in {@code V13__outbox_canonical_transport_compatibility.sql} + the - * relay lease in {@code V17__outbox_event_lease_fencing.sql}). Does not extend {@code - * AuditableEntity} (infra record, not a domain aggregate) and exposes mutating setters on purpose - * (relay transitions state in-place). + * relay lease in {@code V17__outbox_event_lease_fencing.sql} + the canonical-only rule in {@code + * V19__outbox_event_canonical_only.sql}). Does not extend {@code AuditableEntity} (infra record, + * not a domain aggregate) and exposes mutating setters on purpose (relay transitions state + * in-place). * *

{@link Persistable} so that {@code save} of a new row is always an insert. With an assigned * identifier and no version, Spring Data treats every entity as existing and merges it, and a @@ -41,10 +40,6 @@ public class OutboxEventEntity implements Persistable { @Column(name = "event_type", nullable = false, length = 256, updatable = false) private String eventType; - @JdbcTypeCode(SqlTypes.LONGVARCHAR) - @Column(name = "payload", nullable = false, updatable = false) - private String payload; - @Column(name = "occurred_at", nullable = false, updatable = false) private Instant occurredAt; @@ -70,10 +65,9 @@ public class OutboxEventEntity implements Persistable { @Column(name = "correlation_id", nullable = false, length = 128, updatable = false) private String correlationId; - @Column(name = "idempotency_key", nullable = false, length = 256, updatable = false) - private String idempotencyKey; - - // V13 canonical transport-only compatibility columns. Null as a set means an R0 legacy row. + // The canonical envelope (V13). A claimable row always has all of them (V19); the pre-canonical + // payload and idempotency_key columns stay in the table, unmapped and nullable, for rows written + // before and read by nothing now. @Column(name = "contract_id", length = 160, updatable = false) private String contractId; @@ -171,14 +165,6 @@ public class OutboxEventEntity implements Persistable { this.eventType = eventType; } - public String getPayload() { - return payload; - } - - public void setPayload(String payload) { - this.payload = payload; - } - public Instant getOccurredAt() { return occurredAt; } @@ -235,14 +221,6 @@ public class OutboxEventEntity implements Persistable { this.correlationId = correlationId; } - public String getIdempotencyKey() { - return idempotencyKey; - } - - public void setIdempotencyKey(String idempotencyKey) { - this.idempotencyKey = idempotencyKey; - } - public String getContractId() { return contractId; } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlOutboxClaimRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/postgresql/PostgreSqlOutboxClaimRepository.java similarity index 61% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlOutboxClaimRepository.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/postgresql/PostgreSqlOutboxClaimRepository.java index e84f6948..09e29330 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlOutboxClaimRepository.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/postgresql/PostgreSqlOutboxClaimRepository.java @@ -1,7 +1,7 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql; +package dev.caskeleton.adapter.outbound.persistence.outbox.postgresql; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository; -import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; import jakarta.persistence.EntityManager; import java.time.Instant; import java.util.List; @@ -14,8 +14,8 @@ import java.util.List; * rows are the same aggregate only with the same {@code (tenant_scope, aggregate_type, * aggregate_id)}, and earlier means a lower {@code (aggregate_sequence, event_index)} — so events * that share an {@code occurred_at} are still released one at a time, and a DEAD row of another - * tenant or type does not block this one. Any pair involving a legacy row keeps the {@code - * occurred_at} comparison it always had. + * tenant or type does not block this one. Every row the gate compares is canonical: V19 refuses an + * unpublished row without the canonical envelope. */ public class PostgreSqlOutboxClaimRepository implements OutboxClaimRepository { @@ -26,17 +26,13 @@ public class PostgreSqlOutboxClaimRepository implements OutboxClaimRepository { AND o.status IN ('PENDING', 'FAILED', 'IN_FLIGHT') AND NOT EXISTS ( SELECT 1 FROM outbox_event p - WHERE p.aggregate_id = o.aggregate_id - AND p.status <> 'PUBLISHED' - AND CASE - WHEN o.contract_id IS NOT NULL AND p.contract_id IS NOT NULL THEN - p.tenant_scope = o.tenant_scope - AND p.aggregate_type = o.aggregate_type - AND (p.aggregate_sequence < o.aggregate_sequence - OR (p.aggregate_sequence = o.aggregate_sequence - AND p.event_index < o.event_index)) - ELSE p.occurred_at < o.occurred_at - END + WHERE p.aggregate_id = o.aggregate_id + AND p.tenant_scope = o.tenant_scope + AND p.aggregate_type = o.aggregate_type + AND p.status <> 'PUBLISHED' + AND (p.aggregate_sequence < o.aggregate_sequence + OR (p.aggregate_sequence = o.aggregate_sequence + AND p.event_index < o.event_index)) ) ORDER BY o.occurred_at ASC, o.aggregate_sequence ASC, o.event_index ASC LIMIT :limit diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlPersistenceConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlPersistenceConfig.java index b389c76d..c9f17158 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlPersistenceConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlPersistenceConfig.java @@ -3,7 +3,8 @@ package dev.caskeleton.adapter.outbound.persistence.postgresql; import dev.caskeleton.adapter.outbound.persistence.config.PersistenceJpaConfig; import dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings; import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.postgresql.PostgreSqlOutboxClaimRepository; import jakarta.persistence.EntityManager; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.flyway.autoconfigure.FlywayConfigurationCustomizer; diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml b/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml index c83c8304..d6330787 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml @@ -175,8 +175,9 @@ ca-skeleton: enabled: ${APP_REALTIME_REPLAY_ENABLED:false} retention: ${APP_REALTIME_REPLAY_RETENTION:1h} outbox: - # feature-domain-event-outbox-contract I11 — all six values are literal defaults; - # NO env placeholders (spec: 신규 env key 없음). Bound into OutboxProperties. + # feature-domain-event-outbox-contract I11 — the tuning values are literal defaults; + # NO env placeholders (spec: 신규 env key 없음). Declared, validated and strictly bound by + # composition:outbox-relay OutboxSettings: an unknown key here fails startup. # true | false — enable/disable the relay scheduler (OutboxRelayScheduler). # The scheduler starts only when a publishing capability contributes an # OutboxMessagePublishPort, so an environment without one keeps its PENDING rows instead of @@ -187,9 +188,6 @@ ca-skeleton: # port that a database-less deployment does not have. enabled: ${APP_OUTBOX_ENABLED:false} relay-enabled: ${APP_OUTBOX_RELAY_ENABLED:false} - # Transport-only MSG-015 cutover gate. It does not start a second relay. - # When true, startup also requires the canonical IntegrationEventPublishPort. - canonical-transport-enabled: ${APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED:false} # ISO-8601 duration — how often the relay polls for pending rows poll-interval: PT5S # integer >= 1 — maximum rows claimed per relay cycle diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V19__outbox_event_canonical_only.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V19__outbox_event_canonical_only.sql new file mode 100644 index 00000000..fa9cf8f3 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V19__outbox_event_canonical_only.sql @@ -0,0 +1,36 @@ +-- The outbox has one append model now: the canonical ValidatedIntegrationEvent (envelope bytes plus +-- the V13 metadata). The pre-canonical relay that published rows from the free-text payload column +-- is gone, so a row without the envelope can no longer be delivered by anything. +-- +-- 1. Refuse to migrate while such a row still waits. Dead-lettering it here would drop an event an +-- older release could still publish, and letting it through would leave it blocking its +-- aggregate's FIFO queue for ever. Drain the relay with the previous release first, or resolve +-- the rows by hand (see the outbox DEAD-row runbook), then run this migration again. +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM outbox_event WHERE contract_id IS NULL AND status <> 'PUBLISHED' + ) THEN + RAISE EXCEPTION + 'outbox_event still holds unpublished rows without a canonical envelope; drain them with ' + 'the previous release (or resolve them by hand) before applying V19'; + END IF; +END +$$; + +-- 2. The canonical append writes neither pre-canonical column. They stay, nullable, so a rollback +-- to the previous release still finds them; nothing reads them any more. +ALTER TABLE outbox_event + ALTER COLUMN payload DROP NOT NULL, + ALTER COLUMN idempotency_key DROP NOT NULL; + +-- 3. From here on every row that can still be claimed carries the envelope. PUBLISHED rows written +-- before this migration are exempt until the reaper deletes them. +ALTER TABLE outbox_event + ADD CONSTRAINT ck_outbox_event_canonical_unless_published + CHECK (contract_id IS NOT NULL OR status = 'PUBLISHED'); + +COMMENT ON COLUMN outbox_event.payload IS + 'Pre-canonical payload text. Not written since V19; the envelope is envelope_bytes.'; +COMMENT ON COLUMN outbox_event.idempotency_key IS + 'Pre-canonical dedup key. Not written since V19; consumers deduplicate on event_id.'; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java index 19b7d712..92c49366 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java @@ -4,13 +4,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.persistence.operation.entity.DurableOperationEntity; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter; -import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort; +import dev.caskeleton.adapter.outbound.support.messaging.JsonIntegrationEventEncoder; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.operation.DurableOperationId; +import dev.caskeleton.application.operation.DurableOperationSubmittedContract; import dev.caskeleton.application.operation.OperationAcceptance; import dev.caskeleton.application.operation.OperationCommand; import dev.caskeleton.application.operation.SubmitDurableOperationUseCase; @@ -91,6 +93,19 @@ class DurableOperationSubmissionOutboxIntegrationTest { execute("TRUNCATE durable_operation, outbox_event"); } + @Test + void aSubmissionStoresTheEncodedSubmittedEventAsACanonicalRow() throws SQLException { + // given + SubmitDurableOperationUseCase useCase = context.getBean(SubmitDurableOperationUseCase.class); + + // when + useCase.handle(command()); + + // then + assertThat(queryStrings("SELECT contract_id || '|' || aggregate_id FROM outbox_event")) + .containsExactly("durable-operation.submitted|op-1"); + } + @Test void retryUnderTheSameOperationIdLeavesThePublishedOutboxRowAlone() throws SQLException { // given @@ -135,14 +150,16 @@ class DurableOperationSubmissionOutboxIntegrationTest { null, new RequestFingerprint("a".repeat(64)), "{\"range\":\"2026-08\"}", - OperationCommand.SUBMITTED_EVENT_TYPE, Duration.ofDays(1)); } private static List outboxStatuses() throws SQLException { + return queryStrings("SELECT status FROM outbox_event ORDER BY event_id"); + } + + private static List queryStrings(String sql) throws SQLException { try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement("SELECT status FROM outbox_event ORDER BY event_id"); + PreparedStatement statement = connection.prepareStatement(sql); ResultSet rows = statement.executeQuery()) { List statuses = new ArrayList<>(); while (rows.next()) { @@ -198,6 +215,7 @@ class DurableOperationSubmissionOutboxIntegrationTest { new DurableOperationStoreAdapter(operations), // The claim is never exercised here; submission only appends. new OutboxStoreAdapter(outbox, (now, limit) -> List.of()), + new JsonIntegrationEventEncoder(List.of(new DurableOperationSubmittedContract())), transactions, Clock.fixed(NOW, ZoneOffset.UTC)); } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/LegacyOutboxIntegrationSupport.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxIntegrationSupport.java similarity index 93% rename from src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/LegacyOutboxIntegrationSupport.java rename to src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxIntegrationSupport.java index 3328c8d1..ffe7025d 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/LegacyOutboxIntegrationSupport.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxIntegrationSupport.java @@ -1,9 +1,9 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter; -import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlOutboxClaimRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter; +import dev.caskeleton.adapter.outbound.persistence.outbox.postgresql.PostgreSqlOutboxClaimRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort; import dev.caskeleton.application.outbox.OutboxBackoffPolicy; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; @@ -29,19 +29,19 @@ import org.springframework.orm.jpa.SharedEntityManagerCreator; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; /** - * Shared real-PostgreSQL + Spring context support for legacy outbox integration tests + * Shared real-PostgreSQL + Spring context support for outbox integration tests * (feature-domain-event-outbox-contract Task E). * *

Does NOT boot the full {@code CaSkeletonApplication}. Builds a minimal {@link * AnnotationConfigApplicationContext} with only the JPA / outbox persistence beans needed for the * outbox integration tests. */ -final class LegacyOutboxIntegrationSupport { +final class OutboxIntegrationSupport { static final int BATCH_SIZE_CONTRACT = 50; static final Duration IN_FLIGHT_TIMEOUT = Duration.ofSeconds(30); - private LegacyOutboxIntegrationSupport() {} + private OutboxIntegrationSupport() {} /** * Runs Flyway migrations against the given DataSource. All three migrations (V1 idempotency, V2 @@ -84,8 +84,7 @@ final class LegacyOutboxIntegrationSupport { .getPropertySources() .addFirst( new MapPropertySource( - "legacy-outbox-integration", - java.util.Map.of("ca-skeleton.outbox.enabled", "true"))); + "outbox-integration", java.util.Map.of("ca-skeleton.outbox.enabled", "true"))); // Register DataSource — no destroy (caller owns lifecycle). ctx.registerBean( diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java index 7e676444..6424d3b1 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java @@ -2,7 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.PostgreSqlOwnerSafeIdempotencyStore; +import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlOwnerSafeIdempotencyStore; import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt; import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome; import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAppendTransactionalIntegrationTest.java similarity index 70% rename from src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest.java rename to src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAppendTransactionalIntegrationTest.java index ac0be38f..5034b48c 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAppendTransactionalIntegrationTest.java @@ -1,8 +1,8 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.testkit.LegacyOutboxAppendContract; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository; +import dev.caskeleton.application.outbox.OutboxAppendPort; +import dev.caskeleton.application.outbox.testkit.OutboxAppendContract; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.time.Instant; @@ -20,7 +20,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext *

Proves the no-dual-write guarantee (D2): if the business transaction rolls back, the outbox * row vanishes with it — there is no separate out-of-band insert. */ -class PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest { +class PostgreSqlOutboxAppendTransactionalIntegrationTest { private static PostgreSqlReadinessSupport postgres; private static DataSource sharedDataSource; @@ -29,7 +29,7 @@ class PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest { static void setup() { postgres = PostgreSqlReadinessSupport.start(); sharedDataSource = postgres.dataSource(); - LegacyOutboxIntegrationSupport.migrate(sharedDataSource); + OutboxIntegrationSupport.migrate(sharedDataSource); } @AfterAll @@ -44,13 +44,13 @@ class PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest { Clock clock = Clock.fixed(Instant.now(), ZoneOffset.UTC); try (AnnotationConfigApplicationContext ctx = - LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { + OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { TransactionPort tx = ctx.getBean(TransactionPort.class); - LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class); + OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); OutboxEventJpaRepository repo = ctx.getBean(OutboxEventJpaRepository.class); - LegacyOutboxAppendContract.verifyRollbackRemovesEvent( + OutboxAppendContract.verifyRollbackRemovesEvent( tx, append, eventId -> repo.findById(eventId).isPresent(), clock); } } @@ -60,13 +60,13 @@ class PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest { Clock clock = Clock.fixed(Instant.now(), ZoneOffset.UTC); try (AnnotationConfigApplicationContext ctx = - LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { + OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { TransactionPort tx = ctx.getBean(TransactionPort.class); - LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class); + OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); OutboxEventJpaRepository repo = ctx.getBean(OutboxEventJpaRepository.class); - LegacyOutboxAppendContract.verifyCommitPersistsEvent( + OutboxAppendContract.verifyCommitPersistsEvent( tx, append, eventId -> repo.findById(eventId).isPresent(), clock); } } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java index 1528fafb..5b6a0a8c 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java @@ -1,10 +1,11 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxReaper; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxReaper; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; import dev.caskeleton.application.transaction.TransactionPort; @@ -20,6 +21,8 @@ import java.util.HexFormat; import java.util.List; import java.util.Map; import javax.sql.DataSource; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.FlywayException; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -27,14 +30,15 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.dao.DataIntegrityViolationException; import org.springframework.jdbc.core.JdbcTemplate; /** * The claim gate, the claim's handling of unreadable rows, the status gauge query and the reaper, * against real PostgreSQL through the shipped outbox store. * - *

Canonical rows are written with SQL because the canonical append adapter is internal to its - * package; the columns are the ones that adapter writes. + *

Rows are written with SQL so a test can store one the append port would refuse — a damaged + * envelope, a row without one; the columns are the ones the append writes. */ @Tag("jpa-contract") class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { @@ -55,7 +59,7 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { static void start() { postgres = PostgreSqlReadinessSupport.start(); dataSource = postgres.dataSource(); - LegacyOutboxIntegrationSupport.migrate(dataSource); + OutboxIntegrationSupport.migrate(dataSource); } @AfterAll @@ -70,7 +74,7 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { jdbc = new JdbcTemplate(dataSource); jdbc.execute("TRUNCATE outbox_event"); context = - LegacyOutboxIntegrationSupport.buildContext( + OutboxIntegrationSupport.buildContext( dataSource, event -> {}, Clock.fixed(NOW, ZoneOffset.UTC)); } @@ -113,9 +117,8 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { void anUnreadableCanonicalRowDoesNotStopTheRestOfTheBatchFromBeingClaimed() { // given insertCanonical("unreadable", "tenant-a", "worklog", 1, 0, "PENDING"); - jdbc.update( - "UPDATE outbox_event SET payload = 'not the envelope' WHERE event_id = 'unreadable'"); - insertLegacy("readable", "PENDING", OCCURRED); + damageEnvelopeHash("unreadable"); + insertStandalone("readable", "PENDING"); // when List claimed = claim(); @@ -128,8 +131,7 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { void anUnreadableCanonicalRowIsMovedToDeadByTheClaim() { // given insertCanonical("unreadable", "tenant-a", "worklog", 1, 0, "PENDING"); - jdbc.update( - "UPDATE outbox_event SET payload = 'not the envelope' WHERE event_id = 'unreadable'"); + damageEnvelopeHash("unreadable"); // when claim(); @@ -141,8 +143,8 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { @Test void countByStatusLeavesPublishedRowsUncounted() { // given - insertLegacy("published", "PUBLISHED", OCCURRED); - insertLegacy("pending", "PENDING", OCCURRED); + insertStandalone("published", "PUBLISHED"); + insertStandalone("pending", "PENDING"); // when Map counts = context.getBean(OutboxStoreAdapter.class).countByStatus(); @@ -155,9 +157,9 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { void reaperDeletesOldPublishedRowsOutsideAnyCallerTransaction() { // given for (int index = 0; index < 5; index++) { - insertLegacy("published-" + index, "PUBLISHED", OCCURRED); + insertStandalone("published-" + index, "PUBLISHED"); } - insertLegacy("pending", "PENDING", OCCURRED); + insertStandalone("pending", "PENDING"); OutboxReaper reaper = new OutboxReaper( context.getBean(OutboxEventJpaRepository.class), @@ -171,6 +173,62 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { assertThat(List.of(purged, rowCount())).containsExactly(5, 1); } + @Test + void aRowWithoutTheCanonicalEnvelopeIsRefusedUnlessItIsPublished() { + // when + Throwable thrown = catchThrowable(() -> insertPreCanonical("pre-canonical", "PENDING")); + + // then + assertThat(thrown) + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("ck_outbox_event_canonical_unless_published"); + } + + @Test + void aPublishedPreCanonicalRowIsKeptForTheReaper() { + // when + insertPreCanonical("pre-canonical-published", "PUBLISHED"); + + // then + assertThat(status("pre-canonical-published")).isEqualTo("PUBLISHED"); + } + + @Test + void theCanonicalOnlyMigrationRefusesADatabaseThatStillHoldsAnUndeliveredPreCanonicalRow() { + // given + String schema = "outbox_v19_guard"; + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .locations("classpath:db/migration/postgresql") + .target("18") + .load() + .migrate(); + jdbc.update( + "INSERT INTO " + + schema + + ".outbox_event (event_id, aggregate_id, event_type, payload, occurred_at, status," + + " attempt_count, next_attempt_at, correlation_id, idempotency_key)" + + " VALUES ('waiting', 'agg-1', 'TestEvent', '{}', now(), 'PENDING', 0, now()," + + " 'corr-1', 'waiting')"); + + // when + Throwable thrown = + catchThrowable( + () -> + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .locations("classpath:db/migration/postgresql") + .load() + .migrate()); + + // then + assertThat(thrown) + .isInstanceOf(FlywayException.class) + .hasMessageContaining("unpublished rows without a canonical envelope"); + } + private List claim() { OutboxStoreAdapter store = context.getBean(OutboxStoreAdapter.class); List leases = @@ -187,7 +245,8 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { long sequence, int eventIndex, String status) { - insertCanonical(eventId, tenantScope, aggregateType, sequence, eventIndex, status, OCCURRED); + insertCanonical( + eventId, "worklog-42", tenantScope, aggregateType, sequence, eventIndex, status, OCCURRED); } private void insertCanonical( @@ -198,25 +257,44 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { int eventIndex, String status, Instant occurredAt) { + insertCanonical( + eventId, + "worklog-42", + tenantScope, + aggregateType, + sequence, + eventIndex, + status, + occurredAt); + } + + private void insertCanonical( + String eventId, + String aggregateId, + String tenantScope, + String aggregateType, + long sequence, + int eventIndex, + String status, + Instant occurredAt) { jdbc.update( """ INSERT INTO outbox_event ( - event_id, aggregate_id, event_type, payload, occurred_at, status, attempt_count, - next_attempt_at, correlation_id, idempotency_key, + event_id, aggregate_id, event_type, occurred_at, status, attempt_count, + next_attempt_at, correlation_id, contract_id, envelope_version, payload_version, logical_destination, tenant_scope, aggregate_type, aggregate_sequence, event_index, partition_key, envelope_bytes, content_type, schema_set_hash, envelope_sha256, envelope_schema_hash, payload_schema_hash, contract_catalog_revision, destination_binding_revision) - VALUES (?, 'worklog-42', 'portfolio.worklog.reserved', ?, ?, ?, 0, ?, 'corr-1', ?, + VALUES (?, ?, 'portfolio.worklog.reserved', ?, ?, 0, ?, 'corr-1', 'portfolio.worklog.reserved', 1, 3, 'portfolio-domain-events', ?, ?, ?, ?, ?, ?, 'application/json', ?, ?, ?, ?, 'catalog-r1', 'binding-r1') """, eventId, - ENVELOPE, + aggregateId, Timestamp.from(occurredAt), status, Timestamp.from(occurredAt), - eventId, tenantScope, aggregateType, sequence, @@ -229,7 +307,19 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { "4".repeat(64)); } - private void insertLegacy(String eventId, String status, Instant occurredAt) { + /** A canonical row that is the only event of its own aggregate. */ + private void insertStandalone(String eventId, String status) { + insertCanonical(eventId, "agg-" + eventId, "tenant-a", "worklog", 1, 0, status, OCCURRED); + } + + /** The hash no longer matches the bytes, so the claim cannot restore the event. */ + private void damageEnvelopeHash(String eventId) { + jdbc.update( + "UPDATE outbox_event SET envelope_sha256 = ? WHERE event_id = ?", "2".repeat(64), eventId); + } + + /** A row as the pre-canonical append wrote it: payload text, no envelope. */ + private void insertPreCanonical(String eventId, String status) { jdbc.update( """ INSERT INTO outbox_event ( @@ -239,9 +329,9 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { """, eventId, "agg-" + eventId, - Timestamp.from(occurredAt), + Timestamp.from(OCCURRED), status, - Timestamp.from(occurredAt), + Timestamp.from(OCCURRED), eventId); } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java similarity index 82% rename from src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest.java rename to src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java index 7a883450..ea3c79ae 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java @@ -2,14 +2,14 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxRelayResult; import dev.caskeleton.application.outbox.OutboxStorePort; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; import dev.caskeleton.application.outbox.testkit.OutboxLeaseFencingContract; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; @@ -42,7 +42,7 @@ import org.springframework.jdbc.core.JdbcTemplate; * ConcurrentHashMap}. Both relay loops run until the store is drained (claimedCount == 0 for both * instances). Then assert total = 1000, duplicates = 0. */ -class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFencingContract { +class PostgreSqlOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFencingContract { private static PostgreSqlReadinessSupport postgres; private static DataSource sharedDataSource; @@ -52,9 +52,9 @@ class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFe static void setup() { postgres = PostgreSqlReadinessSupport.start(); sharedDataSource = postgres.dataSource(); - LegacyOutboxIntegrationSupport.migrate(sharedDataSource); + OutboxIntegrationSupport.migrate(sharedDataSource); contractContext = - LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, Clock.systemUTC()); + OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, Clock.systemUTC()); } @BeforeEach @@ -85,23 +85,16 @@ class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFe Clock clock = Clock.fixed(t0.plusSeconds(1), ZoneOffset.UTC); AnnotationConfigApplicationContext seedCtx = - LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock); + OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock); TransactionPort seedTx = seedCtx.getBean(TransactionPort.class); - LegacyOutboxAppendPort appendPort = seedCtx.getBean(LegacyOutboxAppendPort.class); + OutboxAppendPort appendPort = seedCtx.getBean(OutboxAppendPort.class); seedTx.inWrite( () -> { for (int i = 0; i < 1000; i++) { String id = "evt-leader-" + i; - appendPort.append( - new NewOutboxEvent( - id, - "TestEvent", - "agg-leader-" + i, // distinct aggregateId per row - "{\"seq\":" + i + "}", - t0, // fixed occurredAt = t0 so next_attempt_at = t0 <= relay now - "corr-leader-" + i, - id)); + // distinct aggregate per row; occurredAt = t0 so next_attempt_at = t0 <= relay now + appendPort.append(OutboxEvents.event(id, "agg-leader-" + i, 1, t0)); } return null; }); @@ -113,7 +106,7 @@ class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFe // ---- build two independent contexts, each with its own stub publisher ---- AnnotationConfigApplicationContext ctx1 = - LegacyOutboxIntegrationSupport.buildContext( + OutboxIntegrationSupport.buildContext( sharedDataSource, event -> { String prev = publishedByEventId.put(event.eventId(), "instance-1"); @@ -124,7 +117,7 @@ class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFe clock); AnnotationConfigApplicationContext ctx2 = - LegacyOutboxIntegrationSupport.buildContext( + OutboxIntegrationSupport.buildContext( sharedDataSource, event -> { String prev = publishedByEventId.put(event.eventId(), "instance-2"); @@ -134,8 +127,8 @@ class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFe }, clock); - PublishPendingOutboxEventsUseCase relay1 = LegacyOutboxIntegrationSupport.relayUseCase(ctx1); - PublishPendingOutboxEventsUseCase relay2 = LegacyOutboxIntegrationSupport.relayUseCase(ctx2); + PublishPendingOutboxEventsUseCase relay1 = OutboxIntegrationSupport.relayUseCase(ctx1); + PublishPendingOutboxEventsUseCase relay2 = OutboxIntegrationSupport.relayUseCase(ctx2); // ---- drive both relay loops concurrently until drained ---- ExecutorService executor = Executors.newFixedThreadPool(2); @@ -169,7 +162,7 @@ class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFe } @Override - protected LegacyOutboxAppendPort append() { + protected OutboxAppendPort append() { return contractContext.getBean(OutboxStoreAdapter.class); } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxRowLifecycleIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxRowLifecycleIntegrationTest.java similarity index 87% rename from src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxRowLifecycleIntegrationTest.java rename to src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxRowLifecycleIntegrationTest.java index 6b4b8ab2..c636b65e 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxRowLifecycleIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxRowLifecycleIntegrationTest.java @@ -2,12 +2,12 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxReaper; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter; -import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxReaper; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.OutboxBackoffPolicy; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; @@ -15,6 +15,7 @@ import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.application.outbox.OutboxRelayResult; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.time.Duration; @@ -46,7 +47,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext *

  • Reaper TTL deletion of PUBLISHED rows * */ -class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { +class PostgreSqlOutboxRowLifecycleIntegrationTest { private static PostgreSqlReadinessSupport postgres; private static DataSource sharedDataSource; @@ -55,7 +56,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { static void setup() { postgres = PostgreSqlReadinessSupport.start(); sharedDataSource = postgres.dataSource(); - LegacyOutboxIntegrationSupport.migrate(sharedDataSource); + OutboxIntegrationSupport.migrate(sharedDataSource); } @AfterAll @@ -73,10 +74,10 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { void pendingRowTransitionsToPublishedOnSuccessfulRelay() { Clock clock = Clock.fixed(Instant.now(), ZoneOffset.UTC); try (AnnotationConfigApplicationContext ctx = - LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { + OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { TransactionPort tx = ctx.getBean(TransactionPort.class); - LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class); + OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); String eventId = "lifecycle-happy-" + System.nanoTime(); tx.inWrite( @@ -85,7 +86,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { return null; }); - PublishPendingOutboxEventsUseCase relay = LegacyOutboxIntegrationSupport.relayUseCase(ctx); + PublishPendingOutboxEventsUseCase relay = OutboxIntegrationSupport.relayUseCase(ctx); OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); long published = @@ -112,7 +113,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { AtomicBoolean fail = new AtomicBoolean(true); try (AnnotationConfigApplicationContext ctx = - LegacyOutboxIntegrationSupport.buildContext( + OutboxIntegrationSupport.buildContext( sharedDataSource, e -> { if (fail.get()) { @@ -122,7 +123,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { clock)) { TransactionPort tx = ctx.getBean(TransactionPort.class); - LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class); + OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class); String eventId = "lifecycle-fail-" + System.nanoTime(); @@ -132,7 +133,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { return null; }); - PublishPendingOutboxEventsUseCase relay = LegacyOutboxIntegrationSupport.relayUseCase(ctx); + PublishPendingOutboxEventsUseCase relay = OutboxIntegrationSupport.relayUseCase(ctx); OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); long failed = @@ -169,7 +170,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { AtomicInteger publishAttempts = new AtomicInteger(0); try (AnnotationConfigApplicationContext ctx = - LegacyOutboxIntegrationSupport.buildContext( + OutboxIntegrationSupport.buildContext( sharedDataSource, e -> { publishAttempts.incrementAndGet(); @@ -178,7 +179,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { appendClock)) { TransactionPort tx = ctx.getBean(TransactionPort.class); - LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class); + OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class); String eventId = "lifecycle-dead-" + System.nanoTime(); @@ -242,10 +243,10 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { Clock clock = Clock.fixed(t0.plusSeconds(1), ZoneOffset.UTC); try (AnnotationConfigApplicationContext ctx = - LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { + OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { TransactionPort tx = ctx.getBean(TransactionPort.class); - LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class); + OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); String aggId = "agg-fifo-order-" + System.nanoTime(); String headId = "fifo-order-head-" + System.nanoTime(); @@ -260,7 +261,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { return null; }); - PublishPendingOutboxEventsUseCase relay = LegacyOutboxIntegrationSupport.relayUseCase(ctx); + PublishPendingOutboxEventsUseCase relay = OutboxIntegrationSupport.relayUseCase(ctx); // --- Relay cycle 1: FIFO gate blocks tail while head is PENDING --- // The NOT EXISTS gate allows only the head (head has no non-PUBLISHED @@ -305,16 +306,22 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { } } + /** + * The gate orders by aggregate sequence, not by time: two events of one aggregate that share an + * {@code occurred_at} are still released one at a time. The pre-canonical gate compared {@code + * occurred_at} with {@code <} and released both together. + */ @Test - void equalTimestampRowsAreClaimedTogetherLegacyFifoLimitationCharacterization() { + void eventsSharingAnOccurredAtAreReleasedOneAtATimeInAggregateOrder() { + // given Instant occurredAt = Instant.now(); Clock clock = Clock.fixed(occurredAt.plusSeconds(1), ZoneOffset.UTC); try (AnnotationConfigApplicationContext ctx = - LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { + OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { TransactionPort tx = ctx.getBean(TransactionPort.class); - LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class); + OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); String aggregateId = "agg-fifo-tie-" + System.nanoTime(); String firstId = "fifo-tie-first-" + System.nanoTime(); @@ -322,23 +329,22 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { tx.inWrite( () -> { - append.append(newEventAt(firstId, aggregateId, occurredAt)); - append.append(newEventAt(secondId, aggregateId, occurredAt)); + append.append(OutboxEvents.event(secondId, aggregateId, 2, occurredAt)); + append.append(OutboxEvents.event(firstId, aggregateId, 1, occurredAt)); return null; }); + // when OutboxRelayResult cycle = - LegacyOutboxIntegrationSupport.relayUseCase(ctx) + OutboxIntegrationSupport.relayUseCase(ctx) .handle(PublishPendingOutboxEventsCommand.INSTANCE); + // then assertThat(cycle.outcomes()) - .as( - "legacy FIFO compares only occurred_at with '<', so equal timestamps do not gate" - + " either row") .filteredOn( outcome -> outcome.eventId().equals(firstId) || outcome.eventId().equals(secondId)) .extracting(OutboxRelayResult.EventOutcome::eventId) - .containsExactlyInAnyOrder(firstId, secondId); + .containsExactly(firstId); } } @@ -360,7 +366,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { Clock clock = Clock.fixed(t0, ZoneOffset.UTC); try (AnnotationConfigApplicationContext ctx = - LegacyOutboxIntegrationSupport.buildContext( + OutboxIntegrationSupport.buildContext( sharedDataSource, e -> { throw new RuntimeException("forced failure for head"); @@ -368,7 +374,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { clock)) { TransactionPort tx = ctx.getBean(TransactionPort.class); - LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class); + OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class); String aggId = "agg-fifo-blocked-" + System.nanoTime(); @@ -386,7 +392,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { // Relay cycle 1: head is claimed and fails → transitions to FAILED // with nextAttemptAt = t0 + backoff (far in the future). // Tail is already blocked by the FIFO gate (head is PENDING). - PublishPendingOutboxEventsUseCase relay = LegacyOutboxIntegrationSupport.relayUseCase(ctx); + PublishPendingOutboxEventsUseCase relay = OutboxIntegrationSupport.relayUseCase(ctx); OutboxRelayResult cycle1 = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); assertThat( @@ -433,10 +439,10 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { Clock clock = Clock.fixed(t0.plusSeconds(1), ZoneOffset.UTC); try (AnnotationConfigApplicationContext ctx = - LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { + OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { TransactionPort tx = ctx.getBean(TransactionPort.class); - LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class); + OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); String aggId = "agg-fifo-unblock-" + System.nanoTime(); String headId = "fifo-unblock-head-" + System.nanoTime(); @@ -450,7 +456,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { return null; }); - PublishPendingOutboxEventsUseCase relay = LegacyOutboxIntegrationSupport.relayUseCase(ctx); + PublishPendingOutboxEventsUseCase relay = OutboxIntegrationSupport.relayUseCase(ctx); // Cycle 1: head is claimed and published, tail is blocked. OutboxRelayResult cycle1 = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -491,7 +497,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { Instant t0 = Instant.now(); try (AnnotationConfigApplicationContext ctx = - LegacyOutboxIntegrationSupport.buildContext( + OutboxIntegrationSupport.buildContext( sharedDataSource, e -> { throw new RuntimeException("always fails"); @@ -499,7 +505,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { Clock.fixed(t0, ZoneOffset.UTC))) { TransactionPort tx = ctx.getBean(TransactionPort.class); - LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class); + OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class); String aggId = "agg-fifo-dead-" + System.nanoTime(); @@ -572,10 +578,10 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { Clock reclaimClock = Clock.fixed(t0.plus(Duration.ofSeconds(31)), ZoneOffset.UTC); try (AnnotationConfigApplicationContext ctx = - LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, claimClock)) { + OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, claimClock)) { TransactionPort tx = ctx.getBean(TransactionPort.class); - LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class); + OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class); String eventId = "lifecycle-orphan-" + System.nanoTime(); @@ -603,8 +609,8 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { ctx.getBean(TransactionPort.class), new OutboxBackoffPolicy(RandomGenerator.getDefault()), reclaimClock, - LegacyOutboxIntegrationSupport.BATCH_SIZE_CONTRACT, - LegacyOutboxIntegrationSupport.IN_FLIGHT_TIMEOUT, + OutboxIntegrationSupport.BATCH_SIZE_CONTRACT, + OutboxIntegrationSupport.IN_FLIGHT_TIMEOUT, UUID.randomUUID().toString()); OutboxRelayResult reclaimResult = @@ -630,10 +636,10 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { Clock clock = Clock.fixed(Instant.now(), ZoneOffset.UTC); try (AnnotationConfigApplicationContext ctx = - LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { + OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { TransactionPort tx = ctx.getBean(TransactionPort.class); - LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class); + OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class); String eventId = "lifecycle-reap-" + System.nanoTime(); @@ -694,23 +700,23 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { ctx.getBean(TransactionPort.class), new OutboxBackoffPolicy(RandomGenerator.getDefault()), Clock.fixed(clockInstant, ZoneOffset.UTC), - LegacyOutboxIntegrationSupport.BATCH_SIZE_CONTRACT, - LegacyOutboxIntegrationSupport.IN_FLIGHT_TIMEOUT, + OutboxIntegrationSupport.BATCH_SIZE_CONTRACT, + OutboxIntegrationSupport.IN_FLIGHT_TIMEOUT, UUID.randomUUID().toString()); } - private static NewOutboxEvent newEvent(String eventId, String aggregateId, Clock clock) { + private static ValidatedIntegrationEvent newEvent( + String eventId, String aggregateId, Clock clock) { return newEventAt(eventId, aggregateId, clock.instant()); } - private static NewOutboxEvent newEventAt(String eventId, String aggregateId, Instant occurredAt) { - return new NewOutboxEvent( - eventId, - "TestEvent", - aggregateId, - "{\"test\":true}", - occurredAt, - "corr-" + eventId, - eventId); + /** + * An event whose aggregate sequence is its occurrence time in microseconds, so events of one + * aggregate appended in time order are also in aggregate order. + */ + private static ValidatedIntegrationEvent newEventAt( + String eventId, String aggregateId, Instant occurredAt) { + long sequence = occurredAt.getEpochSecond() * 1_000_000L + occurredAt.getNano() / 1_000; + return OutboxEvents.event(eventId, aggregateId, sequence, occurredAt); } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java index ed6e06b8..abb0b5fb 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java @@ -23,7 +23,7 @@ class CandidateAdapterCompositionTest { @DisplayName("the idempotency store that already fixed this stays fixed") void theIdempotencyStoreThatAlreadyFixedThisStaysFixed() { Class store = - dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency + dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql .PostgreSqlOwnerSafeIdempotencyStore.class; assertThat(store.getAnnotation(Repository.class)) 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 5cb1cc20..44a7deb6 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 @@ -79,6 +79,9 @@ class JpaModuleBoundaryTest { "config", "h2", "hibernate", + // The PostgreSQL idempotency store, which lives with its feature + // (idempotency.postgresql) and is registered from here. + "idempotency", "notification", "observation", "postgresql", diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfigTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfigTest.java index 84ddced1..27f00b56 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfigTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfigTest.java @@ -2,8 +2,8 @@ package dev.caskeleton.adapter.outbound.persistence.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.IdempotencySchemaStream; -import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.PostgreSqlOwnerSafeIdempotencyStore; +import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.IdempotencySchemaStream; +import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlOwnerSafeIdempotencyStore; import dev.caskeleton.application.idempotency.IdempotencyStorePort; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyActivationContractTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyActivationContractTest.java similarity index 91% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyActivationContractTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyActivationContractTest.java index fe58d979..b4b899cb 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyActivationContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyActivationContractTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyReaperTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyReaperTest.java similarity index 90% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyReaperTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyReaperTest.java index a6dfcaa8..72235d67 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyReaperTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyReaperTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyDigestPolicyTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicyTest.java similarity index 97% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyDigestPolicyTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicyTest.java index b1d4eb97..a71dcee6 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyDigestPolicyTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicyTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/OwnerSafeIdempotencyPreconditionTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/OwnerSafeIdempotencyPreconditionTest.java similarity index 98% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/OwnerSafeIdempotencyPreconditionTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/OwnerSafeIdempotencyPreconditionTest.java index 0f9b83f1..ce2c52c0 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/OwnerSafeIdempotencyPreconditionTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/OwnerSafeIdempotencyPreconditionTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; +package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapterActivationTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapterActivationTest.java deleted file mode 100644 index 6c066e59..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapterActivationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.outbox; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import dev.caskeleton.application.outbox.OutboxAppendPort; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -class CanonicalOutboxAppendAdapterActivationTest { - - private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(TestConfig.class); - - @Test - void canonicalFlagAloneDoesNotExposeAppendWhenOutboxCapabilityIsOff() { - runner - .withPropertyValues( - "ca-skeleton.outbox.enabled=false", - "ca-skeleton.outbox.canonical-transport-enabled=true") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(OutboxAppendPort.class); - }); - } - - @Test - void bothOutboxAndCanonicalFlagsExposeExactlyOneCanonicalAppendPort() { - runner - .withPropertyValues( - "ca-skeleton.outbox.enabled=true", - "ca-skeleton.outbox.canonical-transport-enabled=true") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(OutboxAppendPort.class); - assertThat(context.getBean(OutboxAppendPort.class)) - .isInstanceOf(CanonicalOutboxAppendAdapter.class); - }); - } - - @Test - void defaultOffDoesNotExposeCanonicalAppendPort() { - runner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(OutboxAppendPort.class); - }); - } - - @Configuration(proxyBeanMethods = false) - @Import(CanonicalOutboxAppendAdapter.class) - static class TestConfig { - - @Bean - OutboxEventJpaRepository outboxEventJpaRepository() { - return mock(OutboxEventJpaRepository.class); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapterTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapterTest.java deleted file mode 100644 index a07300a9..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapterTest.java +++ /dev/null @@ -1,143 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.outbox; - -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 static org.mockito.ArgumentCaptor.forClass; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; - -import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity; -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; -import dev.caskeleton.application.messaging.event.AggregateIdentity; -import dev.caskeleton.application.messaging.event.AggregateOrder; -import dev.caskeleton.application.messaging.event.EventId; -import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.Optional; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -class CanonicalOutboxAppendAdapterTest { - - private static final Instant OCCURRED_AT = Instant.parse("2026-09-18T03:00:00Z"); - - private final OutboxEventJpaRepository repository = mock(OutboxEventJpaRepository.class); - private final CanonicalOutboxAppendAdapter adapter = new CanonicalOutboxAppendAdapter(repository); - - @BeforeEach - void openCallerTransactionBoundary() { - TransactionSynchronizationManager.setActualTransactionActive(true); - } - - @AfterEach - void clearCallerTransactionBoundary() { - TransactionSynchronizationManager.clear(); - } - - @Test - void appendOutsideACallerTransactionIsRefusedBeforeAnyWrite() { - // given - TransactionSynchronizationManager.setActualTransactionActive(false); - ValidatedIntegrationEvent event = event("{}".getBytes(StandardCharsets.UTF_8)); - - // when - Throwable thrown = catchThrowable(() -> adapter.append(event)); - - // then - assertThat(thrown) - .isInstanceOf(IllegalStateException.class) - .hasMessage("outbox append requires an active caller transaction"); - } - - @Test - void appendPersistsExactCanonicalMetadataAndLegacyCompatibilityProjection() { - byte[] exactEnvelope = - "{\"event\":\"canonical\",\"value\":\"한글\"}".getBytes(StandardCharsets.UTF_8); - ValidatedIntegrationEvent event = event(exactEnvelope); - - adapter.append(event); - - ArgumentCaptor saved = forClass(OutboxEventEntity.class); - verify(repository).save(saved.capture()); - OutboxEventEntity entity = saved.getValue(); - - assertThat(entity.getEventId()).isEqualTo("01994e11-4d88-7000-8000-000000000001"); - assertThat(entity.getEventType()).isEqualTo("portfolio.worklog.reserved"); - assertThat(entity.getAggregateId()).isEqualTo("worklog-42"); - assertThat(entity.getPayload()).isEqualTo(new String(exactEnvelope, StandardCharsets.UTF_8)); - assertThat(entity.getOccurredAt()).isEqualTo(OCCURRED_AT); - assertThat(entity.getStatus()).isEqualTo("PENDING"); - assertThat(entity.getAttemptCount()).isZero(); - assertThat(entity.getNextAttemptAt()).isEqualTo(OCCURRED_AT); - assertThat(entity.getCorrelationId()).isEqualTo("corr-1"); - assertThat(entity.getIdempotencyKey()).isEqualTo(event.eventId().value()); - - assertThat(entity.getContractId()).isEqualTo("portfolio.worklog.reserved"); - assertThat(entity.getEnvelopeVersion()).isEqualTo(1); - assertThat(entity.getPayloadVersion()).isEqualTo(3); - assertThat(entity.getLogicalDestination()).isEqualTo("portfolio-domain-events"); - assertThat(entity.getTenantScope()).isEqualTo("tenant-a"); - assertThat(entity.getAggregateType()).isEqualTo("worklog"); - assertThat(entity.getAggregateSequence()).isEqualTo(17L); - assertThat(entity.getEventIndex()).isEqualTo(2); - assertThat(entity.getPartitionKey()).isEqualTo("a".repeat(64)); - assertThat(entity.getEnvelopeBytes()).containsExactly(exactEnvelope); - assertThat(entity.getContentType()).isEqualTo("application/json"); - assertThat(entity.getSchemaSetHash()).isEqualTo("1".repeat(64)); - assertThat(entity.getEnvelopeSha256()).isEqualTo(Sha256.of(exactEnvelope).toString()); - assertThat(entity.getEnvelopeSchemaHash()).isEqualTo("3".repeat(64)); - assertThat(entity.getPayloadSchemaHash()).isEqualTo("4".repeat(64)); - assertThat(entity.getContractCatalogRevision()).isEqualTo("catalog-r1"); - assertThat(entity.getDestinationBindingRevision()).isEqualTo("binding-r1"); - assertThat(entity.getCausationId()).isEqualTo("01994e11-4d88-7000-8000-000000000000"); - } - - @Test - void invalidUtf8EnvelopeIsRejectedBeforeRepositoryWrite() { - ValidatedIntegrationEvent event = event(new byte[] {(byte) 0xC3, (byte) 0x28}); - - assertThatThrownBy(() -> adapter.append(event)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("UTF-8") - .hasMessageContaining("compatibility"); - - verifyNoInteractions(repository); - } - - private static ValidatedIntegrationEvent event(byte[] envelopeBytes) { - String partition = "a".repeat(64); - return new ValidatedIntegrationEvent( - new EventId("01994e11-4d88-7000-8000-000000000001"), - new ContractId("portfolio.worklog.reserved"), - 1, - 3, - new LogicalDestinationId("portfolio-domain-events"), - new AggregateIdentity("tenant-a", "worklog", "worklog-42"), - new AggregateOrder(17, 2), - OCCURRED_AT, - "corr-1", - Optional.of("01994e11-4d88-7000-8000-000000000000"), - partition, - partition.getBytes(StandardCharsets.US_ASCII), - envelopeBytes, - "application/json", - sha("1"), - Sha256.of(envelopeBytes), - sha("3"), - sha("4"), - "catalog-r1", - "binding-r1"); - } - - private static Sha256 sha(String nibble) { - return new Sha256(java.util.HexFormat.of().parseHex(nibble.repeat(64))); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapterTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapterTest.java deleted file mode 100644 index fd7f6de1..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapterTest.java +++ /dev/null @@ -1,401 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.outbox; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentCaptor.forClass; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity; -import dev.caskeleton.application.messaging.contract.Sha256; -import dev.caskeleton.application.outbox.CanonicalClaimedOutboxEvent; -import dev.caskeleton.application.outbox.NewOutboxEvent; -import dev.caskeleton.application.outbox.OutboxCompletion; -import dev.caskeleton.application.outbox.OutboxEvent; -import dev.caskeleton.application.outbox.OutboxEventStatus; -import dev.caskeleton.application.outbox.OutboxLease; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** - * Unit tests for {@link OutboxStoreAdapter} — covers append mapping, claim transition, mark - * operations, countByStatus, and oldestUnpublishedAgeSecondsByEventType. - * - *

    FIFO gate location contract

    - * - *

    The per-aggregate FIFO gate (I4) lives entirely in the {@link - * OutboxClaimRepository#claimEligible} native SQL query via a {@code NOT EXISTS} correlated - * subquery. The adapter itself performs NO in-memory filtering: every row returned by the claim - * repository passes through to the caller. Verifying that the SQL gate enforces FIFO is the - * responsibility of the Testcontainers contract test in {@code app-bootstrap}. - * - *

    Real SKIP LOCKED / FIFO gate behaviour is covered by the Task E PG contract tests. - */ -class OutboxStoreAdapterTest { - - private static final Instant NOW = Instant.parse("2026-06-11T10:00:00Z"); - private static final Duration IN_FLIGHT_TIMEOUT = Duration.ofMinutes(5); - - private final OutboxEventJpaRepository repo = mock(OutboxEventJpaRepository.class); - private final OutboxClaimRepository claimRepo = mock(OutboxClaimRepository.class); - private final OutboxStoreAdapter adapter = new OutboxStoreAdapter(repo, claimRepo); - - @BeforeEach - void openCallerTransactionBoundary() { - TransactionSynchronizationManager.setActualTransactionActive(true); - } - - @AfterEach - void clearCallerTransactionBoundary() { - TransactionSynchronizationManager.clear(); - } - - // ---- helper ---- - - private static final String OWNER = "relay-1"; - - private static OutboxLease lease(String eventId) { - return new OutboxLease( - new OutboxEvent( - eventId, - "UserCreated", - "agg-1", - "{}", - NOW, - "corr-1", - "idem-1", - OutboxEventStatus.IN_FLIGHT, - 1), - OWNER, - 1); - } - - private static NewOutboxEvent newEvent(String eventId) { - return new NewOutboxEvent(eventId, "UserCreated", "agg-1", "{}", NOW, "corr-1", "idem-1"); - } - - private static OutboxEventEntity pendingEntity(String eventId) { - OutboxEventEntity e = new OutboxEventEntity(); - e.setEventId(eventId); - e.setAggregateId("agg-1"); - e.setEventType("UserCreated"); - e.setPayload("{}"); - e.setOccurredAt(NOW.minusSeconds(60)); - e.setStatus("PENDING"); - e.setAttemptCount(0); - e.setNextAttemptAt(NOW.minusSeconds(60)); - e.setCorrelationId("corr-1"); - e.setIdempotencyKey("idem-1"); - return e; - } - - private static OutboxEventEntity canonicalPendingEntity(String eventId) { - OutboxEventEntity e = pendingEntity(eventId); - byte[] envelope = "{\"wire\":\"exact\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8); - e.setAggregateId("worklog-42"); - e.setEventType("portfolio.worklog.reserved"); - e.setPayload(new String(envelope, java.nio.charset.StandardCharsets.UTF_8)); - e.setCorrelationId("corr-1"); - e.setIdempotencyKey(eventId); - e.setContractId("portfolio.worklog.reserved"); - e.setEnvelopeVersion(1); - e.setPayloadVersion(3); - e.setLogicalDestination("portfolio-domain-events"); - e.setTenantScope("tenant-a"); - e.setAggregateType("worklog"); - e.setAggregateSequence(17L); - e.setEventIndex(2); - e.setPartitionKey("a".repeat(64)); - e.setEnvelopeBytes(envelope); - e.setContentType("application/json"); - e.setSchemaSetHash("1".repeat(64)); - e.setEnvelopeSha256(Sha256.of(envelope).toString()); - e.setEnvelopeSchemaHash("3".repeat(64)); - e.setPayloadSchemaHash("4".repeat(64)); - e.setContractCatalogRevision("catalog-r1"); - e.setDestinationBindingRevision("binding-r1"); - e.setCausationId("01994e11-4d88-7000-8000-000000000000"); - return e; - } - - // ---- append ---- - - @Test - void appendPersistsEntityWithCorrectFieldMapping() { - NewOutboxEvent event = newEvent("evt-001"); - - adapter.append(event); - - ArgumentCaptor saved = forClass(OutboxEventEntity.class); - verify(repo).save(saved.capture()); - OutboxEventEntity entity = saved.getValue(); - - assertThat(entity.getEventId()).isEqualTo("evt-001"); - assertThat(entity.getEventType()).isEqualTo("UserCreated"); - assertThat(entity.getAggregateId()).isEqualTo("agg-1"); - assertThat(entity.getPayload()).isEqualTo("{}"); - assertThat(entity.getOccurredAt()).isEqualTo(NOW); - assertThat(entity.getStatus()).isEqualTo("PENDING"); - assertThat(entity.getAttemptCount()).isEqualTo(0); - assertThat(entity.getNextAttemptAt()).isEqualTo(NOW); // nextAttemptAt = occurredAt on PENDING - assertThat(entity.getCorrelationId()).isEqualTo("corr-1"); - assertThat(entity.getIdempotencyKey()).isEqualTo("idem-1"); - } - - // ---- claimBatch ---- - - @Test - void claimAndMarkOperationsRejectAMissingCallerTransaction() { - TransactionSynchronizationManager.clear(); - - assertThatThrownBy(() -> adapter.append(newEvent("evt-append-guard"))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("append") - .hasMessageContaining("active caller transaction"); - assertThatThrownBy(() -> adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("claimBatch") - .hasMessageContaining("active caller transaction"); - assertThatThrownBy(() -> adapter.markPublished(lease("evt-guard"))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("markPublished"); - assertThatThrownBy(() -> adapter.markFailed(lease("evt-guard"), NOW.plusSeconds(1))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("markFailed"); - assertThatThrownBy(() -> adapter.markDead(lease("evt-guard"))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("markDead"); - } - - @Test - void claimBatchTransitionsEntityToInFlightAndReturnsMappedEvent() { - OutboxEventEntity entity = pendingEntity("evt-002"); - when(claimRepo.claimEligible(eq(NOW), eq(2))).thenReturn(List.of(entity)); - - List claimed = adapter.claimBatch(OWNER, 2, NOW, IN_FLIGHT_TIMEOUT); - - // status, attemptCount and the lease updated on the locked entity - assertThat(entity.getStatus()).isEqualTo("IN_FLIGHT"); - assertThat(entity.getAttemptCount()).isEqualTo(1); - assertThat(entity.getNextAttemptAt()).isEqualTo(NOW.plus(IN_FLIGHT_TIMEOUT)); - assertThat(entity.getLeaseOwner()).isEqualTo(OWNER); - assertThat(entity.getLeaseToken()).isEqualTo(1); - assertThat(claimed.get(0).token()).isEqualTo(1); - - // returned OutboxEvent reflects post-transition state - assertThat(claimed).hasSize(1); - OutboxEvent result = (OutboxEvent) claimed.get(0).event(); - assertThat(result.eventId()).isEqualTo("evt-002"); - assertThat(result.status()).isEqualTo(OutboxEventStatus.IN_FLIGHT); - assertThat(result.attemptCount()).isEqualTo(1); - } - - @Test - void reclaimTakesTheRowOverWithTheNextToken() { - // given - OutboxEventEntity orphan = pendingEntity("evt-orphan"); - orphan.setStatus("IN_FLIGHT"); - orphan.setLeaseOwner("stalled-relay"); - orphan.setLeaseToken(4); - when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(orphan)); - - // when - OutboxLease lease = adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT).getFirst(); - - // then - assertThat( - List.of(lease.owner(), lease.token(), orphan.getLeaseOwner(), orphan.getLeaseToken())) - .containsExactly(OWNER, 5L, OWNER, 5L); - } - - @Test - void claimBatchMapsCompleteCanonicalMetadataToCanonicalClaim() { - OutboxEventEntity entity = canonicalPendingEntity("01994e11-4d88-7000-8000-000000000001"); - when(claimRepo.claimEligible(eq(NOW), eq(2))).thenReturn(List.of(entity)); - - List claimed = adapter.claimBatch(OWNER, 2, NOW, IN_FLIGHT_TIMEOUT); - - assertThat(claimed).hasSize(1); - assertThat(claimed.getFirst().event()).isInstanceOf(CanonicalClaimedOutboxEvent.class); - CanonicalClaimedOutboxEvent result = (CanonicalClaimedOutboxEvent) claimed.getFirst().event(); - assertThat(result.event().eventId().value()).isEqualTo("01994e11-4d88-7000-8000-000000000001"); - assertThat(result.event().contractId().value()).isEqualTo("portfolio.worklog.reserved"); - assertThat(result.event().aggregate().tenantScope()).isEqualTo("tenant-a"); - assertThat(result.event().aggregate().aggregateType()).isEqualTo("worklog"); - assertThat(result.event().order().sequence()).isEqualTo(17); - assertThat(result.event().order().eventIndex()).isEqualTo(2); - assertThat(result.event().envelopeBytes()) - .containsExactly("{\"wire\":\"exact\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8)); - assertThat(result.status()).isEqualTo(OutboxEventStatus.IN_FLIGHT); - assertThat(result.attemptCount()).isEqualTo(1); - } - - /** - * Partial canonical metadata still fails closed — it is never downgraded to a legacy claim — but - * it fails that one row. Throwing out of the claim rolled the whole batch back, and the next - * claim selected the same row first, so one bad row stopped the relay for good. - */ - @Test - void claimBatchMovesAnUnreadableRowToDeadAndClaimsTheRestOfTheBatch() { - // given - OutboxEventEntity partial = pendingEntity("partial-canonical"); - partial.setEnvelopeVersion(1); - when(claimRepo.claimEligible(eq(NOW), eq(2))) - .thenReturn(List.of(partial, pendingEntity("evt-readable"))); - - // when - List claimed = adapter.claimBatch(OWNER, 2, NOW, IN_FLIGHT_TIMEOUT); - - // then - assertThat(List.of(claimed.stream().map(OutboxLease::eventId).toList(), partial.getStatus())) - .containsExactly(List.of("evt-readable"), "DEAD"); - } - - @Test - void claimBatchMovesACanonicalRowWhoseStoredEnvelopeHashIsNotItsBytesHashToDead() { - // given - OutboxEventEntity entity = canonicalPendingEntity("01994e11-4d88-7000-8000-000000000001"); - entity.setEnvelopeSha256("2".repeat(64)); - when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(entity)); - - // when - List claimed = adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT); - - // then - assertThat(List.of(claimed, entity.getStatus())).containsExactly(List.of(), "DEAD"); - } - - @Test - void claimBatchReturnsEmptyWhenRepoReturnsNothing() { - when(claimRepo.claimEligible(any(), anyInt())).thenReturn(List.of()); - - assertThat(adapter.claimBatch(OWNER, 5, NOW, IN_FLIGHT_TIMEOUT)).isEmpty(); - } - - /** - * Regression guard: the per-aggregate FIFO gate lives in the SQL query (I4). The adapter must NOT - * apply any in-memory filtering — all rows returned by the repository must appear in the result, - * including multiple rows for the same aggregate. - * - *

    If this test fails it means in-memory filtering was re-introduced in the adapter; the fix is - * to move that logic back to the {@code claimEligible} SQL query. - */ - @Test - void claimBatchPassesAllRepoResultsThroughWithoutInMemoryFifoFiltering() { - // Two rows for the same aggregate — repo returns both (SQL gate already enforces FIFO) - OutboxEventEntity head = pendingEntity("evt-head"); - OutboxEventEntity tail = new OutboxEventEntity(); - tail.setEventId("evt-tail"); - tail.setAggregateId("agg-1"); // same aggregate as head - tail.setEventType("UserCreated"); - tail.setPayload("{}"); - tail.setOccurredAt(NOW.minusSeconds(30)); // later than head (head is at -60s) - tail.setStatus("PENDING"); - tail.setAttemptCount(0); - tail.setNextAttemptAt(NOW.minusSeconds(30)); - tail.setCorrelationId("corr-2"); - tail.setIdempotencyKey("idem-2"); - - when(claimRepo.claimEligible(eq(NOW), eq(10))).thenReturn(List.of(head, tail)); - - List claimed = adapter.claimBatch(OWNER, 10, NOW, IN_FLIGHT_TIMEOUT); - - // Adapter must return both rows — no in-memory FIFO filtering - assertThat(claimed) - .hasSize(2) - .extracting(OutboxLease::eventId) - .containsExactly("evt-head", "evt-tail"); - } - - // ---- completions: one conditional UPDATE under the lease ---- - - @Test - void markPublishedCompletesOnlyUnderTheLease() { - when(repo.completeLease("evt-003", OWNER, 1, "PUBLISHED")).thenReturn(1); - - assertThat(adapter.markPublished(lease("evt-003"))).isEqualTo(OutboxCompletion.APPLIED); - } - - @Test - void markFailedCompletesOnlyUnderTheLeaseAndSchedulesTheRetry() { - Instant retryAt = NOW.plus(Duration.ofSeconds(30)); - when(repo.failLease("evt-004", OWNER, 1, retryAt)).thenReturn(1); - - assertThat(adapter.markFailed(lease("evt-004"), retryAt)).isEqualTo(OutboxCompletion.APPLIED); - } - - @Test - void markDeadCompletesOnlyUnderTheLease() { - when(repo.completeLease("evt-005", OWNER, 1, "DEAD")).thenReturn(1); - - assertThat(adapter.markDead(lease("evt-005"))).isEqualTo(OutboxCompletion.APPLIED); - } - - /** - * Zero rows means the lease no longer holds the row — another relay reclaimed it after the - * in-flight timeout, or it is already complete. That relay owns the row, so this is a result, not - * an error, and nothing is loaded and overwritten. - */ - @Test - void aCompletionThatMatchesNoRowIsStale() { - when(repo.completeLease("evt-stale", OWNER, 1, "PUBLISHED")).thenReturn(0); - - OutboxCompletion completion = adapter.markPublished(lease("evt-stale")); - - assertThat(completion).isEqualTo(OutboxCompletion.STALE); - verify(repo, never()).findById(any()); - } - - // ---- countByStatus ---- - - @Test - void countByStatusMapsProjectionResultsToStatusEnumMap() { - List rows = - List.of( - new Object[] {"PENDING", 5L}, - new Object[] {"IN_FLIGHT", 2L}, - new Object[] {"PUBLISHED", 10L}); - when(repo.countGroupedByStatus()).thenReturn(rows); - - Map counts = adapter.countByStatus(); - - assertThat(counts).containsEntry(OutboxEventStatus.PENDING, 5L); - assertThat(counts).containsEntry(OutboxEventStatus.IN_FLIGHT, 2L); - assertThat(counts).containsEntry(OutboxEventStatus.PUBLISHED, 10L); - assertThat(counts).doesNotContainKey(OutboxEventStatus.FAILED); - assertThat(counts).doesNotContainKey(OutboxEventStatus.DEAD); - } - - // ---- oldestUnpublishedAgeSecondsByEventType ---- - - @Test - void oldestUnpublishedAgeComputesSecondsFromOldestRowOccurredAt() { - // oldest row for "UserCreated" occurred 120 seconds before NOW - Instant oldestAt = NOW.minusSeconds(120); - List rows = List.of(new Object[] {"UserCreated", oldestAt}); - when(repo.findOldestUnpublishedOccurredAtByEventType()).thenReturn(rows); - - Map ages = adapter.oldestUnpublishedAgeSecondsByEventType(NOW); - - assertThat(ages).containsEntry("UserCreated", 120L); - } - - @Test - void oldestUnpublishedAgeReturnsEmptyMapWhenNoUnpublishedRows() { - when(repo.findOldestUnpublishedOccurredAtByEventType()).thenReturn(List.of()); - - assertThat(adapter.oldestUnpublishedAgeSecondsByEventType(NOW)).isEmpty(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/h2/H2ClaimSqlTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/h2/H2ClaimSqlTest.java similarity index 91% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/h2/H2ClaimSqlTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/h2/H2ClaimSqlTest.java index 5bd42c6b..380edccc 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/h2/H2ClaimSqlTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/h2/H2ClaimSqlTest.java @@ -1,9 +1,9 @@ -package dev.caskeleton.adapter.outbound.persistence.h2; +package dev.caskeleton.adapter.outbound.persistence.outbox.h2; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import java.time.Instant; @@ -58,7 +58,7 @@ class H2ClaimSqlTest { factoryBean = new LocalContainerEntityManagerFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setPersistenceUnitName("h2-claim-sql"); - factoryBean.setPackagesToScan("dev.caskeleton.adapter.outbound.persistence.outbox.entity"); + factoryBean.setPackagesToScan("dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity"); factoryBean.setJpaVendorAdapter(vendorAdapter); factoryBean.setJpaProperties(jpaProperties); factoryBean.afterPropertiesSet(); @@ -165,9 +165,6 @@ class H2ClaimSqlTest { private OutboxEventEntity canonical(String eventId, long sequence, int eventIndex) { OutboxEventEntity entity = event(eventId, "worklog-42", now.minusSeconds(60), now); - entity.setContractId("portfolio.worklog.reserved"); - entity.setTenantScope("tenant-a"); - entity.setAggregateType("worklog"); entity.setAggregateSequence(sequence); entity.setEventIndex(eventIndex); return entity; @@ -178,19 +175,27 @@ class H2ClaimSqlTest { entityManager -> new H2OutboxClaimRepository(entityManager).claimEligible(asOf, limit)); } + /** + * A row as the append writes it, reduced to the columns the claim reads. Its aggregate sequence + * is its occurrence second, so rows of one aggregate appended in time order are in aggregate + * order. + */ private static OutboxEventEntity event( String eventId, String aggregateId, Instant occurredAt, Instant nextAttemptAt) { OutboxEventEntity entity = new OutboxEventEntity(); entity.setEventId(eventId); entity.setAggregateId(aggregateId); - entity.setEventType("OrderPlaced"); - entity.setPayload("{}"); + entity.setEventType("portfolio.worklog.reserved"); entity.setOccurredAt(occurredAt); entity.setStatus("PENDING"); entity.setAttemptCount(0); entity.setNextAttemptAt(nextAttemptAt); entity.setCorrelationId("corr-1"); - entity.setIdempotencyKey("idem-" + eventId); + entity.setContractId("portfolio.worklog.reserved"); + entity.setTenantScope("tenant-a"); + entity.setAggregateType("worklog"); + entity.setAggregateSequence(occurredAt.getEpochSecond()); + entity.setEventIndex(0); return entity; } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxReaperTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxReaperTest.java similarity index 96% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxReaperTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxReaperTest.java index 471c1f5c..c337eaee 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxReaperTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxReaperTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.outbox; +package dev.caskeleton.adapter.outbound.persistence.outbox.jpa; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxReaperWiringTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxReaperWiringTest.java similarity index 98% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxReaperWiringTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxReaperWiringTest.java index 2374195a..84fa2c66 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxReaperWiringTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxReaperWiringTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.outbox; +package dev.caskeleton.adapter.outbound.persistence.outbox.jpa; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapterTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapterTest.java new file mode 100644 index 00000000..4061cb0d --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapterTest.java @@ -0,0 +1,435 @@ +package dev.caskeleton.adapter.outbound.persistence.outbox.jpa; + +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 static org.mockito.ArgumentCaptor.forClass; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; +import dev.caskeleton.application.messaging.contract.ContractId; +import dev.caskeleton.application.messaging.contract.LogicalDestinationId; +import dev.caskeleton.application.messaging.contract.Sha256; +import dev.caskeleton.application.messaging.event.AggregateIdentity; +import dev.caskeleton.application.messaging.event.AggregateOrder; +import dev.caskeleton.application.messaging.event.EventId; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.outbox.ClaimedOutboxEvent; +import dev.caskeleton.application.outbox.OutboxCompletion; +import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.OutboxLease; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unit tests for {@link OutboxStoreAdapter} — covers append mapping, claim transition, mark + * operations, countByStatus, and oldestUnpublishedAgeSecondsByEventType. + * + *

    FIFO gate location contract

    + * + *

    The per-aggregate FIFO gate (I4) lives entirely in the {@link + * OutboxClaimRepository#claimEligible} native SQL query via a {@code NOT EXISTS} correlated + * subquery. The adapter itself performs NO in-memory filtering: every row returned by the claim + * repository passes through to the caller. Real SKIP LOCKED / FIFO gate behaviour is covered by the + * PostgreSQL outbox integration tests. + */ +class OutboxStoreAdapterTest { + + private static final Instant NOW = Instant.parse("2026-06-11T10:00:00Z"); + private static final Instant OCCURRED_AT = NOW.minusSeconds(60); + private static final Duration IN_FLIGHT_TIMEOUT = Duration.ofMinutes(5); + private static final String OWNER = "relay-1"; + private static final byte[] ENVELOPE = + "{\"event\":\"canonical\",\"value\":\"한글\"}".getBytes(StandardCharsets.UTF_8); + + private final OutboxEventJpaRepository repo = mock(OutboxEventJpaRepository.class); + private final OutboxClaimRepository claimRepo = mock(OutboxClaimRepository.class); + private final OutboxStoreAdapter adapter = new OutboxStoreAdapter(repo, claimRepo); + + @BeforeEach + void openCallerTransactionBoundary() { + TransactionSynchronizationManager.setActualTransactionActive(true); + } + + @AfterEach + void clearCallerTransactionBoundary() { + TransactionSynchronizationManager.clear(); + } + + // ---- append ---- + + @Test + void appendStoresTheExactEnvelopeAndEveryCanonicalIdentity() { + // given + ValidatedIntegrationEvent event = event("evt-001", "worklog-42"); + + // when + adapter.append(event); + + // then + ArgumentCaptor saved = forClass(OutboxEventEntity.class); + verify(repo).save(saved.capture()); + OutboxEventEntity entity = saved.getValue(); + assertThat(entity) + .extracting( + OutboxEventEntity::getEventId, + OutboxEventEntity::getEventType, + OutboxEventEntity::getAggregateId, + OutboxEventEntity::getOccurredAt, + OutboxEventEntity::getStatus, + OutboxEventEntity::getAttemptCount, + OutboxEventEntity::getNextAttemptAt, + OutboxEventEntity::getCorrelationId, + OutboxEventEntity::getContractId, + OutboxEventEntity::getEnvelopeVersion, + OutboxEventEntity::getPayloadVersion, + OutboxEventEntity::getLogicalDestination, + OutboxEventEntity::getTenantScope, + OutboxEventEntity::getAggregateType, + OutboxEventEntity::getAggregateSequence, + OutboxEventEntity::getEventIndex, + OutboxEventEntity::getPartitionKey, + OutboxEventEntity::getContentType, + OutboxEventEntity::getSchemaSetHash, + OutboxEventEntity::getEnvelopeSha256, + OutboxEventEntity::getEnvelopeSchemaHash, + OutboxEventEntity::getPayloadSchemaHash, + OutboxEventEntity::getContractCatalogRevision, + OutboxEventEntity::getDestinationBindingRevision, + OutboxEventEntity::getCausationId) + .containsExactly( + "evt-001", + "portfolio.worklog.reserved", + "worklog-42", + OCCURRED_AT, + "PENDING", + 0, + OCCURRED_AT, + "corr-1", + "portfolio.worklog.reserved", + 1, + 3, + "portfolio-domain-events", + "tenant-a", + "worklog", + 17L, + 2, + "a".repeat(64), + "application/json", + "1".repeat(64), + Sha256.of(ENVELOPE).toString(), + "3".repeat(64), + "4".repeat(64), + "catalog-r1", + "binding-r1", + "01994e11-4d88-7000-8000-000000000000"); + } + + @Test + void appendKeepsTheEnvelopeBytesExactly() { + // when + adapter.append(event("evt-bytes", "worklog-42")); + + // then + ArgumentCaptor saved = forClass(OutboxEventEntity.class); + verify(repo).save(saved.capture()); + assertThat(saved.getValue().getEnvelopeBytes()).containsExactly(ENVELOPE); + } + + @Test + void appendOutsideACallerTransactionIsRefusedBeforeAnyWrite() { + // given + TransactionSynchronizationManager.clear(); + + // when + Throwable thrown = catchThrowable(() -> adapter.append(event("evt-guard", "worklog-42"))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessage("outbox append requires an active caller transaction"); + verifyNoInteractions(repo); + } + + // ---- claimBatch ---- + + @Test + void claimAndMarkOperationsRejectAMissingCallerTransaction() { + TransactionSynchronizationManager.clear(); + + assertThatThrownBy(() -> adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("claimBatch") + .hasMessageContaining("active caller transaction"); + assertThatThrownBy(() -> adapter.markPublished(lease("evt-guard"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("markPublished"); + assertThatThrownBy(() -> adapter.markFailed(lease("evt-guard"), NOW.plusSeconds(1))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("markFailed"); + assertThatThrownBy(() -> adapter.markDead(lease("evt-guard"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("markDead"); + } + + @Test + void claimBatchTransitionsTheRowToInFlightUnderANewLease() { + // given + OutboxEventEntity entity = pendingEntity("evt-002", "worklog-42"); + when(claimRepo.claimEligible(eq(NOW), eq(2))).thenReturn(List.of(entity)); + + // when + List claimed = adapter.claimBatch(OWNER, 2, NOW, IN_FLIGHT_TIMEOUT); + + // then + assertThat( + List.of( + entity.getStatus(), + entity.getAttemptCount(), + entity.getNextAttemptAt(), + entity.getLeaseOwner(), + entity.getLeaseToken(), + claimed.getFirst().token())) + .containsExactly("IN_FLIGHT", 1, NOW.plus(IN_FLIGHT_TIMEOUT), OWNER, 1L, 1L); + } + + @Test + void claimBatchRestoresTheAppendedEventFromTheStoredEnvelope() { + // given + OutboxEventEntity entity = pendingEntity("evt-restore", "worklog-42"); + when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(entity)); + + // when + ClaimedOutboxEvent claimed = + adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT).getFirst().event(); + + // then + assertThat(claimed) + .isEqualTo( + new ClaimedOutboxEvent( + event("evt-restore", "worklog-42"), OutboxEventStatus.IN_FLIGHT, 1)); + } + + @Test + void reclaimTakesTheRowOverWithTheNextToken() { + // given + OutboxEventEntity orphan = pendingEntity("evt-orphan", "worklog-42"); + orphan.setStatus("IN_FLIGHT"); + orphan.setLeaseOwner("stalled-relay"); + orphan.setLeaseToken(4); + when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(orphan)); + + // when + OutboxLease lease = adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT).getFirst(); + + // then + assertThat( + List.of(lease.owner(), lease.token(), orphan.getLeaseOwner(), orphan.getLeaseToken())) + .containsExactly(OWNER, 5L, OWNER, 5L); + } + + /** + * A row without the canonical envelope — written by the pre-canonical append, or damaged — is + * unreadable. It fails that one row, never the batch: throwing out of the claim rolled the whole + * batch back, and the next claim selected the same row first, so one bad row stopped the relay. + */ + @Test + void claimBatchMovesARowWithoutTheCanonicalEnvelopeToDeadAndClaimsTheRest() { + // given + OutboxEventEntity preCanonical = pendingEntity("pre-canonical", "worklog-7"); + preCanonical.setEnvelopeBytes(null); + OutboxEventEntity readable = pendingEntity("evt-readable", "worklog-42"); + when(claimRepo.claimEligible(eq(NOW), eq(2))).thenReturn(List.of(preCanonical, readable)); + + // when + List claimed = adapter.claimBatch(OWNER, 2, NOW, IN_FLIGHT_TIMEOUT); + + // then + assertThat( + List.of(claimed.stream().map(OutboxLease::eventId).toList(), preCanonical.getStatus())) + .containsExactly(List.of("evt-readable"), "DEAD"); + } + + @Test + void claimBatchMovesARowWhoseStoredEnvelopeHashIsNotItsBytesHashToDead() { + // given + OutboxEventEntity entity = pendingEntity("evt-tampered", "worklog-42"); + entity.setEnvelopeSha256("2".repeat(64)); + when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(entity)); + + // when + List claimed = adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT); + + // then + assertThat(List.of(claimed, entity.getStatus())).containsExactly(List.of(), "DEAD"); + } + + @Test + void claimBatchReturnsEmptyWhenRepoReturnsNothing() { + when(claimRepo.claimEligible(any(), anyInt())).thenReturn(List.of()); + + assertThat(adapter.claimBatch(OWNER, 5, NOW, IN_FLIGHT_TIMEOUT)).isEmpty(); + } + + /** + * Regression guard: the per-aggregate FIFO gate lives in the SQL query (I4). The adapter must NOT + * apply any in-memory filtering — all rows returned by the repository must appear in the result, + * including multiple rows for the same aggregate. + */ + @Test + void claimBatchPassesAllRepoResultsThroughWithoutInMemoryFifoFiltering() { + // given + OutboxEventEntity head = pendingEntity("evt-head", "worklog-42"); + OutboxEventEntity tail = pendingEntity("evt-tail", "worklog-42"); + when(claimRepo.claimEligible(eq(NOW), eq(10))).thenReturn(List.of(head, tail)); + + // when + List claimed = adapter.claimBatch(OWNER, 10, NOW, IN_FLIGHT_TIMEOUT); + + // then + assertThat(claimed).extracting(OutboxLease::eventId).containsExactly("evt-head", "evt-tail"); + } + + // ---- completions: one conditional UPDATE under the lease ---- + + @Test + void markPublishedCompletesOnlyUnderTheLease() { + when(repo.completeLease("evt-003", OWNER, 1, "PUBLISHED")).thenReturn(1); + + assertThat(adapter.markPublished(lease("evt-003"))).isEqualTo(OutboxCompletion.APPLIED); + } + + @Test + void markFailedCompletesOnlyUnderTheLeaseAndSchedulesTheRetry() { + Instant retryAt = NOW.plus(Duration.ofSeconds(30)); + when(repo.failLease("evt-004", OWNER, 1, retryAt)).thenReturn(1); + + assertThat(adapter.markFailed(lease("evt-004"), retryAt)).isEqualTo(OutboxCompletion.APPLIED); + } + + @Test + void markDeadCompletesOnlyUnderTheLease() { + when(repo.completeLease("evt-005", OWNER, 1, "DEAD")).thenReturn(1); + + assertThat(adapter.markDead(lease("evt-005"))).isEqualTo(OutboxCompletion.APPLIED); + } + + /** + * Zero rows means the lease no longer holds the row — another relay reclaimed it after the + * in-flight timeout, or it is already complete. That relay owns the row, so this is a result, not + * an error, and nothing is loaded and overwritten. + */ + @Test + void aCompletionThatMatchesNoRowIsStale() { + when(repo.completeLease("evt-stale", OWNER, 1, "PUBLISHED")).thenReturn(0); + + OutboxCompletion completion = adapter.markPublished(lease("evt-stale")); + + assertThat(completion).isEqualTo(OutboxCompletion.STALE); + verify(repo, never()).findById(any()); + } + + // ---- countByStatus ---- + + @Test + void countByStatusMapsProjectionResultsToStatusEnumMap() { + // given + List rows = List.of(new Object[] {"PENDING", 5L}, new Object[] {"IN_FLIGHT", 2L}); + when(repo.countGroupedByStatus()).thenReturn(rows); + + // when + Map counts = adapter.countByStatus(); + + // then + assertThat(counts) + .containsExactlyInAnyOrderEntriesOf( + Map.of(OutboxEventStatus.PENDING, 5L, OutboxEventStatus.IN_FLIGHT, 2L)); + } + + // ---- oldestUnpublishedAgeSecondsByEventType ---- + + @Test + void oldestUnpublishedAgeComputesSecondsFromOldestRowOccurredAt() { + // given + Instant oldestAt = NOW.minusSeconds(120); + List rows = List.of(new Object[] {"portfolio.worklog.reserved", oldestAt}); + when(repo.findOldestUnpublishedOccurredAtByEventType()).thenReturn(rows); + + // when + Map ages = adapter.oldestUnpublishedAgeSecondsByEventType(NOW); + + // then + assertThat(ages).containsExactly(Map.entry("portfolio.worklog.reserved", 120L)); + } + + @Test + void oldestUnpublishedAgeReturnsEmptyMapWhenNoUnpublishedRows() { + when(repo.findOldestUnpublishedOccurredAtByEventType()).thenReturn(List.of()); + + assertThat(adapter.oldestUnpublishedAgeSecondsByEventType(NOW)).isEmpty(); + } + + // ---- helpers ---- + + private static OutboxLease lease(String eventId) { + return new OutboxLease( + new ClaimedOutboxEvent(event(eventId, "worklog-42"), OutboxEventStatus.IN_FLIGHT, 1), + OWNER, + 1); + } + + private static ValidatedIntegrationEvent event(String eventId, String aggregateId) { + String partition = "a".repeat(64); + return new ValidatedIntegrationEvent( + new EventId(eventId), + new ContractId("portfolio.worklog.reserved"), + 1, + 3, + new LogicalDestinationId("portfolio-domain-events"), + new AggregateIdentity("tenant-a", "worklog", aggregateId), + new AggregateOrder(17, 2), + OCCURRED_AT, + "corr-1", + Optional.of("01994e11-4d88-7000-8000-000000000000"), + partition, + partition.getBytes(StandardCharsets.US_ASCII), + ENVELOPE, + "application/json", + sha("1"), + Sha256.of(ENVELOPE), + sha("3"), + sha("4"), + "catalog-r1", + "binding-r1"); + } + + /** The row {@link OutboxStoreAdapter#append} writes for {@link #event}, still PENDING. */ + private OutboxEventEntity pendingEntity(String eventId, String aggregateId) { + ArgumentCaptor saved = forClass(OutboxEventEntity.class); + OutboxEventJpaRepository capture = mock(OutboxEventJpaRepository.class); + new OutboxStoreAdapter(capture, claimRepo).append(event(eventId, aggregateId)); + verify(capture).save(saved.capture()); + return saved.getValue(); + } + + private static Sha256 sha(String nibble) { + return new Sha256(HexFormat.of().parseHex(nibble.repeat(64))); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxSwitchWiringContractTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxSwitchWiringContractTest.java similarity index 94% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxSwitchWiringContractTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxSwitchWiringContractTest.java index 06537afa..7f562440 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxSwitchWiringContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxSwitchWiringContractTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.outbox; +package dev.caskeleton.adapter.outbound.persistence.outbox.jpa; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 index 0f881949..543067e0 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 +++ b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 @@ -24,6 +24,7 @@ c5f9c638c6d5b7768e803a23b3f16e9e0a5e09918c0838ed9c81cb6d9524ec9c jpa/notificati 1a5983c9212d6c155f0d7bea802bd9cd9c1055f3f0b055ba4168601146eeac0d postgresql/V16__outbox_canonical_hash_columns_varchar.sql b8f571e6cada72a8f2776f4462509ce4b535c964c75b1c3cfb34b9dc07446d59 postgresql/V17__outbox_event_lease_fencing.sql 44cacbde7d1381ca5290fb8ec28005e8127ff6b453ff84277ec8d1b3293d76c8 postgresql/V18__outbox_event_unpublished_aggregate_order.sql +a0306e5b0fbcaf43984d256362dc4244aec57a0ce5031e4f5263be3762fe1caf postgresql/V19__outbox_event_canonical_only.sql 8ab106731d4d04d3719da0692069947736dc490ca46aa5a3ea9bdf65a5d956dc postgresql/V1__idempotency_record.sql 6b62a01a4eeb792b81015b4810ecc6f3f021e0a17dea50c871493f7694d4f0b9 postgresql/V3__outbox_event.sql c57ab8a35a10079190ad8a563be58fae4147c9406c5bb752debb6998324ccdf6 postgresql/V4__int_lock.sql diff --git a/src/adapter/outbound/support/CLAUDE.md b/src/adapter/outbound/support/CLAUDE.md index 850fda4d..82d6f0b6 100644 --- a/src/adapter/outbound/support/CLAUDE.md +++ b/src/adapter/outbound/support/CLAUDE.md @@ -15,6 +15,11 @@ Package roots: `dev.caskeleton.adapter.outbound` and - Own reusable outbound correlation, fail-open dependency logging, and auto-configuration seams. - Provide technical support used by registered messaging/cache/notification/httpclient leaves. +- Own the template's `IntegrationEventEncoderPort` (`messaging/JsonIntegrationEventEncoder`, + registered by `IntegrationEventEncoderAutoConfiguration` over every contract contribution bean, + backing off to a service's own encoder). It lives here because a use case encodes before it + appends to the outbox, in compositions that carry no messaging module; it is the application's + own envelope v1 format, not an external-system protocol. - Keep feature-specific clients and routing policies in their owning leaf. ## Boundaries diff --git a/src/adapter/outbound/support/README.md b/src/adapter/outbound/support/README.md index aed4bde7..bf801a7c 100644 --- a/src/adapter/outbound/support/README.md +++ b/src/adapter/outbound/support/README.md @@ -38,6 +38,32 @@ component scan 없이 이 모듈이 있으면 등록된다). 네 기술 모듈 `@ConditionalOnProperty` 게이팅도 갖지 않는다 — 게이팅은 각 기술 모듈이 자신의 연동 client 단위로 소유한다. +## messaging — 템플릿의 integration event encoder + +`JsonIntegrationEventEncoder`가 `IntegrationEventEncoderPort`의 템플릿 구현이다(소유자 결정 7: +outbox append는 canonical 하나, encoder는 템플릿이 준다). `IntegrationEventEncoderAutoConfiguration`이 +context의 모든 `IntegrationEventContractContribution` bean으로 닫힌 catalog를 만들고, 서비스가 자기 +encoder bean을 두면 물러난다. + +- 형식: `shared-contract`의 envelope v1(`contracts/messaging/envelope/v1.schema.json`) 안에 payload + record를 `CanonicalJson`으로 한 번 렌더링해 넣는다. 한 값에는 렌더링이 하나다: component 선언 + 순서, 공백 없음, RFC 8259 필수 escape만, 숫자는 plain decimal. 그래서 envelope hash가 event를 + 대표한다. +- 받는 component 타입은 닫혀 있다: String, 정수형, BigDecimal, Boolean, enum, Instant, LocalDate, + UUID, Optional, List, public record. `double`/`float`는 거부한다(한 값에 철자가 여럿이라서). `null`도 + 거부한다 — 없을 수 있는 값은 Optional로 선언한다. +- 시작할 때 확인하는 것: payload 타입이 `IntegrationPayload`를 구현한 record인지, 선언한 component + 순서가 record의 것인지, 선언한 schema hash가 classpath schema 파일 bytes의 SHA-256인지. schema를 + 고치고 hash를 안 고치면 기동이 실패한다. +- 확인하지 않는 것: payload를 JSON Schema로 검증하지 않는다(NetworkNT를 production에 다시 싣지 + 않았다). 매 event마다 검증하려는 서비스는 자기 encoder bean을 둔다. +- partition key는 tenant·logical destination·aggregate type·aggregate id의 domain-separated SHA-256이라 + 한 aggregate의 event는 한 partition으로 간다. + +여기 있는 이유: use case가 append 전에 encode하므로 outbox를 쓰는 모든 조립에 있어야 한다. +messaging 모듈은 발행 쪽에만 있고(sample은 messaging이 없다), persistence는 직렬화를 소유하지 +않는다. support는 outbound 어댑터가 있는 모든 조립에 있다. + ## startup — 시작 실패 계약과 모듈 기본 설정 (app-bootstrap에서 이동) capability 모듈이 합성 루트에 의존하지 않고 같은 방식으로 실패하고, 자기 설정을 가져오게 하려고 diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinder.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinder.java index 385867d3..218cccdc 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinder.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinder.java @@ -1,11 +1,18 @@ package dev.caskeleton.adapter.outbound.support; +import java.util.List; +import java.util.Set; import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; import org.springframework.boot.context.properties.bind.BindHandler; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.context.properties.bind.PropertySourcesPlaceholdersResolver; import org.springframework.boot.context.properties.bind.handler.NoUnboundElementsBindHandler; +import org.springframework.boot.context.properties.source.ConfigurationPropertyName; import org.springframework.boot.context.properties.source.ConfigurationPropertySource; +import org.springframework.boot.context.properties.source.ConfigurationPropertySources; import org.springframework.core.env.Environment; /** @@ -79,4 +86,39 @@ public final class StrictSettingsBinder { new CapabilityStartupValidationException( prefix + " could not be bound although the capability is enabled")); } + + /** + * Binds the prefix strictly, except for keys under it that another module owns. + * + *

    For a prefix two modules share: the idempotency lifecycle policy and the Redis store's own + * tuning both live under {@code ca-skeleton.capabilities.idempotency}. Each owner names what is + * not its own, rather than the check being dropped for the whole prefix — a misspelt lifecycle + * key is still refused. + * + * @param environment the environment to bind from + * @param prefix the settings prefix + * @param type the settings type + * @param foreignKeys keys relative to {@code prefix} (e.g. {@code key-version}) that another + * module binds + * @param the settings type + * @return the bound settings + */ + public static T bindExcept( + Environment environment, String prefix, Class type, Set foreignKeys) { + Set foreign = + foreignKeys.stream() + .map(key -> ConfigurationPropertyName.of(prefix + "." + key)) + .collect(Collectors.toUnmodifiableSet()); + List sources = + StreamSupport.stream(ConfigurationPropertySources.get(environment).spliterator(), false) + .map(source -> source.filter(name -> !foreign.contains(name))) + .toList(); + BindHandler strict = new NoUnboundElementsBindHandler(BindHandler.DEFAULT); + return new Binder(sources, new PropertySourcesPlaceholdersResolver(environment)) + .bind(prefix, Bindable.of(type), strict) + .orElseThrow( + () -> + new CapabilityStartupValidationException( + prefix + " could not be bound although the capability is enabled")); + } } diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/CanonicalJson.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/CanonicalJson.java new file mode 100644 index 00000000..ece3c77e --- /dev/null +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/CanonicalJson.java @@ -0,0 +1,195 @@ +package dev.caskeleton.adapter.outbound.support.messaging; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Modifier; +import java.lang.reflect.RecordComponent; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +/** + * Deterministic JSON for an integration-event payload record. + * + *

    One value has exactly one rendering: record components in declaration order, no whitespace, + * the RFC 8259 mandatory escapes and nothing else, numbers in their plain decimal form. That is + * what lets the envelope hash stand for the event — two encodings of the same payload are the same + * bytes, so a republished row cannot drift from the one that was validated. + * + *

    The accepted component types are closed. A floating-point value is refused rather than + * rendered, because {@code 0.1} has more than one faithful decimal spelling; a payload that needs a + * fraction declares {@link BigDecimal}. {@code null} is refused as well: an absent value is an + * {@link Optional}, so the schema, not the encoder, decides whether a field may be missing. + */ +final class CanonicalJson { + + static final int MAXIMUM_DEPTH = 16; + static final int MAXIMUM_OBJECT_PROPERTIES = 64; + static final int MAXIMUM_ARRAY_ITEMS = 1024; + + private CanonicalJson() {} + + /** Renders a payload record as UTF-8 JSON bytes. */ + static byte[] payload(Record payload) { + StringBuilder out = new StringBuilder(128); + writeRecord(out, payload, 1); + return strictUtf8(out); + } + + /** Renders a JSON string literal, quotes included. */ + static void writeString(StringBuilder out, String value) { + out.append('"'); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + switch (c) { + case '"' -> out.append("\\\""); + case '\\' -> out.append("\\\\"); + case '\b' -> out.append("\\b"); + case '\f' -> out.append("\\f"); + case '\n' -> out.append("\\n"); + case '\r' -> out.append("\\r"); + case '\t' -> out.append("\\t"); + default -> { + if (c < 0x20) { + out.append(String.format("\\u%04x", (int) c)); + } else { + out.append(c); + } + } + } + } + out.append('"'); + } + + /** Encodes as UTF-8, refusing an unpaired surrogate instead of replacing it with {@code ?}. */ + static byte[] strictUtf8(CharSequence text) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(text)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException( + "integration event text contains an unpaired surrogate", exception); + } + } + + private static void writeRecord(StringBuilder out, Record value, int depth) { + requireDepth(depth); + Class type = value.getClass(); + if (!Modifier.isPublic(type.getModifiers())) { + throw new IllegalArgumentException( + "payload record " + type.getName() + " must be public so its components can be read"); + } + RecordComponent[] components = type.getRecordComponents(); + if (components.length > MAXIMUM_OBJECT_PROPERTIES) { + throw new IllegalArgumentException( + "payload record " + type.getName() + " has more than 64 components"); + } + out.append('{'); + for (int i = 0; i < components.length; i++) { + if (i > 0) { + out.append(','); + } + writeString(out, components[i].getName()); + out.append(':'); + writeValue(out, read(components[i], value), depth + 1); + } + out.append('}'); + } + + private static Object read(RecordComponent component, Record value) { + try { + return component.getAccessor().invoke(value); + } catch (IllegalAccessException exception) { + throw new IllegalArgumentException( + "payload component " + component.getName() + " is not readable", exception); + } catch (InvocationTargetException exception) { + throw new IllegalArgumentException( + "payload component " + component.getName() + " failed when read", exception.getCause()); + } + } + + private static void writeValue(StringBuilder out, Object value, int depth) { + requireDepth(depth); + if (value == null) { + throw new IllegalArgumentException( + "payload values must not be null; declare an Optional component for an absent value"); + } + if (value instanceof String text) { + writeString(out, text); + } else if (value instanceof Boolean flag) { + out.append(flag.booleanValue()); + } else if (value instanceof Integer + || value instanceof Long + || value instanceof Short + || value instanceof Byte + || value instanceof BigInteger) { + out.append(value); + } else if (value instanceof BigDecimal decimal) { + BigDecimal stripped = decimal.stripTrailingZeros(); + out.append((stripped.scale() < 0 ? stripped.setScale(0) : stripped).toPlainString()); + } else if (value instanceof Enum constant) { + writeString(out, constant.name()); + } else if (value instanceof Instant instant) { + writeString(out, instant.toString()); + } else if (value instanceof LocalDate date) { + writeString(out, date.toString()); + } else if (value instanceof UUID uuid) { + writeString(out, uuid.toString()); + } else if (value instanceof Optional optional) { + if (optional.isPresent()) { + writeValue(out, optional.get(), depth); + } else { + out.append("null"); + } + } else if (value instanceof List list) { + writeList(out, list, depth); + } else if (value instanceof Record nested) { + writeRecord(out, nested, depth); + } else { + throw new IllegalArgumentException( + "payload component type " + + value.getClass().getName() + + " has no canonical JSON form; use String, a whole number, BigDecimal, Boolean," + + " an enum, Instant, LocalDate, UUID, Optional, List or a public record"); + } + } + + private static void writeList(StringBuilder out, List list, int depth) { + // Copied first: a list that changes while it is written would be encoded as a value it never + // held, and the hash would then vouch for it. + List snapshot = new ArrayList<>(list); + if (snapshot.size() > MAXIMUM_ARRAY_ITEMS) { + throw new IllegalArgumentException("payload list has more than 1024 items"); + } + out.append('['); + for (int i = 0; i < snapshot.size(); i++) { + if (i > 0) { + out.append(','); + } + writeValue(out, snapshot.get(i), depth + 1); + } + out.append(']'); + } + + private static void requireDepth(int depth) { + if (depth > MAXIMUM_DEPTH) { + throw new IllegalArgumentException("payload nests deeper than 16 levels"); + } + } +} diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/IntegrationEventEncoderAutoConfiguration.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/IntegrationEventEncoderAutoConfiguration.java new file mode 100644 index 00000000..ce9b0232 --- /dev/null +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/IntegrationEventEncoderAutoConfiguration.java @@ -0,0 +1,31 @@ +package dev.caskeleton.adapter.outbound.support.messaging; + +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; +import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; + +/** + * Provides the template's {@link IntegrationEventEncoderPort} over every contract contribution the + * application registers as a bean. + * + *

    Here rather than in a messaging or persistence module because both sides of the outbox need it + * and neither owns the other: a use case encodes before it appends, and the append port and the + * publish bridge live in different modules. Every composition that has an outbound adapter has this + * module, so the encoder is there wherever an event can be written. + * + *

    A service that supplies its own encoder bean — one that validates payloads against their JSON + * Schema, say — replaces this one. + */ +@AutoConfiguration +public class IntegrationEventEncoderAutoConfiguration { + + @Bean + @ConditionalOnMissingBean(IntegrationEventEncoderPort.class) + public IntegrationEventEncoderPort integrationEventEncoder( + ObjectProvider> contributions) { + return new JsonIntegrationEventEncoder(contributions.orderedStream().toList()); + } +} diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java new file mode 100644 index 00000000..cebd75d6 --- /dev/null +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java @@ -0,0 +1,332 @@ +package dev.caskeleton.adapter.outbound.support.messaging; + +import dev.caskeleton.application.messaging.contract.ContractDescriptor; +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; +import dev.caskeleton.application.messaging.contract.IntegrationPayload; +import dev.caskeleton.application.messaging.contract.Sha256; +import dev.caskeleton.application.messaging.event.IntegrationEventDraft; +import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.RecordComponent; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; + +/** + * The template's {@link IntegrationEventEncoderPort}: JSON envelope v1 around a deterministic JSON + * rendering of the payload record. + * + *

    The catalog is closed. It is the contract contributions given at construction and nothing + * else, and each one is checked then, not at the first event: the payload type is a public record + * implementing {@link IntegrationPayload}, the declared component order is the record's, and the + * declared payload schema hash is the SHA-256 of the schema bytes on the classpath. A contribution + * whose schema file was edited without its hash fails startup instead of stamping every event with + * a hash of a schema that no longer exists. + * + *

    What this encoder does not do is validate the payload against its JSON Schema. The record type + * is the contract the application compiles against, and the schema file is its published + * description; a service that wants the two cross-checked on every event supplies its own encoder + * bean, and this one backs off. + * + *

    The envelope shape is {@code contracts/messaging/envelope/v1.schema.json} (shared-contract), + * and its hash is taken from those bytes. The partition key is the domain-separated v1 derivation + * over tenant, logical destination, aggregate type and aggregate id, so every event of one + * aggregate lands on one partition. + */ +public final class JsonIntegrationEventEncoder implements IntegrationEventEncoderPort { + + /** The shared envelope schema whose bytes this encoder's output conforms to. */ + public static final String ENVELOPE_SCHEMA_RESOURCE = + "contracts/messaging/envelope/v1.schema.json"; + + /** The media type of every envelope this encoder writes. */ + public static final String CONTENT_TYPE = "application/json"; + + private static final int ENVELOPE_VERSION = 1; + private static final byte[] SCHEMA_SET_DOMAIN = utf8("ca-skeleton.messaging.schema-set.v1"); + private static final byte[] CATALOG_DOMAIN = utf8("ca-skeleton.messaging.contract-catalog.v1"); + private static final byte[] DESCRIPTOR_DOMAIN = + utf8("ca-skeleton.messaging.contract-descriptor.v1"); + private static final byte[] PARTITION_KEY_DOMAIN = utf8("ca-skeleton.messaging.partition-key.v1"); + private static final byte[] PAYLOAD_PROPERTY = utf8(",\"payload\":"); + + private final Map entries; + private final Sha256 envelopeSchemaHash; + private final String catalogRevision; + + /** + * An encoder for exactly these contracts. + * + * @param contributions the closed contract catalog; may be empty, in which case every draft is + * refused as unknown + * @throws IllegalArgumentException when a contribution is malformed, duplicated or declares a + * schema hash that its classpath resource does not have + */ + public JsonIntegrationEventEncoder( + Collection> contributions) { + if (contributions == null) { + throw new IllegalArgumentException("contract contributions must not be null"); + } + this.envelopeSchemaHash = + resourceHash(JsonIntegrationEventEncoder.class.getClassLoader(), ENVELOPE_SCHEMA_RESOURCE); + Map indexed = new HashMap<>(); + for (IntegrationEventContractContribution contribution : contributions) { + Entry entry = entryFor(contribution); + if (indexed.putIfAbsent(entry.key(), entry) != null) { + throw new IllegalArgumentException("duplicate integration event contract " + entry.key()); + } + } + this.entries = Map.copyOf(indexed); + this.catalogRevision = catalogRevision(indexed.values()); + } + + @Override + public ValidatedIntegrationEvent encode(IntegrationEventDraft draft) { + if (draft == null) { + throw new IllegalArgumentException("integration event draft must not be null"); + } + String key = key(draft.contractId().value(), draft.payloadVersion()); + Entry entry = entries.get(key); + if (entry == null) { + throw new IllegalArgumentException("no integration event contract is registered for " + key); + } + ContractDescriptor descriptor = entry.contribution().descriptor(); + if (!draft.destinationId().equals(descriptor.logicalDestination())) { + throw new IllegalArgumentException( + "draft destination " + + draft.destinationId().value() + + " is not the destination contract " + + key + + " declares"); + } + IntegrationPayload payload = draft.featurePayload(); + if (payload.getClass() != entry.contribution().exactPayloadRecordType()) { + throw new IllegalArgumentException( + "draft payload must be exactly " + entry.contribution().exactPayloadRecordType()); + } + + byte[] payloadBytes = CanonicalJson.payload((Record) payload); + if (payloadBytes.length > descriptor.maximumPayloadBytes()) { + throw new IllegalArgumentException( + "payload of " + key + " exceeds " + descriptor.maximumPayloadBytes() + " bytes"); + } + byte[] envelopeBytes = envelope(draft, payloadBytes); + if (envelopeBytes.length > descriptor.maximumEnvelopeBytes()) { + throw new IllegalArgumentException( + "envelope of " + key + " exceeds " + descriptor.maximumEnvelopeBytes() + " bytes"); + } + + String partitionKey = partitionKey(draft); + return new ValidatedIntegrationEvent( + draft.eventId(), + draft.contractId(), + ENVELOPE_VERSION, + draft.payloadVersion(), + draft.destinationId(), + draft.aggregate(), + draft.order(), + draft.occurredAt(), + draft.correlationId(), + draft.causationId(), + partitionKey, + partitionKey.getBytes(StandardCharsets.US_ASCII), + envelopeBytes, + CONTENT_TYPE, + entry.schemaSetHash(), + Sha256.of(envelopeBytes), + envelopeSchemaHash, + entry.contribution().payloadSchemaHash(), + catalogRevision, + entry.descriptorRevision()); + } + + private Entry entryFor(IntegrationEventContractContribution contribution) { + if (contribution == null) { + throw new IllegalArgumentException("contract contribution must not be null"); + } + if (contribution.contractId() == null || contribution.payloadVersion() <= 0) { + throw new IllegalArgumentException( + "contract contribution needs a contract id and a positive payload version"); + } + String key = key(contribution.contractId().value(), contribution.payloadVersion()); + Class type = contribution.exactPayloadRecordType(); + if (type == null || !type.isRecord() || !IntegrationPayload.class.isAssignableFrom(type)) { + throw new IllegalArgumentException( + key + " payload type must be a record implementing IntegrationPayload"); + } + List declared = + Arrays.stream(type.getRecordComponents()).map(RecordComponent::getName).toList(); + if (!declared.equals(contribution.canonicalRecordComponentOrder())) { + throw new IllegalArgumentException( + key + + " declares component order " + + contribution.canonicalRecordComponentOrder() + + " but " + + type.getName() + + " declares " + + declared); + } + if (contribution.descriptor() == null + || contribution.payloadSchemaResource() == null + || contribution.payloadSchemaHash() == null) { + throw new IllegalArgumentException(key + " needs a descriptor and a payload schema identity"); + } + Sha256 onClasspath = + resourceHash(type.getClassLoader(), contribution.payloadSchemaResource().value()); + if (!onClasspath.equals(contribution.payloadSchemaHash())) { + throw new IllegalArgumentException( + key + + " declares payload schema hash " + + contribution.payloadSchemaHash() + + " but " + + contribution.payloadSchemaResource().value() + + " hashes to " + + onClasspath); + } + return new Entry( + key, + contribution, + schemaSetHash(envelopeSchemaHash, onClasspath), + descriptorRevision(contribution.descriptor())); + } + + private static byte[] envelope(IntegrationEventDraft draft, byte[] payloadBytes) { + StringBuilder metadata = new StringBuilder(256); + metadata.append("{\"envelopeVersion\":").append(ENVELOPE_VERSION); + property(metadata, "eventId", draft.eventId().value()); + property(metadata, "contractId", draft.contractId().value()); + metadata.append(",\"payloadVersion\":").append(draft.payloadVersion()); + property(metadata, "logicalDestination", draft.destinationId().value()); + metadata.append(",\"aggregate\":{\"type\":"); + CanonicalJson.writeString(metadata, draft.aggregate().aggregateType()); + metadata.append(",\"id\":"); + CanonicalJson.writeString(metadata, draft.aggregate().aggregateId()); + metadata.append(",\"sequence\":").append(draft.order().sequence()); + metadata.append(",\"eventIndex\":").append(draft.order().eventIndex()).append('}'); + property(metadata, "occurredAt", draft.occurredAt().toString()); + property(metadata, "correlationId", draft.correlationId()); + property(metadata, "contentType", CONTENT_TYPE); + byte[] head = CanonicalJson.strictUtf8(metadata); + // The payload is embedded as the exact bytes rendered once above, never re-rendered, so the + // bytes the size check measured are the bytes the envelope carries. + byte[] envelope = new byte[head.length + PAYLOAD_PROPERTY.length + payloadBytes.length + 1]; + System.arraycopy(head, 0, envelope, 0, head.length); + System.arraycopy(PAYLOAD_PROPERTY, 0, envelope, head.length, PAYLOAD_PROPERTY.length); + System.arraycopy( + payloadBytes, 0, envelope, head.length + PAYLOAD_PROPERTY.length, payloadBytes.length); + envelope[envelope.length - 1] = (byte) '}'; + return envelope; + } + + private static void property(StringBuilder out, String name, String value) { + out.append(",\"").append(name).append("\":"); + CanonicalJson.writeString(out, value); + } + + private static String partitionKey(IntegrationEventDraft draft) { + MessageDigest digest = sha256(); + digest.update(PARTITION_KEY_DOMAIN); + digest.update((byte) 0); + lengthPrefixed(digest, CanonicalJson.strictUtf8(draft.aggregate().tenantScope())); + lengthPrefixed(digest, CanonicalJson.strictUtf8(draft.destinationId().value())); + lengthPrefixed(digest, CanonicalJson.strictUtf8(draft.aggregate().aggregateType())); + lengthPrefixed(digest, CanonicalJson.strictUtf8(draft.aggregate().aggregateId())); + return HexFormat.of().formatHex(digest.digest()); + } + + private static Sha256 schemaSetHash(Sha256 envelope, Sha256 payload) { + MessageDigest digest = sha256(); + digest.update(SCHEMA_SET_DOMAIN); + digest.update((byte) 0); + lengthPrefixed(digest, envelope.bytes()); + lengthPrefixed(digest, payload.bytes()); + return new Sha256(digest.digest()); + } + + /** + * The revision of how a contract is delivered: its destination and the limits and ordering it + * declares. Stamped on every event, so a consumer can tell events written under different + * delivery descriptors apart without the template owning a separate binding registry. + */ + private static String descriptorRevision(ContractDescriptor descriptor) { + MessageDigest digest = sha256(); + digest.update(DESCRIPTOR_DOMAIN); + digest.update((byte) 0); + lengthPrefixed(digest, utf8(descriptor.ownerModule())); + lengthPrefixed(digest, utf8(descriptor.logicalDestination().value())); + lengthPrefixed(digest, utf8(descriptor.serializerId())); + lengthPrefixed(digest, utf8(Boolean.toString(descriptor.orderingRequired()))); + lengthPrefixed(digest, utf8(Integer.toString(descriptor.maximumPayloadBytes()))); + lengthPrefixed(digest, utf8(Integer.toString(descriptor.maximumEnvelopeBytes()))); + lengthPrefixed(digest, utf8(descriptor.sensitivityClassification().name())); + lengthPrefixed(digest, utf8(descriptor.sameEventRequeueHorizon().toString())); + return HexFormat.of().formatHex(digest.digest()); + } + + /** The revision of the whole catalog: every contract, in a fixed order, with its schema hash. */ + private static String catalogRevision(Collection entries) { + List ordered = new ArrayList<>(entries); + ordered.sort(Comparator.comparing(Entry::key)); + MessageDigest digest = sha256(); + digest.update(CATALOG_DOMAIN); + digest.update((byte) 0); + for (Entry entry : ordered) { + lengthPrefixed(digest, utf8(entry.key())); + lengthPrefixed(digest, entry.contribution().payloadSchemaHash().bytes()); + lengthPrefixed(digest, utf8(entry.descriptorRevision())); + } + return HexFormat.of().formatHex(digest.digest()); + } + + private static Sha256 resourceHash(ClassLoader loader, String resource) { + ClassLoader effective = loader == null ? ClassLoader.getSystemClassLoader() : loader; + try (InputStream in = effective.getResourceAsStream(resource)) { + if (in == null) { + throw new IllegalArgumentException( + "schema resource " + resource + " is not on the classpath"); + } + return Sha256.of(in.readAllBytes()); + } catch (IOException exception) { + throw new IllegalArgumentException( + "schema resource " + resource + " is unreadable", exception); + } + } + + private static void lengthPrefixed(MessageDigest digest, byte[] value) { + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array()); + digest.update(value); + } + + private static MessageDigest sha256() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("Java runtime does not provide SHA-256", exception); + } + } + + private static String key(String contractId, int payloadVersion) { + return contractId + ":v" + payloadVersion; + } + + private static byte[] utf8(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private record Entry( + String key, + IntegrationEventContractContribution contribution, + Sha256 schemaSetHash, + String descriptorRevision) {} +} diff --git a/src/adapter/outbound/support/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/outbound/support/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 5c1c7343..4d597e1c 100644 --- a/src/adapter/outbound/support/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/adapter/outbound/support/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1 +1,2 @@ dev.caskeleton.adapter.outbound.support.OutboundSupportConfig +dev.caskeleton.adapter.outbound.support.messaging.IntegrationEventEncoderAutoConfiguration diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinderTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinderTest.java new file mode 100644 index 00000000..30762d56 --- /dev/null +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinderTest.java @@ -0,0 +1,70 @@ +package dev.caskeleton.adapter.outbound.support; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.time.Duration; +import java.util.Set; +import org.junit.jupiter.api.Test; +import org.springframework.boot.context.properties.bind.BindException; +import org.springframework.mock.env.MockEnvironment; + +class StrictSettingsBinderTest { + + private static final String PREFIX = "sample.shared"; + + /** Settings that own one key of a shared prefix. */ + public record LifecycleSettings(Duration lease) {} + + @Test + void aKeyAnotherModuleOwnsIsLeftToThatModule() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty(PREFIX + ".lease", "30s") + .withProperty(PREFIX + ".key-version", "1"); + + // when + LifecycleSettings settings = + StrictSettingsBinder.bindExcept( + environment, PREFIX, LifecycleSettings.class, Set.of("key-version")); + + // then + assertThat(settings).isEqualTo(new LifecycleSettings(Duration.ofSeconds(30))); + } + + @Test + void aMisspeltKeyUnderTheSharedPrefixIsStillRefused() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty(PREFIX + ".lease", "30s") + .withProperty(PREFIX + ".leese", "31s"); + + // when + Throwable thrown = + catchThrowable( + () -> + StrictSettingsBinder.bindExcept( + environment, PREFIX, LifecycleSettings.class, Set.of("key-version"))); + + // then + assertThat(thrown).isInstanceOf(BindException.class).hasStackTraceContaining("leese"); + } + + @Test + void placeholdersAreResolvedLikeAnyOtherBinding() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty("LEASE_FROM_ENV", "45s") + .withProperty(PREFIX + ".lease", "${LEASE_FROM_ENV:30s}"); + + // when + LifecycleSettings settings = + StrictSettingsBinder.bindExcept(environment, PREFIX, LifecycleSettings.class, Set.of()); + + // then + assertThat(settings.lease()).isEqualTo(Duration.ofSeconds(45)); + } +} diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/IntegrationEventEncoderAutoConfigurationTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/IntegrationEventEncoderAutoConfigurationTest.java new file mode 100644 index 00000000..896c61b7 --- /dev/null +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/IntegrationEventEncoderAutoConfigurationTest.java @@ -0,0 +1,47 @@ +package dev.caskeleton.adapter.outbound.support.messaging; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.context.annotation.ImportCandidates; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class IntegrationEventEncoderAutoConfigurationTest { + + private final ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(IntegrationEventEncoderAutoConfiguration.class)); + + @Test + void theModuleRegistersTheEncoderAutoConfiguration() { + assertThat(ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader())) + .contains(IntegrationEventEncoderAutoConfiguration.class.getName()); + } + + @Test + void theTemplateEncoderIsProvidedWhenTheServiceBringsNone() { + runner.run( + context -> + assertThat(context.getBean(IntegrationEventEncoderPort.class)) + .isInstanceOf(JsonIntegrationEventEncoder.class)); + } + + @Test + void aServiceEncoderReplacesTheTemplateOne() { + // given + IntegrationEventEncoderPort own = + draft -> { + throw new UnsupportedOperationException("service encoder"); + }; + + // when & then + runner + .withBean(IntegrationEventEncoderPort.class, () -> own) + .run( + context -> + assertThat(context.getBean(IntegrationEventEncoderPort.class)).isSameAs(own)); + } +} diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java new file mode 100644 index 00000000..29c49d37 --- /dev/null +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java @@ -0,0 +1,306 @@ +package dev.caskeleton.adapter.outbound.support.messaging; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.messaging.contract.ContractDescriptor; +import dev.caskeleton.application.messaging.contract.ContractId; +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; +import dev.caskeleton.application.messaging.contract.IntegrationPayload; +import dev.caskeleton.application.messaging.contract.LogicalDestinationId; +import dev.caskeleton.application.messaging.contract.SchemaResourceId; +import dev.caskeleton.application.messaging.contract.Sha256; +import dev.caskeleton.application.messaging.event.AggregateIdentity; +import dev.caskeleton.application.messaging.event.AggregateOrder; +import dev.caskeleton.application.messaging.event.EventId; +import dev.caskeleton.application.messaging.event.IntegrationEventDraft; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.operation.DurableOperationSubmittedContract; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; + +class JsonIntegrationEventEncoderTest { + + private static final String SCHEMA = "contracts/messaging/testkit.encoder-sample/v1.schema.json"; + private static final LogicalDestinationId DESTINATION = new LogicalDestinationId("sample-events"); + private static final Instant OCCURRED_AT = Instant.parse("2026-09-28T01:02:03Z"); + + /** The payload the sample contract carries. */ + public record SamplePayload(String name, long count, List tags, Optional note) + implements IntegrationPayload {} + + /** A payload with a floating-point component, which has no single canonical spelling. */ + public record FloatingPayload(double ratio) implements IntegrationPayload {} + + private final JsonIntegrationEventEncoder encoder = + new JsonIntegrationEventEncoder(List.of(contract(schemaHash(), 4096))); + + @Test + void anEventIsTheEnvelopeV1WithThePayloadComponentsInDeclarationOrder() { + // when + ValidatedIntegrationEvent event = encoder.encode(draft(sample("a\"b\n"), "sample-events")); + + // then + assertThat(new String(event.envelopeBytes(), StandardCharsets.UTF_8)) + .isEqualTo( + "{\"envelopeVersion\":1,\"eventId\":\"event-1\",\"contractId\":\"testkit.encoder-sample\"," + + "\"payloadVersion\":1,\"logicalDestination\":\"sample-events\"," + + "\"aggregate\":{\"type\":\"sample\",\"id\":\"sample-1\",\"sequence\":3,\"eventIndex\":0}," + + "\"occurredAt\":\"2026-09-28T01:02:03Z\",\"correlationId\":\"correlation-1\"," + + "\"contentType\":\"application/json\"," + + "\"payload\":{\"name\":\"a\\\"b\\n\",\"count\":7,\"tags\":[\"x\",\"y\"],\"note\":null}}"); + } + + @Test + void theSameDraftEncodesToTheSameBytesEveryTime() { + // given + IntegrationEventDraft draft = draft(sample("same"), "sample-events"); + ValidatedIntegrationEvent first = encoder.encode(draft); + + // when + ValidatedIntegrationEvent second = encoder.encode(draft); + + // then + assertThat(second).isEqualTo(first); + } + + @Test + void theEventCarriesTheSchemaHashesAndTheJsonContentType() { + // when + ValidatedIntegrationEvent event = encoder.encode(draft(sample("hash"), "sample-events")); + + // then + assertThat(event) + .extracting( + ValidatedIntegrationEvent::payloadSchemaHash, + ValidatedIntegrationEvent::envelopeSchemaHash, + ValidatedIntegrationEvent::contentType, + ValidatedIntegrationEvent::envelopeVersion) + .containsExactly( + schemaHash(), + resourceHash(JsonIntegrationEventEncoder.ENVELOPE_SCHEMA_RESOURCE), + "application/json", + 1); + } + + @Test + void everyEventOfOneAggregateSharesOnePartitionKey() { + // given + String first = encoder.encode(draft(sample("one"), "sample-events")).partitionKeyText(); + + // when + String second = encoder.encode(draft(sample("two"), "sample-events")).partitionKeyText(); + + // then + assertThat(second).isEqualTo(first).matches("[0-9a-f]{64}"); + } + + @Test + void aContributionWhoseSchemaHashIsNotTheClasspathBytesIsRefusedAtConstruction() { + // given + Sha256 stale = Sha256.of("an older schema".getBytes(StandardCharsets.UTF_8)); + + // when + Throwable thrown = + catchThrowable(() -> new JsonIntegrationEventEncoder(List.of(contract(stale, 4096)))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("testkit.encoder-sample:v1 declares payload schema hash " + stale); + } + + @Test + void theDurableOperationContractDeclaresTheSchemaItShips() { + // when + Throwable thrown = + catchThrowable( + () -> + new JsonIntegrationEventEncoder(List.of(new DurableOperationSubmittedContract()))); + + // then + assertThat(thrown).isNull(); + } + + @Test + void aContributionWhoseComponentOrderIsNotTheRecordsIsRefusedAtConstruction() { + // given + TestContribution reordered = + new TestContribution<>( + SamplePayload.class, + List.of("count", "name", "tags", "note"), + schemaHash(), + descriptor(4096)); + + // when + Throwable thrown = catchThrowable(() -> new JsonIntegrationEventEncoder(List.of(reordered))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("declares component order [count, name, tags, note]"); + } + + @Test + void aDraftForAContractOutsideTheCatalogIsRefused() { + // given + JsonIntegrationEventEncoder empty = new JsonIntegrationEventEncoder(List.of()); + + // when + Throwable thrown = catchThrowable(() -> empty.encode(draft(sample("x"), "sample-events"))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("no integration event contract is registered for testkit.encoder-sample:v1"); + } + + @Test + void aDraftAddressedToAnotherDestinationIsRefused() { + // when + Throwable thrown = catchThrowable(() -> encoder.encode(draft(sample("x"), "other-events"))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("draft destination other-events is not the destination"); + } + + @Test + void aPayloadLargerThanTheDeclaredBoundIsRefused() { + // given + JsonIntegrationEventEncoder tight = + new JsonIntegrationEventEncoder(List.of(contract(schemaHash(), 16))); + + // when + Throwable thrown = + catchThrowable(() -> tight.encode(draft(sample("longer than sixteen"), "sample-events"))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("payload of testkit.encoder-sample:v1 exceeds 16 bytes"); + } + + @Test + void aFloatingPointComponentHasNoCanonicalFormAndIsRefused() { + // when + Throwable thrown = catchThrowable(() -> CanonicalJson.payload(new FloatingPayload(0.1))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith( + "payload component type java.lang.Double has no canonical JSON form"); + } + + @Test + void aNullComponentIsRefusedInFavourOfOptional() { + // when + Throwable thrown = + catchThrowable( + () -> CanonicalJson.payload(new SamplePayload(null, 1, List.of(), Optional.empty()))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "payload values must not be null; declare an Optional component for an absent value"); + } + + @Test + void anUnpairedSurrogateIsRefusedRatherThanReplaced() { + // when + Throwable thrown = + catchThrowable( + () -> + CanonicalJson.payload(new SamplePayload("\uD800", 1, List.of(), Optional.empty()))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("integration event text contains an unpaired surrogate"); + } + + private static SamplePayload sample(String name) { + return new SamplePayload(name, 7, List.of("x", "y"), Optional.empty()); + } + + private static IntegrationEventDraft draft( + SamplePayload payload, String destination) { + return new IntegrationEventDraft<>( + new EventId("event-1"), + new ContractId("testkit.encoder-sample"), + 1, + new LogicalDestinationId(destination), + new AggregateIdentity("default", "sample", "sample-1"), + new AggregateOrder(3, 0), + OCCURRED_AT, + "correlation-1", + Optional.empty(), + payload); + } + + private static TestContribution contract(Sha256 hash, int maximumPayloadBytes) { + return new TestContribution<>( + SamplePayload.class, + List.of("name", "count", "tags", "note"), + hash, + descriptor(maximumPayloadBytes)); + } + + private static ContractDescriptor descriptor(int maximumPayloadBytes) { + return new ContractDescriptor( + "adapter-outbound-support", + DESTINATION, + "json-envelope-v1", + true, + maximumPayloadBytes, + 8192, + ContractDescriptor.SensitivityClassification.INTERNAL, + Duration.ofDays(1)); + } + + private static Sha256 schemaHash() { + return resourceHash(SCHEMA); + } + + private static Sha256 resourceHash(String resource) { + try (InputStream in = + JsonIntegrationEventEncoderTest.class.getClassLoader().getResourceAsStream(resource)) { + return Sha256.of(in.readAllBytes()); + } catch (IOException exception) { + throw new UncheckedIOException(exception); + } + } + + private record TestContribution

    ( + Class

    exactPayloadRecordType, + List canonicalRecordComponentOrder, + Sha256 payloadSchemaHash, + ContractDescriptor descriptor) + implements IntegrationEventContractContribution

    { + + @Override + public ContractId contractId() { + return new ContractId("testkit.encoder-sample"); + } + + @Override + public int payloadVersion() { + return 1; + } + + @Override + public SchemaResourceId payloadSchemaResource() { + return new SchemaResourceId(SCHEMA); + } + } +} diff --git a/src/adapter/outbound/support/src/test/resources/contracts/messaging/testkit.encoder-sample/v1.schema.json b/src/adapter/outbound/support/src/test/resources/contracts/messaging/testkit.encoder-sample/v1.schema.json new file mode 100644 index 00000000..87f92510 --- /dev/null +++ b/src/adapter/outbound/support/src/test/resources/contracts/messaging/testkit.encoder-sample/v1.schema.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:dev-caskeleton:contracts:messaging:testkit.encoder-sample:v1", + "title": "Encoder sample payload v1", + "type": "object", + "required": ["name", "count", "tags", "note"], + "properties": { + "name": {"type": "string"}, + "count": {"type": "integer"}, + "tags": {"type": "array", "items": {"type": "string"}}, + "note": {"type": ["string", "null"]} + }, + "unevaluatedProperties": false +} diff --git a/src/app-bootstrap/CLAUDE.md b/src/app-bootstrap/CLAUDE.md index f13b5a16..b8f96fba 100644 --- a/src/app-bootstrap/CLAUDE.md +++ b/src/app-bootstrap/CLAUDE.md @@ -62,14 +62,17 @@ configurations, Redis as one 376-line class. switch registry, no cross-capability dependency validator, no activation endpoint. Component scan covers `dev.caskeleton.bootstrap` only; web (`WebAdapterAutoConfiguration`, `WebSecurityAutoConfiguration`) and support (`OutboundSupportConfig`) arrive through their own `AutoConfiguration.imports`. What stays in `autoconfigure//` is application - composition over application-core ports that names no module type: `outbox` (the relay use case - and its scheduler, on only when the store and publisher ports exist), `operation` (the durable + composition over application-core ports that names no module type: `operation` (the durable operation use cases and their `/operations` endpoints, on only when the operation store and the - outbox append port exist), `idempotency` (the one executor over whichever store is selected), - `tracing`, `common`. + outbox append port exist), `common`. The outbox relay and the idempotency executor are + `composition:outbox-relay` and `composition:idempotency`, selected by one `runtimeOnly` line each + (the sample takes the idempotency one too). The runtime wiring both composition roots need — + tracing, the metrics contract filters, domain-context propagation, user-principal pseudonymization + (`PrivacySettings`) and the actuator chain — is `composition:service-runtime`, which the sample + takes by the same line instead of carrying copies. - **`Settings` lives beside its capability**, not in `settings/`. The `settings/` package holds only settings that belong to no capability — `BootstrapSettings`, `LoggingSettings`, - `PrivacySettings`, `RuntimeSafetySettings`. + `RuntimeSafetySettings`. - **`runtime/` holds guards about the application itself** — secrets, numeric bounds, error-detail exposure, multi-instance coordination, the runtime-profile check (`RuntimeEnvironmentProfileValidator`). A guard about a capability's settings (the JPA OSIV/DDL/pool/TLS/vendor guards, the Mongo diff --git a/src/app-bootstrap/README.md b/src/app-bootstrap/README.md index 5f6ceacc..a5128b66 100644 --- a/src/app-bootstrap/README.md +++ b/src/app-bootstrap/README.md @@ -41,14 +41,12 @@ WebSocket, gRPC, 파일 서버, 알림)는 `build.gradle`에 주석 처리된 `r - [runtime/startup — Fail-fast 시작 파이프라인](#runtimestartup--fail-fast-시작-파이프라인과-시작-실패-분류) - [runtime — 시크릿 소스 선택과 런타임 안전 가드](#runtime--시크릿-소스-선택과-런타임-안전-가드) -- [concurrency — 도메인 컨텍스트 전파](#concurrency--도메인-컨텍스트-전파-전략-조립) +- [concurrency — 도메인 컨텍스트 전파 (composition:service-runtime으로 이동)](#concurrency--도메인-컨텍스트-전파-compositionservice-runtime으로-이동) - [async — 비동기 executor 컨텍스트 전파와 포화 처리](#async--비동기-executor-컨텍스트-전파와-포화-처리) -- [idempotency — 멱등성 provider 선택과 executor 조립](#idempotency--멱등성-provider-선택과-executor-조립) -- [outbox — 트랜잭셔널 아웃박스 릴레이](#outbox--트랜잭셔널-아웃박스-릴레이-와이어링) +- [idempotency — 멱등성 executor 조립 (composition:idempotency로 이동)](#idempotency--멱등성-executor-조립-compositionidempotency로-이동) +- [outbox — 트랜잭셔널 아웃박스 릴레이 (composition:outbox-relay로 이동)](#outbox--트랜잭셔널-아웃박스-릴레이-compositionoutbox-relay로-이동) - [logging — 로그 시크릿 마스킹·샘플링·가명화](#logging--로그-시크릿-마스킹샘플링가명화) -- [metrics — 메트릭 계약 MeterFilter](#metrics--메트릭-계약-meterfilter-설치) -- [management/security — 액추에이터 엔드포인트 보안](#managementsecurity--액추에이터-엔드포인트-보안-체인) -- [tracing — 분산 트레이싱 wiring과 샘플링 정책](#tracing--분산-트레이싱-wiring과-샘플링-정책) +- [metrics·management/security·tracing (composition:service-runtime으로 이동)](#metricsmanagementsecuritytracing-compositionservice-runtime으로-이동) - [settings — @ConfigurationProperties 검증 정책](#settings--configurationproperties-검증-정책) - [build.gradle — 의존성 구성 근거](#buildgradle--의존성-구성-근거) @@ -188,15 +186,9 @@ README의 "startup" 절에 있다. --- -## concurrency — 도메인 컨텍스트 전파 전략 조립 +## concurrency — 도메인 컨텍스트 전파 (composition:service-runtime으로 이동) -### DomainContextConfig -- **`DomainContextPropagator`를 빈으로 노출하고 `ThreadLocalDomainContextPropagator`를 직접 만든다.** - `application-core`는 설정을 직접 읽지 않으므로 propagator 생성은 composition root(여기)에서 끝내고 - 완성된 propagator만 주입한다. 제공하는 전략이 하나뿐이라 선택 설정(strategy enum·factory·설정 키)은 - 두지 않는다. 두 번째 전략이 생기면 그 구현과 선택 설정을 함께 추가한다. - ---- +`DomainContextConfig`는 `composition:service-runtime`으로 옮겼다. 근거는 [그 모듈의 README](../composition/service-runtime/README.md). ## async — 비동기 executor 컨텍스트 전파와 포화 처리 @@ -277,132 +269,19 @@ README의 "startup" 절에 있다. --- -## idempotency — 멱등성 provider 선택과 executor 조립 +## idempotency — 멱등성 executor 조립 (composition:idempotency로 이동) -### IdempotencyProviderSelectionConfig -- **`IdempotencyExecutor`를 여기서 한 번만 만든다.** provider 모듈은 `IdempotencyStorePort`만 - 내놓는다 — `redis`는 `cache-redis`의 `RedisIdempotencyConfig`, `postgresql`은 `persistence-jpa`의 - `PostgreSqlIdempotencyStoreConfig`. lease·replay TTL·retention·codec id·policy revision 은 어느 - store 든 같은 정책이라 `IdempotencySettings` 하나에서 읽는다. executor 를 application-core 밖에서 - 만드는 이유는 이 설정을 `application-core`가 직접 읽으면 안 되기 때문이다. -- **store 가 정확히 하나가 아니면 기동을 거부한다.** 0개는 provider 모듈이 runtime classpath 에 - 없거나 스위치가 꺼진 경우, 2개는 다른 무언가가 store 를 등록한 경우다. 둘 다 빈 누락 오류나 엉뚱한 - store 로 요청을 처리하는 대신 개수를 담은 startup 실패로 드러난다. -- `provider=disabled`(기본)면 executor 빈 자체가 없다. `jdbc` 값과 V1 조립(`IdempotencyConfig`, - `config/idempotency.yml`)은 삭제됐다. -- `postgresql` provider 는 PostgreSQL data source 가 아니면 기동을 거부한다. `bootRunH2` 에서는 - `disabled` 나 `redis` 를 쓴다. +executor 조립(`IdempotencyAutoConfiguration`)과 수명 정책(`IdempotencySettings`, strict 바인딩), +설정 기본값(`config/module-defaults/idempotency.yml`, 예전 `config/capabilities.yml`)은 +`composition:idempotency`로 옮겼다(소유자 결정 3). 이 leaf는 `runtimeOnly` 한 줄로 받고, +sample-portfolio도 같은 줄을 쓴다. 근거는 [그 모듈의 README](../composition/idempotency/README.md). -### IdempotencySettings -- `ca-skeleton.capabilities.idempotency` 에 바인딩되는 유일한 설정 record 다(값은 - `config/capabilities.yml`). +## outbox — 트랜잭셔널 아웃박스 릴레이 (composition:outbox-relay로 이동) - | 키 | env | 기본값 | 상한 | - | --- | --- | --- | --- | - | `provider` | `APP_IDEMPOTENCY_PROVIDER` | `disabled` | `disabled` \| `redis` \| `postgresql` | - | `processing-lease` | `APP_IDEMPOTENCY_PROCESSING_LEASE` | 30s | 1h | - | `replay-ttl` | `APP_IDEMPOTENCY_TTL` | 24h | 72h | - | `failure-retention` | `APP_IDEMPOTENCY_FAILURE_RETENTION` | 24h | 30d | - | `response-codec-id` | — | `json-v2` | 1–64자 | - | `policy-revision` | — | 2 | 양수 | - | `reaper-interval` | — | 10m | 양수 | - - Redis store 튜닝값 `key-version`, `command-timeout`(`APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT`)도 - 같은 prefix 아래 있지만 lifecycle 정책이 아니라서 이 record 에 두지 않고 `cache-redis`가 읽는다. -- **상한 검사는 컴팩트 생성자에서 fail-fast 로 던진다.** `Duration`의 상한은 JSR-303(`@Valid`) - 애너테이션으로 표현할 수 없어 생성자에서 직접 검증한다. 검증을 느슨하게 두면 과도하게 긴 TTL 이 - 저장소를 조용히 부풀리고 멱등성 키 추측 공격의 유효 시간 창을 넓히기 때문에, 부팅 시점에 즉시 - 실패시키는 쪽을 택했다. -- **replay TTL 상한(72h) / 기본값(24h)을 바꿀 때는 보안 베이스라인의 JWT 키 회전 겹침(overlap) - 윈도와 반드시 함께 검토해야 한다.** 멱등성 레코드의 수명이 키 회전 겹침 윈도(현재 24h)보다 길면, - 가명화(pseudonym) 기준이 회전된 principal 에 대해 레코드가 재생(replay)될 수 있다. 이 불변식을 - 강제하는 CI 게이트는 security-operational-baseline 쪽에 위임돼 있다. -- **`reaper-interval`은 전용 환경변수가 없다.** reaper 실행 주기는 비밀이나 배포별 값이 아니라 순수 - 운영 튜닝 값이다. reaper 는 provider 가 `postgresql` 일 때만 돈다. - ---- - -## outbox — 트랜잭셔널 아웃박스 릴레이 와이어링 - -### OutboxConfig -- **릴레이 use case 를 `@Service`가 아니라 `app-bootstrap`에서 수동 조립한다.** - `PublishPendingOutboxEventsUseCase`는 `batchSize`와 `inFlightTimeout` 같은 설정값을 생성자로 받아야 - 하는데, `application-core`는 설정(`OutboxSettings`)을 직접 읽으면 안 된다. 그래서 설정을 볼 수 있는 - 합성 루트(`OutboxConfig`)가 값을 꺼내 use case 를 손으로 만들어 넘긴다. use case 클래스의 - `@UseCaseCapability` 애너테이션은 와이어링 방식과 무관하게 유지된다(ArchUnit 이 강제). -- **bootstrap은 failure reporter를 구현하지 않고 주입만 한다.** `MessagingConfig`가 broker 설정에서 - 정확히 하나의 `OutboxRelayFailureReportPort` 구현을 만들고, `OutboxConfig`는 이를 relay 생성자에 - 전달한다. broker가 비활성이어도 reporter bean은 존재한다. -- **릴레이 use case 를 독립 컨텍스트 빈으로 등록하지 않는다.** 만약 빈으로 올리면 `adapter-web`의 - `MethodSecurityConfig` 메서드 보안 pointcut(`@RequiresPermission`)이 이 타입을 CGLIB 프록시로 - 감싼다. 그런데 use case 가 `final` 클래스라 프록시 생성 자체가 실패하고, 설령 된다 해도 스케줄러 - 스레드에는 `Authentication`이 없어 매 릴레이 틱이 fail-closed 로 거부된다. 그래서 빈으로 올리지 - 않고, `outbox:relay` 권한 확인은 스케줄러 컨텍스트에서 관례로 둔다. -- **`outboxRelayScheduler` 빈은 `ca-skeleton.outbox.relay-enabled=true`일 때만 만든다(기본 - false).** 키가 없으면 꺼진 것으로 본다. 모듈 기본값(`persistence-jpa.yml`의 - `${APP_OUTBOX_RELAY_ENABLED:false}`), `@ConditionalOnProperty`, `OutboxSettings`의 null 기본값이 - 모두 false로 같다. -- **store와 publisher가 있을 때만 켜진다.** 설정 전체는 `OutboxStorePort` 빈(persistence-jpa를 고르고 - outbox를 켰을 때만 존재)을, 스케줄러는 추가로 `OutboxMessagePublishPort` 빈(messaging bridge가 - 제공)을 조건으로 건다. 두 auto-configuration 뒤에 오도록 `afterName`으로 순서를 명시한다. 발행할 - 곳이 없으면 스케줄러가 없으므로 PENDING 행이 그대로 남는다 — 예전에는 - `DisabledMessagingSentinelAutoConfiguration`의 대역 publisher가 모든 claim을 실패시켜 DEAD로 - 소진했고, 그걸 막으려고 `OutboxRelayBrokerRequirementValidator`가 있었다. 둘 다 삭제했다. - messaging bridge의 `MessagingConfig`도 outbox 대역 publisher를 만들지 않는다. bridge가 있고 - 켜져 있는데 broker가 비었고 canonical transport도 없으면 기동을 거부한다. -- **왜 persistence-jpa가 아니라 여기인가.** 릴레이는 use case를 조립해 타이머로 구동하는 합성 - 코드다. driven adapter인 persistence-jpa가 use case를 만들거나 호출하면 - `PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES` 규칙 위반이다. 모듈 타입은 하나도 이름으로 - 부르지 않고 포트만 쓰므로, persistence-jpa 한 줄을 지우면 릴레이도 함께 꺼진다. -- **`outboxLeaderElection` 토큰 빈은 outbox capability 안에서 조건 없이 등록한다.** SKIP LOCKED 는 - 멀티 인스턴스 전역 스위치와 무관하게 outbox relay 자체의 리더십/claim 메커니즘이라, outbox가 켜진 - 상태에서 별도 하위 토글로 끌 수 있게 만들지 않는다. 이 토큰은 outbox 조립의 자기 설명용 marker이지 - `APP_MULTI_INSTANCE_ENABLED`의 전역 필수 빈이 아니다. -- **`outboxMetrics` 빈은 `MeterRegistry`가 없을 때 no-op 이다.** Actuator 가 클래스패스에 없는 - 환경에서도 와이어링이 깨지지 않도록 `ObjectProvider`로 레지스트리를 선택적으로 주입한다. - -### OutboxLeaderElectionToken -- **로직이 전혀 없는 마커(documentation artifact) 빈이다.** 이 타입은 동작을 갖지 않고, Spring - 컨텍스트에 존재한다는 사실만으로 멀티 인스턴스 조정 빈 요구사항을 충족시킨다. -- **리더 선출을 외부 코디네이터 없이 PostgreSQL `FOR UPDATE SKIP LOCKED`로 구현한다는 것을 - 표현한다.** claim 쿼리에 SKIP LOCKED 를 걸면 각 릴레이 인스턴스가 서로 겹치지 않는(disjoint) 행 - 집합을 가져가므로, 별도 코디네이터 없이도 "각 인스턴스가 자기 파티션의 리더" 형태로 리더 선출 - 의미가 성립한다. - -### OutboxMetrics -- **`MeterRegistry`가 없으면 모든 메트릭 연산이 no-op 이다.** Actuator 가 없는 환경에서도 릴레이가 - 정상 동작해야 하므로, 생성자에서 `ObjectProvider`로 레지스트리를 조회해 없으면 게이지도 만들지 - 않고 기록도 건너뛴다. -- **카운터는 PUBLISHED/FAILED/DEAD 만 집계하고 IN_FLIGHT 는 제외한다.** IN_FLIGHT 는 릴레이 사이클의 - 종료 결과(terminal outcome)가 아니라 처리 중을 나타내는 일시적 상태라 카운터 outcome 으로 의미가 - 없다. -- **MultiGauge 갱신 시 `overwrite=true`로 등록한다.** 매 스케줄러 틱마다 store 를 다시 조회해 - 게이지를 갱신하는데, 이전 틱에 있었지만 지금은 사라진 event type 같은 오래된 time-series 태그를 - 덮어써 제거하기 위함이다. - -### OutboxRelayScheduler -- **합성 루트가 직접 등록하고 컴포넌트 스캔하지 않는다.** 이 스케줄러가 구동하는 릴레이 use case 가 - (위 OutboxConfig 사유로) 일부러 빈이 아니기 때문에, 그 use case 를 조립하는 `OutboxConfig`가 - 스케줄러 등록까지 같이 소유한다. -- **릴레이 사이클에서 발생하는 예상치 못한 예외를 잡아 ERROR 로 로깅만 하고 삼킨다.** 스케줄러 - 스레드가 죽으면 릴레이가 조용히 멈추므로, 다음 틱을 위해 스레드를 살려둔다. 단, 개별 발행 실패 - (FAILED/DEAD 전이)는 relay가 persisted transition 성공 뒤 typed reporter로 canonical ERROR를 - 요청하고 결과에 반영하므로 이 catch 블록까지 오지 않는다 — 여기서 삼키는 것은 어디까지나 - "예상치 못한" 예외다. -- **스케줄링은 `OutboxConfig`가 직접 켜고(`@EnableScheduling`) fixed-delay 를 쓴다.** 예전에는 JDBC - idempotency 설정만 스케줄링을 켰기 때문에 다른 provider 를 고르면 릴레이가 조립만 되고 돌지 - 않았다. fixed-delay 는 릴레이 실행 시간과 무관하게 사이클이 겹치지 않도록(non-overlapping) 보장한다. - -### OutboxSettings -- **여섯 개 설정값 모두 코드 리터럴 기본값을 쓰고 env placeholder 를 두지 않는다.** 신규 env key 를 - 추가하지 않는다는 결정에 따라, 값이 없으면 컴팩트 생성자에서 직접 기본값(예: `PT5S`, `20`, - `PT5M`, `PT10M`, `P7D`)을 채운다. -- **`reaper-interval`과 `published-retention`은 `adapter-persistence`의 `OutboxReaper`도 property - 문자열로 읽는다.** 두 모듈이 같은 키를 공유하지만, 이 properties record 가 여섯 값 전체를 문서화 - 하는 단일 지점(single place) 역할을 한다. 기본값 yml(`ca-skeleton.outbox.*`)은 store를 가진 - persistence-jpa 모듈이 `config/module-defaults/persistence-jpa.yml`로 가져온다. - ---- +relay 조립(`OutboxRelayAutoConfiguration`, 스케줄러·metrics·leader token·`OutboxSettings`)은 +`composition:outbox-relay`로 옮겼다(소유자 결정 3 — persistence-jpa가 아닌 이유는 ArchUnit +`PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES`). 이 leaf는 `runtimeOnly` 한 줄로 받는다. +근거는 [그 모듈의 README](../composition/outbox-relay/README.md). ## logging — 로그 시크릿 마스킹·샘플링·가명화 @@ -433,16 +312,6 @@ README의 "startup" 절에 있다. 루트 레벨을 TRACE 로 낮춰야만 가능한 `TRACE` 드롭은 상위 클래스가 여전히 버리지만 카운트하지는 않아서, 태그 카디널리티가 레지스트리 계약을 벗어나지 않게 유지한다. -### PseudonymizationConfig -- **`user_principal`(로그에 남는 사용자 식별자)를 전체 HMAC 방식으로 가명화한다.** - `UserPrincipalPseudonymizerPort`(application-core)를 HMAC-SHA-256 구현(adapter-identifier)에 - 바인딩하고, 솔트는 `PrivacySettings`에서 가져온다. 원본 식별자를 그대로 로그에 남기지 않으려는 - 개인정보 보호 결정이다. 실제 사용처는 `adapter-web`의 `RequestLoggingFilter`로, 보안 principal 이 - MDC/로그에 닿기 전에 이 포트로 가린다. -- **`@ConditionalOnMissingBean`으로 기본 구현을 둔다.** 이 템플릿을 포크한 프로젝트가 자기만의 - 가명화기(예: 향후 솔트 회전을 지원하는 구현)를 등록하면 이 기본 빈이 비켜주도록, 즉 기본값은 - 제공하되 교체를 막지 않도록 하기 위해서다. - ### SamplingTurboFilter - **레벨을 의식하는 로그 샘플러다.** `WARN`/`ERROR`는 절대 샘플링하지 않고 항상 통과시킨다 (`FilterReply.NEUTRAL`). 진단·장애 신호인 경고/오류는 100% 보장해야 하고, 샘플링 대상은 `INFO` @@ -472,164 +341,9 @@ README의 "startup" 절에 있다. --- -## metrics — 메트릭 계약 MeterFilter 설치 +## metrics·management/security·tracing (composition:service-runtime으로 이동) -### MetricsCardinalityMeterFilter -- **금지 태그가 붙은 미터를 런타임에서 막는 방어 필터다.** 미터의 `Meter.Id`에 붙은 태그 키 중 - 하나라도 `ForbiddenMetricTags.FORBIDDEN`에 들어 있으면 그 미터를 `DENY`하고, 아니면 `NEUTRAL`을 - 반환한다. `user_id`, `request_id`, `raw_url`, `raw_query`, `raw_header_value`, `ip_address` 같은 - 고카디널리티(high-cardinality) 라벨 키는 고유 값마다 Prometheus 시계열을 하나씩 만들어 수백만 - 개로 폭증할 수 있어 차단한다. -- **이 필터는 카디널리티 계약의 런타임(runtime) 절반이다.** 정적(static) 절반은 레지스트리 계약 - 테스트(`MetricsAlertingContractTest`)가 담당한다 — 둘이 짝을 이뤄 심층 방어를 구성한다. -- **상태가 없어(stateless) 여러 레지스트리에 공유해도 안전하다.** public no-arg 생성자는 - `MetricsContractConfig.install()`이 직접 인스턴스화하기 위한 계약이다. - -### MetricsContractConfig -- **`@PostConstruct`에서 `MeterFilter`들을 `MeterRegistry`에 직접 설치한다.** `@Bean MeterFilter`로 - 등록하지 않는 이유: 이 템플릿 클래스패스에는 `@Bean MeterFilter`를 자동 수집하는 Spring Boot - Actuator 자동설정(`MeterRegistryCustomizer`)이 없어서 `@Bean MeterFilter`는 그냥 동작하지 않는 - (inert) 죽은 빈이 되기 때문이다. `OutboundHttpResilienceConfig`에서 확립한 선례를 따른다. -- **설치 순서가 중요하다.** (1) `MetricsCardinalityMeterFilter`(deny-list)를 먼저 설치해 금지 태그가 - 붙은 미터가 분포 필터에 닿기 전에 거부되도록 하고, (2) 그다음 `MetricsDistributionMeterFilter` - (SLO 기반 히스토그램 설정)를 설치한다. -- **필터는 설치 이후 등록되는 미터에만 적용된다.** `@PostConstruct`는 Spring 빈 생명주기 중 애플리 - 케이션 코드가 어떤 미터든 등록하기 전에 실행되므로 모든 미터가 필터 적용 대상이 된다. -- **`MeterRegistry` 부재 시 no-op.** `ObjectProvider.getIfAvailable()`로 해석해 레지스트리 빈이 - 없으면(Actuator 미탑재) DEBUG 로그만 남기고 설치를 건너뛴다. -- **`install(MeterRegistry)`를 public static 으로 둔 이유.** 계약 테스트가 Spring 컨텍스트 없이 - `SimpleMeterRegistry`에 대해 직접 구동할 수 있게 하기 위함이다. - -### MetricsDistributionMeterFilter -- **소유한(owned) 타이머 메트릭 5종에만 SLO 기반 히스토그램·백분위 설정을 적용한다.** 대상: - `http.server.requests`, `http.server.requests.latency`, `dependency.client.requests`, - `db.query.duration`, `jvm.gc.pause`. 이들은 `metrics.yaml`에서 이 브랜치가 소유하고 - `histogram_buckets: slo_driven`인 행이다. `resilience4j.circuitbreaker.calls`, - `hikaricp.connections.acquire`처럼 소비만 하고 소유하지 않는(consumed-but-not-owned) 행은 다른 - 브랜치 소유라 의도적으로 제외 — 덮어쓰면 안 된다. -- **히스토그램 전략은 두 축이다.** - - *인스턴스 간 집계 가능한 진실의 원천*: `percentilesHistogram(true)`(= `publishPercentileHistogram`)가 - `_bucket` 시계열을 생성하고, Prometheus 에서 `histogram_quantile()`로 인스턴스 간 집계할 수 있다. - 이것이 다중 인스턴스 배포의 정식 p50/p95/p99 다. - - *클라이언트 측 편의값(집계 불가)*: `percentiles(0.5, 0.9, 0.95, 0.99)`(= `publishPercentiles`)는 - 단일 인스턴스 가시성을 위한 사전 계산 분위 게이지를 제공한다. 이 값들은 인스턴스 간 평균을 내면 - 안 된다(통계적으로 틀림). 인스턴스 간 집계는 반드시 `histogram_quantile()`로 한다. -- **SLO 경계값 `100ms / 500ms / 1s / 5s`는 잠정 SLO 역산이며 외부 표준에서 유도한 값이 아니다.** - 정식 SLO 가 채택되면 재검토 대상이다. 함께 설정하는 `minimumExpectedValue=1ms`, - `maximumExpectedValue=10s`는 히스토그램 버킷의 관측 범위를 한정한다. -- **상태가 없어 여러 레지스트리에 공유해도 안전하고,** public no-arg 생성자는 - `MetricsContractConfig.install()`이 직접 인스턴스화하기 위한 계약이다. - ---- - -## management/security — 액추에이터 엔드포인트 보안 체인 - -### ManagementSecurityConfig -- **`actuatorSecurityFilterChain`은 `@Order(0)`으로 메인 앱 체인(adapter-web `SecurityConfig`)보다 - 앞서 실행된다.** 그래서 액추에이터 엔드포인트에 매칭되는 요청은 앱 체인이 아니라 이 체인이 - 처리한다. 보안 매처는 `EndpointRequest.toAnyEndpoint()`로, 관리 포트의 `/actuator/**` 경로만 이 - 체인 범위에 든다. -- **접근 정책.** `health`, `info`, `prometheus`는 permit-all 이다. 자격 증명 없이 Kubernetes 프로브와 - Prometheus 스크레이프가 접근할 수 있어야 하고, 이 엔드포인트들은 민감 데이터를 노출하지 않기 - 때문이다(health 상세는 `never`). 나머지(`/actuator` 링크 등)는 모두 인증이 필요하다. -- **`loggers`는 노출하지 않는다.** 이 체인에는 인증 수단(`httpBasic`·`oauth2ResourceServer`)이 없어 - `authenticated()`에 걸리는 엔드포인트는 어떤 자격 증명으로도 도달할 수 없다. 그래서 `loggers` - 노출과 `show-details: when-authorized`를 뺐다. 로그 레벨을 런타임에 보거나 바꿔야 하면 인증 - 수단을 이 체인에 먼저 붙이고 노출한다. -- **인증 실패 시 기본값 403 대신 401(자격 증명 필요)을 반환한다(`HttpStatusEntryPoint(UNAUTHORIZED)`).** - 대화형 로그인이나 basic-auth realm 은 제공하지 않는다 — 관리 포트는 네트워크 ACL 뒤에 있으므로 - 올바른 HTTP 의미(credentials required)만 신호하면 된다. -- **운영에서 deny-by-default 보장은 관리 포트를 별도 포트로 분리해 네트워크 ACL 수준에서 강제한다.** - 이 in-process 체인은 그 위의 심층 방어 계층이다. -- **SHAPE-OWNERSHIP(하드 규칙): 이 클래스는 `HealthEndpoint` / `HealthIndicator` / `HealthComponent`를 - import·구현·의존해선 안 된다** — health 엔드포인트의 형태(shape)는 runtime-health 브랜치 소유다. - 보안 매칭은 오직 엔드포인트 id 문자열로만 하고 health 내부 구조에는 절대 손대지 않는다. ArchUnit - 규칙 `management_security_does_not_depend_on_health_internals`(`CleanArchitectureTest`)가 이를 정적 - 으로 강제한다. - ---- - -## tracing — 분산 트레이싱 wiring과 샘플링 정책 - -### TracingConfig -- **컴포지션 루트에서 트레이싱을 조립한다.** 두 가지를 한다: (1) 시작 시 `tracing.sampling.rate` - 게이지 등록, (2) `SpanErrorRecorder` 빈 등록. -- **`SpanErrorRecorder` 빈은 `@ConditionalOnBean(Tracer.class)`가 아니라 `ObjectProvider`로 - 런타임 존재 여부를 직접 조회한다.** 이유: `@ConditionalOnBean`은 사용자 정의 `@Configuration`에서 - autoconfiguration 이 만드는 빈(여기서는 `Tracer`)을 조건으로 쓸 때 빈 등록 순서가 보장되지 않아 - 신뢰할 수 없기 때문이다. `Tracer`가 있으면 `MicrometerSpanErrorRecorder`를, 없으면 - `SpanErrorRecorder.NOOP`을 반환한다. -- **`@ConditionalOnMissingBean(SpanErrorRecorder.class)`를 붙여, 테스트 mock 이나 fork 가 자체 - `SpanErrorRecorder` 빈을 이미 등록한 경우 이 빈은 backoff 한다.** adapter-web 의 - `GlobalExceptionHandler`는 `ObjectProvider`로 `SpanErrorRecorder`를 조회하므로, 자기 자신의 NOOP - self-default 에서 여기서 등록한 실제 구현으로 자동 교체된다. -- **OTel/Micrometer tracer 런타임은 이 repo 에서 seam 이 활성 상태다.** `micrometer-tracing-bridge-otel` - + `opentelemetry-exporter-otlp`가 `app-bootstrap/build.gradle`에 실제로 wiring 되어 있다. 단, span - exporter 는 `OTEL_EXPORTER_OTLP_ENDPOINT`가 비어 있는 동안 꺼져 있고, 엔드포인트를 설정하면 - export 가 시작된다. -- **게이지 등록 시 active profile 은 `Environment.getActiveProfiles()`의 첫 번째 값을 쓴다.** 멀티 - 프로파일 배포에서는 맨 앞에 나열된 프로파일이 권위 있는 배포 환경이라는 규약이다. `MeterRegistry`가 - classpath 에 없으면(Actuator 미탑재) 게이지 등록은 조용히 no-op 이 된다. -- **`TracingSamplingRateGaugeRegistrar` record 는 등록된 active profile 과 resolved rate 를 노출하는 - 값 홀더다.** 정식 포트나 use case 가 아니라, 살아있는 `MeterRegistry` 없이도 테스트가 "무엇이 - 등록되었는지" 검사할 수 있게 하는 bootstrap 내부 전용 장치다. - -### TracingSettings -- **`ca-skeleton.tracing.*` 바인딩 `@ConfigurationProperties` record.** 세 env 키가 들어온다: - `APP_TRACING_ENABLED` → `enabled`, `APP_TRACING_SAMPLE_RATE` → `sampleRate`, - `OTEL_EXPORTER_OTLP_ENDPOINT` → `exporter.otlpEndpoint`. -- **`sampleRate`가 blank 이면 숫자 검증을 건너뛴다.** blank 는 "값이 잘못됐다"가 아니라 "프로파일별 - 기본값에 위임하라"는 신호이기 때문이다. 실제 런타임별 기본값(prod=0.01, dev/local=1.0)은 `TracingSampleRateResolver`가 적용하고, - profile vocabulary 자체는 `RuntimeEnvironment`가 소유한다. resolved 된 값은 - `TracingSamplingEnvironmentPostProcessor`가 Spring Boot 네이티브 - `management.tracing.sampling.probability`로 브리지한다. -- **검증은 시작 시 fail-fast 다.** `sampleRate`가 non-blank 인데 [0.0, 1.0] float 이 아니면 시작이 - 실패하고, `otlpEndpoint`가 non-empty 인데 scheme 없는 잘못된 URL 이면 시작이 실패한다. `enabled`는 - Spring 바인딩이 `boolean` 타입을 강제하므로 추가 검증이 필요 없다. `otlpEndpoint`가 비어 있으면 - exporter off 상태(seam 기본값)이고, 이것이 정상 동작이므로 검증을 통과시킨다. -- **`sampleRateValue()`는 호출 전 `sampleRate().isBlank()` 확인이 caller 규약이다.** blank 인 상태로 - 호출하면 `IllegalStateException`을 던지는데, 이는 파싱 오류가 아니라 caller 규약 위반을 드러내기 - 위한 것이다. - -### TracingSampleRateResolver -- **런타임별 트레이싱 샘플 정책을 적용한다.** prod=0.01(1%), dev/local=1.0(100%)이며, - 런타임 이름의 SSOT는 `RuntimeEnvironment`다. shipped runtime이 아닌 값은 1.0 안전값을 사용한다. `APP_TRACING_SAMPLE_RATE`가 non-blank 이고 [0,1] float 로 파싱되면 프로파일 기본값을 - override 한다. -- **Spring 의존성이 전혀 없는 순수 Java 로 작성했다.** 어떤 컨텍스트도 없이 단위 테스트할 수 있고, - `EnvironmentPostProcessor`(컨텍스트 생성 이전 단계)와 `TracingConfig`(빈 생성 단계) 양쪽에서 동일 - 로직을 재사용하기 위함이다. - -### TracingSamplingRateGauge -- **`tracing.sampling.rate` 게이지를 등록한다.** metric 계약: type=gauge, tag=`profile`(prod/dev/local - 허용), value=resolved effective sample rate(double in [0.0, 1.0]). -- **deployable `RuntimeEnvironment`가 정확히 하나 해석될 때만 시리즈 하나를 방출한다.** - test/profileless/unknown 컨텍스트를 `local`로 가장하지 않으며, shipped app은 그보다 앞선 profile - validator에서 잘못된 런타임 환경을 거부한다. -- **`MeterRegistry`를 `ObjectProvider`로 조회하며, Actuator 미탑재로 빈이 없으면 등록을 조용히 - 건너뛴다.** 이는 `BackgroundJobMetrics` / `OutboxMetrics`의 선례를 그대로 따른다. - -### TracingSamplingEnvironmentPostProcessor -- **resolved 된 유효 샘플 비율을 Spring Boot 네이티브 키 `management.tracing.sampling.probability`로 - 단일화(브리지)하는 `EnvironmentPostProcessor`다.** 이를 통해 "프로파일별 기본값 + env override"라는 - 우리 규약을 Spring Boot 의 기본 샘플링 메커니즘에 그대로 연결한다. -- **브리지 우선순위.** (1) 사용자가 `management.tracing.sampling.probability`를 이미 명시했으면 - 덮어쓰지 않고 그대로 둔다, (2) `ca-skeleton.tracing.sample-rate`가 non-blank 면 그 값 사용, (3) - blank 면 `TracingSampleRateResolver.defaultRateForProfile(...)`로 active profile 기본값 적용. -- **`META-INF/spring.factories`에 `org.springframework.boot.EnvironmentPostProcessor` 키로 등록된다.** - `EnvironmentPostProcessor`는 ApplicationContext 가 생성되기 전에 실행되므로 일반 빈이 아니라 - Spring Boot bootstrap factory 로 등록해야 한다. - -### MicrometerSpanErrorRecorder -- **NOOP 을 대체하는 Micrometer/OTel 기반 실제 `SpanErrorRecorder`다.** 현재 span 에 예외와 - `error.code` 태그를 기록한다. 계약 이행: `Span.error(Throwable)` 호출(OTel bridge 를 통해 - `recordException` + span status ERROR 매핑), `span.tag("error.code", errorCode)`(ca-tmpl 레지스트리 - 속성명), null `error`는 방어적 no-op, 현재 span 이 없으면 no-op. -- **"sampled span 에만 스택트레이스 부착" 정책은 의도적으로 구현하지 않았다.** Micrometer Tracing - 추상화 레벨에서는 sampled 여부를 직접 제어할 수 없기 때문이다(`Span.isNoop()`은 OTel NOOP span - 여부일 뿐 sampling 여부가 아니다). 다만 OTel SDK 의 unsampled span 은 이미 no-op 으로 처리되므로 - 명시적 sampled-only 분기가 없어도 실제 성능 부담은 없다. - ---- +메트릭 계약 filter(`MetricsContractConfig`), actuator 보안 chain(`ManagementSecurityConfig`), tracing 배선(`TracingConfig` 외 5개), 가명화(`PseudonymizationConfig`·`PrivacySettings`)는 `composition:service-runtime`으로 옮겼다. 근거는 [그 모듈의 README](../composition/service-runtime/README.md). ## settings — @ConfigurationProperties 검증 정책 @@ -654,18 +368,6 @@ README의 "startup" 절에 있다. - **size 문자열(`maxSize`, `totalSizeCap`)은 검증하지 않는다.** 이 값들의 파싱 계약은 logback 이 소유하므로 logback 에게 맡긴다. -### PrivacySettings -- **보안/감사 로그에서 `user_principal`을 가명화하는 데 쓰는 HMAC salt 를 보관한다.** - `ca-skeleton.privacy.*` 바인딩(원천 `APP_PRIVACY_PSEUDONYMIZATION_SALT`). 알고리즘은 HMAC-SHA-256 - + 90일 회전 salt 이고, 이 salt 는 `secret`-tier 값이라 prod 에서는 반드시 secret manager 에서 - 공급되어야 한다. -- **검증은 `LoggingSettings`와 일관되게 "warn-and-default"다.** blank salt 는 경고를 남기고, 명확히 - 표시된 dev sentinel(`__LOCAL_DEV_` 접두사)로 폴백해 local/test 실행이 절대 기동에 실패하지 않게 - 한다. -- **이 sentinel 을 prod 로 승격하는 것은 별도 계약이 독립적으로 - 차단한다** — prod 프로파일에서 `__LOCAL_DEV_` 값이면 시작이 실패한다. 그 게이트는 이 record 의 - 책임 밖이라 여기서 중복 강제하지 않는다. - ### RuntimeSafetySettings - **시작 시 `StartupSafetyValidator`가 강제하는 운영 안전 설정이다.** 현재 구현된 runtime contract는 `APP_MULTI_INSTANCE_ENABLED`이며, 활성화 시 cross-instance `DistributedLockPort`가 diff --git a/src/app-bootstrap/build.gradle b/src/app-bootstrap/build.gradle index c6116b8d..72c5fc7c 100644 --- a/src/app-bootstrap/build.gradle +++ b/src/app-bootstrap/build.gradle @@ -154,6 +154,17 @@ dependencies { // runtimeOnly project(':composition:fileserver-platform') // 파일 서버 // runtimeOnly project(':composition:notification-platform') // 알림 (persistence-jpa 줄도 함께 푼다) + // 기본 조립에 있는 application composition. 둘 다 포트만 보고, 필요한 것(outbox store, 멱등성 + // provider)이 없으면 아무것도 만들지 않는다. sample-portfolio도 같은 멱등성 모듈을 쓴다. + runtimeOnly project(':composition:outbox-relay') // outbox relay (store·발행 포트가 있을 때만) + runtimeOnly project(':composition:idempotency') // 요청 멱등성 executor (provider≠disabled) + // 모든 서비스가 받는 runtime 배선: tracing, metrics 계약 filter, domain context, user principal + // 가명화, actuator 보안 chain. sample-portfolio도 같은 줄을 쓴다. + runtimeOnly project(':composition:service-runtime') + // Contract tests pin those pieces by type (tracing gauge, metrics filters, actuator chain). + testImplementation project(':composition:service-runtime') + integrationTestImplementation project(':composition:service-runtime') + capabilityProjects.each { architectureTestRuntimeOnly project(it) } // The sample is the reference adopters copy, so the whole-repository rules read it too (review // BUILD-중복-8). Architecture-test runtime only: no production configuration reaches it. @@ -168,6 +179,8 @@ dependencies { // would, and turns off whichever one a test is not about. integrationTestImplementation project(':composition:fileserver-platform') integrationTestImplementation project(':adapter:inbound:web-fileserver') + // PostgreSqlIdempotencyProviderIntegrationTest composes the executor module over the real store. + integrationTestImplementation project(':composition:idempotency') testImplementation(testFixtures(project(':adapter:outbound:persistence-jpa'))) testImplementation(testFixtures(project(':adapter:inbound:web'))) @@ -196,7 +209,7 @@ dependencies { // Actuator + Prometheus registry (health/info/prometheus/loggers endpoints). implementation 'org.springframework.boot:spring-boot-starter-actuator' implementation 'io.micrometer:micrometer-registry-prometheus' - // Security types for ManagementSecurityConfig (not reachable via adapter-web's implementation dep). See README. + // Spring Security on the runtime graph (the actuator chain itself is composition:service-runtime's). See README. implementation 'org.springframework.boot:spring-boot-starter-security' // test-only: ArchUnit needs actuator types to verify the health-shape guardrail. See README. diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java index 04627d67..795e58db 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java @@ -687,7 +687,11 @@ class ApplicationBoundaryArchitectureTest { */ private static boolean isInProcessDrivenOutbound(String packageName) { return packageName.contains(".adapter.outbound.persistence") - || packageName.contains(".adapter.outbound.identifier"); + || packageName.contains(".adapter.outbound.identifier") + // The template's IntegrationEventEncoderPort: a deterministic in-memory rendering of the + // application's own envelope, no IO — the same shape as the identifier codecs. Only this + // package; the rest of support stays covered. + || packageName.contains(".adapter.outbound.support.messaging"); } @ArchTest diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/StartupFailureContractArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/StartupFailureContractArchitectureTest.java index 9d70fd14..4aec0d0a 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/StartupFailureContractArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/StartupFailureContractArchitectureTest.java @@ -63,7 +63,7 @@ class StartupFailureContractArchitectureTest { * per-profile default"; calling the accessor anyway is a bug in the caller, not in configuration. */ private static final String TRACING_SETTINGS = - "dev.caskeleton.bootstrap.autoconfigure.tracing.TracingSettings"; + "dev.caskeleton.composition.runtime.tracing.TracingSettings"; /** * {@code RedisKeys} — two JCE invariants ("HmacSHA256 must be available", "a Mac must be diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/TypeBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/TypeBoundaryArchitectureTest.java index 2f9fd686..282aac6b 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/TypeBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/TypeBoundaryArchitectureTest.java @@ -151,7 +151,7 @@ class TypeBoundaryArchitectureTest { .and(implementsApplicationLayerPort())) // @Configuration factory classes are excluded: a @Bean method legitimately // returns the adapter's own outbound port type for DI wiring (e.g. - // MessagingConfig#messagePublisher -> MessagePublisher) — that is + // MessagingConfig#outboxMessagePublishPort -> OutboxMessagePublishPort) — that is // composition-root assembly, not an adapter *response* method leaking an // external type. B7 targets the latter (ACL leakage), not DI factories // (feature-integration-adapter-templates Layer 1 @ConditionalOnProperty configs). diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/OutboundWithoutPermissionUseCase.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/OutboundWithoutPermissionUseCase.java index b18829cb..f578ca33 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/OutboundWithoutPermissionUseCase.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/OutboundWithoutPermissionUseCase.java @@ -4,12 +4,10 @@ import dev.caskeleton.application.capability.Idempotency; import dev.caskeleton.application.capability.RepositoryAccess; import dev.caskeleton.application.capability.UseCaseCapability; import dev.caskeleton.application.command.Command; -import dev.caskeleton.application.outbox.OutboxEvent; -import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.ClaimedOutboxEvent; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.usecase.CommandUseCase; -import java.time.Instant; /** * Intentional violation of {@code @@ -27,24 +25,17 @@ public final class OutboundWithoutPermissionUseCase implements CommandUseCase { private final OutboxMessagePublishPort publisher; + private final ClaimedOutboxEvent event; - public OutboundWithoutPermissionUseCase(OutboxMessagePublishPort publisher) { + public OutboundWithoutPermissionUseCase( + OutboxMessagePublishPort publisher, ClaimedOutboxEvent event) { this.publisher = publisher; + this.event = event; } @Override public Void handle(DummyCommand input) { - publisher.publish( - new OutboxEvent( - "event-1", - "fixture.created", - "aggregate-1", - "{}", - Instant.EPOCH, - "correlation-1", - "idempotency-1", - OutboxEventStatus.PENDING, - 0)); + publisher.publish(event); return null; } diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/async/ScheduledJobOverlapPolicyTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/async/ScheduledJobOverlapPolicyTest.java index 0afd5a57..69d4f16c 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/async/ScheduledJobOverlapPolicyTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/async/ScheduledJobOverlapPolicyTest.java @@ -25,7 +25,8 @@ import org.springframework.scheduling.annotation.Scheduled; * genuinely needs fixed-rate must first prove idempotency and relax this rule deliberately. * *

    Every production {@code @Scheduled} today ({@code IdempotencyReaper}, {@code OutboxReaper}, - * {@code OutboxRelayScheduler}) uses {@code fixedDelayString} — this rule pins that. + * {@code OutboxRelayScheduler} in composition:outbox-relay) uses {@code fixedDelayString} — this + * rule pins that. */ @AnalyzeClasses(packages = "dev.caskeleton", importOptions = ProductionClassImportOption.class) class ScheduledJobOverlapPolicyTest { diff --git a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java index a196ccde..de45ff70 100644 --- a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java +++ b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java @@ -8,9 +8,9 @@ import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapp import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.bootstrap.async.AsyncContextTaskDecorator; -import dev.caskeleton.bootstrap.concurrency.DomainContextConfig; import dev.caskeleton.bootstrap.integration.PostgreSqlTestContainer; import dev.caskeleton.composition.fileserver.FileserverPlatformAutoConfiguration; +import dev.caskeleton.composition.runtime.context.DomainContextConfig; import dev.caskeleton.shared.concurrency.DomainContextPropagator; import java.io.IOException; import java.io.UncheckedIOException; diff --git a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/idempotency/PostgreSqlIdempotencyProviderIntegrationTest.java b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/idempotency/PostgreSqlIdempotencyProviderIntegrationTest.java index 1bf2dab4..99da1951 100644 --- a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/idempotency/PostgreSqlIdempotencyProviderIntegrationTest.java +++ b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/idempotency/PostgreSqlIdempotencyProviderIntegrationTest.java @@ -8,8 +8,8 @@ import dev.caskeleton.application.idempotency.IdempotentAction; import dev.caskeleton.application.idempotency.IdempotentResponseCodec; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.transaction.OperationId; -import dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig; import dev.caskeleton.bootstrap.integration.PostgreSqlTestContainer; +import dev.caskeleton.composition.idempotency.IdempotencyAutoConfiguration; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; @@ -108,7 +108,7 @@ class PostgreSqlIdempotencyProviderIntegrationTest { JdbcTemplateAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, FlywayAutoConfiguration.class, - IdempotencyProviderSelectionConfig.class)) + IdempotencyAutoConfiguration.class)) .withUserConfiguration(Class.forName(POSTGRESQL_STORE_CONFIG)) .withPropertyValues( "ca-skeleton.capabilities.idempotency.provider=postgresql", diff --git a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java index febd24a4..cb93b24f 100644 --- a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java +++ b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java @@ -12,8 +12,8 @@ import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig; import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy; import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry; import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; -import dev.caskeleton.bootstrap.concurrency.DomainContextConfig; import dev.caskeleton.bootstrap.integration.PostgreSqlTestContainer; +import dev.caskeleton.composition.runtime.context.DomainContextConfig; import java.util.List; import java.util.Set; import org.flywaydb.core.Flyway; @@ -110,7 +110,7 @@ class DurableOperationCompositionIntegrationTest { String.class, operationId), jdbc.queryForList("SELECT event_type FROM outbox_event", String.class))) - .containsExactly("PENDING", List.of("DurableOperationSubmitted")); + .containsExactly("PENDING", List.of("durable-operation.submitted")); } @Test diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java index 41a3e140..8884d716 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java @@ -20,7 +20,6 @@ import org.springframework.boot.context.properties.ConfigurationPropertiesScan; @ConfigurationPropertiesScan( basePackages = { "dev.caskeleton.bootstrap.async", - "dev.caskeleton.bootstrap.concurrency", "dev.caskeleton.bootstrap.runtime", "dev.caskeleton.bootstrap.security", "dev.caskeleton.bootstrap.settings" diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/operation/DurableOperationConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/operation/DurableOperationConfig.java index c498d5af..82c8f571 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/operation/DurableOperationConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/operation/DurableOperationConfig.java @@ -1,11 +1,13 @@ package dev.caskeleton.bootstrap.autoconfigure.operation; import dev.caskeleton.adapter.inbound.web.operation.DurableOperationController; +import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; import dev.caskeleton.application.operation.CancelDurableOperationUseCase; import dev.caskeleton.application.operation.DurableOperationStorePort; +import dev.caskeleton.application.operation.DurableOperationSubmittedContract; import dev.caskeleton.application.operation.GetDurableOperationUseCase; import dev.caskeleton.application.operation.SubmitDurableOperationUseCase; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import org.springframework.boot.autoconfigure.AutoConfiguration; @@ -26,27 +28,34 @@ import org.springframework.context.annotation.Import; *

    The use cases are beans rather than objects built inside the controller so that the method * security advisor proxies them: {@code @RequiresPermission} on submit and cancel is enforced by * that proxy, and a use case constructed by hand would carry the annotation and skip the check. + * + *

    The submission event's contract is registered here as a bean, which is how the application's + * {@link IntegrationEventEncoderPort} learns it: the encoder is built over every contract + * contribution the context holds. */ @AutoConfiguration( afterName = "dev.caskeleton.adapter.outbound.persistence.autoconfigure.PersistenceJpaAutoConfiguration") @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) -@ConditionalOnBean({ - DurableOperationStorePort.class, - LegacyOutboxAppendPort.class, - TransactionPort.class -}) +@ConditionalOnBean({DurableOperationStorePort.class, OutboxAppendPort.class, TransactionPort.class}) @Import(DurableOperationController.class) public class DurableOperationConfig { + /** The {@code durable-operation.submitted} contract, so the encoder can validate the event. */ + @Bean + public DurableOperationSubmittedContract durableOperationSubmittedContract() { + return new DurableOperationSubmittedContract(); + } + /** Accepts work: the operation row and its outbox event in one transaction. */ @Bean public SubmitDurableOperationUseCase submitDurableOperationUseCase( DurableOperationStorePort operations, - LegacyOutboxAppendPort outbox, + OutboxAppendPort outbox, + IntegrationEventEncoderPort encoder, TransactionPort transactions, Clock clock) { - return new SubmitDurableOperationUseCase(operations, outbox, transactions, clock); + return new SubmitDurableOperationUseCase(operations, outbox, encoder, transactions, clock); } /** Reads one operation for the caller that submitted it. */ diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidator.java deleted file mode 100644 index ea29a724..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidator.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.outbox; - -import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; -import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; -import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; -import java.util.Objects; -import org.springframework.beans.factory.InitializingBean; - -/** - * Fail-closed activation guard for the transport-only canonical outbox path. - * - *

    Turning on canonical transport without a canonical publisher would let the legacy relay claim - * a canonical row and then spend its retry budget against a disabled transport. The flag therefore - * requires the application-owned canonical publish port at startup. - */ -public final class OutboxCanonicalTransportRequirementValidator implements InitializingBean { - - private static final String CANONICAL_KEY = "ca-skeleton.outbox.canonical-transport-enabled"; - - private final OutboxSettings settings; - private final IntegrationEventPublishPort publisher; - private final IntegrationEventEncoderPort encoder; - - public OutboxCanonicalTransportRequirementValidator( - OutboxSettings settings, - IntegrationEventPublishPort publisher, - IntegrationEventEncoderPort encoder) { - this.settings = Objects.requireNonNull(settings, "settings must not be null"); - this.publisher = publisher; - this.encoder = encoder; - } - - @Override - public void afterPropertiesSet() { - validate(); - } - - public void validate() { - if (!settings.canonicalTransportEnabled()) { - return; - } - if (publisher == null) { - throw StartupFailures.requiredAdapterDisabled( - CANONICAL_KEY - + "=true requires an IntegrationEventPublishPort so canonical claimed rows cannot be " - + "consumed by the relay without a platform publication route. Configure the canonical " - + "messaging bridge (including app.messaging.producer-id) or set " - + CANONICAL_KEY - + "=false."); - } - if (encoder == null) { - throw StartupFailures.requiredAdapterDisabled( - CANONICAL_KEY - + "=true also requires an IntegrationEventEncoderPort bean. The template ships no " - + "implementation: the adopter owns its event contracts and must provide the " - + "encoder as part of the application messaging composition, or set " - + CANONICAL_KEY - + "=false."); - } - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettings.java deleted file mode 100644 index af5cc9cc..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettings.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.outbox; - -import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; -import java.time.Duration; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.validation.annotation.Validated; - -/** - * Outbox relay runtime knobs bound from {@code ca-skeleton.outbox.*} (literal defaults, no env - * placeholders). See README for the design rationale. - * - * @param relayEnabled whether the relay scheduler is enabled; default {@code false} - * @param canonicalTransportEnabled whether canonical rows may use the platform transport; default - * {@code false} - * @param pollInterval how often the relay polls the outbox table; default {@code PT5S} - * @param batchSize maximum rows claimed per relay cycle; default {@code 20} - * @param inFlightTimeout in-flight orphan visibility window; default {@code PT5M} - * @param reaperInterval how often the reaper purges old PUBLISHED rows; default {@code PT10M} - * @param publishedRetention how long PUBLISHED rows are kept before the reaper deletes them; - * default {@code P7D} - */ -@Validated -@ConfigurationProperties(prefix = "ca-skeleton.outbox") -public record OutboxSettings( - Boolean relayEnabled, - Boolean canonicalTransportEnabled, - Duration pollInterval, - Integer batchSize, - Duration inFlightTimeout, - Duration reaperInterval, - Duration publishedRetention) { - - public OutboxSettings { - if (relayEnabled == null) { - // Off unless asked for, like the module default and the scheduler condition: three sources - // answering "is the relay on" differently is how a missing key started it. - relayEnabled = false; - } - if (canonicalTransportEnabled == null) { - canonicalTransportEnabled = false; - } - - if (pollInterval == null) { - pollInterval = Duration.ofSeconds(5); - } else if (pollInterval.isZero() || pollInterval.isNegative()) { - throw StartupFailures.envValidation( - "ca-skeleton.outbox.pollInterval must be positive, was " + pollInterval); - } - - if (batchSize == null) { - batchSize = 20; - } else if (batchSize <= 0) { - throw StartupFailures.envValidation( - "ca-skeleton.outbox.batchSize must be > 0, was " + batchSize); - } - - if (inFlightTimeout == null) { - inFlightTimeout = Duration.ofMinutes(5); - } else if (inFlightTimeout.isZero() || inFlightTimeout.isNegative()) { - throw StartupFailures.envValidation( - "ca-skeleton.outbox.inFlightTimeout must be positive, was " + inFlightTimeout); - } - - if (reaperInterval == null) { - reaperInterval = Duration.ofMinutes(10); - } else if (reaperInterval.isZero() || reaperInterval.isNegative()) { - throw StartupFailures.envValidation( - "ca-skeleton.outbox.reaperInterval must be positive, was " + reaperInterval); - } - - if (publishedRetention == null) { - publishedRetention = Duration.ofDays(7); - } else if (publishedRetention.isZero() || publishedRetention.isNegative()) { - throw StartupFailures.envValidation( - "ca-skeleton.outbox.publishedRetention must be positive, was " + publishedRetention); - } - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/management/security/ManagementSecurityConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/management/security/ManagementSecurityConfig.java deleted file mode 100644 index 56ef2d0b..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/management/security/ManagementSecurityConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.bootstrap.management.security; - -import org.springframework.boot.security.autoconfigure.actuate.web.servlet.EndpointRequest; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.annotation.Order; -import org.springframework.http.HttpStatus; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.authentication.HttpStatusEntryPoint; - -/** - * Actuator endpoint security chain, ordered ahead of the main app chain. Security matching is done - * by endpoint id string only, never by health endpoint internals. See README for the design - * rationale. - */ -@Configuration -public class ManagementSecurityConfig { - - @Bean - @Order(0) - public SecurityFilterChain actuatorSecurityFilterChain(HttpSecurity http) throws Exception { - http.securityMatcher(EndpointRequest.toAnyEndpoint()) - .csrf(csrf -> csrf.disable()) - .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) - // Answer 401 (credentials required) instead of the default 403; no interactive login. - .exceptionHandling( - ex -> ex.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))) - .authorizeHttpRequests( - auth -> - auth - // permit-all for probes and Prometheus scrape. - .requestMatchers(EndpointRequest.to("health", "info", "prometheus")) - .permitAll() - .anyRequest() - .authenticated()); - return http.build(); - } -} diff --git a/src/app-bootstrap/src/main/resources/META-INF/spring.factories b/src/app-bootstrap/src/main/resources/META-INF/spring.factories index 6d8b085a..6b51f6db 100644 --- a/src/app-bootstrap/src/main/resources/META-INF/spring.factories +++ b/src/app-bootstrap/src/main/resources/META-INF/spring.factories @@ -1,6 +1,5 @@ org.springframework.boot.EnvironmentPostProcessor=\ -dev.caskeleton.bootstrap.runtime.RuntimeEnvironmentProfileValidator,\ -dev.caskeleton.bootstrap.autoconfigure.tracing.TracingSamplingEnvironmentPostProcessor +dev.caskeleton.bootstrap.runtime.RuntimeEnvironmentProfileValidator org.springframework.boot.SpringBootExceptionReporter=\ dev.caskeleton.bootstrap.runtime.startup.StartupFailureExceptionReporter diff --git a/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 019304f3..be37db73 100644 --- a/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1,5 +1,2 @@ dev.caskeleton.bootstrap.autoconfigure.common.BootstrapClockAutoConfiguration -dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxConfig dev.caskeleton.bootstrap.autoconfigure.operation.DurableOperationConfig -dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig -dev.caskeleton.bootstrap.autoconfigure.tracing.TracingConfig diff --git a/src/app-bootstrap/src/main/resources/application.yml b/src/app-bootstrap/src/main/resources/application.yml index 951673bc..f4e5bd11 100644 --- a/src/app-bootstrap/src/main/resources/application.yml +++ b/src/app-bootstrap/src/main/resources/application.yml @@ -88,6 +88,5 @@ spring: import: - classpath:config/server.yml - classpath:config/observability.yml - - classpath:config/capabilities.yml - classpath:config/runtime.yml - classpath:config/security.yml diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/DefaultCompositionBootTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/DefaultCompositionBootTest.java index 7b7893ba..030b04f1 100644 --- a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/DefaultCompositionBootTest.java +++ b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/DefaultCompositionBootTest.java @@ -44,7 +44,13 @@ class DefaultCompositionBootTest { "dev.caskeleton.adapter.inbound.graphql", "dev.caskeleton.adapter.inbound.websocket", "dev.caskeleton.adapter.inbound.grpc", - "dev.caskeleton.composition"); + // composition:service-runtime (`composition.runtime`) is part of the default composition; + // the outbox relay and idempotency modules are selected but build nothing until their + // store or provider is there. + "dev.caskeleton.composition.fileserver", + "dev.caskeleton.composition.notification", + "dev.caskeleton.composition.outbox", + "dev.caskeleton.composition.idempotency"); /** Infrastructure a capability connects to; a bean of any of these would open a connection. */ private static final List INFRASTRUCTURE_TYPES = diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/common/BootstrapClockAutoConfigurationTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/common/BootstrapClockAutoConfigurationTest.java index 15d3c1fa..ced3d72f 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/common/BootstrapClockAutoConfigurationTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/common/BootstrapClockAutoConfigurationTest.java @@ -2,17 +2,14 @@ package dev.caskeleton.bootstrap.autoconfigure.common; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; -import java.util.Arrays; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.context.annotation.ImportCandidates; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.context.annotation.Bean; class BootstrapClockAutoConfigurationTest { @@ -38,14 +35,6 @@ class BootstrapClockAutoConfigurationTest { }); } - @Test - void idempotencyCompositionDoesNotOwnTheApplicationClock() { - assertThat(Arrays.stream(IdempotencyProviderSelectionConfig.class.getDeclaredMethods())) - .noneMatch( - method -> - method.getReturnType() == Clock.class && method.isAnnotationPresent(Bean.class)); - } - @Test void anAdopterClockWinsOverTheDefault() throws Exception { Clock adopterClock = Clock.fixed(Instant.parse("2026-09-18T00:00:00Z"), ZoneOffset.UTC); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettingsTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettingsTest.java deleted file mode 100644 index d77fadfc..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettingsTest.java +++ /dev/null @@ -1,147 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.idempotency; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; - -import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode; -import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; -import java.time.Duration; -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.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -class IdempotencySettingsTest { - - private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(Binding.class); - - @Test - void absentKeysBindToTheDocumentedDefaults() { - runner.run( - context -> - assertThat(context.getBean(IdempotencySettings.class)) - .usingRecursiveComparison() - .isEqualTo( - new IdempotencySettings( - IdempotencySettings.Provider.DISABLED, - Duration.ofSeconds(30), - Duration.ofHours(24), - Duration.ofHours(24), - "json-v2", - 2, - Duration.ofMinutes(10)))); - } - - @Test - void kebabCaseKeysBindEveryField() { - runner - .withPropertyValues( - "ca-skeleton.capabilities.idempotency.provider=postgresql", - "ca-skeleton.capabilities.idempotency.processing-lease=45s", - "ca-skeleton.capabilities.idempotency.replay-ttl=72h", - "ca-skeleton.capabilities.idempotency.failure-retention=2h", - "ca-skeleton.capabilities.idempotency.response-codec-id=json-v3", - "ca-skeleton.capabilities.idempotency.policy-revision=3", - "ca-skeleton.capabilities.idempotency.reaper-interval=1m") - .run( - context -> - assertThat(context.getBean(IdempotencySettings.class)) - .usingRecursiveComparison() - .isEqualTo( - new IdempotencySettings( - IdempotencySettings.Provider.POSTGRESQL, - Duration.ofSeconds(45), - Duration.ofHours(72), - Duration.ofHours(2), - "json-v3", - 3, - Duration.ofMinutes(1)))); - } - - @Test - void anUnknownProviderFailsBinding() { - runner - .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=jdbc") - .run( - context -> - assertThat(context) - .hasFailed() - .getFailure() - .hasStackTraceContaining("ca-skeleton.capabilities.idempotency.provider")); - } - - @ParameterizedTest - @DisplayName("an out-of-range duration is refused with its key and bound") - @CsvSource({ - "PT0S, PT24H, PT24H, PT10M, processing-lease must be positive", - "PT61M, PT24H, PT24H, PT10M, processing-lease must be at most PT1H", - "PT30S, PT73H, PT24H, PT10M, replay-ttl must be at most PT72H", - "PT30S, -PT1H, PT24H, PT10M, replay-ttl must be positive", - "PT30S, PT24H, P31D, PT10M, failure-retention must be at most PT720H", - "PT30S, PT24H, PT24H, PT0S, reaper-interval must be positive" - }) - void outOfRangeDurationIsRefused( - Duration lease, Duration replay, Duration retention, Duration reaper, String message) { - // when - Throwable thrown = - catchThrowable( - () -> - new IdempotencySettings( - IdempotencySettings.Provider.REDIS, - lease, - replay, - retention, - null, - null, - reaper)); - - // then - assertThat(thrown) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasMessageContaining("ca-skeleton.capabilities.idempotency." + message); - } - - @ParameterizedTest - @CsvSource({"'', response-codec-id must contain 1-64 characters", "' ', response-codec-id"}) - void blankCodecIdIsRefused(String codecId, String message) { - // when - Throwable thrown = - catchThrowable( - () -> - new IdempotencySettings( - IdempotencySettings.Provider.REDIS, null, null, null, codecId, null, null)); - - // then - assertThat(thrown) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasMessageContaining("ca-skeleton.capabilities.idempotency." + message); - } - - @Test - void nonPositivePolicyRevisionIsRefused() { - // when - Throwable thrown = - catchThrowable( - () -> - new IdempotencySettings( - IdempotencySettings.Provider.REDIS, null, null, null, null, 0, null)); - - // then - assertThat(thrown) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasMessageContaining( - "ca-skeleton.capabilities.idempotency.policy-revision must be positive"); - } - - @EnableConfigurationProperties(IdempotencySettings.class) - static class Binding {} -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportCompositionTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportCompositionTest.java deleted file mode 100644 index 35f38718..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportCompositionTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.outbox; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; -import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; -import dev.caskeleton.application.outbox.OutboxPublishOutcome; -import dev.caskeleton.application.outbox.OutboxStorePort; -import java.util.concurrent.CompletableFuture; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -class OutboxCanonicalTransportCompositionTest { - - private final ApplicationContextRunner runner = - new ApplicationContextRunner() - .withUserConfiguration(OutboxConfig.class) - .withBean(OutboxStorePort.class, () -> mock(OutboxStorePort.class)) - .withPropertyValues( - "ca-skeleton.outbox.enabled=true", "ca-skeleton.outbox.relay-enabled=false"); - - @Test - void defaultCanonicalTransportOffStartsWithoutCanonicalPublisher() { - runner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(OutboxCanonicalTransportRequirementValidator.class); - assertThat(context).doesNotHaveBean(IntegrationEventPublishPort.class); - }); - } - - @Test - void canonicalTransportOnWithoutPublisherFailsTheComposedContext() { - runner - .withPropertyValues("ca-skeleton.outbox.canonical-transport-enabled=true") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasMessageContaining("IntegrationEventPublishPort"); - }); - } - - @Test - void canonicalTransportOnWithPublisherButWithoutEncoderFailsClosed() { - runner - .withPropertyValues("ca-skeleton.outbox.canonical-transport-enabled=true") - .withBean( - IntegrationEventPublishPort.class, - () -> event -> CompletableFuture.completedFuture(OutboxPublishOutcome.CONFIRMED)) - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasMessageContaining("IntegrationEventEncoderPort"); - }); - } - - @Test - void canonicalTransportOnWithPublisherAndEncoderStartsWithoutCreatingAnotherScheduler() { - runner - .withPropertyValues("ca-skeleton.outbox.canonical-transport-enabled=true") - .withBean( - IntegrationEventPublishPort.class, - () -> event -> CompletableFuture.completedFuture(OutboxPublishOutcome.CONFIRMED)) - .withBean(IntegrationEventEncoderPort.class, () -> draft -> null) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(IntegrationEventPublishPort.class); - assertThat(context).hasSingleBean(IntegrationEventEncoderPort.class); - assertThat(context).doesNotHaveBean(OutboxRelayScheduler.class); - }); - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidatorTest.java deleted file mode 100644 index cad3387e..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidatorTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.outbox; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; -import dev.caskeleton.application.outbox.OutboxPublishOutcome; -import java.util.concurrent.CompletableFuture; -import org.junit.jupiter.api.Test; - -class OutboxCanonicalTransportRequirementValidatorTest { - - @Test - void enabledCanonicalTransportWithoutPublisherFailsStartup() { - OutboxSettings settings = new OutboxSettings(true, true, null, null, null, null, null); - - assertThatThrownBy( - () -> new OutboxCanonicalTransportRequirementValidator(settings, null, null).validate()) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("canonical-transport-enabled") - .hasMessageContaining("IntegrationEventPublishPort"); - } - - @Test - void disabledCanonicalTransportDoesNotRequirePublisher() { - OutboxSettings settings = new OutboxSettings(true, false, null, null, null, null, null); - - assertThatCode( - () -> new OutboxCanonicalTransportRequirementValidator(settings, null, null).validate()) - .doesNotThrowAnyException(); - } - - @Test - void enabledCanonicalTransportWithPublisherButWithoutEncoderFailsStartup() { - OutboxSettings settings = new OutboxSettings(true, true, null, null, null, null, null); - IntegrationEventPublishPort publisher = - event -> CompletableFuture.completedFuture(OutboxPublishOutcome.CONFIRMED); - - assertThatThrownBy( - () -> - new OutboxCanonicalTransportRequirementValidator(settings, publisher, null) - .validate()) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("IntegrationEventEncoderPort"); - } - - @Test - void enabledCanonicalTransportWithPublisherStarts() { - OutboxSettings settings = new OutboxSettings(true, true, null, null, null, null, null); - IntegrationEventPublishPort publisher = - event -> CompletableFuture.completedFuture(OutboxPublishOutcome.CONFIRMED); - - assertThatCode( - () -> - new OutboxCanonicalTransportRequirementValidator(settings, publisher, draft -> null) - .validate()) - .doesNotThrowAnyException(); - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettingsTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettingsTest.java deleted file mode 100644 index bcb083c3..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettingsTest.java +++ /dev/null @@ -1,122 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.outbox; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode; -import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; -import java.time.Duration; -import org.junit.jupiter.api.Test; - -/** - * Binding and validation tests for {@link OutboxSettings} (feature-domain-event-outbox-contract I11 - * — mirrors IdempotencyPropertiesTest). - */ -class OutboxSettingsTest { - - @Test - void bindsAllSixDefaultsWhenFieldsAreNull() { - OutboxSettings props = new OutboxSettings(null, null, null, null, null, null, null); - assertThat(props.relayEnabled()).isFalse(); - assertThat(props.canonicalTransportEnabled()).isFalse(); - assertThat(props.pollInterval()).isEqualTo(Duration.ofSeconds(5)); - assertThat(props.batchSize()).isEqualTo(20); - assertThat(props.inFlightTimeout()).isEqualTo(Duration.ofMinutes(5)); - assertThat(props.reaperInterval()).isEqualTo(Duration.ofMinutes(10)); - assertThat(props.publishedRetention()).isEqualTo(Duration.ofDays(7)); - } - - @Test - void acceptsExplicitValidValues() { - OutboxSettings props = - new OutboxSettings( - false, - true, - Duration.ofSeconds(10), - 50, - Duration.ofMinutes(2), - Duration.ofHours(1), - Duration.ofDays(14)); - assertThat(props.relayEnabled()).isFalse(); - assertThat(props.canonicalTransportEnabled()).isTrue(); - assertThat(props.pollInterval()).isEqualTo(Duration.ofSeconds(10)); - assertThat(props.batchSize()).isEqualTo(50); - assertThat(props.inFlightTimeout()).isEqualTo(Duration.ofMinutes(2)); - assertThat(props.reaperInterval()).isEqualTo(Duration.ofHours(1)); - assertThat(props.publishedRetention()).isEqualTo(Duration.ofDays(14)); - } - - @Test - void rejectsZeroBatchSize() { - assertThatThrownBy(() -> new OutboxSettings(true, false, null, 0, null, null, null)) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasMessageContaining("batchSize"); - } - - @Test - void rejectsNegativeBatchSize() { - assertThatThrownBy(() -> new OutboxSettings(true, false, null, -1, null, null, null)) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasMessageContaining("batchSize"); - } - - @Test - void rejectsNonPositivePollInterval() { - assertThatThrownBy(() -> new OutboxSettings(true, false, Duration.ZERO, null, null, null, null)) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasMessageContaining("pollInterval"); - } - - @Test - void rejectsNonPositiveInFlightTimeout() { - assertThatThrownBy(() -> new OutboxSettings(true, false, null, null, Duration.ZERO, null, null)) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasMessageContaining("inFlightTimeout"); - } - - @Test - void rejectsZeroReaperInterval() { - assertThatThrownBy(() -> new OutboxSettings(true, false, null, null, null, Duration.ZERO, null)) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasMessageContaining("reaperInterval"); - } - - @Test - void rejectsNegativeReaperInterval() { - assertThatThrownBy( - () -> new OutboxSettings(true, false, null, null, null, Duration.ofMinutes(-1), null)) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasMessageContaining("reaperInterval"); - } - - @Test - void rejectsZeroPublishedRetention() { - assertThatThrownBy(() -> new OutboxSettings(true, false, null, null, null, null, Duration.ZERO)) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasMessageContaining("publishedRetention"); - } - - @Test - void rejectsNegativePublishedRetention() { - assertThatThrownBy( - () -> new OutboxSettings(true, false, null, null, null, null, Duration.ofHours(-1))) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasMessageContaining("publishedRetention"); - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ActuatorSecurityHttpTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ActuatorSecurityHttpTest.java index e0de7791..edc4d703 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ActuatorSecurityHttpTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ActuatorSecurityHttpTest.java @@ -6,7 +6,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration; -import dev.caskeleton.bootstrap.management.security.ManagementSecurityConfig; +import dev.caskeleton.composition.runtime.management.security.ManagementSecurityConfig; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -17,7 +17,7 @@ import org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration; import org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; -import org.springframework.context.annotation.Import; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.test.web.servlet.MockMvc; /** @@ -109,6 +109,9 @@ class ActuatorSecurityHttpTest { WebAdapterAutoConfiguration.class, WebSecurityAutoConfiguration.class }) - @Import(ManagementSecurityConfig.class) + // The web adapter's SecurityConfig is what enables web security in the shipped composition; + // with it excluded, the slice enables it itself so composition:service-runtime's + // ManagementSecurityConfig arrives the way it does in production — as an auto-configuration. + @EnableWebSecurity static class MinimalActuatorApp {} } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BootstrapCapabilityAutoConfigurationReachabilityTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BootstrapCapabilityAutoConfigurationReachabilityTest.java index 23f8f510..717ed2ed 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BootstrapCapabilityAutoConfigurationReachabilityTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BootstrapCapabilityAutoConfigurationReachabilityTest.java @@ -22,12 +22,11 @@ class BootstrapCapabilityAutoConfigurationReachabilityTest { // Redis and the distributed lock are no longer here. Each moved into the module that // implements it — `adapter:outbound:cache-redis` (with its readiness append and // activation guard) and `adapter:outbound:persistence-jpa` — which ships its own - // registration and its own reachability test. The outbox relay stays: it assembles a use - // case over ports, which is composition, and it turns on from the store port the - // persistence module contributes. - "dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxConfig", - "dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig", - "dev.caskeleton.bootstrap.autoconfigure.tracing.TracingConfig"); + // registration and its own reachability test. So did the outbox relay and the + // idempotency executor: `composition:outbox-relay` and `composition:idempotency`, which + // the sample composes too. Tracing, metrics, domain context, pseudonymization and the + // actuator chain are `composition:service-runtime`, which proves its own registration. + "dev.caskeleton.bootstrap.autoconfigure.operation.DurableOperationConfig"); @Test void everyBootstrapOwnedCapabilityRootIsDiscoverableByBoot() { diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConfigurationNamespaceContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConfigurationNamespaceContractTest.java index 835f4067..76684723 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConfigurationNamespaceContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConfigurationNamespaceContractTest.java @@ -84,14 +84,10 @@ class ConfigurationNamespaceContractTest { List.of( "ca-skeleton.async.executor", "ca-skeleton.bootstrap", - "ca-skeleton.capabilities.idempotency", "ca-skeleton.logging", - "ca-skeleton.outbox", - "ca-skeleton.privacy", "ca-skeleton.runtime", "ca-skeleton.secret-source", - "ca-skeleton.security", - "ca-skeleton.tracing")); + "ca-skeleton.security")); private static final Pattern PREFIX_ANNOTATION = Pattern.compile("@ConfigurationProperties\\(\\s*(?:prefix\\s*=\\s*)?\"([^\"]+)\""); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DistributedTracingContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DistributedTracingContractTest.java index 1293e0a7..38f409d5 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DistributedTracingContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DistributedTracingContractTest.java @@ -5,8 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.inbound.web.observability.MdcKeys; import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory; import dev.caskeleton.bootstrap.async.AsyncContextTaskDecorator; -import dev.caskeleton.bootstrap.autoconfigure.tracing.TracingSamplingRateGauge; import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; +import dev.caskeleton.composition.runtime.tracing.TracingSamplingRateGauge; import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator; import dev.caskeleton.shared.response.ResponseMeta; import dev.caskeleton.shared.tracing.BaggageAllowlist; @@ -39,7 +39,7 @@ import org.yaml.snakeyaml.Yaml; * dev.caskeleton.bootstrap.autoconfigure.tracing.TracingPropertiesTest} *

  • {@code tracing-contract:meta-traceid-when-disabled} — this class *
  • {@code tracing-contract:sample-rate-per-profile} — see {@link - * dev.caskeleton.bootstrap.autoconfigure.tracing.TracingSampleRateResolverTest} + * dev.caskeleton.composition.runtime.tracing.TracingSampleRateResolverTest} *
  • {@code contract-verification:trace-propagation} — this class *
  • {@code contract-verification:metrics-cardinality} — this class *
  • {@code contract-verification:log-mdc-keys} — this class diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/MetricsAlertingContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/MetricsAlertingContractTest.java index e4f51697..7b7f903d 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/MetricsAlertingContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/MetricsAlertingContractTest.java @@ -3,8 +3,8 @@ package dev.caskeleton.bootstrap.contract; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; -import dev.caskeleton.bootstrap.metrics.MetricsContractConfig; -import dev.caskeleton.bootstrap.metrics.MetricsDistributionMeterFilter; +import dev.caskeleton.composition.runtime.metrics.MetricsContractConfig; +import dev.caskeleton.composition.runtime.metrics.MetricsDistributionMeterFilter; import dev.caskeleton.shared.metrics.AlertSeverity; import dev.caskeleton.shared.metrics.CardinalityBounds; import dev.caskeleton.shared.metrics.ForbiddenMetricTags; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingActivationContextTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/TracingActivationContextTest.java similarity index 94% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingActivationContextTest.java rename to src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/TracingActivationContextTest.java index 2b506e14..1d8350ee 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingActivationContextTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/TracingActivationContextTest.java @@ -1,9 +1,12 @@ -package dev.caskeleton.bootstrap.autoconfigure.tracing; +package dev.caskeleton.bootstrap.contract; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration; +import dev.caskeleton.composition.runtime.tracing.MicrometerSpanErrorRecorder; +import dev.caskeleton.composition.runtime.tracing.TracingConfig; +import dev.caskeleton.composition.runtime.tracing.TracingSamplingRateGauge; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.tracing.Tracer; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java index 4bda0988..29736385 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java @@ -16,10 +16,10 @@ import org.junit.jupiter.api.Test; * How many things own {@code app.messaging}, and how many can publish one event (MSG-INT-002). * *

    Two types declare {@code @ConfigurationProperties} on that prefix: {@code MessagingSettings} - * in the outbound adapter, which owns {@code broker}, and {@code MessagingSettings} in the starter, - * which owns everything else. Spring binds both without complaint — each takes the fields it - * declares — so the split is invisible at runtime and shows up only as two places to look, neither - * of which validates the other's view. + * in the outbound adapter, which owns {@code producer-id}, and {@code MessagingSettings} in the + * starter, which owns everything else, {@code broker} included. Spring binds both without complaint + * — each takes the fields it declares — so the split is invisible at runtime and shows up only as + * two places to look, neither of which validates the other's view. * *

    This test does not assert the split away. Collapsing it means the adapter stops selecting a * broker and becomes a port bridge over the platform's publish contract, which it can only do once @@ -102,8 +102,8 @@ class MessagingAuthorityContractTest { assertThat(leaks) .as( - "MessagePublisher in the adapter is an adapter-local type; if general publish ever " - + "becomes a use-case need, an application port is defined first") + "the messaging adapter's types are adapter-local; if a use case ever needs to " + + "publish, an application port is defined first") .isEmpty(); } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java index 64ed2c4b..e1a1672c 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java @@ -16,7 +16,7 @@ import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfi import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter; import dev.caskeleton.adapter.inbound.web.settings.PresentationSettings; import dev.caskeleton.bootstrap.CaSkeletonApplication; -import dev.caskeleton.bootstrap.logging.PseudonymizationConfig; +import dev.caskeleton.composition.runtime.logging.PseudonymizationConfig; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrderContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrderContractTest.java index bc2e6411..2f7983a4 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrderContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrderContractTest.java @@ -3,7 +3,6 @@ package dev.caskeleton.bootstrap.runtime.startup; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; -import dev.caskeleton.bootstrap.autoconfigure.tracing.TracingSamplingEnvironmentPostProcessor; import dev.caskeleton.bootstrap.runtime.RuntimeEnvironmentProfileValidator; import java.io.IOException; import java.io.InputStream; @@ -20,11 +19,12 @@ class StartupOrderContractTest { @Test void everyRegisteredEnvironmentPostProcessorHasTheExpectedCentralOrder() throws Exception { + // The tracing sampling bridge is composition:service-runtime's registration now; that module + // pins its StartupOrder position itself. Map expected = Map.of( RuntimeEnvironmentProfileValidator.class.getName(), - StartupOrder.RUNTIME_ENVIRONMENT_PROFILE, - TracingSamplingEnvironmentPostProcessor.class.getName(), StartupOrder.TRACING_SAMPLING); + StartupOrder.RUNTIME_ENVIRONMENT_PROFILE); Map actual = registeredEnvironmentPostProcessorOrders(); diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index 081cd289..bd4f9a71 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -71,7 +71,8 @@ Package root: `dev.caskeleton.application`. | `messaging.contract.IntegrationEventContractContribution

    ` | Closed exact-record payload type, canonical component order, local schema identity/hash and provider-neutral descriptor contribution. | | `messaging.event.IntegrationEventDraft

    ` | Typed semantic event before local encoding; never JSON, Kafka or persistence state. | | `messaging.event.ValidatedIntegrationEvent` | Stable semantic identities plus immutable exact encoded bytes and hashes, ready for a later durable append boundary. | -| `messaging.event.IntegrationEventEncoderPort` | Framework-free local draft-to-validated-event boundary implemented by an outbound adapter. | +| `messaging.event.IntegrationEventEncoderPort` | Framework-free local draft-to-validated-event boundary implemented by an outbound adapter (the template's: `adapter:outbound:support` `JsonIntegrationEventEncoder`). | +| `outbox.OutboxAppendPort` | The one outbox append: a `ValidatedIntegrationEvent`, in the caller's write transaction. | ## Notification (NOTIF-ADR-005) @@ -161,7 +162,7 @@ generation; the V1 `IdempotencyScope`/`tryBegin` API is gone. - **Store**: `IdempotencyStorePort`, contributed by exactly one provider selected with `ca-skeleton.capabilities.idempotency.provider` (`redis` → `cache-redis`, `postgresql` → `persistence-jpa`; default `disabled`). In-memory prod storage is forbidden. -- **Executor**: built once by app-bootstrap `IdempotencyProviderSelectionConfig` from +- **Executor**: built once by `composition:idempotency` `IdempotencyAutoConfiguration` from `IdempotencySettings` (processing lease 30s, replay TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h, failure retention 24h). Do not construct it in a use case or a sample config. - The action returns `IdempotentAction.Outcome` (`Success` / `RetryableNoEffect` / diff --git a/src/application-core/README.md b/src/application-core/README.md index ff429b89..fbd8e001 100644 --- a/src/application-core/README.md +++ b/src/application-core/README.md @@ -33,8 +33,10 @@ Cache도 같은 원칙을 따른다. `cache` 패키지에는 cache-redis가 구 보유한다. tenant가 없는 모드도 null 대신 canonical system tenant scope를 `AggregateIdentity`에 넣어 dedupe/order identity가 PostgreSQL nullable uniqueness에 기대지 않게 한다. -- `IntegrationEventEncoderPort` 뒤의 adapter가 deterministic encoding과 schema validation을 - 수행하고 `ValidatedIntegrationEvent`를 돌려준다. 결과는 logical destination, exact US-ASCII +- `IntegrationEventEncoderPort` 뒤의 adapter가 deterministic encoding을 수행하고 + `ValidatedIntegrationEvent`를 돌려준다. 템플릿의 구현은 `adapter:outbound:support`의 + `JsonIntegrationEventEncoder`다(envelope v1 + payload record의 결정적 JSON, 선언한 schema hash를 + classpath 파일과 대조). 결과는 logical destination, exact US-ASCII partition key, exact encoded envelope bytes, schema/envelope hash와 catalog/binding revision을 defensive copy로 보존한다. - `ContractDescriptor`는 owner module, logical destination, serializer ID, ordering requirement, @@ -372,7 +374,7 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. 못한다. - **안전한 allowlist report**: `OutboxRelayFailureReport`는 `code/eventId/eventType/aggregateId/correlationId/attemptCount/nextAttemptAt/cause`만 가진다. - payload, idempotency key, whole `OutboxEvent`, severity/template, arbitrary map은 타입 수준에서 + payload, envelope bytes, whole `ClaimedOutboxEvent`, severity/template, arbitrary map은 타입 수준에서 전달할 수 없다. retry factory는 `OUTBOX_PUBLISH_FAILED`와 필수 `nextAttemptAt`, dead factory는 `OUTBOX_DEAD_LETTER`와 null retry time을 고정한다. - **상태 갱신 실패는 시끄럽게 전파한다**: 발행 성공 후의 `markPublished` 실패는 store/인프라 @@ -406,17 +408,18 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. 업데이트와 **함께만** 바꾼다. - 지수 계산은 overflow 방지를 위해 `2^30` 에서 cap 한다(`2^30 × 30s > 30년` 이라 안전). -### outbox 값/상태 타입 (Status · Event · NewOutboxEvent · RelayResult · Command) +### outbox 값/상태 타입 (Status · ClaimedOutboxEvent · RelayResult · Command) - `OutboxEventStatus` — 행 상태 머신(D5). `PENDING → IN_FLIGHT → {PUBLISHED | FAILED | DEAD}`, `FAILED → IN_FLIGHT`(재claim), `IN_FLIGHT 고아 → IN_FLIGHT`(I6). `DEAD` 는 FIFO 형제를 막는다 — 같은 aggregate 의 뒤 행 claim 을 차단하므로 runbook 개입이 필요하다. -- `OutboxEvent` — `claimBatch` 가 반환하는 claim-result 읽기 모델. `NewOutboxEvent` 필드 + 현재 - `status` + `attemptCount`. relay 가 `attemptCount` 로 다음 실패 시 dead-letter 여부를 결정한다. -- `NewOutboxEvent` — caller 의 write 트랜잭션 안에서 append 할 새 이벤트 값 객체. 모든 필드가 - 필수이고 null/blank 면 생성 시점에 거부한다(D12). caller 가 `eventId`·`idempotencyKey` 를 - 공급한다(I12 — outbox core 는 ID 생성에 비의존). 권장 기본값은 `idempotencyKey = eventId` - (per-event dedup, CloudEvents-C2). +- append 는 `OutboxAppendPort.append(ValidatedIntegrationEvent)` 하나다(2026-09-28, 소유자 결정 7). + use case 가 `IntegrationEventDraft` 를 만들고 `IntegrationEventEncoderPort` 로 encode 한 뒤 같은 + write 트랜잭션 안에서 append 한다. consumer 의 중복 제거 키는 event id 다. +- `ClaimedOutboxEvent` — `claimBatch` 가 반환하는 claim-result 읽기 모델. append 된 validated event + (저장된 exact envelope bytes 에서 복원) + 현재 `status` + `attemptCount`. relay 가 `attemptCount` 로 + 다음 실패 시 dead-letter 여부를 결정한다. 옛 `OutboxEvent`/`NewOutboxEvent`/`LegacyOutboxAppendPort` + (free-text payload 모델)는 삭제됐다. - `OutboxRelayResult` — relay 한 사이클의 결과. `claimedCount` + per-event outcome 목록. 내부 `Outcome` enum 이 `OutboxEventStatus` 의 5값을 재사용하지 않고 4값(PUBLISHED/FAILED/DEAD/ STALE — 마지막은 lease 를 잃어 결과를 쓰지 못한 경우)을 diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmitted.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmitted.java new file mode 100644 index 00000000..81a8252c --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmitted.java @@ -0,0 +1,23 @@ +package dev.caskeleton.application.operation; + +import dev.caskeleton.application.messaging.contract.IntegrationPayload; +import java.util.Objects; + +/** + * The payload of the event that wakes a worker for an accepted operation. + * + *

    Which operation, and what kind of work it is — nothing more. The worker reads what to run from + * the submission it claims, so the request itself never travels through the broker and a worker + * never acts on a copy that could disagree with the stored one. + * + * @param operationId the operation to claim + * @param operationName what kind of work it is, so a worker can ignore work it does not run + */ +public record DurableOperationSubmitted(String operationId, String operationName) + implements IntegrationPayload { + + public DurableOperationSubmitted { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(operationName, "operationName"); + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmittedContract.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmittedContract.java new file mode 100644 index 00000000..091f925b --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmittedContract.java @@ -0,0 +1,85 @@ +package dev.caskeleton.application.operation; + +import dev.caskeleton.application.messaging.contract.ContractDescriptor; +import dev.caskeleton.application.messaging.contract.ContractId; +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; +import dev.caskeleton.application.messaging.contract.LogicalDestinationId; +import dev.caskeleton.application.messaging.contract.SchemaResourceId; +import dev.caskeleton.application.messaging.contract.Sha256; +import java.util.HexFormat; +import java.util.List; + +/** + * The {@code durable-operation.submitted} v1 contract: the one event a durable-operation submission + * appends, whichever transport accepted it. + * + *

    One type for every operation. The event only wakes a worker, and letting a caller choose the + * type would let it publish any event the broker carries. The composition that turns durable + * operations on registers this contribution, so the encoder knows the contract. + */ +public final class DurableOperationSubmittedContract + implements IntegrationEventContractContribution { + + /** The contract id every submission event carries. */ + public static final ContractId CONTRACT_ID = new ContractId("durable-operation.submitted"); + + /** Where submission events go; a deployment binds it to a broker destination. */ + public static final LogicalDestinationId DESTINATION = + new LogicalDestinationId("durable-operations"); + + private static final SchemaResourceId SCHEMA_RESOURCE = + new SchemaResourceId("contracts/messaging/durable-operation.submitted/v1.schema.json"); + + // SHA-256 of the schema file's exact bytes. The encoder recomputes it at startup and refuses a + // mismatch, so editing the schema without updating this fails the boot, not the consumer. + private static final Sha256 SCHEMA_HASH = + new Sha256( + HexFormat.of() + .parseHex("4d2f780bf6c23fa548fc2b0e6ef02302" + "e17fca44a20f21ebf5ba07aaac11a245")); + + private static final ContractDescriptor DESCRIPTOR = + new ContractDescriptor( + "application-core", + DESTINATION, + "json-envelope-v1", + false, + 16 * 1024, + 32 * 1024, + ContractDescriptor.SensitivityClassification.INTERNAL, + OperationCommand.DEFAULT_TIME_TO_LIVE); + + @Override + public ContractId contractId() { + return CONTRACT_ID; + } + + @Override + public int payloadVersion() { + return 1; + } + + @Override + public Class exactPayloadRecordType() { + return DurableOperationSubmitted.class; + } + + @Override + public List canonicalRecordComponentOrder() { + return List.of("operationId", "operationName"); + } + + @Override + public SchemaResourceId payloadSchemaResource() { + return SCHEMA_RESOURCE; + } + + @Override + public Sha256 payloadSchemaHash() { + return SCHEMA_HASH; + } + + @Override + public ContractDescriptor descriptor() { + return DESCRIPTOR; + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/OperationCommand.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/OperationCommand.java index 68446003..0d401654 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/operation/OperationCommand.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/OperationCommand.java @@ -13,13 +13,16 @@ import java.util.Objects; * value the caller can retry: a generated id would differ on every attempt, so a retry after an * ambiguous failure would create a second operation. * + *

    There is no event type to choose. Every accepted operation announces itself with the one + * {@link DurableOperationSubmittedContract} event, which only wakes a worker; letting a caller name + * the type would let it publish any event the broker carries. + * * @param operationId the identity to use * @param operationName what work this is * @param principal who is asking * @param tenantId the tenant, or null when the operation is not tenant scoped * @param fingerprint the semantic fingerprint of the request * @param payload the serialized request a worker will execute - * @param eventType the outbox event type a worker subscribes to * @param timeToLive how long the record and its result stay available */ public record OperationCommand( @@ -29,20 +32,9 @@ public record OperationCommand( String tenantId, RequestFingerprint fingerprint, String payload, - String eventType, Duration timeToLive) implements Command { - /** - * The outbox event type for an operation whose caller does not publish an event of its own, such - * as the HTTP operation endpoint. - * - *

    One type for all of them: the event only wakes a worker, and the worker reads what to run - * from the submission it claims. Letting such a caller choose the type would let it publish any - * event the broker carries. - */ - public static final String SUBMITTED_EVENT_TYPE = "DurableOperationSubmitted"; - /** How long an operation submitted without a caller-specific lifetime stays pollable. */ public static final Duration DEFAULT_TIME_TO_LIVE = Duration.ofDays(1); @@ -58,10 +50,5 @@ public record OperationCommand( if (operationName.isBlank()) { throw new IllegalArgumentException("an operation command needs the operation it is for"); } - if (eventType == null || eventType.isBlank()) { - throw new IllegalArgumentException( - "an operation command needs an event type; without one the outbox row reaches no worker" - + " and the operation is accepted into silence"); - } } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java index 60797e8d..ac4cb158 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java @@ -3,14 +3,24 @@ package dev.caskeleton.application.operation; import dev.caskeleton.application.capability.Idempotency; import dev.caskeleton.application.capability.RepositoryAccess; import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.messaging.event.AggregateIdentity; +import dev.caskeleton.application.messaging.event.AggregateOrder; +import dev.caskeleton.application.messaging.event.EventId; +import dev.caskeleton.application.messaging.event.IntegrationEventDraft; +import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.security.RequiresPermission; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.usecase.CommandUseCase; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Clock; +import java.util.HexFormat; import java.util.Objects; +import java.util.Optional; +import java.util.regex.Pattern; /** * Accepts long-running work: one transaction that writes the operation row and the outbox row. @@ -54,8 +64,15 @@ import java.util.Objects; public class SubmitDurableOperationUseCase implements CommandUseCase { + private static final String TENANT_SCOPE = "global"; + private static final String AGGREGATE_TYPE = "durable-operation"; + private static final AggregateOrder FIRST_EVENT = new AggregateOrder(1, 0); + private static final int MAXIMUM_EVENT_ID_LENGTH = 96; + private static final Pattern EVENT_ID_GRAMMAR = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]*"); + private final DurableOperationStorePort operations; - private final LegacyOutboxAppendPort outbox; + private final OutboxAppendPort outbox; + private final IntegrationEventEncoderPort encoder; private final TransactionPort transactions; private final Clock clock; @@ -64,16 +81,20 @@ public class SubmitDurableOperationUseCase * * @param operations where operations are recorded * @param outbox where the publish intent is recorded + * @param encoder turns the submission event into the validated event the outbox stores; it must + * know {@link DurableOperationSubmittedContract} * @param transactions opens the write transaction both share * @param clock the submission clock */ public SubmitDurableOperationUseCase( DurableOperationStorePort operations, - LegacyOutboxAppendPort outbox, + OutboxAppendPort outbox, + IntegrationEventEncoderPort encoder, TransactionPort transactions, Clock clock) { this.operations = Objects.requireNonNull(operations, "operations"); this.outbox = Objects.requireNonNull(outbox, "outbox"); + this.encoder = Objects.requireNonNull(encoder, "encoder"); this.transactions = Objects.requireNonNull(transactions, "transactions"); this.clock = Objects.requireNonNull(clock, "clock"); } @@ -110,18 +131,53 @@ public class SubmitDurableOperationUseCase // operation would have a worker claim it, find it already RUNNING or finished, and // discard the message — harmless but indistinguishable in the logs from a real // duplicate, which is exactly the signal an operator needs to stay trustworthy. - outbox.append( - new NewOutboxEvent( - operation.operationId().value(), - command.eventType(), - operation.operationId().value(), - command.payload(), - operation.submittedAt(), - operation.operationId().value(), - operation.operationId().value())); + outbox.append(encoder.encode(submittedEvent(operation))); } return new OperationAcceptance( operation.operationId(), operation.submittedAt(), alreadyAccepted); }); } + + /** + * The event for a new operation, anchored to it: the operation is its own aggregate, so its id is + * the event id, the aggregate id and the correlation id, and a worker that receives the message + * twice can tell it is the same work. + */ + private static IntegrationEventDraft submittedEvent( + DurableOperation operation) { + String identity = canonicalIdentity(operation.operationId()); + return new IntegrationEventDraft<>( + new EventId(identity), + DurableOperationSubmittedContract.CONTRACT_ID, + 1, + DurableOperationSubmittedContract.DESTINATION, + new AggregateIdentity(TENANT_SCOPE, AGGREGATE_TYPE, identity), + FIRST_EVENT, + operation.submittedAt(), + identity, + Optional.empty(), + new DurableOperationSubmitted(operation.operationId().value(), operation.operationName())); + } + + /** + * The operation id itself when it fits the integration-event identity grammar — every id the HTTP + * adapter mints does — and otherwise a digest of it. + * + *

    An operation id may contain {@code ~} or run to 128 characters, and an event id may do + * neither. The digest keeps the event deterministic for the operation, so a retry still produces + * the same event, and the payload carries the id unchanged for the worker. + */ + static String canonicalIdentity(DurableOperationId operationId) { + String value = operationId.value(); + if (value.length() <= MAXIMUM_EVENT_ID_LENGTH && EVENT_ID_GRAMMAR.matcher(value).matches()) { + return value; + } + try { + byte[] digest = + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); + return "operation-" + HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException unreachable) { + throw new IllegalStateException("Java runtime does not provide SHA-256", unreachable); + } + } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/CanonicalClaimedOutboxEvent.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/CanonicalClaimedOutboxEvent.java deleted file mode 100644 index 70c52bf0..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/CanonicalClaimedOutboxEvent.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.application.outbox; - -import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import java.time.Instant; -import java.util.Objects; - -/** - * Claimed legacy-authority row whose immutable payload is a complete canonical integration event. - */ -public record CanonicalClaimedOutboxEvent( - ValidatedIntegrationEvent event, OutboxEventStatus status, int attemptCount) - implements ClaimedOutboxEvent { - - public CanonicalClaimedOutboxEvent { - Objects.requireNonNull(event, "event must not be null"); - Objects.requireNonNull(status, "status must not be null"); - if (attemptCount < 0) { - throw new IllegalArgumentException("attemptCount must be >= 0, was " + attemptCount); - } - } - - @Override - public String eventId() { - return event.eventId().value(); - } - - @Override - public String eventType() { - return event.contractId().value(); - } - - @Override - public String aggregateId() { - return event.aggregate().aggregateId(); - } - - @Override - public String correlationId() { - return event.correlationId(); - } - - @Override - public Instant occurredAt() { - return event.occurredAt(); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/ClaimedOutboxEvent.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/ClaimedOutboxEvent.java index cbbd1e51..a115caa9 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/ClaimedOutboxEvent.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/ClaimedOutboxEvent.java @@ -1,26 +1,50 @@ package dev.caskeleton.application.outbox; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; import java.time.Instant; +import java.util.Objects; /** - * Relay-facing claimed row identity shared by legacy and canonical outbox generations. + * One outbox row as a claim returns it: the validated integration event that was appended, plus + * where the row stands in the relay state machine. * - *

    Only fields needed by the legacy relay state machine and diagnostics live here. Payload and - * canonical envelope data remain on their concrete subtype. + *

    The event is restored from the exact envelope bytes and hashes the append stored, so the relay + * publishes the bytes that were validated rather than a re-rendering of them. The accessors below + * name the few identities the relay and its diagnostics read without reaching into the envelope. + * + * @param event the appended event + * @param status the row's lifecycle status; {@link OutboxEventStatus#IN_FLIGHT} right after a claim + * @param attemptCount delivery attempts made, counting the claim that returned this row */ -public sealed interface ClaimedOutboxEvent permits OutboxEvent, CanonicalClaimedOutboxEvent { +public record ClaimedOutboxEvent( + ValidatedIntegrationEvent event, OutboxEventStatus status, int attemptCount) { - String eventId(); + public ClaimedOutboxEvent { + Objects.requireNonNull(event, "event must not be null"); + Objects.requireNonNull(status, "status must not be null"); + if (attemptCount < 0) { + throw new IllegalArgumentException("attemptCount must be >= 0, was " + attemptCount); + } + } - String eventType(); + public String eventId() { + return event.eventId().value(); + } - String aggregateId(); + /** The contract id; the outbox's event type is the contract the event was validated against. */ + public String eventType() { + return event.contractId().value(); + } - String correlationId(); + public String aggregateId() { + return event.aggregate().aggregateId(); + } - Instant occurredAt(); + public String correlationId() { + return event.correlationId(); + } - OutboxEventStatus status(); - - int attemptCount(); + public Instant occurredAt() { + return event.occurredAt(); + } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/LegacyOutboxAppendPort.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/LegacyOutboxAppendPort.java deleted file mode 100644 index 1c3febba..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/LegacyOutboxAppendPort.java +++ /dev/null @@ -1,14 +0,0 @@ -package dev.caskeleton.application.outbox; - -/** - * Compatibility-only append boundary for the pre-canonical outbox payload model. - * - *

    New integration-event code must use {@link OutboxAppendPort}. This port remains only while - * legacy/sample producers still persist {@link NewOutboxEvent} rows through the transport-only - * cutover window. - */ -@FunctionalInterface -public interface LegacyOutboxAppendPort { - - void append(NewOutboxEvent event); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/NewOutboxEvent.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/NewOutboxEvent.java deleted file mode 100644 index 726aed6c..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/NewOutboxEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.application.outbox; - -import java.time.Instant; -import java.util.Objects; - -/** - * Value object for a new outbox event, appended within the caller's write transaction. All fields - * are required (null/blank is rejected at construction). Callers supply {@code eventId} and {@code - * idempotencyKey} (the outbox core is ID-generation-agnostic); the recommended default is {@code - * idempotencyKey = eventId}. See README. - * - * @param eventId unique identifier for this event (e.g. a UUIDv7 string) - * @param eventType logical event type name (e.g. {@code "UserCreated"}) - * @param aggregateId the aggregate that emitted this event; used as the message routing key and - * FIFO-gate anchor - * @param payload serialised event payload (pre-serialised JSON string) - * @param occurredAt wall-clock time at which the domain event occurred - * @param correlationId trace / correlation identifier for log correlation - * @param idempotencyKey consumer-side deduplication key (D12 / I12) - */ -public record NewOutboxEvent( - String eventId, - String eventType, - String aggregateId, - String payload, - Instant occurredAt, - String correlationId, - String idempotencyKey) { - - public NewOutboxEvent { - requireNonBlank(eventId, "eventId"); - requireNonBlank(eventType, "eventType"); - requireNonBlank(aggregateId, "aggregateId"); - requireNonBlank(payload, "payload"); - // Validated here, on the append side, and not only on the read model. - // - // OutboxEvent — the type the relay maps a stored row into — already applied this policy, so a - // malformed or oversized payload was accepted at write and first threw when the relay read it - // back. And it threw out of `claimBatch`, which maps a whole batch in one stream: one poisoned - // row failed every subsequent relay pass rather than the single transaction that could still - // have refused it. The append boundary is where the caller is still there to be told. - OutboxPayloadPolicy.requireValidPayload(payload); - Objects.requireNonNull(occurredAt, "occurredAt must not be null"); - requireNonBlank(correlationId, "correlationId"); - requireNonBlank(idempotencyKey, "idempotencyKey"); - } - - private static void requireNonBlank(String value, String field) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException(field + " must not be null or blank"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAppendPort.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAppendPort.java index 62390e05..ec8362c6 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAppendPort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAppendPort.java @@ -3,11 +3,13 @@ package dev.caskeleton.application.outbox; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; /** - * Canonical durable append boundary for a fully validated integration event. + * The one outbox append boundary: a fully validated integration event, written in the caller's + * write transaction. * *

    The implementation participates in the caller's existing write transaction and persists the - * exact validated envelope bytes. Raw legacy payload append is intentionally separated into {@link - * LegacyOutboxAppendPort}. + * exact validated envelope bytes; it never opens a transaction of its own, because a row committed + * apart from the business write it announces is the dual write the outbox exists to prevent. A use + * case builds the event with {@code IntegrationEventEncoderPort} and appends it here. */ @FunctionalInterface public interface OutboxAppendPort { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxEvent.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxEvent.java deleted file mode 100644 index 9d3a8fa1..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.application.outbox; - -import java.time.Instant; -import java.util.Objects; - -/** - * Immutable view of an outbox event row returned by {@link OutboxStorePort#claimBatch}. - * - *

    This is a claim-result read model: it carries the full {@link NewOutboxEvent} fields plus the - * current {@link OutboxEventStatus} and the number of delivery attempts already made. The relay - * uses {@code attemptCount} to decide whether to DEAD-letter the event on the next failure ({@code - * attemptCount >= maxAttempts}). - * - * @param eventId unique identifier for this event - * @param eventType logical event type name - * @param aggregateId the aggregate that emitted this event - * @param payload serialised event payload (pre-serialised JSON string) - * @param occurredAt wall-clock time at which the domain event occurred - * @param correlationId trace / correlation identifier - * @param idempotencyKey consumer-side deduplication key - * @param status current lifecycle status (will be {@link OutboxEventStatus#IN_FLIGHT} immediately - * after a successful claim) - * @param attemptCount number of delivery attempts already made (1-based after the first claim) - */ -public record OutboxEvent( - String eventId, - String eventType, - String aggregateId, - String payload, - Instant occurredAt, - String correlationId, - String idempotencyKey, - OutboxEventStatus status, - int attemptCount) - implements ClaimedOutboxEvent { - - public OutboxEvent { - Objects.requireNonNull(eventId, "eventId"); - Objects.requireNonNull(eventType, "eventType"); - Objects.requireNonNull(aggregateId, "aggregateId"); - // Not merely non-null: the envelope serialiser inserts this verbatim and unescaped, so an - // invalid or oversized payload becomes a permanently unparseable message that the relay - // retries forever. See OutboxPayloadPolicy. - OutboxPayloadPolicy.requireValidPayload(payload); - Objects.requireNonNull(occurredAt, "occurredAt"); - Objects.requireNonNull(correlationId, "correlationId"); - Objects.requireNonNull(idempotencyKey, "idempotencyKey"); - Objects.requireNonNull(status, "status"); - if (attemptCount < 0) { - throw new IllegalArgumentException("attemptCount must be >= 0, was " + attemptCount); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPayloadPolicy.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPayloadPolicy.java deleted file mode 100644 index b0f2d610..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPayloadPolicy.java +++ /dev/null @@ -1,271 +0,0 @@ -package dev.caskeleton.application.outbox; - -import java.nio.charset.StandardCharsets; - -/** - * What an outbox payload has to be before a row is written. - * - *

    {@code OutboxEvent} checked that the payload was non-null and nothing else, and the envelope - * serialiser then inserted it into the JSON document verbatim, unescaped, because it is documented - * as "already valid JSON". Nothing enforced that. A payload that was not valid JSON produced a - * malformed envelope that the broker accepted and every consumer failed to parse — permanently, - * because the row is durable and the relay retries it forever. A payload containing {@code - * "},"eventType":"} rewrote the envelope's own fields. - * - *

    Size was equally unbounded. The row goes into a database column, through a broker with a - * message limit, and into a JSON log line; a payload larger than any of those is a failure - * discovered after the transaction committed, which is the one point at which it can no longer be - * rejected. - * - *

    This is a validator, not a parser: it walks the text and returns nothing. Building a tree - * would mean a JSON library on {@code application-core}'s classpath, which the module's contract - * forbids, and would allocate a second copy of every payload for a check that needs neither. - */ -public final class OutboxPayloadPolicy { - - /** - * The payload ceiling in UTF-8 bytes. - * - *

    256 KiB: comfortably under the one mebibyte default of every broker in the platform, with - * room for the envelope's own fields and for a log line that quotes it. - */ - public static final int MAX_PAYLOAD_BYTES = 262_144; - - private OutboxPayloadPolicy() {} - - /** - * Refuses a payload that is not a single valid JSON value, or is too large. - * - * @param payload the serialised payload - * @throws IllegalArgumentException naming what is wrong and where - */ - public static void requireValidPayload(String payload) { - if (payload == null) { - throw new IllegalArgumentException("outbox payload must not be null"); - } - int bytes = payload.getBytes(StandardCharsets.UTF_8).length; - if (bytes > MAX_PAYLOAD_BYTES) { - throw new IllegalArgumentException( - "outbox payload is " - + bytes - + " UTF-8 bytes; the limit is " - + MAX_PAYLOAD_BYTES - + ". Rejecting it here is the last point at which it can be rejected at all — after" - + " the row commits, the relay retries it forever."); - } - Scanner scanner = new Scanner(payload); - scanner.skipWhitespace(); - scanner.readValue(0); - scanner.skipWhitespace(); - if (!scanner.exhausted()) { - throw new IllegalArgumentException( - "outbox payload has trailing content at offset " - + scanner.position - + "; it must be exactly one JSON value"); - } - } - - /** A single-pass structural JSON validator over the payload text. */ - private static final class Scanner { - - /** - * The nesting ceiling. - * - *

    Present because this validator recurses: without it a payload of ten thousand open - * brackets overflows the stack of whatever thread appends the row. - */ - private static final int MAX_DEPTH = 64; - - private final String text; - private int position; - - private Scanner(String text) { - this.text = text; - } - - private boolean exhausted() { - return position >= text.length(); - } - - private void skipWhitespace() { - while (position < text.length()) { - char current = text.charAt(position); - if (current == ' ' || current == '\t' || current == '\n' || current == '\r') { - position++; - } else { - return; - } - } - } - - private void readValue(int depth) { - if (depth > MAX_DEPTH) { - throw fail("nesting deeper than " + MAX_DEPTH + " levels"); - } - if (exhausted()) { - throw fail("a JSON value was expected"); - } - char current = text.charAt(position); - switch (current) { - case '{' -> readObject(depth); - case '[' -> readArray(depth); - case '"' -> readString(); - case 't' -> readLiteral("true"); - case 'f' -> readLiteral("false"); - case 'n' -> readLiteral("null"); - default -> readNumber(); - } - } - - private void readObject(int depth) { - expect('{'); - skipWhitespace(); - if (peekIs('}')) { - position++; - return; - } - while (true) { - skipWhitespace(); - readString(); - skipWhitespace(); - expect(':'); - skipWhitespace(); - readValue(depth + 1); - skipWhitespace(); - if (peekIs(',')) { - position++; - continue; - } - expect('}'); - return; - } - } - - private void readArray(int depth) { - expect('['); - skipWhitespace(); - if (peekIs(']')) { - position++; - return; - } - while (true) { - skipWhitespace(); - readValue(depth + 1); - skipWhitespace(); - if (peekIs(',')) { - position++; - continue; - } - expect(']'); - return; - } - } - - private void readString() { - expect('"'); - while (true) { - if (exhausted()) { - throw fail("an unterminated string"); - } - char current = text.charAt(position++); - if (current == '"') { - return; - } - if (current == '\\') { - readEscape(); - } else if (current < 0x20) { - // A raw control character inside a string is invalid JSON, and it is also exactly what - // turns one log line into two. - throw fail("a raw control character inside a string"); - } - } - } - - private void readEscape() { - if (exhausted()) { - throw fail("an escape at the end of the payload"); - } - char escaped = text.charAt(position++); - switch (escaped) { - case '"', '\\', '/', 'b', 'f', 'n', 'r', 't' -> { - // A complete escape. - } - case 'u' -> { - if (position + 4 > text.length()) { - throw fail("a truncated unicode escape"); - } - for (int index = 0; index < 4; index++) { - char digit = text.charAt(position++); - boolean hexadecimal = - (digit >= '0' && digit <= '9') - || (digit >= 'a' && digit <= 'f') - || (digit >= 'A' && digit <= 'F'); - if (!hexadecimal) { - throw fail("a unicode escape that is not hexadecimal"); - } - } - } - default -> throw fail("an unknown escape \\" + escaped); - } - } - - private void readNumber() { - int start = position; - if (peekIs('-')) { - position++; - } - readDigits(); - if (peekIs('.')) { - position++; - readDigits(); - } - if (peekIs('e') || peekIs('E')) { - position++; - if (peekIs('+') || peekIs('-')) { - position++; - } - readDigits(); - } - if (position == start) { - throw fail("a JSON value was expected"); - } - } - - private void readDigits() { - int start = position; - while (position < text.length() - && text.charAt(position) >= '0' - && text.charAt(position) <= '9') { - position++; - } - if (position == start) { - throw fail("a number with no digits"); - } - } - - private void readLiteral(String literal) { - if (!text.startsWith(literal, position)) { - throw fail("an unrecognised literal"); - } - position += literal.length(); - } - - private boolean peekIs(char expected) { - return position < text.length() && text.charAt(position) == expected; - } - - private void expect(char expected) { - if (!peekIs(expected)) { - throw fail("'" + expected + "' was expected"); - } - position++; - } - - private IllegalArgumentException fail(String what) { - // Deliberately reports the offset and not the text: the payload is business content and this - // message reaches logs. - return new IllegalArgumentException( - "outbox payload is not valid JSON: " + what + " at offset " + position); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayFailureReport.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayFailureReport.java index 62ec2746..f0723dc6 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayFailureReport.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayFailureReport.java @@ -7,8 +7,8 @@ import java.util.Objects; /** * Safe immutable allowlist for reporting a confirmed FAILED or DEAD outbox relay transition. * - *

    The report deliberately cannot carry an event payload, idempotency key, rendered message, - * severity, arbitrary fields, or the whole {@link OutboxEvent}. + *

    The report deliberately cannot carry an event payload, envelope bytes, rendered message, + * severity, arbitrary fields, or the whole {@link ClaimedOutboxEvent}. * *

    It also cannot carry the exception. It used to, and the renderer passed that {@code Throwable} * to the logger as the event's cause — so the operational JSON gained a message and a stack trace diff --git a/src/application-core/src/main/resources/contracts/messaging/durable-operation.submitted/v1.schema.json b/src/application-core/src/main/resources/contracts/messaging/durable-operation.submitted/v1.schema.json new file mode 100644 index 00000000..0b6c2f5a --- /dev/null +++ b/src/application-core/src/main/resources/contracts/messaging/durable-operation.submitted/v1.schema.json @@ -0,0 +1,24 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:dev-caskeleton:contracts:messaging:durable-operation.submitted:v1", + "title": "DurableOperationSubmitted payload v1", + "description": "Wakes a worker for one accepted durable operation. The worker reads what to run from the submission it claims, so the event carries only which operation and what kind of work it is.", + "type": "object", + "required": [ + "operationId", + "operationName" + ], + "properties": { + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[A-Za-z0-9._~-]+$" + }, + "operationName": { + "type": "string", + "minLength": 1 + } + }, + "unevaluatedProperties": false +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java b/src/application-core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java index b0e624f8..a3cd9d53 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java @@ -4,9 +4,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStore; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.usecase.CommandUseCase; import java.time.Clock; @@ -38,9 +39,10 @@ class SubmitDurableOperationUseCaseTest { private final RecordingOutbox outbox = new RecordingOutbox(insideTransaction); private final RollbackAwareTransactions transactions = new RollbackAwareTransactions(operations, outbox, insideTransaction); + private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder(); private final CommandUseCase useCase = new SubmitDurableOperationUseCase( - operations, outbox, transactions, Clock.fixed(NOW, ZoneOffset.UTC)); + operations, outbox, encoder, transactions, Clock.fixed(NOW, ZoneOffset.UTC)); private static OperationCommand command(DurableOperationId id, String hash) { return new OperationCommand( @@ -50,7 +52,6 @@ class SubmitDurableOperationUseCaseTest { null, new RequestFingerprint(hash), "{\"range\":\"2026-08\"}", - "ReportRequested", Duration.ofHours(6)); } @@ -131,40 +132,58 @@ class SubmitDurableOperationUseCaseTest { } @Test - @DisplayName("the outbox event carries the operation id as its routing key and dedup key") - void outboxEventIsAnchoredToTheOperation() { + void theOutboxEventIsTheSubmittedContractAnchoredToTheOperation() { + // given useCase.handle(command(ID, "a".repeat(64))); - NewOutboxEvent event = outbox.appended.get(0); + // when + ValidatedIntegrationEvent event = outbox.appended.get(0); + // then // A worker that receives the message twice — which the relay's at-least-once delivery makes // ordinary — must be able to tell it is the same work. The operation id is what says so. - assertThat(event.aggregateId()).isEqualTo("op-1"); - assertThat(event.idempotencyKey()).isEqualTo("op-1"); - assertThat(event.eventType()).isEqualTo("ReportRequested"); + assertThat(event) + .extracting( + e -> e.eventId().value(), + e -> e.aggregate().aggregateId(), + e -> e.contractId(), + e -> e.logicalDestinationId()) + .containsExactly( + "op-1", + "op-1", + DurableOperationSubmittedContract.CONTRACT_ID, + DurableOperationSubmittedContract.DESTINATION); } @Test - @DisplayName("a command with no event type is refused rather than accepted into silence") - void missingEventTypeIsRefused() { - assertThatThrownBy( - () -> - new OperationCommand( - ID, - "reports.generate", - "alice", - null, - new RequestFingerprint("a".repeat(64)), - "{}", - " ", - Duration.ofHours(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("reaches no worker"); + void theSubmittedEventNamesTheOperationAndNotTheRequest() { + // when + useCase.handle(command(ID, "a".repeat(64))); + + // then + // The worker reads what to run from the submission it claims; the request never travels. + assertThat(encoder.drafts()) + .extracting(draft -> draft.featurePayload()) + .containsExactly(new DurableOperationSubmitted("op-1", "reports.generate")); } - private static final class RecordingOutbox implements LegacyOutboxAppendPort { + @Test + void anOperationIdOutsideTheEventIdGrammarBecomesAStableDigestIdentity() { + // given + DurableOperationId tilde = new DurableOperationId("~report"); - private final List appended = new ArrayList<>(); + // when + String identity = SubmitDurableOperationUseCase.canonicalIdentity(tilde); + + // then + assertThat(List.of(identity, SubmitDurableOperationUseCase.canonicalIdentity(tilde))) + .allMatch(value -> value.matches("operation-[0-9a-f]{64}")) + .containsOnly(identity); + } + + private static final class RecordingOutbox implements OutboxAppendPort { + + private final List appended = new ArrayList<>(); private final List appendedOutsideTransaction = new ArrayList<>(); private final AtomicBoolean insideTransaction; private boolean failNext; @@ -174,11 +193,11 @@ class SubmitDurableOperationUseCaseTest { } @Override - public void append(NewOutboxEvent event) { + public void append(ValidatedIntegrationEvent event) { if (!insideTransaction.get()) { // The port's own contract: appending outside the caller's write transaction is silent // event loss, and it is invisible to any assertion about what ended up in the list. - appendedOutsideTransaction.add(event.eventId()); + appendedOutsideTransaction.add(event.eventId().value()); } if (failNext) { failNext = false; diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/ClaimedOutboxEventContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/ClaimedOutboxEventContractTest.java index 3e24fafa..a5a6a3fa 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/ClaimedOutboxEventContractTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/ClaimedOutboxEventContractTest.java @@ -1,79 +1,55 @@ package dev.caskeleton.application.outbox; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; -import dev.caskeleton.application.messaging.event.AggregateIdentity; -import dev.caskeleton.application.messaging.event.AggregateOrder; -import dev.caskeleton.application.messaging.event.EventId; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import java.nio.charset.StandardCharsets; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; import java.time.Instant; -import java.util.Optional; import org.junit.jupiter.api.Test; class ClaimedOutboxEventContractTest { + private static final Instant OCCURRED_AT = Instant.parse("2026-09-18T03:00:00Z"); + @Test - void canonicalClaimExposesRelayIdentityWithoutLosingValidatedEvent() { - ValidatedIntegrationEvent event = canonicalEvent(); + void aClaimExposesTheRelayIdentitiesOfTheValidatedEventItCarries() { + // given + ValidatedIntegrationEvent event = OutboxEvents.event("evt-1", "worklog-42", 17, OCCURRED_AT); - ClaimedOutboxEvent claimed = - new CanonicalClaimedOutboxEvent(event, OutboxEventStatus.IN_FLIGHT, 2); + // when + ClaimedOutboxEvent claimed = new ClaimedOutboxEvent(event, OutboxEventStatus.IN_FLIGHT, 2); - assertThat(claimed.eventId()).isEqualTo(event.eventId().value()); - assertThat(claimed.eventType()).isEqualTo(event.contractId().value()); - assertThat(claimed.aggregateId()).isEqualTo(event.aggregate().aggregateId()); - assertThat(claimed.correlationId()).isEqualTo(event.correlationId()); - assertThat(claimed.occurredAt()).isEqualTo(event.occurredAt()); - assertThat(claimed.status()).isEqualTo(OutboxEventStatus.IN_FLIGHT); - assertThat(claimed.attemptCount()).isEqualTo(2); - assertThat(((CanonicalClaimedOutboxEvent) claimed).event()).isEqualTo(event); + // then + assertThat(claimed) + .extracting( + ClaimedOutboxEvent::eventId, + ClaimedOutboxEvent::eventType, + ClaimedOutboxEvent::aggregateId, + ClaimedOutboxEvent::correlationId, + ClaimedOutboxEvent::occurredAt, + ClaimedOutboxEvent::event) + .containsExactly( + "evt-1", + OutboxEvents.CONTRACT_ID, + "worklog-42", + "correlation-evt-1", + OCCURRED_AT, + event); } @Test - void legacyOutboxEventRemainsAClaimedSubtype() { - ClaimedOutboxEvent claimed = - new OutboxEvent( - "legacy-1", - "LegacyEvent", - "aggregate-1", - "{}", - Instant.parse("2026-09-18T03:00:00Z"), - "corr-1", - "legacy-1", - OutboxEventStatus.IN_FLIGHT, - 1); + void aNegativeAttemptCountIsRefused() { + // given + ValidatedIntegrationEvent event = OutboxEvents.event("evt-2", OCCURRED_AT); - assertThat(claimed).isInstanceOf(OutboxEvent.class); - } + // when + Throwable thrown = + catchThrowable(() -> new ClaimedOutboxEvent(event, OutboxEventStatus.PENDING, -1)); - private static ValidatedIntegrationEvent canonicalEvent() { - String partition = "a".repeat(64); - byte[] envelope = "{\"wire\":\"exact\"}".getBytes(StandardCharsets.UTF_8); - Sha256 zero = new Sha256(new byte[32]); - return new ValidatedIntegrationEvent( - new EventId("01994e11-4d88-7000-8000-000000000001"), - new ContractId("portfolio.worklog.reserved"), - 1, - 3, - new LogicalDestinationId("portfolio-domain-events"), - new AggregateIdentity("tenant-a", "worklog", "worklog-42"), - new AggregateOrder(17, 2), - Instant.parse("2026-09-18T03:00:00Z"), - "corr-1", - Optional.empty(), - partition, - partition.getBytes(StandardCharsets.US_ASCII), - envelope, - "application/json", - zero, - Sha256.of(envelope), - zero, - zero, - "catalog-r1", - "binding-r1"); + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("attemptCount must be >= 0, was -1"); } } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/NewOutboxEventTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/NewOutboxEventTest.java deleted file mode 100644 index 57d41f05..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/NewOutboxEventTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package dev.caskeleton.application.outbox; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Instant; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.NullAndEmptySource; -import org.junit.jupiter.params.provider.ValueSource; - -/** Validates {@link NewOutboxEvent} required-field invariants (D12). */ -class NewOutboxEventTest { - - private static final Instant OCCURRED_AT = Instant.parse("2026-06-11T10:00:00Z"); - - @Test - void validEventConstructsSuccessfully() { - NewOutboxEvent event = - new NewOutboxEvent("evt-1", "UserCreated", "agg-1", "{}", OCCURRED_AT, "corr-1", "ikey-1"); - assertThat(event.eventId()).isEqualTo("evt-1"); - assertThat(event.eventType()).isEqualTo("UserCreated"); - assertThat(event.aggregateId()).isEqualTo("agg-1"); - assertThat(event.payload()).isEqualTo("{}"); - assertThat(event.occurredAt()).isEqualTo(OCCURRED_AT); - assertThat(event.correlationId()).isEqualTo("corr-1"); - assertThat(event.idempotencyKey()).isEqualTo("ikey-1"); - } - - @ParameterizedTest - @NullAndEmptySource - @ValueSource(strings = {" ", "\t", "\n"}) - void nullOrBlankEventIdIsRejected(String bad) { - assertThatThrownBy( - () -> - new NewOutboxEvent( - bad, "UserCreated", "agg-1", "{}", OCCURRED_AT, "corr-1", "ikey-1")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("eventId"); - } - - @ParameterizedTest - @NullAndEmptySource - @ValueSource(strings = {" ", "\t"}) - void nullOrBlankEventTypeIsRejected(String bad) { - assertThatThrownBy( - () -> new NewOutboxEvent("evt-1", bad, "agg-1", "{}", OCCURRED_AT, "corr-1", "ikey-1")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("eventType"); - } - - @ParameterizedTest - @NullAndEmptySource - @ValueSource(strings = {" "}) - void nullOrBlankAggregateIdIsRejected(String bad) { - assertThatThrownBy( - () -> - new NewOutboxEvent( - "evt-1", "UserCreated", bad, "{}", OCCURRED_AT, "corr-1", "ikey-1")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("aggregateId"); - } - - @ParameterizedTest - @NullAndEmptySource - @ValueSource(strings = {" "}) - void nullOrBlankPayloadIsRejected(String bad) { - assertThatThrownBy( - () -> - new NewOutboxEvent( - "evt-1", "UserCreated", "agg-1", bad, OCCURRED_AT, "corr-1", "ikey-1")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("payload"); - } - - @Test - void nullOccurredAtIsRejected() { - assertThatThrownBy( - () -> - new NewOutboxEvent("evt-1", "UserCreated", "agg-1", "{}", null, "corr-1", "ikey-1")) - .isInstanceOf(NullPointerException.class) - .hasMessageContaining("occurredAt"); - } - - @ParameterizedTest - @NullAndEmptySource - @ValueSource(strings = {" "}) - void nullOrBlankCorrelationIdIsRejected(String bad) { - assertThatThrownBy( - () -> - new NewOutboxEvent( - "evt-1", "UserCreated", "agg-1", "{}", OCCURRED_AT, bad, "ikey-1")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("correlationId"); - } - - @ParameterizedTest - @NullAndEmptySource - @ValueSource(strings = {" "}) - void nullOrBlankIdempotencyKeyIsRejected(String bad) { - assertThatThrownBy( - () -> - new NewOutboxEvent( - "evt-1", "UserCreated", "agg-1", "{}", OCCURRED_AT, "corr-1", bad)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("idempotencyKey"); - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxAppendPortBoundaryTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxAppendPortBoundaryTest.java index 472b67ef..5cdd4dbd 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxAppendPortBoundaryTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxAppendPortBoundaryTest.java @@ -10,19 +10,12 @@ import org.junit.jupiter.api.Test; class OutboxAppendPortBoundaryTest { @Test - void canonicalAndLegacyAppendPortsHaveDisjointTypedInputs() { - assertThat(singleAppendParameter(OutboxAppendPort.class)) - .isEqualTo(ValidatedIntegrationEvent.class); - assertThat(singleAppendParameter(LegacyOutboxAppendPort.class)).isEqualTo(NewOutboxEvent.class); - } - - private static Class singleAppendParameter(Class portType) { - Method append = - Arrays.stream(portType.getDeclaredMethods()) - .filter(method -> method.getName().equals("append")) - .findFirst() - .orElseThrow(); - assertThat(append.getParameterCount()).isEqualTo(1); - return append.getParameterTypes()[0]; + void theOnlyOutboxAppendTakesAValidatedIntegrationEvent() { + assertThat( + Arrays.stream(OutboxAppendPort.class.getDeclaredMethods()) + .map(Method::getParameterTypes) + .map(Arrays::asList) + .toList()) + .containsExactly(java.util.List.of(ValidatedIntegrationEvent.class)); } } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxPayloadPolicyTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxPayloadPolicyTest.java deleted file mode 100644 index cb96e731..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxPayloadPolicyTest.java +++ /dev/null @@ -1,139 +0,0 @@ -package dev.caskeleton.application.outbox; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.nio.charset.StandardCharsets; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * What the outbox accepts as a payload. - * - *

    It accepted anything. The envelope serialiser inserts the payload into the JSON document - * verbatim and unescaped — that is documented, and nothing enforced the precondition it documents. - * A payload that is not valid JSON produces an envelope no consumer can parse, permanently, because - * the row is durable and the relay retries it until the attempt budget is gone. A payload - * containing the envelope's own field syntax rewrites the envelope. - */ -class OutboxPayloadPolicyTest { - - @Test - @DisplayName("ordinary JSON values are accepted") - void ordinaryJsonValuesAreAccepted() { - assertThatCode( - () -> { - OutboxPayloadPolicy.requireValidPayload("{}"); - OutboxPayloadPolicy.requireValidPayload("{\"orderId\":\"o-1\",\"amount\":12.5e3}"); - OutboxPayloadPolicy.requireValidPayload("[1,2,{\"a\":[true,false,null]}]"); - OutboxPayloadPolicy.requireValidPayload("\"a string\""); - OutboxPayloadPolicy.requireValidPayload("-0.5"); - OutboxPayloadPolicy.requireValidPayload(" {\"padded\": true} "); - }) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("a payload that is not JSON is refused before the row is written") - void aPayloadThatIsNotJsonIsRefused() { - assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload("not json")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("not valid JSON"); - assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload("{\"a\":}")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload("{\"a\":1,}")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload("[1,2")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload("")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a payload that would rewrite the envelope's own fields is refused") - void aPayloadThatWouldRewriteTheEnvelopeIsRefused() { - // Inserted verbatim, this closes the payload value and appends a field of its own. - assertThatThrownBy( - () -> OutboxPayloadPolicy.requireValidPayload("{\"a\":1},\"eventType\":\"forged\"")) - .as("the payload is concatenated into the envelope, so trailing content is an injection") - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("trailing content"); - } - - @Test - @DisplayName("two JSON values are not one payload") - void twoJsonValuesAreNotOnePayload() { - assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload("{} {}")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("exactly one JSON value"); - } - - @Test - @DisplayName("a raw control character inside a string is refused") - void aRawControlCharacterInsideAStringIsRefused() { - assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload("{\"a\":\"line\nbreak\"}")) - .as("a raw newline is invalid JSON and is also what turns one log line into two") - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("control character"); - } - - @Test - @DisplayName("the size limit is applied in UTF-8 bytes, at the boundary") - void theSizeLimitIsAppliedInUtf8Bytes() { - // A multi-byte character: a limit counted in char units would accept three times too much. - String fill = "가"; - int perCharacter = fill.getBytes(StandardCharsets.UTF_8).length; - int charactersThatFit = (OutboxPayloadPolicy.MAX_PAYLOAD_BYTES - 2) / perCharacter; - - assertThatCode( - () -> - OutboxPayloadPolicy.requireValidPayload( - "\"" + fill.repeat(charactersThatFit) + "\"")) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - OutboxPayloadPolicy.requireValidPayload( - "\"" + fill.repeat(charactersThatFit + 1) + "\"")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("UTF-8 bytes"); - } - - @Test - @DisplayName("a surrogate pair survives the validator") - void aSurrogatePairSurvivesTheValidator() { - assertThatCode(() -> OutboxPayloadPolicy.requireValidPayload("{\"emoji\":\"🚀\"}")) - .doesNotThrowAnyException(); - assertThatCode( - () -> OutboxPayloadPolicy.requireValidPayload("{\"escaped\":\"\\ud83d\\ude80\"}")) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("deep nesting is refused rather than overflowing the appending thread's stack") - void deepNestingIsRefused() { - String deep = "[".repeat(5_000) + "]".repeat(5_000); - - assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload(deep)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("nesting"); - } - - @Test - @DisplayName("the outbox event applies the policy at construction") - void theOutboxEventAppliesThePolicy() { - assertThatThrownBy( - () -> - new OutboxEvent( - "evt-1", - "WorkLogReserved", - "agg-1", - "{\"unterminated\": ", - java.time.Instant.parse("2026-08-10T09:00:00Z"), - "corr-1", - "idem-1", - OutboxEventStatus.PENDING, - 0)) - .as("after the row commits, the relay retries an unparseable message until it is DEAD") - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutcomeAwareRelayTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutcomeAwareRelayTest.java index bd699265..e883549e 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutcomeAwareRelayTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutcomeAwareRelayTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.application.outbox; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.time.Duration; @@ -148,17 +149,8 @@ class OutcomeAwareRelayTest { assertThat(store.failed()).containsKey("evt-5"); } - private static OutboxEvent event(String eventId, int attemptCount) { - return new OutboxEvent( - eventId, - "UserCreated", - "agg-1", - "{\"data\": \"test\"}", - NOW.minusSeconds(60), - "corr-" + eventId, - "ikey-" + eventId, - OutboxEventStatus.IN_FLIGHT, - attemptCount); + private static ClaimedOutboxEvent event(String eventId, int attemptCount) { + return OutboxEvents.claimed(eventId, NOW.minusSeconds(60), attemptCount); } /** A port that answers with an outcome, or throws when the test asks it to. */ diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java index 70dcb293..db890f8c 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.time.Duration; @@ -72,7 +73,7 @@ class PublishPendingOutboxEventsUseCaseTest { @Test void legacyVoidPublisherNormalReturnTransitionsEventToPublishedCharacterization() { - OutboxEvent event = makeEvent("evt-1", "UserCreated", "agg-1", NOW.minusSeconds(60), 1); + ClaimedOutboxEvent event = makeEvent("evt-1", "agg-1", NOW.minusSeconds(60), 1); store.addClaimable(event); OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -89,8 +90,8 @@ class PublishPendingOutboxEventsUseCaseTest { @Test void multipleEventsPublishedInOccurredAtAscendingOrder() { // Add events out of order to ensure relay sorts defensively - OutboxEvent late = makeEvent("evt-late", "UserUpdated", "agg-1", NOW.minusSeconds(10), 1); - OutboxEvent early = makeEvent("evt-early", "UserCreated", "agg-1", NOW.minusSeconds(60), 1); + ClaimedOutboxEvent late = makeEvent("evt-late", "agg-1", NOW.minusSeconds(10), 1); + ClaimedOutboxEvent early = makeEvent("evt-early", "agg-1", NOW.minusSeconds(60), 1); store.addClaimable(late); store.addClaimable(early); @@ -104,7 +105,7 @@ class PublishPendingOutboxEventsUseCaseTest { @Test void senderExceptionTransitionsEventToFailedWithBackoffCharacterization() { - OutboxEvent event = makeEvent("evt-fail", "UserCreated", "agg-1", NOW.minusSeconds(60), 1); + ClaimedOutboxEvent event = makeEvent("evt-fail", "agg-1", NOW.minusSeconds(60), 1); store.addClaimable(event); publishPort.failOn("evt-fail", new RuntimeException("broker down")); @@ -123,9 +124,9 @@ class PublishPendingOutboxEventsUseCaseTest { .containsExactly( OutboxRelayFailureReport.retryableFailure( "evt-fail", - "UserCreated", + OutboxEvents.CONTRACT_ID, "agg-1", - "corr-evt-fail", + "correlation-evt-fail", 1, nextAttemptAt, publishPort.failureOn("evt-fail"))); @@ -134,7 +135,7 @@ class PublishPendingOutboxEventsUseCaseTest { @Test void senderExceptionAtRetryLimitTransitionsEventToDeadCharacterization() { // attemptCount=3 means this is the 3rd attempt — next failure should DEAD - OutboxEvent event = makeEvent("evt-dead", "UserCreated", "agg-1", NOW.minusSeconds(60), 3); + ClaimedOutboxEvent event = makeEvent("evt-dead", "agg-1", NOW.minusSeconds(60), 3); store.addClaimable(event); publishPort.failOn("evt-dead", new RuntimeException("persistent broker down")); @@ -147,9 +148,9 @@ class PublishPendingOutboxEventsUseCaseTest { .containsExactly( OutboxRelayFailureReport.deadLetter( "evt-dead", - "UserCreated", + OutboxEvents.CONTRACT_ID, "agg-1", - "corr-evt-dead", + "correlation-evt-dead", 3, publishPort.failureOn("evt-dead"))); } @@ -159,8 +160,8 @@ class PublishPendingOutboxEventsUseCaseTest { @Test void failureIsNotSwallowedRelayContinuesWithNextEvent() { // Two events: first fails, second succeeds — both must produce status transitions - OutboxEvent fail = makeEvent("evt-fail", "UserCreated", "agg-1", NOW.minusSeconds(120), 1); - OutboxEvent ok = makeEvent("evt-ok", "UserUpdated", "agg-1", NOW.minusSeconds(60), 1); + ClaimedOutboxEvent fail = makeEvent("evt-fail", "agg-1", NOW.minusSeconds(120), 1); + ClaimedOutboxEvent ok = makeEvent("evt-ok", "agg-1", NOW.minusSeconds(60), 1); store.addClaimable(fail); store.addClaimable(ok); publishPort.failOn("evt-fail", new RuntimeException("transient")); @@ -190,7 +191,7 @@ class PublishPendingOutboxEventsUseCaseTest { @Test void failureOnSecondAttemptTransitionsToFailedNotDead() { - OutboxEvent event = makeEvent("evt-2nd", "UserCreated", "agg-1", NOW.minusSeconds(60), 2); + ClaimedOutboxEvent event = makeEvent("evt-2nd", "agg-1", NOW.minusSeconds(60), 2); store.addClaimable(event); publishPort.failOn("evt-2nd", new RuntimeException("2nd attempt failure")); @@ -231,8 +232,7 @@ class PublishPendingOutboxEventsUseCaseTest { */ @Test void legacyMarkPublishedFailureLeavesInFlightAndDuplicatePossibleCharacterization() { - OutboxEvent event = - makeEvent("evt-store-fail", "UserCreated", "agg-1", NOW.minusSeconds(60), 1); + ClaimedOutboxEvent event = makeEvent("evt-store-fail", "agg-1", NOW.minusSeconds(60), 1); MutableClock mutableClock = new MutableClock(NOW, ZoneOffset.UTC); TimeoutAwareThrowingOnMarkPublishedStorePort throwingStore = @@ -300,8 +300,8 @@ class PublishPendingOutboxEventsUseCaseTest { */ @Test void markPublishedFailureAbortsRemainingBatchForCurrentTick() { - OutboxEvent first = makeEvent("evt-first", "UserCreated", "agg-1", NOW.minusSeconds(120), 1); - OutboxEvent second = makeEvent("evt-second", "UserUpdated", "agg-1", NOW.minusSeconds(60), 1); + ClaimedOutboxEvent first = makeEvent("evt-first", "agg-1", NOW.minusSeconds(120), 1); + ClaimedOutboxEvent second = makeEvent("evt-second", "agg-1", NOW.minusSeconds(60), 1); ThrowingOnMarkPublishedStorePort throwingStore = new ThrowingOnMarkPublishedStorePort(new RuntimeException("DB down on markPublished")); @@ -341,7 +341,7 @@ class PublishPendingOutboxEventsUseCaseTest { @Test void markFailedFailurePropagatesAndEmitsNoReport() { - OutboxEvent event = makeEvent("evt-fail", "UserCreated", "agg-1", NOW.minusSeconds(60), 1); + ClaimedOutboxEvent event = makeEvent("evt-fail", "agg-1", NOW.minusSeconds(60), 1); ThrowingTransitionStorePort throwingStore = new ThrowingTransitionStorePort(new RuntimeException("markFailed failed"), null); throwingStore.addClaimable(event); @@ -365,7 +365,7 @@ class PublishPendingOutboxEventsUseCaseTest { @Test void markDeadFailurePropagatesAndEmitsNoReport() { - OutboxEvent event = makeEvent("evt-dead", "UserCreated", "agg-1", NOW.minusSeconds(60), 3); + ClaimedOutboxEvent event = makeEvent("evt-dead", "agg-1", NOW.minusSeconds(60), 3); ThrowingTransitionStorePort throwingStore = new ThrowingTransitionStorePort(null, new RuntimeException("markDead failed")); throwingStore.addClaimable(event); @@ -389,8 +389,8 @@ class PublishPendingOutboxEventsUseCaseTest { @Test void throwingReporterPreservesFailedOutcomeAndRelayContinues() { - OutboxEvent failed = makeEvent("evt-fail", "UserCreated", "agg-1", NOW.minusSeconds(120), 1); - OutboxEvent succeeded = makeEvent("evt-ok", "UserUpdated", "agg-1", NOW.minusSeconds(60), 1); + ClaimedOutboxEvent failed = makeEvent("evt-fail", "agg-1", NOW.minusSeconds(120), 1); + ClaimedOutboxEvent succeeded = makeEvent("evt-ok", "agg-1", NOW.minusSeconds(60), 1); store.addClaimable(failed); store.addClaimable(succeeded); publishPort.failOn("evt-fail", new RuntimeException("broker down")); @@ -420,43 +420,12 @@ class PublishPendingOutboxEventsUseCaseTest { assertThat(store.published()).containsExactly("evt-ok"); } - @Test - void malformedReportDataPreservesFailedAndDeadOutcomesAndRelayContinues() { - OutboxEvent failed = makeEvent("evt-fail", "UserCreated", " ", NOW.minusSeconds(180), 1); - OutboxEvent dead = makeEvent("evt-dead", "UserDeleted", " ", NOW.minusSeconds(120), 3); - OutboxEvent succeeded = makeEvent("evt-ok", "UserUpdated", "agg-1", NOW.minusSeconds(60), 1); - store.addClaimable(failed); - store.addClaimable(dead); - store.addClaimable(succeeded); - publishPort.failOn("evt-fail", new RuntimeException("transient broker failure")); - publishPort.failOn("evt-dead", new RuntimeException("persistent broker failure")); - - OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); - - assertThat(result.outcomes()) - .extracting(OutboxRelayResult.EventOutcome::outcome) - .containsExactly( - OutboxRelayResult.Outcome.FAILED, - OutboxRelayResult.Outcome.DEAD, - OutboxRelayResult.Outcome.PUBLISHED); - assertThat(store.failed()).containsKey("evt-fail"); - assertThat(store.dead()).containsExactly("evt-dead"); - assertThat(store.published()).containsExactly("evt-ok"); - assertThat(reporter.reports).isEmpty(); - } - // ---- helper ---- - private static OutboxEvent makeEvent( - String eventId, String eventType, String aggregateId, Instant occurredAt, int attemptCount) { - return new OutboxEvent( - eventId, - eventType, - aggregateId, - "{\"data\": \"test\"}", - occurredAt, - "corr-" + eventId, - "ikey-" + eventId, + private static ClaimedOutboxEvent makeEvent( + String eventId, String aggregateId, Instant occurredAt, int attemptCount) { + return new ClaimedOutboxEvent( + OutboxEvents.event(eventId, aggregateId, 1, occurredAt), OutboxEventStatus.IN_FLIGHT, attemptCount); } @@ -491,7 +460,7 @@ class PublishPendingOutboxEventsUseCaseTest { private int markDeadCalls; TimeoutAwareThrowingOnMarkPublishedStorePort( - OutboxEvent event, RuntimeException markPublishedException) { + ClaimedOutboxEvent event, RuntimeException markPublishedException) { this.eventId = event.eventId(); this.markPublishedException = markPublishedException; addClaimable(event); diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreLeaseFencingContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreLeaseFencingContractTest.java index d4b4539d..49f51433 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreLeaseFencingContractTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreLeaseFencingContractTest.java @@ -1,6 +1,6 @@ package dev.caskeleton.application.outbox.testkit; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxStorePort; import dev.caskeleton.application.transaction.TransactionPort; @@ -16,7 +16,7 @@ class InMemoryOutboxStoreLeaseFencingContractTest extends OutboxLeaseFencingCont } @Override - protected LegacyOutboxAppendPort append() { + protected OutboxAppendPort append() { return store; } diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoder.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoder.java new file mode 100644 index 00000000..dda89154 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoder.java @@ -0,0 +1,63 @@ +package dev.caskeleton.application.messaging.event.testkit; + +import dev.caskeleton.application.messaging.contract.Sha256; +import dev.caskeleton.application.messaging.event.IntegrationEventDraft; +import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; + +/** + * The encoder fake: keeps every draft it was given and returns a validated event that carries the + * draft's identities unchanged. + * + *

    The envelope bytes are the draft's {@code toString()}, which is enough for a use-case test to + * tell two events apart and nothing more; the canonical JSON rendering is the real encoder's + * contract and is tested there. + */ +public final class FakeIntegrationEventEncoder implements IntegrationEventEncoderPort { + + private static final Sha256 SCHEMA_HASH = + Sha256.of("fake-integration-event-schema".getBytes(StandardCharsets.UTF_8)); + + private final List> drafts = new ArrayList<>(); + + @Override + public ValidatedIntegrationEvent encode(IntegrationEventDraft draft) { + drafts.add(draft); + byte[] envelope = draft.toString().getBytes(StandardCharsets.UTF_8); + String partitionKey = + HexFormat.of() + .formatHex( + Sha256.of(draft.aggregate().aggregateId().getBytes(StandardCharsets.UTF_8)) + .bytes()); + return new ValidatedIntegrationEvent( + draft.eventId(), + draft.contractId(), + 1, + draft.payloadVersion(), + draft.destinationId(), + draft.aggregate(), + draft.order(), + draft.occurredAt(), + draft.correlationId(), + draft.causationId(), + partitionKey, + partitionKey.getBytes(StandardCharsets.US_ASCII), + envelope, + "application/json", + SCHEMA_HASH, + Sha256.of(envelope), + SCHEMA_HASH, + SCHEMA_HASH, + "fake-catalog", + "fake-binding"); + } + + /** Every draft encoded so far, in order. */ + public List> drafts() { + return List.copyOf(drafts); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java index 9ca43dac..73c6292c 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java @@ -1,9 +1,9 @@ package dev.caskeleton.application.outbox.testkit; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.outbox.ClaimedOutboxEvent; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.OutboxCompletion; -import dev.caskeleton.application.outbox.OutboxEvent; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; import dev.caskeleton.application.outbox.OutboxStorePort; @@ -26,7 +26,7 @@ import java.util.Set; * *

    Not final so a test can override one operation to inject a storage failure. */ -public class InMemoryOutboxStore implements OutboxStorePort, LegacyOutboxAppendPort { +public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { private static final Set CLAIMABLE = Set.of(OutboxEventStatus.PENDING, OutboxEventStatus.FAILED, OutboxEventStatus.IN_FLIGHT); @@ -37,19 +37,8 @@ public class InMemoryOutboxStore implements OutboxStorePort, LegacyOutboxAppendP private final List dead = new ArrayList<>(); @Override - public void append(NewOutboxEvent event) { - add( - new OutboxEvent( - event.eventId(), - event.eventType(), - event.aggregateId(), - event.payload(), - event.occurredAt(), - event.correlationId(), - event.idempotencyKey(), - OutboxEventStatus.PENDING, - 0), - 0); + public void append(ValidatedIntegrationEvent event) { + add(event, 0); } /** @@ -59,16 +48,22 @@ public class InMemoryOutboxStore implements OutboxStorePort, LegacyOutboxAppendP * @param claimedAs the event as the next claim returns it; its attempt count is the count after * that claim and must be at least 1 */ - public void addClaimable(OutboxEvent claimedAs) { + public void addClaimable(ClaimedOutboxEvent claimedAs) { if (claimedAs.attemptCount() < 1) { throw new IllegalArgumentException("a claimed event has made at least one attempt"); } - add(claimedAs, claimedAs.attemptCount() - 1); + add(claimedAs.event(), claimedAs.attemptCount() - 1); } - private void add(OutboxEvent event, int attemptsSoFar) { - if (rows.putIfAbsent(event.eventId(), new Row(event, attemptsSoFar)) != null) { - throw new IllegalStateException("duplicate outbox eventId " + event.eventId()); + /** Every event appended and still held, in append order. */ + public List appended() { + return rows.values().stream().map(row -> row.event).toList(); + } + + private void add(ValidatedIntegrationEvent event, int attemptsSoFar) { + String eventId = event.eventId().value(); + if (rows.putIfAbsent(eventId, new Row(event, attemptsSoFar)) != null) { + throw new IllegalStateException("duplicate outbox eventId " + eventId); } } @@ -88,7 +83,11 @@ public class InMemoryOutboxStore implements OutboxStorePort, LegacyOutboxAppendP row.nextAttemptAt = now.plus(inFlightTimeout); row.leaseOwner = owner; row.leaseToken++; - leases.add(new OutboxLease(row.claimed(), owner, row.leaseToken)); + leases.add( + new OutboxLease( + new ClaimedOutboxEvent(row.event, row.status, row.attemptCount), + owner, + row.leaseToken)); } return leases; } @@ -153,7 +152,7 @@ public class InMemoryOutboxStore implements OutboxStorePort, LegacyOutboxAppendP for (Row row : rows.values()) { if (row.status != OutboxEventStatus.PUBLISHED) { long age = Duration.between(row.event.occurredAt(), now).toSeconds(); - ages.merge(row.event.eventType(), age, Math::max); + ages.merge(row.event.contractId().value(), age, Math::max); } } return ages; @@ -195,30 +194,17 @@ public class InMemoryOutboxStore implements OutboxStorePort, LegacyOutboxAppendP } private static final class Row { - private final OutboxEvent event; + private final ValidatedIntegrationEvent event; private OutboxEventStatus status = OutboxEventStatus.PENDING; private int attemptCount; private Instant nextAttemptAt; private String leaseOwner; private long leaseToken; - private Row(OutboxEvent event, int attemptCount) { + private Row(ValidatedIntegrationEvent event, int attemptCount) { this.event = event; this.attemptCount = attemptCount; this.nextAttemptAt = event.occurredAt(); } - - private OutboxEvent claimed() { - return new OutboxEvent( - event.eventId(), - event.eventType(), - event.aggregateId(), - event.payload(), - event.occurredAt(), - event.correlationId(), - event.idempotencyKey(), - status, - attemptCount); - } } } diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/LegacyOutboxAppendContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAppendContract.java similarity index 57% rename from src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/LegacyOutboxAppendContract.java rename to src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAppendContract.java index 0842b578..df8488cc 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/LegacyOutboxAppendContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAppendContract.java @@ -1,7 +1,6 @@ package dev.caskeleton.application.outbox.testkit; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.util.Objects; @@ -9,15 +8,16 @@ import java.util.UUID; import java.util.function.Predicate; /** - * Provider-neutral contract kit for the compatibility outbox append boundary. + * Provider-neutral contract kit for the outbox append boundary: an append belongs to the caller's + * write transaction, so it commits and rolls back with it. * - *

    The contract is intentionally expressed only in application-owned types. A persistence adapter - * supplies its transaction port, append port, and a probe that can observe whether the event became - * durable. No Spring, JPA, SQL, or provider type is part of this fixture. + *

    The contract is expressed only in application-owned types. A persistence adapter supplies its + * transaction port, append port, and a probe that can observe whether the event became durable. No + * Spring, JPA, SQL, or provider type is part of this fixture. */ -public final class LegacyOutboxAppendContract { +public final class OutboxAppendContract { - private LegacyOutboxAppendContract() {} + private OutboxAppendContract() {} /** * Verifies that an append performed inside a caller-owned write transaction disappears when that @@ -25,16 +25,16 @@ public final class LegacyOutboxAppendContract { */ public static void verifyRollbackRemovesEvent( TransactionPort transactions, - LegacyOutboxAppendPort append, + OutboxAppendPort append, Predicate eventExists, Clock clock) { requireInputs(transactions, append, eventExists, clock); - String eventId = "legacy-outbox-contract-rollback-" + UUID.randomUUID(); + String eventId = "outbox-contract-rollback-" + UUID.randomUUID(); try { transactions.inWrite( () -> { - append.append(event(eventId, "rollback", clock)); + append.append(OutboxEvents.event(eventId, clock.instant())); throw new ExpectedRollback(); }); throw new AssertionError("write transaction swallowed the contract rollback signal"); @@ -44,46 +44,34 @@ public final class LegacyOutboxAppendContract { if (eventExists.test(eventId)) { throw new AssertionError( - "legacy outbox append survived caller transaction rollback for event " + eventId); + "outbox append survived caller transaction rollback for event " + eventId); } } /** Verifies that an append becomes durable when the caller-owned write transaction commits. */ public static void verifyCommitPersistsEvent( TransactionPort transactions, - LegacyOutboxAppendPort append, + OutboxAppendPort append, Predicate eventExists, Clock clock) { requireInputs(transactions, append, eventExists, clock); - String eventId = "legacy-outbox-contract-commit-" + UUID.randomUUID(); + String eventId = "outbox-contract-commit-" + UUID.randomUUID(); transactions.inWrite( () -> { - append.append(event(eventId, "commit", clock)); + append.append(OutboxEvents.event(eventId, clock.instant())); return null; }); if (!eventExists.test(eventId)) { throw new AssertionError( - "legacy outbox append was not durable after caller transaction commit for event " - + eventId); + "outbox append was not durable after caller transaction commit for event " + eventId); } } - private static NewOutboxEvent event(String eventId, String scenario, Clock clock) { - return new NewOutboxEvent( - eventId, - "LegacyOutboxContractEvent", - "aggregate-" + eventId, - "{\"scenario\":\"" + scenario + "\"}", - clock.instant(), - "correlation-" + eventId, - eventId); - } - private static void requireInputs( TransactionPort transactions, - LegacyOutboxAppendPort append, + OutboxAppendPort append, Predicate eventExists, Clock clock) { Objects.requireNonNull(transactions, "transactions"); diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxEvents.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxEvents.java new file mode 100644 index 00000000..824bcd90 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxEvents.java @@ -0,0 +1,75 @@ +package dev.caskeleton.application.outbox.testkit; + +import dev.caskeleton.application.messaging.contract.ContractId; +import dev.caskeleton.application.messaging.contract.LogicalDestinationId; +import dev.caskeleton.application.messaging.contract.Sha256; +import dev.caskeleton.application.messaging.event.AggregateIdentity; +import dev.caskeleton.application.messaging.event.AggregateOrder; +import dev.caskeleton.application.messaging.event.EventId; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.outbox.ClaimedOutboxEvent; +import dev.caskeleton.application.outbox.OutboxEventStatus; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Optional; + +/** + * Validated integration events for outbox tests. + * + *

    Built directly rather than through an encoder: an outbox test is about where a row goes, not + * how its bytes were rendered, and the value type still checks every invariant a real event has — + * the envelope hash in particular is the SHA-256 of the envelope bytes. + */ +public final class OutboxEvents { + + /** The contract every fixture event carries. */ + public static final String CONTRACT_ID = "testkit.outbox-event"; + + private static final Sha256 SCHEMA_HASH = + Sha256.of("testkit-outbox-event-schema".getBytes(StandardCharsets.UTF_8)); + + private OutboxEvents() {} + + /** An event of aggregate {@code aggregate-} at sequence 1. */ + public static ValidatedIntegrationEvent event(String eventId, Instant occurredAt) { + return event(eventId, "aggregate-" + eventId, 1, occurredAt); + } + + /** An event of the given aggregate at the given sequence. */ + public static ValidatedIntegrationEvent event( + String eventId, String aggregateId, long sequence, Instant occurredAt) { + byte[] envelope = + ("{\"eventId\":\"" + eventId + "\",\"aggregateId\":\"" + aggregateId + "\"}") + .getBytes(StandardCharsets.UTF_8); + String partitionKey = + HexFormat.of().formatHex(Sha256.of(aggregateId.getBytes(StandardCharsets.UTF_8)).bytes()); + return new ValidatedIntegrationEvent( + new EventId(eventId), + new ContractId(CONTRACT_ID), + 1, + 1, + new LogicalDestinationId("testkit-events"), + new AggregateIdentity("default", "testkit", aggregateId), + new AggregateOrder(sequence, 0), + occurredAt, + "correlation-" + eventId, + Optional.empty(), + partitionKey, + partitionKey.getBytes(StandardCharsets.US_ASCII), + envelope, + "application/json", + SCHEMA_HASH, + Sha256.of(envelope), + SCHEMA_HASH, + SCHEMA_HASH, + "testkit-catalog", + "testkit-binding"); + } + + /** The event as a claim returns it after {@code attemptCount} attempts. */ + public static ClaimedOutboxEvent claimed(String eventId, Instant occurredAt, int attemptCount) { + return new ClaimedOutboxEvent( + event(eventId, occurredAt), OutboxEventStatus.IN_FLIGHT, attemptCount); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java index 5f5d29bc..6deb761b 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java @@ -2,8 +2,7 @@ package dev.caskeleton.application.outbox.testkit; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.OutboxBackoffPolicy; import dev.caskeleton.application.outbox.OutboxCompletion; import dev.caskeleton.application.outbox.OutboxEventStatus; @@ -47,7 +46,7 @@ public abstract class OutboxLeaseFencingContract { protected abstract OutboxStorePort store(); - protected abstract LegacyOutboxAppendPort append(); + protected abstract OutboxAppendPort append(); protected abstract TransactionPort transactions(); @@ -161,16 +160,7 @@ public abstract class OutboxLeaseFencingContract { transactions() .inWrite( () -> { - append() - .append( - new NewOutboxEvent( - eventId, - "LeaseFencingContractEvent", - "aggregate-" + eventId, - "{\"scenario\":\"" + scenario + "\"}", - CLAIMED_AT.minusSeconds(1), - "correlation-" + eventId, - eventId)); + append().append(OutboxEvents.event(eventId, CLAIMED_AT.minusSeconds(1))); return null; }); return eventId; diff --git a/src/composition/idempotency/README.md b/src/composition/idempotency/README.md new file mode 100644 index 00000000..e16f4f53 --- /dev/null +++ b/src/composition/idempotency/README.md @@ -0,0 +1,93 @@ +# composition:idempotency — 요청 멱등성 executor 조립 + +- Module ID: `composition-idempotency` +- Gradle path: `:composition:idempotency` +- Package: `dev.caskeleton.composition.idempotency` +- 테스트: `./gradlew :composition:idempotency:test --console=plain` + +## 제공하는 것 + +선택한 provider의 저장소 위에 `IdempotencyExecutor`를 하나 만든다. KEYED use case는 +application-core의 `IdempotencyExecutor`만 받는다. + +``` +composition:idempotency + ├─ IdempotencyAutoConfiguration provider != disabled 일 때만: 설정 바인딩 + executor 하나 + ├─ IdempotencySettings 수명 정책(lease·replay TTL·retention·codec·revision), strict 바인딩 + └─ config/module-defaults/idempotency.yml (설정 기본값, support 로더가 읽음) +``` + +- 저장소는 포트(`IdempotencyStorePort`)다. Redis는 `adapter:outbound:cache-redis`, PostgreSQL은 + `adapter:outbound:persistence-jpa`가 `ca-skeleton.capabilities.idempotency.provider`에 따라 하나를 + 기여한다. 선택한 provider의 저장소가 정확히 하나가 아니면(0개: 모듈이 없거나 꺼짐, 2개: 다른 + 곳이 하나 더 등록) 기동이 개수와 함께 실패한다. +- 켜기와 끄기: 모듈이 있어도 `provider=disabled`(기본)면 아무것도 바인딩하거나 만들지 않는다. +- 설정 바인딩은 `StrictSettingsBinder`다. 같은 prefix 아래 Redis 저장소가 자기 키(`key-version`, + `command-timeout`)를 두므로 그 두 키만 빼고 엄격하게 본다. 수명 정책 키를 잘못 쓰면 기본값이 + 조용히 쓰이는 대신 기동이 실패한다. +- app-bootstrap과 sample-portfolio가 같은 한 줄을 쓴다. 예전의 sample 복사본 + (`SampleIdempotencyConfig`, 상한 검증 없이 `Binder`로 읽고 저장소를 하나로 가정)은 삭제했다. + +## 추가할 한 줄 + +```groovy +// app-bootstrap/build.gradle (sample-portfolio/build.gradle 도 같다) +runtimeOnly project(':composition:idempotency') // 요청 멱등성 executor +``` + +기본 조립에 있다. provider가 `disabled`면 꺼져 있으므로 저장소 모듈 없이도 안전하다. 이 줄을 지우면 +executor, 설정 기본값이 함께 빠진다(그때 KEYED use case는 executor를 받지 못해 기동이 실패한다). + +## 필요한 env 키 + +전체 목록과 타입은 `docs/registries/env-keys.yaml`의 `APP_IDEMPOTENCY_*` 행이 SSOT다. + +| 언제 | 키 | +| --- | --- | +| 켤 때 | `APP_IDEMPOTENCY_PROVIDER` (`redis` 또는 `postgresql`), 그리고 그 provider 모듈의 줄과 env | +| 조정할 때 | `APP_IDEMPOTENCY_PROCESSING_LEASE`(≤1h), `APP_IDEMPOTENCY_TTL`(≤72h), `APP_IDEMPOTENCY_FAILURE_RETENTION`(≤30d) | + +## 설계 결정 참조 (app-bootstrap에서 옮김) + +이 모듈의 코드는 2026-09-28에 app-bootstrap `autoconfigure/idempotency`에서 옮겨 왔다(소유자 결정 3). 아래 근거는 그때의 기록이다. + +### IdempotencyAutoConfiguration +- **`IdempotencyExecutor`를 여기서 한 번만 만든다.** provider 모듈은 `IdempotencyStorePort`만 + 내놓는다 — `redis`는 `cache-redis`의 `RedisIdempotencyConfig`, `postgresql`은 `persistence-jpa`의 + `PostgreSqlIdempotencyStoreConfig`. lease·replay TTL·retention·codec id·policy revision 은 어느 + store 든 같은 정책이라 `IdempotencySettings` 하나에서 읽는다. executor 를 application-core 밖에서 + 만드는 이유는 이 설정을 `application-core`가 직접 읽으면 안 되기 때문이다. +- **store 가 정확히 하나가 아니면 기동을 거부한다.** 0개는 provider 모듈이 runtime classpath 에 + 없거나 스위치가 꺼진 경우, 2개는 다른 무언가가 store 를 등록한 경우다. 둘 다 빈 누락 오류나 엉뚱한 + store 로 요청을 처리하는 대신 개수를 담은 startup 실패로 드러난다. +- `provider=disabled`(기본)면 executor 빈 자체가 없다. `jdbc` 값과 V1 조립(`IdempotencyConfig`, + `config/idempotency.yml`)은 삭제됐다. +- `postgresql` provider 는 PostgreSQL data source 가 아니면 기동을 거부한다. `bootRunH2` 에서는 + `disabled` 나 `redis` 를 쓴다. + +### IdempotencySettings +- `ca-skeleton.capabilities.idempotency` 에 바인딩되는 유일한 설정 record 다(값은 + `config/module-defaults/idempotency.yml`). + + | 키 | env | 기본값 | 상한 | + | --- | --- | --- | --- | + | `provider` | `APP_IDEMPOTENCY_PROVIDER` | `disabled` | `disabled` \| `redis` \| `postgresql` | + | `processing-lease` | `APP_IDEMPOTENCY_PROCESSING_LEASE` | 30s | 1h | + | `replay-ttl` | `APP_IDEMPOTENCY_TTL` | 24h | 72h | + | `failure-retention` | `APP_IDEMPOTENCY_FAILURE_RETENTION` | 24h | 30d | + | `response-codec-id` | — | `json-v2` | 1–64자 | + | `policy-revision` | — | 2 | 양수 | + | `reaper-interval` | — | 10m | 양수 | + + Redis store 튜닝값 `key-version`, `command-timeout`(`APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT`)도 + 같은 prefix 아래 있지만 lifecycle 정책이 아니라서 이 record 에 두지 않고 `cache-redis`가 읽는다. +- **상한 검사는 컴팩트 생성자에서 fail-fast 로 던진다.** `Duration`의 상한은 JSR-303(`@Valid`) + 애너테이션으로 표현할 수 없어 생성자에서 직접 검증한다. 검증을 느슨하게 두면 과도하게 긴 TTL 이 + 저장소를 조용히 부풀리고 멱등성 키 추측 공격의 유효 시간 창을 넓히기 때문에, 부팅 시점에 즉시 + 실패시키는 쪽을 택했다. +- **replay TTL 상한(72h) / 기본값(24h)을 바꿀 때는 보안 베이스라인의 JWT 키 회전 겹침(overlap) + 윈도와 반드시 함께 검토해야 한다.** 멱등성 레코드의 수명이 키 회전 겹침 윈도(현재 24h)보다 길면, + 가명화(pseudonym) 기준이 회전된 principal 에 대해 레코드가 재생(replay)될 수 있다. 이 불변식을 + 강제하는 CI 게이트는 security-operational-baseline 쪽에 위임돼 있다. +- **`reaper-interval`은 전용 환경변수가 없다.** reaper 실행 주기는 비밀이나 배포별 값이 아니라 순수 + 운영 튜닝 값이다. reaper 는 provider 가 `postgresql` 일 때만 돈다. diff --git a/src/composition/idempotency/build.gradle b/src/composition/idempotency/build.gradle new file mode 100644 index 00000000..17053ed3 --- /dev/null +++ b/src/composition/idempotency/build.gradle @@ -0,0 +1,35 @@ +plugins { + id 'ca.spring-library' + id 'ca.spring-config' +} + +// The request-idempotency composition, selected by one line in a composition root: +// +// runtimeOnly project(':composition:idempotency') +// +// It builds the one IdempotencyExecutor over whichever IdempotencyStorePort the selected provider +// contributes (Redis from cache-redis, PostgreSQL from persistence-jpa), and ships the lifecycle +// settings (config/module-defaults/idempotency.yml). It names no provider module: the store is a +// port. app-bootstrap and sample-portfolio take the same line, so the executor is built one way. +// +// Not a composition root: it composes one capability and does not run. Same shape as +// :composition:notification-platform. +dependencies { + implementation project(':application-core') + // StrictSettingsBinder and the typed startup failures. + implementation project(':adapter:outbound:support') + + implementation 'org.springframework.boot:spring-boot-autoconfigure' + implementation 'org.springframework:spring-context' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + // The executor tests drive the port owner's shared fake store. + testImplementation testFixtures(project(':application-core')) + // IdempotencyAutoConfigurationTest composes the real PostgreSQL provider configuration, so a + // selection that stops reaching it shows up here. Test scope only: nothing in main names it. + testRuntimeOnly project(':adapter:outbound:persistence-jpa') + testImplementation 'org.springframework:spring-jdbc' + testImplementation 'org.mockito:mockito-core' + // IdempotencyModuleDefaultsTest reads the shipped file through the loader that serves it. + testRuntimeOnly 'org.yaml:snakeyaml' +} diff --git a/src/composition/idempotency/gradle.lockfile b/src/composition/idempotency/gradle.lockfile new file mode 100644 index 00000000..3669792f --- /dev/null +++ b/src/composition/idempotency/gradle.lockfile @@ -0,0 +1,199 @@ +# 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=testCompileClasspath +ch.qos.logback:logback-classic:1.5.38=testCompileClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-core:2.21.5=testRuntimeClasspath +com.fasterxml.jackson.core:jackson-databind:2.21.5=testRuntimeClasspath +com.fasterxml.jackson:jackson-bom:2.21.5=testRuntimeClasspath +com.fasterxml:classmate:1.7.3=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=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.h2database:h2:2.4.240=testRuntimeClasspath +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=testRuntimeClasspath +com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath +com.zaxxer:HikariCP:7.0.2=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-core:1.16.7=testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.projectreactor:reactor-core:3.8.7=testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=testCompileClasspath,testRuntimeClasspath +jakarta.inject:jakarta.inject-api:2.0.1=testRuntimeClasspath +jakarta.persistence:jakarta.persistence-api:3.2.0=testRuntimeClasspath +jakarta.transaction:jakarta.transaction-api:2.0.1=testRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=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.logstash.logback:logstash-logback-encoder:8.0=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,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=spotbugs,testCompileClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-core:2.25.5=spotbugs +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=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=testRuntimeClasspath +org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath +org.checkerframework:checker-qual:3.55.1=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=testRuntimeClasspath +org.flywaydb:flyway-core:11.14.1=testRuntimeClasspath +org.flywaydb:flyway-database-postgresql:11.14.1=testRuntimeClasspath +org.glassfish.jaxb:jaxb-core:4.0.9=testRuntimeClasspath +org.glassfish.jaxb:jaxb-runtime:4.0.9=testRuntimeClasspath +org.glassfish.jaxb:txw2:4.0.9=testRuntimeClasspath +org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=testRuntimeClasspath +org.hibernate.models:hibernate-models:1.0.1=testRuntimeClasspath +org.hibernate.orm:hibernate-core:7.2.24.Final=testRuntimeClasspath +org.javassist:javassist:3.28.0-GA=checkstyle +org.jboss.logging:jboss-logging:3.6.3.Final=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.latencyutils:LatencyUtils:2.0.3=testRuntimeClasspath +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=testCompileClasspath +org.osgi:org.osgi.annotation.versioning:1.1.2=testCompileClasspath +org.osgi:org.osgi.resource:1.0.0=testCompileClasspath +org.osgi:org.osgi.service.serviceloader:1.0.0=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.postgresql:postgresql:42.7.13=testRuntimeClasspath +org.reactivestreams:reactive-streams:1.0.4=testRuntimeClasspath +org.reflections:reflections:0.10.2=checkstyle +org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath +org.slf4j:jul-to-slf4j:2.0.18=testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=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-configuration-processor:4.0.8=annotationProcessor +org.springframework.boot:spring-boot-data-commons:4.0.8=testRuntimeClasspath +org.springframework.boot:spring-boot-data-jpa:4.0.8=testRuntimeClasspath +org.springframework.boot:spring-boot-flyway:4.0.8=testRuntimeClasspath +org.springframework.boot:spring-boot-hibernate:4.0.8=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=testRuntimeClasspath +org.springframework.boot:spring-boot-jpa:4.0.8=testRuntimeClasspath +org.springframework.boot:spring-boot-persistence:4.0.8=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=testRuntimeClasspath +org.springframework.boot:spring-boot-starter-data-jpa:4.0.8=testRuntimeClasspath +org.springframework.boot:spring-boot-starter-flyway:4.0.8=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=testRuntimeClasspath +org.springframework.boot:spring-boot-starter-logging:4.0.8=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=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=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=testRuntimeClasspath +org.springframework.data:spring-data-jpa:4.0.7=testRuntimeClasspath +org.springframework.integration:spring-integration-core:7.0.6=testRuntimeClasspath +org.springframework.integration:spring-integration-jdbc:7.0.6=testRuntimeClasspath +org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-aspects:7.0.9=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=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-messaging:7.0.9=testRuntimeClasspath +org.springframework:spring-orm:7.0.9=testRuntimeClasspath +org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-tx:7.0.9=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=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/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java b/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfiguration.java similarity index 70% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java rename to src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfiguration.java index 8ef7a06f..abf9a85d 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java +++ b/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfiguration.java @@ -1,14 +1,15 @@ -package dev.caskeleton.bootstrap.autoconfigure.idempotency; +package dev.caskeleton.composition.idempotency; import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import dev.caskeleton.application.idempotency.IdempotencyExecutor; import dev.caskeleton.application.idempotency.IdempotencyStorePort; import java.util.List; +import java.util.Locale; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; +import org.springframework.core.env.Environment; /** * Assembles the request-idempotency executor, once, for whichever provider is selected. @@ -18,28 +19,37 @@ import org.springframework.context.annotation.Bean; * conditional on {@code ca-skeleton.capabilities.idempotency.provider}. The lifecycle policy — * lease, replay TTL, retention, codec id, policy revision — is the same whichever store holds the * records, so it lives in one {@link IdempotencySettings} record and the executor is built here - * from it. + * from it. Every composition root that serves idempotent requests takes this module rather than a + * copy of it: the application and the sample build the same executor from the same checks. * *

    A selected provider must yield exactly one store. None means the provider's module is not on * the runtime classpath or its switch is off; two means something else registered one (a scan-found * stereotype, a hand-written bean). Either is refused at startup with the count, rather than - * surfacing as an unsatisfied dependency or as requests served by the wrong store. + * surfacing as an unsatisfied dependency or as requests served by the wrong store. The store is + * looked up when the executor is built, not when this class is evaluated, so no ordering against + * the provider modules is needed. + * + *

    {@code provider=disabled} (the default) is the off switch: nothing is bound or built. */ @AutoConfiguration -@EnableConfigurationProperties(IdempotencySettings.class) -public class IdempotencyProviderSelectionConfig { +@ConditionalOnExpression( + "!'${ca-skeleton.capabilities.idempotency.provider:disabled}'.trim()" + + ".equalsIgnoreCase('disabled')") +public class IdempotencyAutoConfiguration { + + @Bean + IdempotencySettings idempotencySettings(Environment environment) { + return IdempotencySettings.bind(environment); + } @Bean - @ConditionalOnExpression( - "!'${ca-skeleton.capabilities.idempotency.provider:disabled}'.trim()" - + ".equalsIgnoreCase('disabled')") IdempotencyExecutor idempotencyExecutor( ObjectProvider stores, IdempotencySettings settings) { List found = stores.orderedStream().toList(); if (found.size() != 1) { throw StartupFailures.requiredAdapterDisabled( "ca-skeleton.capabilities.idempotency.provider=" - + settings.provider().name().toLowerCase(java.util.Locale.ROOT) + + settings.provider().name().toLowerCase(Locale.ROOT) + " needs exactly one IdempotencyStorePort, but found " + found.size() + ". Add the provider's module to the runtime classpath and enable it, and make sure" diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettings.java b/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java similarity index 80% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettings.java rename to src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java index 42c58498..d4de570c 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettings.java +++ b/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java @@ -1,8 +1,10 @@ -package dev.caskeleton.bootstrap.autoconfigure.idempotency; +package dev.caskeleton.composition.idempotency; +import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder; import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import java.time.Duration; -import org.springframework.boot.context.properties.ConfigurationProperties; +import java.util.Set; +import org.springframework.core.env.Environment; /** * The one settings record for request idempotency, bound at {@code @@ -11,7 +13,9 @@ import org.springframework.boot.context.properties.ConfigurationProperties; * first request. * *

    The Redis store reads its own two knobs ({@code key-version}, {@code command-timeout}) under - * the same prefix; they are store tuning, not lifecycle policy, so they are not repeated here. + * the same prefix; they are store tuning, not lifecycle policy, so they are not repeated here. The + * binding is strict for everything else under the prefix: a misspelt lifecycle key fails startup + * instead of leaving its default silently in force. * * @param provider which store is composed: {@code disabled}, {@code redis} or {@code postgresql} * @param processingLease how long one attempt holds a claim before another may take it over @@ -21,7 +25,6 @@ import org.springframework.boot.context.properties.ConfigurationProperties; * @param policyRevision replay policy revision written into and compared on each record * @param reaperInterval how often the PostgreSQL provider purges expired rows */ -@ConfigurationProperties(prefix = IdempotencySettings.PREFIX) public record IdempotencySettings( Provider provider, Duration processingLease, @@ -32,6 +35,10 @@ public record IdempotencySettings( Duration reaperInterval) { static final String PREFIX = "ca-skeleton.capabilities.idempotency"; + + /** Keys under the prefix that the Redis store binds for itself. */ + static final Set STORE_OWNED_KEYS = Set.of("key-version", "command-timeout"); + private static final Duration MAX_PROCESSING_LEASE = Duration.ofHours(1); private static final Duration MAX_REPLAY_TTL = Duration.ofDays(3); private static final Duration MAX_FAILURE_RETENTION = Duration.ofDays(30); @@ -66,6 +73,17 @@ public record IdempotencySettings( } } + /** + * Binds the prefix strictly, leaving the store's own keys to the store. + * + * @param environment the environment to bind from + * @return the validated settings + */ + public static IdempotencySettings bind(Environment environment) { + return StrictSettingsBinder.bindExcept( + environment, PREFIX, IdempotencySettings.class, STORE_OWNED_KEYS); + } + private static Duration orDefault(Duration value, Duration fallback) { return value == null ? fallback : value; } diff --git a/src/composition/idempotency/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/composition/idempotency/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..764eee66 --- /dev/null +++ b/src/composition/idempotency/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +dev.caskeleton.composition.idempotency.IdempotencyAutoConfiguration diff --git a/src/app-bootstrap/src/main/resources/config/capabilities.yml b/src/composition/idempotency/src/main/resources/config/module-defaults/idempotency.yml similarity index 55% rename from src/app-bootstrap/src/main/resources/config/capabilities.yml rename to src/composition/idempotency/src/main/resources/config/module-defaults/idempotency.yml index 78c505c0..553c42b1 100644 --- a/src/app-bootstrap/src/main/resources/config/capabilities.yml +++ b/src/composition/idempotency/src/main/resources/config/module-defaults/idempotency.yml @@ -1,13 +1,15 @@ -# 멱등성 제공자 선택과 수명 정책. Redis 역할(cache/rate-limit/lease)과 Redis 저장소 튜닝은 -# cache-redis 모듈이 config/module-defaults/cache-redis.yml 로 가져온다. +# 멱등성 제공자 선택과 수명 정책의 설정 기본값. Redis 역할(cache/rate-limit/lease)과 Redis 저장소 +# 튜닝(key-version, command-timeout)은 cache-redis 모듈이 config/module-defaults/cache-redis.yml 로 +# 가져온다. # -# application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다 -# 낮고 application-{profile}.yml 보다도 낮으므로, 배포별 오버라이드는 그대로 우선한다. +# adapter:outbound:support 의 ModuleDefaultsEnvironmentPostProcessor 가 읽는다. 우선순위는 가장 낮아서 +# application*.yml, 환경 변수, 시스템 속성이 항상 이긴다. 이 모듈을 빌드에서 빼면 이 파일도 함께 +# 빠진다. ca-skeleton: capabilities: idempotency: # disabled | redis | postgresql. Exactly one store; the executor is built once over it from - # the lifecycle keys below, whichever provider is selected. + # the lifecycle keys below, whichever provider is selected. disabled binds and builds nothing. provider: ${APP_IDEMPOTENCY_PROVIDER:disabled} # Lifecycle policy (IdempotencySettings), the same whichever provider holds the records. processing-lease: ${APP_IDEMPOTENCY_PROCESSING_LEASE:30s} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderCompositionTest.java b/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfigurationTest.java similarity index 88% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderCompositionTest.java rename to src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfigurationTest.java index ca678deb..e0fc7a28 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderCompositionTest.java +++ b/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfigurationTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.idempotency; +package dev.caskeleton.composition.idempotency; import static org.assertj.core.api.Assertions.assertThat; @@ -6,10 +6,12 @@ import dev.caskeleton.application.idempotency.IdempotencyExecutor; import dev.caskeleton.application.idempotency.IdempotencyStorePort; import dev.caskeleton.application.idempotency.testkit.InMemoryIdempotencyStore; import java.time.Clock; +import java.util.Arrays; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcOperations; @@ -23,14 +25,14 @@ import org.springframework.jdbc.core.JdbcOperations; * store. The component scan of the PostgreSQL store package is included in every case, pinning the * old regression where a stereotype on the store registered it under every selection. */ -class IdempotencyProviderCompositionTest { +class IdempotencyAutoConfigurationTest { private static final String POSTGRESQL_STORE_CONFIG = "dev.caskeleton.adapter.outbound.persistence.autoconfigure.PostgreSqlIdempotencyStoreConfig"; private final ApplicationContextRunner runner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(IdempotencyProviderSelectionConfig.class)) + .withConfiguration(AutoConfigurations.of(IdempotencyAutoConfiguration.class)) .withUserConfiguration(ScannedPersistence.class, postgreSqlStoreConfig()) .withBean(JdbcOperations.class, () -> org.mockito.Mockito.mock(JdbcOperations.class)) .withBean(Clock.class, Clock::systemUTC) @@ -101,6 +103,14 @@ class IdempotencyProviderCompositionTest { assertThat(context).hasFailed().getFailure().hasStackTraceContaining("found 2")); } + @Test + void theIdempotencyCompositionDoesNotOwnTheApplicationClock() { + assertThat(Arrays.stream(IdempotencyAutoConfiguration.class.getDeclaredMethods())) + .noneMatch( + method -> + method.getReturnType() == Clock.class && method.isAnnotationPresent(Bean.class)); + } + private static Class postgreSqlStoreConfig() { try { return Class.forName(POSTGRESQL_STORE_CONFIG); @@ -111,6 +121,6 @@ class IdempotencyProviderCompositionTest { /** What the composition root once scanned, narrowed to the store package. */ @Configuration(proxyBeanMethods = false) - @ComponentScan("dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency") + @ComponentScan("dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql") static class ScannedPersistence {} } diff --git a/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencyModuleDefaultsTest.java b/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencyModuleDefaultsTest.java new file mode 100644 index 00000000..ef3679e9 --- /dev/null +++ b/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencyModuleDefaultsTest.java @@ -0,0 +1,64 @@ +package dev.caskeleton.composition.idempotency; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.support.startup.ModuleDefaultsEnvironmentPostProcessor; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.context.annotation.ImportCandidates; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.StandardEnvironment; + +/** + * The module arrives with its own registration and settings, and a deployment's value beats them. + */ +class IdempotencyModuleDefaultsTest { + + @Test + void theModuleRegistersItsAutoConfiguration() { + assertThat(ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader())) + .contains(IdempotencyAutoConfiguration.class.getName()); + } + + @Test + void theShippedDefaultsLeaveIdempotencyOff() { + // when + StandardEnvironment environment = processed(Map.of()); + + // then + assertThat(environment.getProperty("ca-skeleton.capabilities.idempotency.provider")) + .isEqualTo("disabled"); + } + + @Test + void theEnvironmentVariableSelectsTheProviderThroughTheShippedPlaceholder() { + // when + StandardEnvironment environment = processed(Map.of("APP_IDEMPOTENCY_PROVIDER", "postgresql")); + + // then + assertThat(environment.getProperty("ca-skeleton.capabilities.idempotency.provider")) + .isEqualTo("postgresql"); + } + + @Test + void theShippedLifecycleKeysBindWithoutAStrayKey() { + // given + StandardEnvironment environment = processed(Map.of("APP_IDEMPOTENCY_PROVIDER", "redis")); + + // when + IdempotencySettings settings = IdempotencySettings.bind(environment); + + // then + assertThat(settings.responseCodecId()).isEqualTo("json-v2"); + } + + private static StandardEnvironment processed(Map deployment) { + StandardEnvironment environment = new StandardEnvironment(); + environment.getPropertySources().addFirst(new MapPropertySource("deployment", deployment)); + new ModuleDefaultsEnvironmentPostProcessor() + .postProcessEnvironment(environment, new SpringApplication()); + return environment; + } +} diff --git a/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencySettingsTest.java b/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencySettingsTest.java new file mode 100644 index 00000000..770dc6ff --- /dev/null +++ b/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencySettingsTest.java @@ -0,0 +1,189 @@ +package dev.caskeleton.composition.idempotency; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; +import java.time.Duration; +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.springframework.boot.context.properties.bind.BindException; +import org.springframework.mock.env.MockEnvironment; + +class IdempotencySettingsTest { + + private static final String PREFIX = "ca-skeleton.capabilities.idempotency."; + + @Test + void absentLifecycleKeysBindToTheDocumentedDefaults() { + // given + MockEnvironment environment = new MockEnvironment().withProperty(PREFIX + "provider", "redis"); + + // when + IdempotencySettings settings = IdempotencySettings.bind(environment); + + // then + assertThat(settings) + .usingRecursiveComparison() + .isEqualTo( + new IdempotencySettings( + IdempotencySettings.Provider.REDIS, + Duration.ofSeconds(30), + Duration.ofHours(24), + Duration.ofHours(24), + "json-v2", + 2, + Duration.ofMinutes(10))); + } + + @Test + void kebabCaseKeysBindEveryField() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty(PREFIX + "provider", "postgresql") + .withProperty(PREFIX + "processing-lease", "45s") + .withProperty(PREFIX + "replay-ttl", "72h") + .withProperty(PREFIX + "failure-retention", "2h") + .withProperty(PREFIX + "response-codec-id", "json-v3") + .withProperty(PREFIX + "policy-revision", "3") + .withProperty(PREFIX + "reaper-interval", "1m"); + + // when + IdempotencySettings settings = IdempotencySettings.bind(environment); + + // then + assertThat(settings) + .usingRecursiveComparison() + .isEqualTo( + new IdempotencySettings( + IdempotencySettings.Provider.POSTGRESQL, + Duration.ofSeconds(45), + Duration.ofHours(72), + Duration.ofHours(2), + "json-v3", + 3, + Duration.ofMinutes(1))); + } + + @Test + void anUnknownProviderFailsBinding() { + // given + MockEnvironment environment = new MockEnvironment().withProperty(PREFIX + "provider", "jdbc"); + + // when + Throwable thrown = catchThrowable(() -> IdempotencySettings.bind(environment)); + + // then + assertThat(thrown) + .isInstanceOf(BindException.class) + .hasStackTraceContaining("ca-skeleton.capabilities.idempotency.provider"); + } + + /** + * A misspelt lifecycle key used to bind to nothing and leave the default in force: {@code + * replay-tll=1h} ran with a 24-hour replay window. + */ + @Test + void aMisspeltLifecycleKeyFailsBindingInsteadOfLeavingTheDefaultInForce() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty(PREFIX + "provider", "redis") + .withProperty(PREFIX + "replay-tll", "1h"); + + // when + Throwable thrown = catchThrowable(() -> IdempotencySettings.bind(environment)); + + // then + assertThat(thrown).isInstanceOf(BindException.class).hasStackTraceContaining("replay-tll"); + } + + @Test + void theRedisStoresOwnKeysUnderTheSharedPrefixAreLeftToTheStore() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty(PREFIX + "provider", "redis") + .withProperty(PREFIX + "key-version", "1") + .withProperty(PREFIX + "command-timeout", "200ms"); + + // when + IdempotencySettings settings = IdempotencySettings.bind(environment); + + // then + assertThat(settings.provider()).isEqualTo(IdempotencySettings.Provider.REDIS); + } + + @ParameterizedTest + @DisplayName("an out-of-range duration is refused with its key and bound") + @CsvSource({ + "PT0S, PT24H, PT24H, PT10M, processing-lease must be positive", + "PT61M, PT24H, PT24H, PT10M, processing-lease must be at most PT1H", + "PT30S, PT73H, PT24H, PT10M, replay-ttl must be at most PT72H", + "PT30S, -PT1H, PT24H, PT10M, replay-ttl must be positive", + "PT30S, PT24H, P31D, PT10M, failure-retention must be at most PT720H", + "PT30S, PT24H, PT24H, PT0S, reaper-interval must be positive" + }) + void outOfRangeDurationIsRefused( + Duration lease, Duration replay, Duration retention, Duration reaper, String message) { + // when + Throwable thrown = + catchThrowable( + () -> + new IdempotencySettings( + IdempotencySettings.Provider.REDIS, + lease, + replay, + retention, + null, + null, + reaper)); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + StartupFailureException.class, + e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) + .hasMessageContaining("ca-skeleton.capabilities.idempotency." + message); + } + + @ParameterizedTest + @CsvSource({"'', response-codec-id must contain 1-64 characters", "' ', response-codec-id"}) + void blankCodecIdIsRefused(String codecId, String message) { + // when + Throwable thrown = + catchThrowable( + () -> + new IdempotencySettings( + IdempotencySettings.Provider.REDIS, null, null, null, codecId, null, null)); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + StartupFailureException.class, + e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) + .hasMessageContaining("ca-skeleton.capabilities.idempotency." + message); + } + + @Test + void nonPositivePolicyRevisionIsRefused() { + // when + Throwable thrown = + catchThrowable( + () -> + new IdempotencySettings( + IdempotencySettings.Provider.REDIS, null, null, null, null, 0, null)); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + StartupFailureException.class, + e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) + .hasMessageContaining( + "ca-skeleton.capabilities.idempotency.policy-revision must be positive"); + } +} diff --git a/src/composition/outbox-relay/README.md b/src/composition/outbox-relay/README.md new file mode 100644 index 00000000..1e7d97a5 --- /dev/null +++ b/src/composition/outbox-relay/README.md @@ -0,0 +1,137 @@ +# composition:outbox-relay — transactional outbox relay 조립 + +- Module ID: `composition-outbox-relay` +- Gradle path: `:composition:outbox-relay` +- Package: `dev.caskeleton.composition.outbox` +- 테스트: `./gradlew :composition:outbox-relay:test --console=plain` + +## 제공하는 것 + +outbox에 쌓인 event를 broker로 내보내는 relay를 조립한다. use case는 이 모듈을 부르지 않는다 — +use case는 `OutboxAppendPort`로 append만 하고, relay가 나머지를 한다. + +``` +composition:outbox-relay + └─ OutboxRelayAutoConfiguration ca-skeleton.outbox.enabled=true + OutboxStorePort 가 있을 때만 + ├─ OutboxSettings ca-skeleton.outbox.* strict 바인딩(오타는 기동 실패) + ├─ OutboxRelayScheduler relay-enabled=true + OutboxMessagePublishPort 가 있을 때만, + │ PublishPendingOutboxEventsUseCase 를 fixed-delay 로 구동 + ├─ OutboxMetrics outbox.pending.size / outbox.publisher.lag / published.total + └─ OutboxLeaderElectionToken SKIP LOCKED 가 리더 선출이라는 표시(로직 없음) +``` + +- 조립 순서: `PersistenceJpaAutoConfiguration`(store)과 `MessagingBridgeRootAutoConfiguration`(발행 + 포트) 뒤에 온다(`afterName`, 문자열이라 컴파일 의존이 없다). 둘 다 포트라서 이 모듈은 어떤 모듈 + 타입도 이름으로 부르지 않는다. +- 발행 포트가 없으면 스케줄러를 만들지 않는다. messaging을 고르지 않은 배포는 PENDING row를 그대로 + 둔다(대역 publisher로 DEAD까지 소진하지 않는다). +- persistence-jpa 안이 아니라 여기 있는 이유: driven adapter는 use case를 만들거나 부르지 않는다 + (ArchUnit `PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES`). +- 설정 기본값: `ca-skeleton.outbox.*`의 기본값은 store를 가진 persistence-jpa가 + `config/module-defaults/persistence-jpa.yml`로 싣는다(store와 reaper도 `enabled`, + `reaper-interval`, `published-retention`을 읽는다). 키의 선언과 검증은 이 모듈의 `OutboxSettings` + 하나다. + +## 추가할 한 줄 + +```groovy +// app-bootstrap/build.gradle +runtimeOnly project(':composition:outbox-relay') // outbox relay +``` + +기본 조립에 있다. store(persistence-jpa + `APP_OUTBOX_ENABLED=true`)가 없으면 아무것도 만들지 않으므로 +안전하다. 이 줄을 지우면 relay, metrics가 함께 빠진다(append한 row는 발행되지 않고 남는다). + +## 필요한 env 키 + +전체 목록과 타입은 `docs/registries/env-keys.yaml`의 `APP_OUTBOX_*` 행이 SSOT다. + +| 언제 | 키 | +| --- | --- | +| 항상 | persistence-jpa 줄과 그 연결 env, `APP_OUTBOX_ENABLED=true` | +| relay를 돌릴 때 | `APP_OUTBOX_RELAY_ENABLED=true`, 그리고 발행 capability(`adapter:outbound:messaging-kafka` 줄과 `APP_MESSAGING_PRODUCER_ID`, `APP_MESSAGING_KAFKA_BROKERS`) | + +poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `ca-skeleton.outbox.*` 기본값으로 +동작한다. + +## 설계 결정 참조 (app-bootstrap에서 옮김) + +이 모듈의 코드는 2026-09-28에 app-bootstrap `autoconfigure/outbox`에서 옮겨 왔다(소유자 결정 3). 아래 근거는 그때의 기록이다. `OutboxSettings`는 이제 strict 바인딩이고 `enabled`도 선언한다. + +### OutboxRelayAutoConfiguration +- **릴레이 use case 를 `@Service`가 아니라 이 모듈에서 수동 조립한다.** + `PublishPendingOutboxEventsUseCase`는 `batchSize`와 `inFlightTimeout` 같은 설정값을 생성자로 받아야 + 하는데, `application-core`는 설정(`OutboxSettings`)을 직접 읽으면 안 된다. 그래서 설정을 볼 수 있는 + 조립 모듈(`OutboxRelayAutoConfiguration`)이 값을 꺼내 use case 를 손으로 만들어 넘긴다. use case 클래스의 + `@UseCaseCapability` 애너테이션은 와이어링 방식과 무관하게 유지된다(ArchUnit 이 강제). +- **이 모듈은 failure reporter를 구현하지 않고 주입만 한다.** messaging bridge의 `MessagingConfig`가 + 정확히 하나의 `OutboxRelayFailureReportPort` 구현을 만들고, `OutboxRelayAutoConfiguration`은 이를 + relay 생성자에 전달한다. +- **릴레이 use case 를 독립 컨텍스트 빈으로 등록하지 않는다.** 만약 빈으로 올리면 `adapter-web`의 + `MethodSecurityConfig` 메서드 보안 pointcut(`@RequiresPermission`)이 이 타입을 CGLIB 프록시로 + 감싼다. 그런데 use case 가 `final` 클래스라 프록시 생성 자체가 실패하고, 설령 된다 해도 스케줄러 + 스레드에는 `Authentication`이 없어 매 릴레이 틱이 fail-closed 로 거부된다. 그래서 빈으로 올리지 + 않고, `outbox:relay` 권한 확인은 스케줄러 컨텍스트에서 관례로 둔다. +- **`outboxRelayScheduler` 빈은 `ca-skeleton.outbox.relay-enabled=true`일 때만 만든다(기본 + false).** 키가 없으면 꺼진 것으로 본다. 모듈 기본값(`persistence-jpa.yml`의 + `${APP_OUTBOX_RELAY_ENABLED:false}`), `@ConditionalOnProperty`, `OutboxSettings`의 null 기본값이 + 모두 false로 같다. +- **store와 publisher가 있을 때만 켜진다.** 설정 전체는 `OutboxStorePort` 빈(persistence-jpa를 고르고 + outbox를 켰을 때만 존재)을, 스케줄러는 추가로 `OutboxMessagePublishPort` 빈(messaging bridge가 + 제공)을 조건으로 건다. 두 auto-configuration 뒤에 오도록 `afterName`으로 순서를 명시한다. 발행할 + 곳이 없으면 스케줄러가 없으므로 PENDING 행이 그대로 남는다 — 예전에는 + `DisabledMessagingSentinelAutoConfiguration`의 대역 publisher가 모든 claim을 실패시켜 DEAD로 + 소진했고, 그걸 막으려고 `OutboxRelayBrokerRequirementValidator`가 있었다. 둘 다 삭제했다. + messaging bridge의 `MessagingConfig`도 outbox 대역 publisher를 만들지 않는다. bridge가 있고 + 켜져 있는데 canonical `IntegrationEventPublishPort`가 없으면(producer id 없음) 기동을 거부한다. +- **왜 persistence-jpa가 아니라 여기인가.** 릴레이는 use case를 조립해 타이머로 구동하는 합성 + 코드다. driven adapter인 persistence-jpa가 use case를 만들거나 호출하면 + `PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES` 규칙 위반이다. 모듈 타입은 하나도 이름으로 + 부르지 않고 포트만 쓰므로, persistence-jpa 한 줄을 지우면 릴레이도 함께 꺼진다. +- **`outboxLeaderElection` 토큰 빈은 outbox capability 안에서 조건 없이 등록한다.** SKIP LOCKED 는 + 멀티 인스턴스 전역 스위치와 무관하게 outbox relay 자체의 리더십/claim 메커니즘이라, outbox가 켜진 + 상태에서 별도 하위 토글로 끌 수 있게 만들지 않는다. 이 토큰은 outbox 조립의 자기 설명용 marker이지 + `APP_MULTI_INSTANCE_ENABLED`의 전역 필수 빈이 아니다. +- **`outboxMetrics` 빈은 `MeterRegistry`가 없을 때 no-op 이다.** Actuator 가 클래스패스에 없는 + 환경에서도 와이어링이 깨지지 않도록 `ObjectProvider`로 레지스트리를 선택적으로 주입한다. + +### OutboxLeaderElectionToken +- **로직이 전혀 없는 마커(documentation artifact) 빈이다.** 이 타입은 동작을 갖지 않고, Spring + 컨텍스트에 존재한다는 사실만으로 멀티 인스턴스 조정 빈 요구사항을 충족시킨다. +- **리더 선출을 외부 코디네이터 없이 PostgreSQL `FOR UPDATE SKIP LOCKED`로 구현한다는 것을 + 표현한다.** claim 쿼리에 SKIP LOCKED 를 걸면 각 릴레이 인스턴스가 서로 겹치지 않는(disjoint) 행 + 집합을 가져가므로, 별도 코디네이터 없이도 "각 인스턴스가 자기 파티션의 리더" 형태로 리더 선출 + 의미가 성립한다. + +### OutboxMetrics +- **`MeterRegistry`가 없으면 모든 메트릭 연산이 no-op 이다.** Actuator 가 없는 환경에서도 릴레이가 + 정상 동작해야 하므로, 생성자에서 `ObjectProvider`로 레지스트리를 조회해 없으면 게이지도 만들지 + 않고 기록도 건너뛴다. +- **카운터는 PUBLISHED/FAILED/DEAD 만 집계하고 IN_FLIGHT 는 제외한다.** IN_FLIGHT 는 릴레이 사이클의 + 종료 결과(terminal outcome)가 아니라 처리 중을 나타내는 일시적 상태라 카운터 outcome 으로 의미가 + 없다. +- **MultiGauge 갱신 시 `overwrite=true`로 등록한다.** 매 스케줄러 틱마다 store 를 다시 조회해 + 게이지를 갱신하는데, 이전 틱에 있었지만 지금은 사라진 event type 같은 오래된 time-series 태그를 + 덮어써 제거하기 위함이다. + +### OutboxRelayScheduler +- **합성 루트가 직접 등록하고 컴포넌트 스캔하지 않는다.** 이 스케줄러가 구동하는 릴레이 use case 가 + (위 OutboxRelayAutoConfiguration 사유로) 일부러 빈이 아니기 때문에, 그 use case 를 조립하는 `OutboxRelayAutoConfiguration`가 + 스케줄러 등록까지 같이 소유한다. +- **릴레이 사이클에서 발생하는 예상치 못한 예외를 잡아 ERROR 로 로깅만 하고 삼킨다.** 스케줄러 + 스레드가 죽으면 릴레이가 조용히 멈추므로, 다음 틱을 위해 스레드를 살려둔다. 단, 개별 발행 실패 + (FAILED/DEAD 전이)는 relay가 persisted transition 성공 뒤 typed reporter로 canonical ERROR를 + 요청하고 결과에 반영하므로 이 catch 블록까지 오지 않는다 — 여기서 삼키는 것은 어디까지나 + "예상치 못한" 예외다. +- **스케줄링은 `OutboxRelayAutoConfiguration`가 직접 켜고(`@EnableScheduling`) fixed-delay 를 쓴다.** 예전에는 JDBC + idempotency 설정만 스케줄링을 켰기 때문에 다른 provider 를 고르면 릴레이가 조립만 되고 돌지 + 않았다. fixed-delay 는 릴레이 실행 시간과 무관하게 사이클이 겹치지 않도록(non-overlapping) 보장한다. + +### OutboxSettings +- **튜닝 값(poll 주기·batch·timeout·보존)은 코드 리터럴 기본값을 쓰고 env placeholder 를 두지 않는다.** 신규 env key 를 + 추가하지 않는다는 결정에 따라, 값이 없으면 컴팩트 생성자에서 직접 기본값(예: `PT5S`, `20`, + `PT5M`, `PT10M`, `P7D`)을 채운다. +- **`reaper-interval`과 `published-retention`은 `adapter-persistence`의 `OutboxReaper`도 property + 문자열로 읽는다.** 두 모듈이 같은 키를 공유하지만, 이 settings record 가 일곱 값 전체를 선언 + 하는 단일 지점(single place) 역할을 한다. strict 바인딩이라 prefix 아래 모르는 키는 기동 실패다. 기본값 yml(`ca-skeleton.outbox.*`)은 store를 가진 + persistence-jpa 모듈이 `config/module-defaults/persistence-jpa.yml`로 가져온다. diff --git a/src/composition/outbox-relay/build.gradle b/src/composition/outbox-relay/build.gradle new file mode 100644 index 00000000..c051a819 --- /dev/null +++ b/src/composition/outbox-relay/build.gradle @@ -0,0 +1,35 @@ +plugins { + id 'ca.spring-library' + id 'ca.spring-config' +} + +// The transactional outbox relay composition, selected by one line in a composition root: +// +// runtimeOnly project(':composition:outbox-relay') +// +// It builds the relay use case over the outbox store and the publish port and drives it on a +// timer, with its metrics. It names no module: the store (persistence-jpa, with +// ca-skeleton.outbox.enabled) and the publish port (the messaging bridge) are ports, and the relay +// assembles nothing until both exist. It lives here rather than in persistence-jpa because a +// driven adapter must not construct or call a use case. +// +// Not a composition root: it composes one capability and does not run. Same shape as +// :composition:notification-platform. +dependencies { + implementation project(':application-core') + // StrictSettingsBinder, the typed startup failures and the runtime warning fields. + implementation project(':adapter:outbound:support') + + implementation 'org.springframework.boot:spring-boot-autoconfigure' + implementation 'org.springframework:spring-context' + implementation 'io.micrometer:micrometer-core' + implementation 'org.slf4j:slf4j-api' + // The relay's failure log writes its fields with StructuredArguments (see support's build.gradle: + // a module that logs structured fields declares the encoder itself). + implementation libs.logstash.logback.encoder + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.mockito:mockito-core' + testImplementation 'ch.qos.logback:logback-classic' + testRuntimeOnly 'org.yaml:snakeyaml' +} diff --git a/src/composition/outbox-relay/gradle.lockfile b/src/composition/outbox-relay/gradle.lockfile new file mode 100644 index 00000000..8b95823a --- /dev/null +++ b/src/composition/outbox-relay/gradle.lockfile @@ -0,0 +1,157 @@ +# 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=testCompileClasspath +ch.qos.logback:logback-classic:1.5.38=testCompileClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=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.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=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.vaadin.external.google:android-json:0.0.20131108.vaadin1=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-core: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=testCompileClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=testCompileClasspath,testRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=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.logstash.logback:logstash-logback-encoder:8.0=compileClasspath,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 +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=spotbugs,testCompileClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-core:2.25.5=spotbugs +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=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.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.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath +org.javassist:javassist:3.28.0-GA=checkstyle +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.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath +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=testCompileClasspath +org.osgi:org.osgi.annotation.versioning:1.1.2=testCompileClasspath +org.osgi:org.osgi.resource:1.0.0=testCompileClasspath +org.osgi:org.osgi.service.serviceloader:1.0.0=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=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-configuration-processor:4.0.8=annotationProcessor +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-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.8=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-logging:4.0.8=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=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-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:spring-aop: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-test:7.0.9=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=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/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxLeaderElectionToken.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxLeaderElectionToken.java similarity index 92% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxLeaderElectionToken.java rename to src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxLeaderElectionToken.java index 35c167d1..4e4e9887 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxLeaderElectionToken.java +++ b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxLeaderElectionToken.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.outbox; +package dev.caskeleton.composition.outbox; /** * Marker bean: presence in the context satisfies the multi-instance coordination requirement (no diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxMetrics.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxMetrics.java similarity index 98% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxMetrics.java rename to src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxMetrics.java index e81d07d6..c81cc154 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxMetrics.java +++ b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxMetrics.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.outbox; +package dev.caskeleton.composition.outbox; import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings; import dev.caskeleton.application.outbox.OutboxEventStatus; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfig.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java similarity index 73% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfig.java rename to src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java index 1da4038d..a78b53cd 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfig.java +++ b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java @@ -1,7 +1,5 @@ -package dev.caskeleton.bootstrap.autoconfigure.outbox; +package dev.caskeleton.composition.outbox; -import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; -import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; import dev.caskeleton.application.outbox.OutboxBackoffPolicy; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort; @@ -17,18 +15,19 @@ import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; +import org.springframework.core.env.Environment; import org.springframework.scheduling.annotation.EnableScheduling; /** * The transactional outbox relay: assembles the relay use case manually and registers the leader - * election token, metrics, and scheduler. See README for the design rationale. + * election token, metrics, and scheduler. * - *

    Application composition, like the idempotency executor: it wires application-core ports into a - * use case and drives it on a timer, which is why it stays in the composition root rather than in - * the persistence module — a driven adapter must not construct or call use cases. It names no - * module type, only ports, and it turns itself on from what the selected modules provide. + *

    Application composition: it wires application-core ports into a use case and drives it on a + * timer, which is why it is a composition module rather than part of the persistence module — a + * driven adapter must not construct or call use cases ({@code + * PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES}). It names no module type, only ports, and + * turns itself on from what the selected modules provide. * *

    {@code ca-skeleton.outbox.enabled} is the capability switch; {@code relay-enabled} only * decides whether the scheduler runs. The store port exists only while the persistence-jpa module @@ -48,20 +47,15 @@ import org.springframework.scheduling.annotation.EnableScheduling; }) @ConditionalOnProperty(prefix = "ca-skeleton.outbox", name = "enabled", havingValue = "true") @ConditionalOnBean(OutboxStorePort.class) -@EnableConfigurationProperties(OutboxSettings.class) // The relay is @Scheduled. It must switch scheduling on itself rather than rely on another // capability (the PostgreSQL idempotency provider also does), or the relay runs only by accident. @EnableScheduling -public class OutboxConfig { +public class OutboxRelayAutoConfiguration { - /** Requires the canonical messaging bridge whenever canonical outbox transport is enabled. */ + /** Bound only once the capability is on, and strictly: see {@link OutboxSettings}. */ @Bean - public OutboxCanonicalTransportRequirementValidator outboxCanonicalTransportRequirementValidator( - OutboxSettings settings, - ObjectProvider canonicalPublisherProvider, - ObjectProvider encoderProvider) { - return new OutboxCanonicalTransportRequirementValidator( - settings, canonicalPublisherProvider.getIfAvailable(), encoderProvider.getIfAvailable()); + public OutboxSettings outboxSettings(Environment environment) { + return OutboxSettings.bind(environment); } /** Relay use case is assembled manually here (not a bean) from {@link OutboxSettings} values. */ @@ -99,10 +93,7 @@ public class OutboxConfig { return new SplittableRandom(); } - /** - * Registered unconditionally so the SKIP LOCKED leadership mechanism is always present. See - * README for the design rationale. - */ + /** Registered unconditionally so the SKIP LOCKED leadership mechanism is always present. */ @Bean(name = "outboxLeaderElection") public OutboxLeaderElectionToken outboxLeaderElection() { return new OutboxLeaderElectionToken(); diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelayScheduler.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayScheduler.java similarity index 97% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelayScheduler.java rename to src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayScheduler.java index 5b9d80a5..1a4c58c6 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelayScheduler.java +++ b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayScheduler.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.outbox; +package dev.caskeleton.composition.outbox; import static net.logstash.logback.argument.StructuredArguments.kv; diff --git a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxSettings.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxSettings.java new file mode 100644 index 00000000..d438286e --- /dev/null +++ b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxSettings.java @@ -0,0 +1,74 @@ +package dev.caskeleton.composition.outbox; + +import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; +import java.time.Duration; +import org.springframework.core.env.Environment; + +/** + * The outbox capability's settings, bound strictly from {@code ca-skeleton.outbox.*}: every key + * under the prefix is one of these, so a misspelt one fails startup instead of leaving a default in + * force. The persistence module reads {@code enabled}, {@code reaper-interval} and {@code + * published-retention} too — the store and its reaper — but the keys are declared and validated + * once, here. + * + * @param enabled the capability switch; the relay composition only exists while it is true + * @param relayEnabled whether the relay scheduler runs; default {@code false} + * @param pollInterval how often the relay polls the outbox table; default {@code PT5S} + * @param batchSize maximum rows claimed per relay cycle; default {@code 20} + * @param inFlightTimeout in-flight orphan visibility window; default {@code PT5M} + * @param reaperInterval how often the reaper purges old PUBLISHED rows; default {@code PT10M} + * @param publishedRetention how long PUBLISHED rows are kept before the reaper deletes them; + * default {@code P7D} + */ +public record OutboxSettings( + Boolean enabled, + Boolean relayEnabled, + Duration pollInterval, + Integer batchSize, + Duration inFlightTimeout, + Duration reaperInterval, + Duration publishedRetention) { + + static final String PREFIX = "ca-skeleton.outbox"; + + public OutboxSettings { + if (enabled == null) { + enabled = false; + } + if (relayEnabled == null) { + // Off unless asked for, like the module default and the scheduler condition: three sources + // answering "is the relay on" differently is how a missing key started it. + relayEnabled = false; + } + pollInterval = positive("poll-interval", pollInterval, Duration.ofSeconds(5)); + if (batchSize == null) { + batchSize = 20; + } else if (batchSize <= 0) { + throw StartupFailures.envValidation(PREFIX + ".batch-size must be > 0, was " + batchSize); + } + inFlightTimeout = positive("in-flight-timeout", inFlightTimeout, Duration.ofMinutes(5)); + reaperInterval = positive("reaper-interval", reaperInterval, Duration.ofMinutes(10)); + publishedRetention = positive("published-retention", publishedRetention, Duration.ofDays(7)); + } + + /** + * Binds the prefix strictly. + * + * @param environment the environment to bind from + * @return the validated settings + */ + public static OutboxSettings bind(Environment environment) { + return StrictSettingsBinder.bind(environment, PREFIX, OutboxSettings.class); + } + + private static Duration positive(String key, Duration value, Duration fallback) { + if (value == null) { + return fallback; + } + if (value.isZero() || value.isNegative()) { + throw StartupFailures.envValidation(PREFIX + "." + key + " must be positive, was " + value); + } + return value; + } +} diff --git a/src/composition/outbox-relay/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/composition/outbox-relay/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..4af38d57 --- /dev/null +++ b/src/composition/outbox-relay/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +dev.caskeleton.composition.outbox.OutboxRelayAutoConfiguration diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfigTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfigurationTest.java similarity index 67% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfigTest.java rename to src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfigurationTest.java index b2f50ef9..0ed99bc4 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfigTest.java +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfigurationTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.outbox; +package dev.caskeleton.composition.outbox; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -11,26 +11,51 @@ import java.lang.reflect.Proxy; import java.time.Clock; import java.util.random.RandomGenerator; import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.context.annotation.ImportCandidates; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.scheduling.config.TaskManagementConfigUtils; -class OutboxConfigTest { +class OutboxRelayAutoConfigurationTest { @Test void outboxRandomGeneratorIsAvailableInTheSlimJavaBaseRuntime() { - RandomGenerator random = new OutboxConfig().outboxRandomGenerator(); + RandomGenerator random = new OutboxRelayAutoConfiguration().outboxRandomGenerator(); assertThat(random.getClass().getModule().getName()).isEqualTo("java.base"); } + @Test + void theModuleRegistersItsAutoConfiguration() { + assertThat(ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader())) + .contains(OutboxRelayAutoConfiguration.class.getName()); + } + + /** + * The settings used to be a scanned {@code @ConfigurationProperties} record, which ignores keys + * it does not declare: {@code batch-sise=500} ran with 20. + */ + @Test + void aMisspeltOutboxKeyFailsStartupInsteadOfLeavingTheDefaultInForce() { + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class)) + .withBean(OutboxStorePort.class, OutboxRelayAutoConfigurationTest::unusedStore) + .withPropertyValues("ca-skeleton.outbox.enabled=true", "ca-skeleton.outbox.batch-sise=500") + .run( + context -> + assertThat(context) + .getFailure() + .hasStackTraceContaining("ca-skeleton.outbox.batch-sise")); + } + @Test void outboxCapabilityEnablesSchedulingWithIdempotencyDisabled() { // given ApplicationContextRunner runner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(OutboxConfig.class)) - .withBean(OutboxStorePort.class, OutboxConfigTest::unusedStore) + .withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class)) + .withBean(OutboxStorePort.class, OutboxRelayAutoConfigurationTest::unusedStore) .withPropertyValues( "ca-skeleton.outbox.enabled=true", "ca-skeleton.outbox.relay-enabled=false", @@ -47,8 +72,8 @@ class OutboxConfigTest { void theRelayRunsOnlyWhenSomethingCanPublishWhatItClaims() { ApplicationContextRunner relayOn = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(OutboxConfig.class)) - .withBean(OutboxStorePort.class, OutboxConfigTest::unusedStore) + .withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class)) + .withBean(OutboxStorePort.class, OutboxRelayAutoConfigurationTest::unusedStore) .withBean(OutboxRelayFailureReportPort.class, () -> report -> {}) .withBean(TransactionPort.class, () -> mock(TransactionPort.class)) .withBean(Clock.class, Clock::systemUTC) @@ -65,8 +90,8 @@ class OutboxConfigTest { @Test void withoutTheRelayKeyTheRelaySchedulerIsNotAssembled() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(OutboxConfig.class)) - .withBean(OutboxStorePort.class, OutboxConfigTest::unusedStore) + .withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class)) + .withBean(OutboxStorePort.class, OutboxRelayAutoConfigurationTest::unusedStore) .withBean(OutboxRelayFailureReportPort.class, () -> report -> {}) .withBean(TransactionPort.class, () -> mock(TransactionPort.class)) .withBean(Clock.class, Clock::systemUTC) @@ -82,7 +107,7 @@ class OutboxConfigTest { @Test void withoutTheRelationalStoreTheOutboxAssemblesNothing() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(OutboxConfig.class)) + .withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class)) .withPropertyValues("ca-skeleton.outbox.enabled=true") .run(context -> assertThat(context).doesNotHaveBean(OutboxMetrics.class)); } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelaySchedulerLoggingTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerLoggingTest.java similarity index 98% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelaySchedulerLoggingTest.java rename to src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerLoggingTest.java index fa682a0e..26de8226 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelaySchedulerLoggingTest.java +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerLoggingTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.outbox; +package dev.caskeleton.composition.outbox; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; diff --git a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxSettingsTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxSettingsTest.java new file mode 100644 index 00000000..07dede80 --- /dev/null +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxSettingsTest.java @@ -0,0 +1,102 @@ +package dev.caskeleton.composition.outbox; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; +import java.time.Duration; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.mock.env.MockEnvironment; + +/** Binding and validation of {@link OutboxSettings} (feature-domain-event-outbox-contract I11). */ +class OutboxSettingsTest { + + @Test + void absentValuesTakeTheDocumentedDefaults() { + // when + OutboxSettings settings = new OutboxSettings(null, null, null, null, null, null, null); + + // then + assertThat(settings) + .isEqualTo( + new OutboxSettings( + false, + false, + Duration.ofSeconds(5), + 20, + Duration.ofMinutes(5), + Duration.ofMinutes(10), + Duration.ofDays(7))); + } + + @Test + void kebabCaseKeysBindEveryField() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty("ca-skeleton.outbox.enabled", "true") + .withProperty("ca-skeleton.outbox.relay-enabled", "true") + .withProperty("ca-skeleton.outbox.poll-interval", "10s") + .withProperty("ca-skeleton.outbox.batch-size", "50") + .withProperty("ca-skeleton.outbox.in-flight-timeout", "2m") + .withProperty("ca-skeleton.outbox.reaper-interval", "1h") + .withProperty("ca-skeleton.outbox.published-retention", "14d"); + + // when + OutboxSettings settings = OutboxSettings.bind(environment); + + // then + assertThat(settings) + .isEqualTo( + new OutboxSettings( + true, + true, + Duration.ofSeconds(10), + 50, + Duration.ofMinutes(2), + Duration.ofHours(1), + Duration.ofDays(14))); + } + + @ParameterizedTest + @CsvSource({"0, batch-size must be > 0", "-1, batch-size must be > 0"}) + void aNonPositiveBatchSizeIsRefused(int batchSize, String message) { + // when + Throwable thrown = + catchThrowable(() -> new OutboxSettings(true, true, null, batchSize, null, null, null)); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + StartupFailureException.class, + e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) + .hasMessageContaining("ca-skeleton.outbox." + message); + } + + @ParameterizedTest + @CsvSource({ + "PT0S, PT5M, PT10M, P7D, poll-interval must be positive", + "PT5S, PT0S, PT10M, P7D, in-flight-timeout must be positive", + "PT5S, PT5M, PT0S, P7D, reaper-interval must be positive", + "PT5S, PT5M, -PT1M, P7D, reaper-interval must be positive", + "PT5S, PT5M, PT10M, PT0S, published-retention must be positive", + "PT5S, PT5M, PT10M, -PT1H, published-retention must be positive" + }) + void aNonPositiveDurationIsRefusedWithItsKey( + Duration poll, Duration inFlight, Duration reaper, Duration retention, String message) { + // when + Throwable thrown = + catchThrowable( + () -> new OutboxSettings(true, true, poll, null, inFlight, reaper, retention)); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + StartupFailureException.class, + e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) + .hasMessageContaining("ca-skeleton.outbox." + message); + } +} diff --git a/src/composition/service-runtime/README.md b/src/composition/service-runtime/README.md new file mode 100644 index 00000000..8c87931b --- /dev/null +++ b/src/composition/service-runtime/README.md @@ -0,0 +1,248 @@ +# composition:service-runtime — 모든 서비스가 받는 runtime 배선 + +- Module ID: `composition-service-runtime` +- Gradle path: `:composition:service-runtime` +- Package: `dev.caskeleton.composition.runtime` +- 테스트: `./gradlew :composition:service-runtime:test --console=plain` + +## 제공하는 것 + +capability와 무관하게 서비스 구성 루트 둘(app-bootstrap, sample-portfolio)이 모두 필요로 하는 +runtime 배선이다. 예전에는 app-bootstrap에 있었고 sample이 그 복사본을 들고 있었다. + +``` +composition:service-runtime + ├─ tracing/ TracingConfig(+ Tracer·SpanErrorRecorder·sampling gauge), TracingSettings, + │ TracingSampleRateResolver, TracingSamplingEnvironmentPostProcessor + ├─ metrics/ MetricsContractConfig(cardinality deny-list + SLO 분포 filter) + ├─ context/ DomainContextConfig + ├─ logging/ PseudonymizationConfig, PrivacySettings (user_principal HMAC 가명화) + └─ management/security/ ManagementSecurityConfig (actuator chain) +``` + +- 모두 이 모듈의 `AutoConfiguration.imports`로 등록된다(sampling bridge는 `spring.factories`의 + `EnvironmentPostProcessor`). 구성 루트의 component scan에 기대지 않는다. +- 설정 키는 옮기지 않았다: `ca-skeleton.tracing.*`, `ca-skeleton.privacy.*`. 값은 각 구성 루트의 `application.yml`/`config/observability.yml`에 있다. +- actuator chain은 servlet 웹 애플리케이션에서만 만들어지고, 구성 루트가 같은 이름 + `actuatorSecurityFilterChain`의 bean을 두면 물러난다. sample-portfolio는 공개 데모라 그렇게 + 모든 요청을 허용하는 자기 chain을 둔다. +- sample 복사본과의 차이 중 원본을 따른 것: 샘플 레이트는 `RuntimeEnvironment` 어휘(prod 0.01, + 그 밖 1.0)이고 `staging=0.10` 분기는 없다. 설정 검증 실패는 `IllegalStateException`이 아니라 + `StartupFailures.envValidation`이다. + +## 추가할 한 줄 + +```groovy +// app-bootstrap/build.gradle (sample-portfolio/build.gradle 도 같다) +runtimeOnly project(':composition:service-runtime') +``` + +기본 조립에 있다. 이 줄을 지우면 Tracer·SpanErrorRecorder·가명화 포트·DomainContextPropagator가 +빠지고, 그것을 주입받는 web adapter(`RequestLoggingFilter`)와 persistence audit이 기동에 실패한다. + +## 필요한 env 키 + +전체 목록과 타입은 `docs/registries/env-keys.yaml`이 SSOT다. + +| 언제 | 키 | +| --- | --- | +| 프로덕션 전 | `APP_PRIVACY_PSEUDONYMIZATION_SALT` (비면 dev sentinel로 경고 후 기동) | +| 조정할 때 | `APP_TRACING_SAMPLE_RATE`, `OTEL_EXPORTER_OTLP_ENDPOINT` | + +## 설계 결정 참조 (app-bootstrap에서 옮김) + +이 모듈의 코드는 2026-09-28에 app-bootstrap(`autoconfigure/tracing`, `concurrency`, `metrics`, +`management/security`, `logging/PseudonymizationConfig`, `settings/PrivacySettings`)에서 옮겨 왔다. +아래 근거는 그때의 기록이다. + +### tracing — 분산 트레이싱 wiring과 샘플링 정책 + +#### TracingConfig +- **컴포지션 루트에서 트레이싱을 조립한다.** 두 가지를 한다: (1) 시작 시 `tracing.sampling.rate` + 게이지 등록, (2) `SpanErrorRecorder` 빈 등록. +- **`SpanErrorRecorder` 빈은 `@ConditionalOnBean(Tracer.class)`가 아니라 `ObjectProvider`로 + 런타임 존재 여부를 직접 조회한다.** 이유: `@ConditionalOnBean`은 사용자 정의 `@Configuration`에서 + autoconfiguration 이 만드는 빈(여기서는 `Tracer`)을 조건으로 쓸 때 빈 등록 순서가 보장되지 않아 + 신뢰할 수 없기 때문이다. `Tracer`가 있으면 `MicrometerSpanErrorRecorder`를, 없으면 + `SpanErrorRecorder.NOOP`을 반환한다. +- **`@ConditionalOnMissingBean(SpanErrorRecorder.class)`를 붙여, 테스트 mock 이나 fork 가 자체 + `SpanErrorRecorder` 빈을 이미 등록한 경우 이 빈은 backoff 한다.** adapter-web 의 + `GlobalExceptionHandler`는 `ObjectProvider`로 `SpanErrorRecorder`를 조회하므로, 자기 자신의 NOOP + self-default 에서 여기서 등록한 실제 구현으로 자동 교체된다. +- **OTel/Micrometer tracer 런타임은 이 repo 에서 seam 이 활성 상태다.** `micrometer-tracing-bridge-otel` + + `opentelemetry-exporter-otlp`가 `app-bootstrap/build.gradle`에 실제로 wiring 되어 있다. 단, span + exporter 는 `OTEL_EXPORTER_OTLP_ENDPOINT`가 비어 있는 동안 꺼져 있고, 엔드포인트를 설정하면 + export 가 시작된다. +- **게이지 등록 시 active profile 은 `Environment.getActiveProfiles()`의 첫 번째 값을 쓴다.** 멀티 + 프로파일 배포에서는 맨 앞에 나열된 프로파일이 권위 있는 배포 환경이라는 규약이다. `MeterRegistry`가 + classpath 에 없으면(Actuator 미탑재) 게이지 등록은 조용히 no-op 이 된다. +- **`TracingSamplingRateGaugeRegistrar` record 는 등록된 active profile 과 resolved rate 를 노출하는 + 값 홀더다.** 정식 포트나 use case 가 아니라, 살아있는 `MeterRegistry` 없이도 테스트가 "무엇이 + 등록되었는지" 검사할 수 있게 하는 bootstrap 내부 전용 장치다. + +#### TracingSettings +- **`ca-skeleton.tracing.*` 바인딩 `@ConfigurationProperties` record.** 세 env 키가 들어온다: + `APP_TRACING_ENABLED` → `enabled`, `APP_TRACING_SAMPLE_RATE` → `sampleRate`, + `OTEL_EXPORTER_OTLP_ENDPOINT` → `exporter.otlpEndpoint`. +- **`sampleRate`가 blank 이면 숫자 검증을 건너뛴다.** blank 는 "값이 잘못됐다"가 아니라 "프로파일별 + 기본값에 위임하라"는 신호이기 때문이다. 실제 런타임별 기본값(prod=0.01, dev/local=1.0)은 `TracingSampleRateResolver`가 적용하고, + profile vocabulary 자체는 `RuntimeEnvironment`가 소유한다. resolved 된 값은 + `TracingSamplingEnvironmentPostProcessor`가 Spring Boot 네이티브 + `management.tracing.sampling.probability`로 브리지한다. +- **검증은 시작 시 fail-fast 다.** `sampleRate`가 non-blank 인데 [0.0, 1.0] float 이 아니면 시작이 + 실패하고, `otlpEndpoint`가 non-empty 인데 scheme 없는 잘못된 URL 이면 시작이 실패한다. `enabled`는 + Spring 바인딩이 `boolean` 타입을 강제하므로 추가 검증이 필요 없다. `otlpEndpoint`가 비어 있으면 + exporter off 상태(seam 기본값)이고, 이것이 정상 동작이므로 검증을 통과시킨다. +- **`sampleRateValue()`는 호출 전 `sampleRate().isBlank()` 확인이 caller 규약이다.** blank 인 상태로 + 호출하면 `IllegalStateException`을 던지는데, 이는 파싱 오류가 아니라 caller 규약 위반을 드러내기 + 위한 것이다. + +#### TracingSampleRateResolver +- **런타임별 트레이싱 샘플 정책을 적용한다.** prod=0.01(1%), dev/local=1.0(100%)이며, + 런타임 이름의 SSOT는 `RuntimeEnvironment`다. shipped runtime이 아닌 값은 1.0 안전값을 사용한다. `APP_TRACING_SAMPLE_RATE`가 non-blank 이고 [0,1] float 로 파싱되면 프로파일 기본값을 + override 한다. +- **Spring 의존성이 전혀 없는 순수 Java 로 작성했다.** 어떤 컨텍스트도 없이 단위 테스트할 수 있고, + `EnvironmentPostProcessor`(컨텍스트 생성 이전 단계)와 `TracingConfig`(빈 생성 단계) 양쪽에서 동일 + 로직을 재사용하기 위함이다. + +#### TracingSamplingRateGauge +- **`tracing.sampling.rate` 게이지를 등록한다.** metric 계약: type=gauge, tag=`profile`(prod/dev/local + 허용), value=resolved effective sample rate(double in [0.0, 1.0]). +- **deployable `RuntimeEnvironment`가 정확히 하나 해석될 때만 시리즈 하나를 방출한다.** + test/profileless/unknown 컨텍스트를 `local`로 가장하지 않으며, shipped app은 그보다 앞선 profile + validator에서 잘못된 런타임 환경을 거부한다. +- **`MeterRegistry`를 `ObjectProvider`로 조회하며, Actuator 미탑재로 빈이 없으면 등록을 조용히 + 건너뛴다.** 이는 `BackgroundJobMetrics` / `OutboxMetrics`의 선례를 그대로 따른다. + +#### TracingSamplingEnvironmentPostProcessor +- **resolved 된 유효 샘플 비율을 Spring Boot 네이티브 키 `management.tracing.sampling.probability`로 + 단일화(브리지)하는 `EnvironmentPostProcessor`다.** 이를 통해 "프로파일별 기본값 + env override"라는 + 우리 규약을 Spring Boot 의 기본 샘플링 메커니즘에 그대로 연결한다. +- **브리지 우선순위.** (1) 사용자가 `management.tracing.sampling.probability`를 이미 명시했으면 + 덮어쓰지 않고 그대로 둔다, (2) `ca-skeleton.tracing.sample-rate`가 non-blank 면 그 값 사용, (3) + blank 면 `TracingSampleRateResolver.defaultRateForProfile(...)`로 active profile 기본값 적용. +- **`META-INF/spring.factories`에 `org.springframework.boot.EnvironmentPostProcessor` 키로 등록된다.** + `EnvironmentPostProcessor`는 ApplicationContext 가 생성되기 전에 실행되므로 일반 빈이 아니라 + Spring Boot bootstrap factory 로 등록해야 한다. + +#### MicrometerSpanErrorRecorder +- **NOOP 을 대체하는 Micrometer/OTel 기반 실제 `SpanErrorRecorder`다.** 현재 span 에 예외와 + `error.code` 태그를 기록한다. 계약 이행: `Span.error(Throwable)` 호출(OTel bridge 를 통해 + `recordException` + span status ERROR 매핑), `span.tag("error.code", errorCode)`(ca-tmpl 레지스트리 + 속성명), null `error`는 방어적 no-op, 현재 span 이 없으면 no-op. +- **"sampled span 에만 스택트레이스 부착" 정책은 의도적으로 구현하지 않았다.** Micrometer Tracing + 추상화 레벨에서는 sampled 여부를 직접 제어할 수 없기 때문이다(`Span.isNoop()`은 OTel NOOP span + 여부일 뿐 sampling 여부가 아니다). 다만 OTel SDK 의 unsampled span 은 이미 no-op 으로 처리되므로 + 명시적 sampled-only 분기가 없어도 실제 성능 부담은 없다. + +--- + +### metrics — 메트릭 계약 MeterFilter 설치 + +#### MetricsCardinalityMeterFilter +- **금지 태그가 붙은 미터를 런타임에서 막는 방어 필터다.** 미터의 `Meter.Id`에 붙은 태그 키 중 + 하나라도 `ForbiddenMetricTags.FORBIDDEN`에 들어 있으면 그 미터를 `DENY`하고, 아니면 `NEUTRAL`을 + 반환한다. `user_id`, `request_id`, `raw_url`, `raw_query`, `raw_header_value`, `ip_address` 같은 + 고카디널리티(high-cardinality) 라벨 키는 고유 값마다 Prometheus 시계열을 하나씩 만들어 수백만 + 개로 폭증할 수 있어 차단한다. +- **이 필터는 카디널리티 계약의 런타임(runtime) 절반이다.** 정적(static) 절반은 레지스트리 계약 + 테스트(`MetricsAlertingContractTest`)가 담당한다 — 둘이 짝을 이뤄 심층 방어를 구성한다. +- **상태가 없어(stateless) 여러 레지스트리에 공유해도 안전하다.** public no-arg 생성자는 + `MetricsContractConfig.install()`이 직접 인스턴스화하기 위한 계약이다. + +#### MetricsContractConfig +- **`@PostConstruct`에서 `MeterFilter`들을 `MeterRegistry`에 직접 설치한다.** `@Bean MeterFilter`로 + 등록하지 않는 이유: 이 템플릿 클래스패스에는 `@Bean MeterFilter`를 자동 수집하는 Spring Boot + Actuator 자동설정(`MeterRegistryCustomizer`)이 없어서 `@Bean MeterFilter`는 그냥 동작하지 않는 + (inert) 죽은 빈이 되기 때문이다. `OutboundHttpResilienceConfig`에서 확립한 선례를 따른다. +- **설치 순서가 중요하다.** (1) `MetricsCardinalityMeterFilter`(deny-list)를 먼저 설치해 금지 태그가 + 붙은 미터가 분포 필터에 닿기 전에 거부되도록 하고, (2) 그다음 `MetricsDistributionMeterFilter` + (SLO 기반 히스토그램 설정)를 설치한다. +- **필터는 설치 이후 등록되는 미터에만 적용된다.** `@PostConstruct`는 Spring 빈 생명주기 중 애플리 + 케이션 코드가 어떤 미터든 등록하기 전에 실행되므로 모든 미터가 필터 적용 대상이 된다. +- **`MeterRegistry` 부재 시 no-op.** `ObjectProvider.getIfAvailable()`로 해석해 레지스트리 빈이 + 없으면(Actuator 미탑재) DEBUG 로그만 남기고 설치를 건너뛴다. +- **`install(MeterRegistry)`를 public static 으로 둔 이유.** 계약 테스트가 Spring 컨텍스트 없이 + `SimpleMeterRegistry`에 대해 직접 구동할 수 있게 하기 위함이다. + +#### MetricsDistributionMeterFilter +- **소유한(owned) 타이머 메트릭 5종에만 SLO 기반 히스토그램·백분위 설정을 적용한다.** 대상: + `http.server.requests`, `http.server.requests.latency`, `dependency.client.requests`, + `db.query.duration`, `jvm.gc.pause`. 이들은 `metrics.yaml`에서 이 브랜치가 소유하고 + `histogram_buckets: slo_driven`인 행이다. `resilience4j.circuitbreaker.calls`, + `hikaricp.connections.acquire`처럼 소비만 하고 소유하지 않는(consumed-but-not-owned) 행은 다른 + 브랜치 소유라 의도적으로 제외 — 덮어쓰면 안 된다. +- **히스토그램 전략은 두 축이다.** + - *인스턴스 간 집계 가능한 진실의 원천*: `percentilesHistogram(true)`(= `publishPercentileHistogram`)가 + `_bucket` 시계열을 생성하고, Prometheus 에서 `histogram_quantile()`로 인스턴스 간 집계할 수 있다. + 이것이 다중 인스턴스 배포의 정식 p50/p95/p99 다. + - *클라이언트 측 편의값(집계 불가)*: `percentiles(0.5, 0.9, 0.95, 0.99)`(= `publishPercentiles`)는 + 단일 인스턴스 가시성을 위한 사전 계산 분위 게이지를 제공한다. 이 값들은 인스턴스 간 평균을 내면 + 안 된다(통계적으로 틀림). 인스턴스 간 집계는 반드시 `histogram_quantile()`로 한다. +- **SLO 경계값 `100ms / 500ms / 1s / 5s`는 잠정 SLO 역산이며 외부 표준에서 유도한 값이 아니다.** + 정식 SLO 가 채택되면 재검토 대상이다. 함께 설정하는 `minimumExpectedValue=1ms`, + `maximumExpectedValue=10s`는 히스토그램 버킷의 관측 범위를 한정한다. +- **상태가 없어 여러 레지스트리에 공유해도 안전하고,** public no-arg 생성자는 + `MetricsContractConfig.install()`이 직접 인스턴스화하기 위한 계약이다. + +--- + +### concurrency — 도메인 컨텍스트 전파 전략 조립 + +#### DomainContextConfig +- **`DomainContextPropagator`를 빈으로 노출하고 `ThreadLocalDomainContextPropagator`를 직접 만든다.** + 제공하는 전략이 하나뿐이라 선택 설정(`strategy`)을 두지 않는다. 두 번째 전략이 생기면 그 구현과 + 둘 중 하나를 고르는 설정을 함께 추가한다(A-10c). use case 코드는 포트만 주입받으므로 어떤 전파 + 방식인지 모른다. + +--- + +### logging — user_principal 가명화 + +#### PseudonymizationConfig +- **`user_principal`(로그에 남는 사용자 식별자)를 전체 HMAC 방식으로 가명화한다.** + `UserPrincipalPseudonymizerPort`(application-core)를 HMAC-SHA-256 구현(adapter-identifier)에 + 바인딩하고, 솔트는 `PrivacySettings`에서 가져온다. 원본 식별자를 그대로 로그에 남기지 않으려는 + 개인정보 보호 결정이다. 실제 사용처는 `adapter-web`의 `RequestLoggingFilter`로, 보안 principal 이 + MDC/로그에 닿기 전에 이 포트로 가린다. +- **`@ConditionalOnMissingBean`으로 기본 구현을 둔다.** 이 템플릿을 포크한 프로젝트가 자기만의 + 가명화기(예: 향후 솔트 회전을 지원하는 구현)를 등록하면 이 기본 빈이 비켜주도록, 즉 기본값은 + 제공하되 교체를 막지 않도록 하기 위해서다. + +#### PrivacySettings +- **보안/감사 로그에서 `user_principal`을 가명화하는 데 쓰는 HMAC salt 를 보관한다.** + `ca-skeleton.privacy.*` 바인딩(원천 `APP_PRIVACY_PSEUDONYMIZATION_SALT`). 알고리즘은 HMAC-SHA-256 + + 90일 회전 salt 이고, 이 salt 는 `secret`-tier 값이라 prod 에서는 반드시 secret manager 에서 + 공급되어야 한다. +- **검증은 `LoggingSettings`와 일관되게 "warn-and-default"다.** blank salt 는 경고를 남기고, 명확히 + 표시된 dev sentinel(`__LOCAL_DEV_` 접두사)로 폴백해 local/test 실행이 절대 기동에 실패하지 않게 + 한다. +- **이 sentinel 을 prod 로 승격하는 것은 별도 계약이 독립적으로 + 차단한다** — prod 프로파일에서 `__LOCAL_DEV_` 값이면 시작이 실패한다. 그 게이트는 이 record 의 + 책임 밖이라 여기서 중복 강제하지 않는다. + +### management/security — 액추에이터 엔드포인트 보안 체인 + +#### ManagementSecurityConfig +- **`actuatorSecurityFilterChain`은 `@Order(0)`으로 메인 앱 체인(adapter-web `SecurityConfig`)보다 + 앞서 실행된다.** 그래서 액추에이터 엔드포인트에 매칭되는 요청은 앱 체인이 아니라 이 체인이 + 처리한다. 보안 매처는 `EndpointRequest.toAnyEndpoint()`로, 관리 포트의 `/actuator/**` 경로만 이 + 체인 범위에 든다. +- **접근 정책.** `health`, `info`, `prometheus`는 permit-all 이다. 자격 증명 없이 Kubernetes 프로브와 + Prometheus 스크레이프가 접근할 수 있어야 하고, 이 엔드포인트들은 민감 데이터를 노출하지 않기 + 때문이다(health 상세는 `never`). 나머지(`/actuator` 링크 등)는 모두 인증이 필요하다. +- **`loggers`는 노출하지 않는다.** 이 체인에는 인증 수단(`httpBasic`·`oauth2ResourceServer`)이 없어 + `authenticated()`에 걸리는 엔드포인트는 어떤 자격 증명으로도 도달할 수 없다. 그래서 `loggers` + 노출과 `show-details: when-authorized`를 뺐다. 로그 레벨을 런타임에 보거나 바꿔야 하면 인증 + 수단을 이 체인에 먼저 붙이고 노출한다. +- **인증 실패 시 기본값 403 대신 401(자격 증명 필요)을 반환한다(`HttpStatusEntryPoint(UNAUTHORIZED)`).** + 대화형 로그인이나 basic-auth realm 은 제공하지 않는다 — 관리 포트는 네트워크 ACL 뒤에 있으므로 + 올바른 HTTP 의미(credentials required)만 신호하면 된다. +- **운영에서 deny-by-default 보장은 관리 포트를 별도 포트로 분리해 네트워크 ACL 수준에서 강제한다.** + 이 in-process 체인은 그 위의 심층 방어 계층이다. +- **SHAPE-OWNERSHIP(하드 규칙): 이 클래스는 `HealthEndpoint` / `HealthIndicator` / `HealthComponent`를 + import·구현·의존해선 안 된다** — health 엔드포인트의 형태(shape)는 runtime-health 브랜치 소유다. + 보안 매칭은 오직 엔드포인트 id 문자열로만 하고 health 내부 구조에는 절대 손대지 않는다. ArchUnit + 규칙 `management_security_does_not_depend_on_health_internals`(`CleanArchitectureTest`)가 이를 정적 + 으로 강제한다. + diff --git a/src/composition/service-runtime/build.gradle b/src/composition/service-runtime/build.gradle new file mode 100644 index 00000000..cadce8d5 --- /dev/null +++ b/src/composition/service-runtime/build.gradle @@ -0,0 +1,40 @@ +plugins { + id 'ca.spring-library' + id 'ca.spring-config' +} + +// The runtime wiring every service composition root needs, whatever its capabilities: distributed +// tracing, the metrics contract filters, domain-context propagation, user-principal +// pseudonymization and the actuator security chain. Selected by one line: +// +// runtimeOnly project(':composition:service-runtime') +// +// app-bootstrap and sample-portfolio take the same line. Before this module the sample carried a +// copy of each piece, and the copies had already drifted (a `staging` sampling rate the runtime +// vocabulary does not have, IllegalStateException where the original raised typed startup failures). +// +// Not a composition root: it assembles shared runtime infrastructure and does not run. +dependencies { + implementation project(':application-core') + implementation project(':shared-contract') + // Runtime profile snapshot, startup order, typed startup failures and runtime warnings. + implementation project(':adapter:outbound:support') + // support compiles against the structured-argument API only; a module that raises its startup + // failures or warnings ships the encoder (the same line outbox-relay carries). + implementation libs.logstash.logback.encoder + // The HMAC user-principal pseudonymizer behind UserPrincipalPseudonymizerPort. + implementation project(':adapter:outbound:identifier') + + implementation 'org.springframework.boot:spring-boot-autoconfigure' + implementation 'org.springframework:spring-context' + // MeterRegistryCustomizer, EndpointRequest and the actuator types the chains match on. + implementation 'org.springframework.boot:spring-boot-starter-actuator' + implementation 'io.micrometer:micrometer-core' + implementation 'io.micrometer:micrometer-tracing-bridge-otel' + implementation 'io.opentelemetry:opentelemetry-sdk' + // The actuator security chain. + implementation 'org.springframework.boot:spring-boot-starter-security' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.mockito:mockito-core' +} diff --git a/src/composition/service-runtime/gradle.lockfile b/src/composition/service-runtime/gradle.lockfile new file mode 100644 index 00000000..82aa5297 --- /dev/null +++ b/src/composition/service-runtime/gradle.lockfile @@ -0,0 +1,185 @@ +# 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. +aopalliance:aopalliance:1.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +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.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.vaadin.external.google:android-json:0.0.20131108.vaadin1=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:context-propagation:1.2.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-core:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-jakarta9:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-tracing-bridge-otel:1.6.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-tracing:1.6.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry.semconv:opentelemetry-semconv:1.37.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-api:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-common:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-context:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-extension-trace-propagators:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-common:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-logs:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-metrics:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-trace:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=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.logstash.logback:logstash-logback-encoder:8.0=compileClasspath,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 +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.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.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath +org.javassist:javassist:3.28.0-GA=checkstyle +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.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath +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-actuator-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-actuator:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,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-health: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-micrometer-metrics:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-observation:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-actuator: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-logging:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-micrometer-metrics:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-security: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-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.security:spring-security-config:7.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-core:7.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-crypto:7.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-web:7.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-aop: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-test:7.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-web:7.0.9=compileClasspath,runtimeClasspath,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/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency/DomainContextConfig.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/context/DomainContextConfig.java similarity index 82% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency/DomainContextConfig.java rename to src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/context/DomainContextConfig.java index 7983143b..fc477690 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency/DomainContextConfig.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/context/DomainContextConfig.java @@ -1,16 +1,16 @@ -package dev.caskeleton.bootstrap.concurrency; +package dev.caskeleton.composition.runtime.context; import dev.caskeleton.shared.concurrency.DomainContextPropagator; import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator; +import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; /** * Wires the {@link DomainContextPropagator} bean. {@link ThreadLocalDomainContextPropagator} is the * only shipped strategy, so there is no selection setting; a second strategy adds its own * implementation and the setting that chooses between them at the same time. */ -@Configuration +@AutoConfiguration public class DomainContextConfig { @Bean diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/PrivacySettings.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/logging/PrivacySettings.java similarity index 96% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/PrivacySettings.java rename to src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/logging/PrivacySettings.java index 73612d76..9f286563 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/PrivacySettings.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/logging/PrivacySettings.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.settings; +package dev.caskeleton.composition.runtime.logging; import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings; import java.nio.charset.StandardCharsets; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/logging/PseudonymizationConfig.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/logging/PseudonymizationConfig.java similarity index 83% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/logging/PseudonymizationConfig.java rename to src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/logging/PseudonymizationConfig.java index 9bb9f221..397e8f69 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/logging/PseudonymizationConfig.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/logging/PseudonymizationConfig.java @@ -1,19 +1,18 @@ -package dev.caskeleton.bootstrap.logging; +package dev.caskeleton.composition.runtime.logging; import dev.caskeleton.adapter.outbound.identifier.HmacUserPrincipalPseudonymizer; import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort; -import dev.caskeleton.bootstrap.settings.PrivacySettings; +import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; /** * Composition-root wiring for {@code user_principal} pseudonymization. * {@code @ConditionalOnMissingBean} lets a forking project substitute its own pseudonymizer. See * README for the design rationale. */ -@Configuration +@AutoConfiguration @EnableConfigurationProperties(PrivacySettings.class) public class PseudonymizationConfig { diff --git a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java new file mode 100644 index 00000000..24551983 --- /dev/null +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java @@ -0,0 +1,67 @@ +package dev.caskeleton.composition.runtime.management.security; + +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.boot.security.autoconfigure.actuate.web.servlet.EndpointRequest; +import org.springframework.boot.security.autoconfigure.actuate.web.servlet.ManagementWebSecurityAutoConfiguration; +import org.springframework.boot.security.autoconfigure.web.servlet.ServletWebSecurityAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.HttpStatusEntryPoint; + +/** + * Actuator endpoint security chain, ordered ahead of the main app chain. Security matching is done + * by endpoint id string only, never by health endpoint internals. See README for the design + * rationale. + * + *

    Ordered before Boot's own web-security auto-configurations: a {@link SecurityFilterChain} bean + * is what makes their default chains back off, exactly as it did when this class was a scanned + * configuration of app-bootstrap. It needs {@link HttpSecurity} to exist by then, which means the + * composition has enabled web security itself — the web adapter's {@code SecurityConfig} does, from + * its highest-precedence auto-configuration. A context without it (a narrow slice that switched web + * security off) gets no chain from here rather than a startup failure, and one that leaves web + * security entirely to Boot gets Boot's actuator default (health open, everything else + * authenticated). + * + *

    A composition root that deliberately wants another actuator posture declares its own bean + * named {@code actuatorSecurityFilterChain}; this one then steps aside instead of putting two + * chains with the same matcher in front of the same requests. The standalone sample does that. + */ +@AutoConfiguration( + before = { + ServletWebSecurityAutoConfiguration.class, + ManagementWebSecurityAutoConfiguration.class + }) +@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) +@ConditionalOnClass({HttpSecurity.class, EndpointRequest.class}) +@ConditionalOnBean(HttpSecurity.class) +public class ManagementSecurityConfig { + + @Bean + @Order(0) + @ConditionalOnMissingBean(name = "actuatorSecurityFilterChain") + public SecurityFilterChain actuatorSecurityFilterChain(HttpSecurity http) throws Exception { + http.securityMatcher(EndpointRequest.toAnyEndpoint()) + .csrf(csrf -> csrf.disable()) + .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + // Answer 401 (credentials required) instead of the default 403; no interactive login. + .exceptionHandling( + ex -> ex.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))) + .authorizeHttpRequests( + auth -> + auth + // permit-all for probes and Prometheus scrape. + .requestMatchers(EndpointRequest.to("health", "info", "prometheus")) + .permitAll() + .anyRequest() + .authenticated()); + return http.build(); + } +} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/metrics/MetricsCardinalityMeterFilter.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/metrics/MetricsCardinalityMeterFilter.java similarity index 94% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/metrics/MetricsCardinalityMeterFilter.java rename to src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/metrics/MetricsCardinalityMeterFilter.java index 308abd1b..d1d0d237 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/metrics/MetricsCardinalityMeterFilter.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/metrics/MetricsCardinalityMeterFilter.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.metrics; +package dev.caskeleton.composition.runtime.metrics; import dev.caskeleton.shared.metrics.ForbiddenMetricTags; import io.micrometer.core.instrument.Meter; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/metrics/MetricsContractConfig.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/metrics/MetricsContractConfig.java similarity index 93% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/metrics/MetricsContractConfig.java rename to src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/metrics/MetricsContractConfig.java index 0439f11e..32c309e5 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/metrics/MetricsContractConfig.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/metrics/MetricsContractConfig.java @@ -1,9 +1,9 @@ -package dev.caskeleton.bootstrap.metrics; +package dev.caskeleton.composition.runtime.metrics; import io.micrometer.core.instrument.MeterRegistry; +import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.micrometer.metrics.autoconfigure.MeterRegistryCustomizer; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; @@ -21,7 +21,7 @@ import org.springframework.core.annotation.Order; * @see MetricsCardinalityMeterFilter * @see MetricsDistributionMeterFilter */ -@Configuration +@AutoConfiguration public class MetricsContractConfig { /** diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/metrics/MetricsDistributionMeterFilter.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/metrics/MetricsDistributionMeterFilter.java similarity index 97% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/metrics/MetricsDistributionMeterFilter.java rename to src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/metrics/MetricsDistributionMeterFilter.java index 10c3e1ee..a8c64772 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/metrics/MetricsDistributionMeterFilter.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/metrics/MetricsDistributionMeterFilter.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.metrics; +package dev.caskeleton.composition.runtime.metrics; import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.config.MeterFilter; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/MicrometerSpanErrorRecorder.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/MicrometerSpanErrorRecorder.java similarity index 92% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/MicrometerSpanErrorRecorder.java rename to src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/MicrometerSpanErrorRecorder.java index eb601934..7d30049b 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/MicrometerSpanErrorRecorder.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/MicrometerSpanErrorRecorder.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.tracing; +package dev.caskeleton.composition.runtime.tracing; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import io.micrometer.tracing.Span; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingConfig.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingConfig.java similarity index 98% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingConfig.java rename to src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingConfig.java index 5d1b8ff0..21551dc0 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingConfig.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingConfig.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.tracing; +package dev.caskeleton.composition.runtime.tracing; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; import dev.caskeleton.shared.runtime.RuntimeEnvironment; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSampleRateResolver.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSampleRateResolver.java similarity index 97% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSampleRateResolver.java rename to src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSampleRateResolver.java index a24a4a0e..ea806883 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSampleRateResolver.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSampleRateResolver.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.tracing; +package dev.caskeleton.composition.runtime.tracing; import dev.caskeleton.shared.runtime.RuntimeEnvironment; import java.util.Collection; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingEnvironmentPostProcessor.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessor.java similarity index 97% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingEnvironmentPostProcessor.java rename to src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessor.java index 8eb1c33a..70914075 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingEnvironmentPostProcessor.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessor.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.tracing; +package dev.caskeleton.composition.runtime.tracing; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingRateGauge.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingRateGauge.java similarity index 96% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingRateGauge.java rename to src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingRateGauge.java index f83206be..af61cec6 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingRateGauge.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingRateGauge.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.tracing; +package dev.caskeleton.composition.runtime.tracing; import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings; import io.micrometer.core.instrument.Gauge; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettings.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSettings.java similarity index 98% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettings.java rename to src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSettings.java index e196720c..848e564e 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettings.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSettings.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.tracing; +package dev.caskeleton.composition.runtime.tracing; import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import java.net.URI; diff --git a/src/composition/service-runtime/src/main/resources/META-INF/spring.factories b/src/composition/service-runtime/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..9f256287 --- /dev/null +++ b/src/composition/service-runtime/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.EnvironmentPostProcessor=\ +dev.caskeleton.composition.runtime.tracing.TracingSamplingEnvironmentPostProcessor diff --git a/src/composition/service-runtime/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/composition/service-runtime/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..e3a9b446 --- /dev/null +++ b/src/composition/service-runtime/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1,5 @@ +dev.caskeleton.composition.runtime.context.DomainContextConfig +dev.caskeleton.composition.runtime.logging.PseudonymizationConfig +dev.caskeleton.composition.runtime.management.security.ManagementSecurityConfig +dev.caskeleton.composition.runtime.metrics.MetricsContractConfig +dev.caskeleton.composition.runtime.tracing.TracingConfig diff --git a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/ServiceRuntimeRegistrationTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/ServiceRuntimeRegistrationTest.java new file mode 100644 index 00000000..0cddb364 --- /dev/null +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/ServiceRuntimeRegistrationTest.java @@ -0,0 +1,94 @@ +package dev.caskeleton.composition.runtime; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; +import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort; +import dev.caskeleton.composition.runtime.context.DomainContextConfig; +import dev.caskeleton.composition.runtime.logging.PseudonymizationConfig; +import dev.caskeleton.composition.runtime.management.security.ManagementSecurityConfig; +import dev.caskeleton.composition.runtime.metrics.MetricsContractConfig; +import dev.caskeleton.composition.runtime.tracing.TracingConfig; +import dev.caskeleton.composition.runtime.tracing.TracingSamplingEnvironmentPostProcessor; +import dev.caskeleton.shared.concurrency.DomainContextPropagator; +import dev.caskeleton.shared.tracing.SpanErrorRecorder; +import java.io.IOException; +import java.util.List; +import java.util.Properties; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.context.annotation.ImportCandidates; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.support.PropertiesLoaderUtils; + +class ServiceRuntimeRegistrationTest { + + private static final List> ROOTS = + List.of( + DomainContextConfig.class, + PseudonymizationConfig.class, + ManagementSecurityConfig.class, + MetricsContractConfig.class, + TracingConfig.class); + + @Test + void everyRootIsAnAutoConfigurationBootDiscoversFromThisModule() { + // given + ClassLoader loader = getClass().getClassLoader(); + + // when + List candidates = + ImportCandidates.load(AutoConfiguration.class, loader).getCandidates(); + + // then + assertThat(candidates).containsAll(ROOTS.stream().map(Class::getName).toList()); + assertThat(ROOTS).allMatch(root -> root.isAnnotationPresent(AutoConfiguration.class)); + } + + @Test + void theSamplingBridgeIsRegisteredAsAnEnvironmentPostProcessor() throws IOException { + // given + ClassPathResource factories = new ClassPathResource("META-INF/spring.factories"); + + // when + Properties registrations = PropertiesLoaderUtils.loadProperties(factories); + + // then + assertThat(registrations.getProperty("org.springframework.boot.EnvironmentPostProcessor")) + .contains(TracingSamplingEnvironmentPostProcessor.class.getName()); + } + + @Test + void theSamplingBridgeTakesItsCentralStartupOrderPosition() { + // given + TracingSamplingEnvironmentPostProcessor bridge = new TracingSamplingEnvironmentPostProcessor(); + + // when + int order = bridge.getOrder(); + + // then + assertThat(order).isEqualTo(StartupOrder.TRACING_SAMPLING); + } + + @Test + void aNonWebContextGetsTheRuntimeBeansWithoutAnActuatorChain() { + // given + ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(ROOTS.toArray(Class[]::new))) + .withPropertyValues("ca-skeleton.privacy.pseudonymization-salt=test-salt"); + + // when + runner.run( + context -> { + // then + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(DomainContextPropagator.class); + assertThat(context).hasSingleBean(UserPrincipalPseudonymizerPort.class); + assertThat(context).hasSingleBean(SpanErrorRecorder.class); + assertThat(context).doesNotHaveBean("actuatorSecurityFilterChain"); + }); + } +} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/PrivacySettingsTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/logging/PrivacySettingsTest.java similarity index 98% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/PrivacySettingsTest.java rename to src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/logging/PrivacySettingsTest.java index dbf45dcf..c42a3fe1 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/PrivacySettingsTest.java +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/logging/PrivacySettingsTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.settings; +package dev.caskeleton.composition.runtime.logging; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/logging/PseudonymizationConfigTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/logging/PseudonymizationConfigTest.java similarity index 97% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/logging/PseudonymizationConfigTest.java rename to src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/logging/PseudonymizationConfigTest.java index a6b647d5..01596d55 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/logging/PseudonymizationConfigTest.java +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/logging/PseudonymizationConfigTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.logging; +package dev.caskeleton.composition.runtime.logging; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/metrics/MetricsCardinalityMeterFilterTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/metrics/MetricsCardinalityMeterFilterTest.java similarity index 99% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/metrics/MetricsCardinalityMeterFilterTest.java rename to src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/metrics/MetricsCardinalityMeterFilterTest.java index 91f8c28f..5fe96b8f 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/metrics/MetricsCardinalityMeterFilterTest.java +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/metrics/MetricsCardinalityMeterFilterTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.metrics; +package dev.caskeleton.composition.runtime.metrics; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/metrics/MetricsContractConfigTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/metrics/MetricsContractConfigTest.java similarity index 98% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/metrics/MetricsContractConfigTest.java rename to src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/metrics/MetricsContractConfigTest.java index 50a8d24c..f334e952 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/metrics/MetricsContractConfigTest.java +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/metrics/MetricsContractConfigTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.metrics; +package dev.caskeleton.composition.runtime.metrics; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/metrics/MetricsDistributionMeterFilterTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/metrics/MetricsDistributionMeterFilterTest.java similarity index 99% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/metrics/MetricsDistributionMeterFilterTest.java rename to src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/metrics/MetricsDistributionMeterFilterTest.java index 8c00f2c6..071b57e9 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/metrics/MetricsDistributionMeterFilterTest.java +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/metrics/MetricsDistributionMeterFilterTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.metrics; +package dev.caskeleton.composition.runtime.metrics; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/MicrometerSpanErrorRecorderTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/MicrometerSpanErrorRecorderTest.java similarity index 96% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/MicrometerSpanErrorRecorderTest.java rename to src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/MicrometerSpanErrorRecorderTest.java index 1a6b4a01..6ca96559 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/MicrometerSpanErrorRecorderTest.java +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/MicrometerSpanErrorRecorderTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.tracing; +package dev.caskeleton.composition.runtime.tracing; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSampleRateResolverTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSampleRateResolverTest.java similarity index 98% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSampleRateResolverTest.java rename to src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSampleRateResolverTest.java index 3167a234..5210b233 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSampleRateResolverTest.java +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSampleRateResolverTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.tracing; +package dev.caskeleton.composition.runtime.tracing; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingEnvironmentPostProcessorTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessorTest.java similarity index 97% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingEnvironmentPostProcessorTest.java rename to src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessorTest.java index 635a9277..cca8d78d 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingEnvironmentPostProcessorTest.java +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessorTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.tracing; +package dev.caskeleton.composition.runtime.tracing; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettingsTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSettingsTest.java similarity index 99% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettingsTest.java rename to src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSettingsTest.java index a3287da4..37258d2d 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettingsTest.java +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSettingsTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.tracing; +package dev.caskeleton.composition.runtime.tracing; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; diff --git a/src/config/architecture/modules.json b/src/config/architecture/modules.json index ee3198e9..f07a0a8d 100644 --- a/src/config/architecture/modules.json +++ b/src/config/architecture/modules.json @@ -285,6 +285,35 @@ "adapter-inbound-web-notification" ] }, + { + "id": "composition-outbox-relay", + "gradle_path": ":composition:outbox-relay", + "source_path": "src/composition/outbox-relay", + "allowed_dependencies": [ + "application-core", + "adapter-outbound-support" + ] + }, + { + "id": "composition-idempotency", + "gradle_path": ":composition:idempotency", + "source_path": "src/composition/idempotency", + "allowed_dependencies": [ + "application-core", + "adapter-outbound-support" + ] + }, + { + "id": "composition-service-runtime", + "gradle_path": ":composition:service-runtime", + "source_path": "src/composition/service-runtime", + "allowed_dependencies": [ + "application-core", + "shared-contract", + "adapter-outbound-support", + "adapter-outbound-identifier" + ] + }, { "id": "app-bootstrap", "gradle_path": ":app-bootstrap", @@ -306,7 +335,10 @@ "adapter-outbound-objectstorage", "adapter-inbound-websocket", "adapter-inbound-grpc", - "composition-fileserver-platform" + "composition-fileserver-platform", + "composition-outbox-relay", + "composition-idempotency", + "composition-service-runtime" ] }, { @@ -321,7 +353,9 @@ "adapter-outbound-objectstorage", "adapter-inbound-web", "shared-contract", - "application-objectstorage" + "application-objectstorage", + "composition-idempotency", + "composition-service-runtime" ] }, { @@ -445,25 +479,25 @@ ] }, { - "id": "messaging-outbox-jdbc-postgresql", - "gradle_path": ":messaging:messaging-outbox-jdbc-postgresql", - "source_path": "src/messaging/messaging-outbox-jdbc-postgresql", + "id": "messaging-reliability", + "gradle_path": ":messaging:messaging-reliability", + "source_path": "src/messaging/messaging-reliability", "allowed_dependencies": [ "messaging-core-api", "messaging-reliability-api", - "messaging-policy", - "messaging-observability", - "messaging-admin-api", "messaging-schema-api" ] }, { - "id": "messaging-inbox-jdbc-postgresql", - "gradle_path": ":messaging:messaging-inbox-jdbc-postgresql", - "source_path": "src/messaging/messaging-inbox-jdbc-postgresql", + "id": "messaging-reliability-jdbc-postgresql", + "gradle_path": ":messaging:messaging-reliability-jdbc-postgresql", + "source_path": "src/messaging/messaging-reliability-jdbc-postgresql", "allowed_dependencies": [ "messaging-core-api", - "messaging-reliability-api" + "messaging-reliability-api", + "messaging-admin-api", + "messaging-policy", + "messaging-schema-api" ] }, { @@ -507,11 +541,11 @@ "messaging-admin-api", "messaging-admin-runtime", "messaging-core-api", - "messaging-inbox-jdbc-postgresql", "messaging-observability", - "messaging-outbox-jdbc-postgresql", "messaging-policy", + "messaging-reliability", "messaging-reliability-api", + "messaging-reliability-jdbc-postgresql", "messaging-runtime-core", "messaging-schema-api", "messaging-schema-json", diff --git a/src/config/runtime/compose-profile-contracts.json b/src/config/runtime/compose-profile-contracts.json index 0e8afde8..a4729a4a 100644 --- a/src/config/runtime/compose-profile-contracts.json +++ b/src/config/runtime/compose-profile-contracts.json @@ -169,6 +169,7 @@ "activationEnv": { "APP_MESSAGING_ENABLED": "true", "APP_MESSAGING_BROKER": "kafka", + "APP_MESSAGING_PRODUCER_ID": "ca-skeleton", "APP_MESSAGING_KAFKA_BROKERS": "kafka:9092" }, "expectedCapabilitiesOn": [ @@ -200,6 +201,7 @@ "activationEnv": { "APP_MESSAGING_ENABLED": "true", "APP_MESSAGING_BROKER": "kafka", + "APP_MESSAGING_PRODUCER_ID": "ca-skeleton", "APP_PERSISTENCE_JPA_ENABLED": "true", "APP_OUTBOX_ENABLED": "true", "APP_OUTBOX_RELAY_ENABLED": "true", @@ -690,6 +692,7 @@ "SPRING_MONGODB_URI": "mongodb://mongo:27017/ca_skeleton?replicaSet=rs0", "APP_MESSAGING_ENABLED": "true", "APP_MESSAGING_BROKER": "kafka", + "APP_MESSAGING_PRODUCER_ID": "ca-skeleton", "APP_NOTIFICATION_PLATFORM_ENABLED": "true", "APP_NOTIFICATION_PLATFORM_MODE": "SERVING", "APP_GRAPHQL_ENABLED": "true", diff --git a/src/messaging/CLAUDE.md b/src/messaging/CLAUDE.md index 6b2ad649..57e6932e 100644 --- a/src/messaging/CLAUDE.md +++ b/src/messaging/CLAUDE.md @@ -16,16 +16,19 @@ leaf의 정확한 id는 registry에서 읽는다. family는 **디렉터리 이 | --- | --- | --- | | `*-api` (`core-api`, `schema-api`, `policy`, `reliability-api`, `admin-api`, `transport-spi`) | 값 타입, 포트, 정책 계약 | Java stdlib만. Spring/broker SDK/logging framework 금지 | | `schema-*` (json/avro/protobuf), `cloudevents` | 인코딩 구현 | 해당 codec 라이브러리만. Spring 금지 | -| `runtime-core`, `security`, `observability`, `admin-runtime` | framework-free 실행 로직 | Micrometer는 `observability`에서만. 나머지는 stdlib | +| `runtime-core`, `security`, `observability`, `admin-runtime`, `reliability` | framework-free 실행 로직 | Micrometer는 `observability`에서만. 나머지는 stdlib | | `kafka` | broker adapter | 해당 broker client. Spring은 client가 곧 Spring인 경우만 | -| `outbox-jdbc-postgresql`, `inbox-jdbc-postgresql` | 관계형 신뢰성 adapter | Spring JDBC / Spring TX. **JPA 아님** — 이름이 곧 계약이다 | +| `reliability-jdbc-postgresql` | 관계형 신뢰성 adapter (outbox·inbox repository, admin journal) | Spring JDBC / Spring TX. **JPA 아님** — 이름이 곧 계약이다 | | `spring-boot-starter`, `spring-boot-starter-kafka` | 조립 경계 | Spring Boot autoconfigure. 여기서만 | | `testkit` | 테스트 지원 | Testcontainers, JUnit. production leaf가 의존하지 않는다 | -`outbox`/`inbox` leaf가 `jdbc-postgresql`로 명명된 이유: 구현은 Spring JDBC이고 SQL은 -`?::jsonb` · `FOR UPDATE SKIP LOCKED` · `ON CONFLICT` · `TIMESTAMPTZ`로 PostgreSQL 전용이다. -`jpa`라는 이름은 사용하지 않는 기술을 광고하고, vendor 중립 port가 어디 있는지도 숨겼다. vendor -중립 계약은 `messaging-reliability-api`에 있다. +신뢰성 기능은 세 leaf다. `messaging-reliability-api`가 vendor 중립 port(`OutboxRepository`, +`InboxRepository`)를, `messaging-reliability`가 그 port만 보는 relay·consumer 로직(stdlib)을, +`messaging-reliability-jdbc-postgresql`이 port의 관계형 구현과 migration(`V1001..V1005`, `V1101`)을 +갖는다. 예전에는 `outbox-jdbc-postgresql` 하나가 relay 로직과 PG repository와 admin journal을 함께 +가졌고 inbox도 같은 모양이었다(S7-#5b). 구현 leaf가 `jdbc-postgresql`로 명명된 이유: 구현은 Spring +JDBC이고 SQL은 `jsonb` · `FOR UPDATE SKIP LOCKED` · `ON CONFLICT` · `TIMESTAMPTZ`로 PostgreSQL +전용이다. `jpa`라는 이름은 사용하지 않는 기술을 광고하고, vendor 중립 port가 어디 있는지도 숨겼다. ## Public surface 정책 @@ -57,7 +60,7 @@ RabbitMQ·Pulsar·NATS·Kafka Share·Spring Cloud Stream bridge leaf와 Debezium 새 leaf를 application에 채택할 때는 starter 또는 composition dependency와 architecture edge policy, qualification/support 상태를 함께 변경한다. -## application이 이 family에 도달하는 경로 (MSG-015, canonical bridge 구현 / legacy cutover 잔존) +## application이 이 family에 도달하는 경로 (MSG-015, cutover 완료) 리뷰(`docs/reviews/2026-08-14-messaging-module-code-review.md` §6.1·§6.3)가 정한 `application-owned port → platform anti-corruption bridge → platform` 경로는 이제 존재한다. @@ -72,21 +75,21 @@ lease/transport/outcome normalization/observation은 platform 중앙 publish pat package는 `messaging-core-api`와 `messaging-schema-api`만 보며 concrete runtime/transport/Kafka 타입을 직접 보지 않는다. -다만 **MSG-015의 전체 cutover가 끝난 것은 아니다.** legacy `OutboxEvent`와 realtime publisher는 -schema/order/tenant 등 canonical metadata가 부족해 아직 `MessageBroker → KafkaSender` R0 경로를 -사용한다. 그 metadata를 추측해 platform envelope를 만드는 것은 금지한다. 따라서 legacy outbox -storage/relay migration을 별도 change set으로 완료한 뒤에만 R0 seam을 제거한다. +**MSG-015 cutover는 끝났다(2026-09-28, 소유자 결정 7).** application의 outbox append는 canonical +`OutboxAppendPort` 하나이고, relay는 claim한 row의 validated event를 이 bridge로만 보낸다. legacy +`OutboxEvent`·`LegacyOutboxAppendPort`와 `MessageBroker → KafkaSender` R0 경로(TLS/SASL을 적용하지 +않던 두 번째 producer)는 삭제했다. 남은 Kafka producer는 platform의 것 하나이고, broker security +profile(`KafkaSecurityConfigurer`)을 적용한다. canonical bridge의 producer identity는 `app.messaging.producer-id`로 명시한다. 값이 없으면 bridge bean을 -만들지 않으며 `spring.application.name`/host/pod 이름에서 identity를 발명하지 않는다. +만들지 않으며 `spring.application.name`/host/pod 이름에서 identity를 발명하지 않는다. bridge가 없으면 +relay가 발행할 곳이 없으므로 messaging 모듈이 켜진 상태에서는 기동이 거부된다. -`ca-skeleton.outbox.canonical-transport-enabled=true`는 bridge 존재만으로 충분하지 않다. Stable -composition은 애플리케이션 계약 catalog/schema source를 임의로 만들지 않으므로 adopter가 -`IntegrationEventEncoderPort`를 명시적으로 제공해야 한다. 템플릿은 구현체를 주지 않는다(후보였던 -R1 JSON Schema encoder는 2026-09-25에 삭제). `OutboxCanonicalTransportRequirementValidator`는 -publisher 또는 encoder 중 하나라도 -없으면 startup을 거부한다. 즉 canonical flag가 켜졌는데 정본 encoder가 없는 상태로 성공 기동하는 -경로는 없다. +`IntegrationEventEncoderPort`는 템플릿이 제공한다: `adapter:outbound:support`의 +`JsonIntegrationEventEncoder`가 envelope v1(`shared-contract`의 `contracts/messaging/envelope/v1.schema.json`) +안에 payload record를 결정적 JSON으로 싣는다. 계약 catalog는 애플리케이션이 bean으로 등록한 +`IntegrationEventContractContribution`뿐이고, 선언한 payload schema hash가 classpath의 schema 파일과 +다르면 기동이 실패한다. payload를 JSON Schema로 매번 검증하려는 서비스는 자기 encoder bean을 두면 된다. ## Stable 승격에 필요한 증거 diff --git a/src/messaging/messaging-inbox-jdbc-postgresql/build.gradle b/src/messaging/messaging-inbox-jdbc-postgresql/build.gradle deleted file mode 100644 index bf339f0d..00000000 --- a/src/messaging/messaging-inbox-jdbc-postgresql/build.gradle +++ /dev/null @@ -1,33 +0,0 @@ -plugins { - id 'ca.auxiliary-source-set' - id 'ca.platform-module' -} - -auxiliarySourceSets { - sourceSet('integrationTest') { - compilesAgainst 'main' - } -} - -dependencies { - api project(':messaging:messaging-core-api') - api project(':messaging:messaging-reliability-api') - - implementation 'org.springframework:spring-jdbc' - implementation 'org.springframework:spring-tx' - - // Live-database certification. The reliability patterns are claims about transaction - // boundaries and uniqueness constraints, and only a real database can settle them. - testImplementation project(':messaging:messaging-testkit') - integrationTestImplementation 'org.testcontainers:testcontainers-postgresql' - integrationTestImplementation 'org.testcontainers:testcontainers-junit-jupiter' - integrationTestImplementation 'org.postgresql:postgresql' -} - -strictTestLanes { - lane('integrationTest') { - integration() - sourceSet = 'integrationTest' - description = 'Runs inbox transaction and uniqueness contracts against real PostgreSQL.' - } -} diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/gradle.lockfile b/src/messaging/messaging-outbox-jdbc-postgresql/gradle.lockfile deleted file mode 100644 index 608e6f7b..00000000 --- a/src/messaging/messaging-outbox-jdbc-postgresql/gradle.lockfile +++ /dev/null @@ -1,111 +0,0 @@ -# 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. -com.fasterxml.jackson.core:jackson-annotations:2.21=integrationTestCompileClasspath,integrationTestRuntimeClasspath -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -com.github.docker-java:docker-java-api:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath -com.github.docker-java:docker-java-transport-zerodep:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath -com.github.docker-java:docker-java-transport:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,integrationTestAnnotationProcessor,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,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,integrationTestAnnotationProcessor,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,integrationTestAnnotationProcessor,testAnnotationProcessor -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,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.6.0-jre=checkstyle -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins -com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -commons-beanutils:commons-beanutils:1.11.0=checkstyle -commons-codec:commons-codec:1.19.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath -commons-collections:commons-collections:3.2.2=checkstyle -commons-io:commons-io:2.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath -commons-io:commons-io:2.21.0=spotbugs -commons-logging:commons-logging:1.3.6=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -io.micrometer:micrometer-commons:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-core:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -javax.inject:javax.inject:1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -net.java.dev.jna:jna:5.18.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath -net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -org.antlr:antlr4-runtime:4.13.2=checkstyle -org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-compress:1.28.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.apache.commons:commons-lang3:3.20.0=checkstyle,integrationTestCompileClasspath,integrationTestRuntimeClasspath,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=spotbugs -org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -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.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=integrationTestCompileClasspath,testCompileClasspath -org.assertj:assertj-core:3.27.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.checkerframework:checker-qual:3.55.1=integrationTestRuntimeClasspath -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.hdrhistogram:HdrHistogram:2.2.2=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath -org.javassist:javassist:3.28.0-GA=checkstyle -org.jetbrains:annotations:17.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-engine:6.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-params:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-engine:6.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-launcher:6.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath -org.junit:junit-bom:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit:junit-bom:6.1.0=spotbugs -org.latencyutils:LatencyUtils:2.0.3=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath -org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -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.pcollections:pcollections:4.0.1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor -org.postgresql:postgresql:42.7.13=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.reflections:reflections:0.10.2=checkstyle -org.rnorth.duct-tape:duct-tape:1.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.slf4j:slf4j-api:2.0.18=integrationTestCompileClasspath,integrationTestRuntimeClasspath,spotbugs,spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.18=checkstyle -org.springframework:spring-beans:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-core:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-jdbc:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-tx:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.testcontainers:testcontainers-database-commons:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.testcontainers:testcontainers-jdbc:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.testcontainers:testcontainers-junit-jupiter:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.testcontainers:testcontainers-postgresql:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.testcontainers:testcontainers:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty= diff --git a/src/messaging/messaging-reliability-api/src/main/java/dev/caskeleton/messaging/reliability/OutboxRepository.java b/src/messaging/messaging-reliability-api/src/main/java/dev/caskeleton/messaging/reliability/OutboxRepository.java index 8197a2c8..6765abfb 100644 --- a/src/messaging/messaging-reliability-api/src/main/java/dev/caskeleton/messaging/reliability/OutboxRepository.java +++ b/src/messaging/messaging-reliability-api/src/main/java/dev/caskeleton/messaging/reliability/OutboxRepository.java @@ -22,38 +22,23 @@ public interface OutboxRepository { void append(OutboxRecord record); /** - * Leases a batch of publishable records. + * Claims a batch and returns the leases, each carrying its owner and fencing token, skipping rows + * that are waiting for their backoff or out of attempts. * - *

    Leasing rather than simply selecting is what makes multiple relay instances safe: a record - * claimed by one relay is invisible to the others until its lease expires, so the same message is - * not published concurrently by two processes. - * - * @param batchSize how many records to claim - * @param leaseDuration how long the claim holds - * @param now the current instant - * @return the leased records, oldest first - */ - List leaseBatch(int batchSize, Duration leaseDuration, Instant now); - - /** - * Claims a batch and returns the leases, each carrying its owner and fencing token. - * - *

    The token is what a terminal write is checked against. {@link #leaseBatch} returns records - * without one, so its callers cannot prove a write belongs to their claim; it remains for - * inspection paths and is deprecated for the relay's use. - * - * @param owner this relay's stable identity - */ - List claimBatch(String owner, int batchSize, Duration leaseDuration, Instant now); - - /** - * Claims a batch, skipping rows that are waiting for their backoff or out of attempts. + *

    Claiming rather than simply selecting is what makes multiple relay instances safe: a record + * claimed by one relay is invisible to the others until its lease expires, and the token is what + * a terminal write is checked against, so a relay that stalled past its lease writes nothing. * *

    Eligibility belongs in the row. A relay that decides in memory forgets on restart, and every * replica decides for itself — so the same message is retried by as many workers as there are * replicas, as often as they poll. * + * @param owner this relay's stable identity + * @param batchSize how many records to claim + * @param leaseDuration how long the claim holds + * @param now the current instant * @param maxAttempts the attempt budget; rows at or above it are not claimed + * @return the leases, oldest first */ List claimBatch( String owner, int batchSize, Duration leaseDuration, Instant now, int maxAttempts); @@ -65,10 +50,10 @@ public interface OutboxRepository { */ OutboxTransitionResult markPublished(OutboxLease lease, Instant now); - /** Records an ambiguous outcome, only if this lease still owns the row. */ - OutboxTransitionResult markAmbiguous(OutboxLease lease, String failureCode, Instant now); - - /** Records an ambiguous outcome and when this row may next be claimed. */ + /** + * Records an ambiguous outcome and when this row may next be claimed, only if this lease still + * owns the row. + */ OutboxTransitionResult markAmbiguous( OutboxLease lease, String failureCode, Instant now, Instant nextAttemptAt); diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/build.gradle b/src/messaging/messaging-reliability-jdbc-postgresql/build.gradle similarity index 69% rename from src/messaging/messaging-outbox-jdbc-postgresql/build.gradle rename to src/messaging/messaging-reliability-jdbc-postgresql/build.gradle index c933afeb..e6c57bb1 100644 --- a/src/messaging/messaging-outbox-jdbc-postgresql/build.gradle +++ b/src/messaging/messaging-reliability-jdbc-postgresql/build.gradle @@ -9,11 +9,13 @@ auxiliarySourceSets { } } +// The relational implementations of the reliability ports: the outbox repository, the inbox +// repository and the destructive-operation journal. Spring JDBC for the transaction join, and SQL +// that is PostgreSQL's (`jsonb`, `FOR UPDATE SKIP LOCKED`, `ON CONFLICT`, `TIMESTAMPTZ`) — the name +// is the contract. The relay and consumer logic that uses them is messaging-reliability. dependencies { api project(':messaging:messaging-core-api') api project(':messaging:messaging-reliability-api') - api project(':messaging:messaging-policy') - api project(':messaging:messaging-observability') // The destructive-operation journal lives here because it needs exactly what the outbox needs: // one relational database every replica can see, and a migration lane that already exists. The @@ -26,9 +28,7 @@ dependencies { // Live-database certification. The reliability patterns are claims about transaction // boundaries and uniqueness constraints, and only a real database can settle them. testImplementation project(':messaging:messaging-testkit') - // Test-only. The relay is also driven through the real DefaultMessagePublisher: a fake publisher - // accepted the pre-encoded rows the real one re-encoded and rejected. - testImplementation project(':messaging:messaging-runtime-core') + integrationTestImplementation project(':messaging:messaging-testkit') integrationTestImplementation 'org.testcontainers:testcontainers-postgresql' integrationTestImplementation 'org.testcontainers:testcontainers-junit-jupiter' integrationTestImplementation 'org.postgresql:postgresql' @@ -38,6 +38,6 @@ strictTestLanes { lane('integrationTest') { integration() sourceSet = 'integrationTest' - description = 'Runs outbox and admin-journal contracts against real PostgreSQL.' + description = 'Runs outbox, inbox and admin-journal contracts against real PostgreSQL.' } } diff --git a/src/messaging/messaging-inbox-jdbc-postgresql/gradle.lockfile b/src/messaging/messaging-reliability-jdbc-postgresql/gradle.lockfile similarity index 100% rename from src/messaging/messaging-inbox-jdbc-postgresql/gradle.lockfile rename to src/messaging/messaging-reliability-jdbc-postgresql/gradle.lockfile diff --git a/src/messaging/messaging-inbox-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/inbox/InboxPostgresIT.java b/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/inbox/InboxPostgresIT.java similarity index 100% rename from src/messaging/messaging-inbox-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/inbox/InboxPostgresIT.java rename to src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/inbox/InboxPostgresIT.java diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/AdminOperationJournalPostgresIT.java b/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/AdminOperationJournalPostgresIT.java similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/AdminOperationJournalPostgresIT.java rename to src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/AdminOperationJournalPostgresIT.java diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java b/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java similarity index 86% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java rename to src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java index 66fba44e..f3f1d2a7 100644 --- a/src/messaging/messaging-outbox-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java +++ b/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java @@ -71,6 +71,9 @@ class OutboxPostgresIT { try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.execute("DROP TABLE IF EXISTS messaging_outbox"); + // The inbox migration ships in the same module now, so "every migration" creates its table + // too. + statement.execute("DROP TABLE IF EXISTS messaging_inbox"); // Every migration in order, not just V1: a test that applies part of the schema certifies a // database nobody deploys. for (String migration : migrations()) { @@ -90,7 +93,7 @@ class OutboxPostgresIT { OutboxRecord record = record(); appendInTransaction(record); - List leased = repository.leaseBatch(10, Duration.ofSeconds(30), NOW); + List leased = claim("relay-a", NOW).stream().map(OutboxLease::record).toList(); assertThat(leased) .singleElement() @@ -109,8 +112,8 @@ class OutboxPostgresIT { void aLeasedRowIsInvisibleToASecondRelayInstance() { appendInTransaction(record()); - List first = repository.leaseBatch(10, Duration.ofSeconds(30), NOW); - List second = repository.leaseBatch(10, Duration.ofSeconds(30), NOW); + List first = claim("relay-a", NOW); + List second = claim("relay-b", NOW); assertThat(first).hasSize(1); assertThat(second).as("SKIP LOCKED plus the lease keeps two relays off the same row").isEmpty(); @@ -119,10 +122,9 @@ class OutboxPostgresIT { @Test void anExpiredLeaseBecomesClaimableAgain() { appendInTransaction(record()); - repository.leaseBatch(10, Duration.ofSeconds(30), NOW); + claim("relay-a", NOW); - List reclaimed = - repository.leaseBatch(10, Duration.ofSeconds(30), NOW.plusSeconds(31)); + List reclaimed = claim("relay-b", NOW.plusSeconds(31)); assertThat(reclaimed).hasSize(1); } @@ -131,18 +133,16 @@ class OutboxPostgresIT { void anAmbiguousRowStaysClaimableUnderItsOriginalIdentity() { OutboxRecord record = record(); appendInTransaction(record); - // Claimed rather than leased: a terminal write is checked against the lease token, so - // `markAmbiguous` takes the lease that owns the row. The identity-keyed overload this test used - // to call is gone, and with it the possibility of one relay writing an outcome onto a row - // another relay currently owns. - OutboxLease lease = - repository.claimBatch("ambiguous-relay", 10, Duration.ofSeconds(30), NOW).getFirst(); + // A terminal write is checked against the lease token, so `markAmbiguous` takes the lease that + // owns the row; no identity-keyed write exists for one relay to put an outcome on a row another + // relay currently owns. + OutboxLease lease = claim("ambiguous-relay", NOW).getFirst(); - repository.markAmbiguous(lease, "CONFIRM_TIMEOUT", NOW); + repository.markAmbiguous(lease, "CONFIRM_TIMEOUT", NOW, NOW); assertThat(repository.find(record.messageId()).orElseThrow().status()) .isEqualTo(OutboxStatus.AMBIGUOUS); - assertThat(repository.leaseBatch(10, Duration.ofSeconds(30), NOW)) + assertThat(claim("relay-b", NOW)) .singleElement() .satisfies(retry -> assertThat(retry.messageId()).isEqualTo(record.messageId())); } @@ -151,24 +151,24 @@ class OutboxPostgresIT { void aPublishedRowIsNotClaimedAgain() { OutboxRecord record = record(); appendInTransaction(record); - repository.leaseBatch(10, Duration.ofSeconds(30), NOW); + OutboxLease lease = claim("relay-a", NOW).getFirst(); - repository.markPublishedUnfenced(record.messageId(), NOW); + repository.markPublished(lease, NOW); assertThat(repository.find(record.messageId()).orElseThrow().status()) .isEqualTo(OutboxStatus.PUBLISHED); - assertThat(repository.leaseBatch(10, Duration.ofSeconds(30), NOW.plusSeconds(60))).isEmpty(); + assertThat(claim("relay-b", NOW.plusSeconds(60))).isEmpty(); } @Test void aFailedRowIsNotClaimedAgainWithoutIntervention() { OutboxRecord record = record(); appendInTransaction(record); - repository.leaseBatch(10, Duration.ofSeconds(30), NOW); + OutboxLease lease = claim("relay-a", NOW).getFirst(); - repository.markFailedUnfenced(record.messageId(), "INVALID_TOPIC", NOW); + repository.markFailed(lease, "INVALID_TOPIC", NOW); - assertThat(repository.leaseBatch(10, Duration.ofSeconds(30), NOW.plusSeconds(60))).isEmpty(); + assertThat(claim("relay-b", NOW.plusSeconds(60))).isEmpty(); } @Test @@ -202,8 +202,8 @@ class OutboxPostgresIT { OutboxRecord published = record(); OutboxRecord pending = record(); appendInTransaction(published); + repository.markPublished(claim("relay-a", NOW).getFirst(), NOW); appendInTransaction(pending); - repository.markPublishedUnfenced(published.messageId(), NOW); int removed = repository.purgePublishedBefore(NOW.plusSeconds(1), 100); @@ -211,6 +211,11 @@ class OutboxPostgresIT { assertThat(repository.find(pending.messageId())).isPresent(); } + /** Claims with an unlimited attempt budget, as a relay does on a row's first attempts. */ + private List claim(String owner, Instant now) { + return repository.claimBatch(owner, 10, Duration.ofSeconds(30), now, Integer.MAX_VALUE); + } + private static OutboxRecord record() { return record( // The routing key is a column now, not a reserved header smuggled through the header map. @@ -228,7 +233,8 @@ class OutboxPostgresIT { appendInTransaction(otherKey); // when - List claimed = repository.claimBatch("relay-a", 10, Duration.ofSeconds(30), NOW); + List claimed = + repository.claimBatch("relay-a", 10, Duration.ofSeconds(30), NOW, Integer.MAX_VALUE); // then assertThat(claimed) @@ -352,12 +358,13 @@ class OutboxPostgresIT { // Relay A claims and stalls. java.util.List first = - repository.claimBatch("relay-a", 10, Duration.ofSeconds(30), NOW); + repository.claimBatch("relay-a", 10, Duration.ofSeconds(30), NOW, Integer.MAX_VALUE); assertThat(first).hasSize(1); // The lease expires and relay B takes the row and publishes it. java.util.List second = - repository.claimBatch("relay-b", 10, Duration.ofSeconds(30), NOW.plusSeconds(31)); + repository.claimBatch( + "relay-b", 10, Duration.ofSeconds(30), NOW.plusSeconds(31), Integer.MAX_VALUE); assertThat(second).hasSize(1); assertThat(second.get(0).token()) .as("every claim increments the token, which is what makes the older one detectable") @@ -366,7 +373,9 @@ class OutboxPostgresIT { .isEqualTo(dev.caskeleton.messaging.reliability.OutboxTransitionResult.APPLIED); // Relay A finally wakes up and tries to record its own outcome. - assertThat(repository.markAmbiguous(first.get(0), "CONFIRM_TIMEOUT", NOW.plusSeconds(40))) + assertThat( + repository.markAmbiguous( + first.get(0), "CONFIRM_TIMEOUT", NOW.plusSeconds(40), NOW.plusSeconds(40))) .as("this write used to succeed and made a published message claimable again") .isEqualTo(dev.caskeleton.messaging.reliability.OutboxTransitionResult.STALE_LEASE); assertThat(repository.find(record.messageId()).orElseThrow().status()) @@ -378,7 +387,7 @@ class OutboxPostgresIT { OutboxRecord record = record(); appendInTransaction(record); dev.caskeleton.messaging.reliability.OutboxLease lease = - repository.claimBatch("relay-a", 10, Duration.ofSeconds(30), NOW).get(0); + repository.claimBatch("relay-a", 10, Duration.ofSeconds(30), NOW, Integer.MAX_VALUE).get(0); assertThat(repository.markPublished(lease, NOW)) .isEqualTo(dev.caskeleton.messaging.reliability.OutboxTransitionResult.APPLIED); @@ -395,9 +404,9 @@ class OutboxPostgresIT { appendInTransaction(two); java.util.List a = - repository.claimBatch("relay-a", 1, Duration.ofSeconds(30), NOW); + repository.claimBatch("relay-a", 1, Duration.ofSeconds(30), NOW, Integer.MAX_VALUE); java.util.List b = - repository.claimBatch("relay-b", 1, Duration.ofSeconds(30), NOW); + repository.claimBatch("relay-b", 1, Duration.ofSeconds(30), NOW, Integer.MAX_VALUE); assertThat(a).hasSize(1); assertThat(b).hasSize(1); @@ -410,9 +419,15 @@ class OutboxPostgresIT { appendInTransaction(record); long firstToken = - repository.claimBatch("relay-a", 10, Duration.ofSeconds(30), NOW).get(0).token(); + repository + .claimBatch("relay-a", 10, Duration.ofSeconds(30), NOW, Integer.MAX_VALUE) + .get(0) + .token(); dev.caskeleton.messaging.reliability.OutboxLease reclaimed = - repository.claimBatch("relay-b", 10, Duration.ofSeconds(30), NOW.plusSeconds(31)).get(0); + repository + .claimBatch( + "relay-b", 10, Duration.ofSeconds(30), NOW.plusSeconds(31), Integer.MAX_VALUE) + .get(0); assertThat(reclaimed.messageId()).isEqualTo(record.messageId()); assertThat(reclaimed.token()).isEqualTo(firstToken + 1); @@ -589,6 +604,38 @@ class OutboxPostgresIT { .containsEntry("x-note", "line one\nline\ttwo"); } + /** + * The hand-rolled reader took a quote preceded by a backslash for an escaped quote, so a value + * ending in an escaped backslash ran on into the next header and both came back wrong. + */ + @Test + void aHeaderValueEndingInABackslashRoundTripsWithoutSwallowingTheNextHeader() { + // given + OutboxRecord record = + new OutboxRecord( + MessageId.newId(), + new DestinationName("order-events"), + new MessageType("order.created"), + new SchemaVersion(1), + ContentType.JSON, + "{}".getBytes(StandardCharsets.UTF_8), + Map.of("x-path", "C:\\exports\\", "x-next", "after"), + OutboxCanonicalMetadata.none(), + NOW.minusSeconds(60), + OutboxStatus.PENDING, + 0, + Optional.empty(), + Optional.empty()); + appendInTransaction(record); + + // when + Map headers = repository.find(record.messageId()).orElseThrow().headers(); + + // then + assertThat(headers) + .containsExactlyInAnyOrderEntriesOf(Map.of("x-path", "C:\\exports\\", "x-next", "after")); + } + private void appendInTransaction(OutboxRecord record) { transactions.executeWithoutResult(status -> repository.append(record)); } diff --git a/src/messaging/messaging-inbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/JdbcInboxRepository.java b/src/messaging/messaging-reliability-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/JdbcInboxRepository.java similarity index 100% rename from src/messaging/messaging-inbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/JdbcInboxRepository.java rename to src/messaging/messaging-reliability-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/JdbcInboxRepository.java diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcAdminOperationJournal.java b/src/messaging/messaging-reliability-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcAdminOperationJournal.java similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcAdminOperationJournal.java rename to src/messaging/messaging-reliability-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcAdminOperationJournal.java diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java b/src/messaging/messaging-reliability-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java similarity index 71% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java rename to src/messaging/messaging-reliability-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java index 13b87a35..49eec646 100644 --- a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java +++ b/src/messaging/messaging-reliability-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java @@ -17,6 +17,7 @@ import dev.caskeleton.messaging.reliability.OutboxRecord; import dev.caskeleton.messaging.reliability.OutboxRepository; import dev.caskeleton.messaging.reliability.OutboxStatus; import dev.caskeleton.messaging.reliability.OutboxTransitionResult; +import java.sql.Array; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -41,7 +42,7 @@ import org.springframework.transaction.support.TransactionSynchronizationManager * already inside, which is the entire mechanism. An outbox row written on a separate connection * commits independently of the business change and reopens the window the pattern exists to close. * - *

    Leasing uses {@code SELECT ... FOR UPDATE SKIP LOCKED}. Two relay instances polling the same + *

    Claiming uses {@code SELECT ... FOR UPDATE SKIP LOCKED}. Two relay instances polling the same * table would otherwise both claim the same rows and publish them twice; {@code SKIP LOCKED} lets * the second instance step over what the first already holds instead of blocking behind it. */ @@ -55,7 +56,7 @@ public final class JdbcOutboxRepository implements OutboxRepository { producer, occurred_at, correlation_id, causation_id, tenant, partition_key, ordering_key, schema_subject, schema_uri, traceparent, tracestate, baggage) - VALUES (?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, + VALUES (?, ?, ?, ?, ?, ?, jsonb_object(?::text[]), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) @@ -72,38 +73,15 @@ public final class JdbcOutboxRepository implements OutboxRepository { private static final String COLUMNS = """ message_id, destination, message_type, schema_version, content_type, - payload, headers, created_at, status, attempts, lease_expires_at, last_failure_code, + payload, + ARRAY(SELECT h.key FROM jsonb_each_text(headers) h ORDER BY h.key) AS header_keys, + ARRAY(SELECT h.value FROM jsonb_each_text(headers) h ORDER BY h.key) AS header_values, + created_at, status, attempts, lease_expires_at, last_failure_code, producer, occurred_at, correlation_id, causation_id, tenant, partition_key, ordering_key, schema_subject, schema_uri, traceparent, tracestate, baggage\ """; - private static final String LEASE = - """ - WITH claimable AS ( - SELECT message_id - FROM messaging_outbox - -- IN_FLIGHT is claimable too, but only once its lease has expired. A relay that dies - -- mid-publish leaves rows in that state; excluding them would strand those messages - -- forever, which is the one failure mode the outbox exists to prevent. - WHERE status IN ('PENDING', 'AMBIGUOUS', 'IN_FLIGHT') - AND (lease_expires_at IS NULL OR lease_expires_at <= ?) - ORDER BY created_at - LIMIT ? - FOR UPDATE SKIP LOCKED - ) - UPDATE messaging_outbox o - SET status = 'IN_FLIGHT', lease_expires_at = ? - FROM claimable c - WHERE o.message_id = c.message_id - RETURNING o.message_id, o.destination, o.message_type, o.schema_version, o.content_type, - o.payload, o.headers, o.created_at, o.status, o.attempts, - o.lease_expires_at, o.last_failure_code, - o.producer, o.occurred_at, o.correlation_id, o.causation_id, o.tenant, - o.partition_key, o.ordering_key, o.schema_subject, o.schema_uri, - o.traceparent, o.tracestate, o.baggage - """; - /** * The claim that records who holds the row and increments its fencing token. * @@ -147,7 +125,11 @@ public final class JdbcOutboxRepository implements OutboxRepository { FROM claimable c WHERE o.message_id = c.message_id RETURNING o.message_id, o.destination, o.message_type, o.schema_version, o.content_type, - o.payload, o.headers, o.created_at, o.status, o.attempts, + o.payload, + ARRAY(SELECT h.key FROM jsonb_each_text(o.headers) h ORDER BY h.key) AS header_keys, + ARRAY(SELECT h.value FROM jsonb_each_text(o.headers) h ORDER BY h.key) + AS header_values, + o.created_at, o.status, o.attempts, o.lease_expires_at, o.last_failure_code, o.lease_owner, o.lease_token, o.producer, o.occurred_at, o.correlation_id, o.causation_id, o.tenant, o.partition_key, o.ordering_key, o.schema_subject, o.schema_uri, @@ -187,7 +169,7 @@ public final class JdbcOutboxRepository implements OutboxRepository { statement.setInt(4, record.schemaVersion().value()); statement.setString(5, record.contentType().value()); statement.setBytes(6, record.payload()); - statement.setString(7, toJson(record.headers())); + statement.setArray(7, connection.createArrayOf("text", flatten(record.headers()))); statement.setTimestamp(8, Timestamp.from(record.createdAt())); statement.setString(9, record.status().name()); statement.setInt(10, record.attempts()); @@ -258,33 +240,6 @@ public final class JdbcOutboxRepository implements OutboxRepository { } } - @Override - public List leaseBatch(int batchSize, Duration leaseDuration, Instant now) { - Objects.requireNonNull(leaseDuration, "leaseDuration must not be null"); - Objects.requireNonNull(now, "now must not be null"); - return withConnection( - connection -> { - List leased = new ArrayList<>(); - try (PreparedStatement statement = connection.prepareStatement(LEASE)) { - statement.setTimestamp(1, Timestamp.from(now)); - statement.setInt(2, batchSize); - statement.setTimestamp(3, Timestamp.from(now.plus(leaseDuration))); - try (ResultSet results = statement.executeQuery()) { - while (results.next()) { - leased.add(read(results)); - } - } - } - return List.copyOf(leased); - }); - } - - @Override - public List claimBatch( - String owner, int batchSize, Duration leaseDuration, Instant now) { - return claimBatch(owner, batchSize, leaseDuration, now, Integer.MAX_VALUE); - } - @Override public List claimBatch( String owner, int batchSize, Duration leaseDuration, Instant now, int maxAttempts) { @@ -328,11 +283,6 @@ public final class JdbcOutboxRepository implements OutboxRepository { null); } - @Override - public OutboxTransitionResult markAmbiguous(OutboxLease lease, String failureCode, Instant now) { - return markAmbiguous(lease, failureCode, now, now); - } - @Override public OutboxTransitionResult markAmbiguous( OutboxLease lease, String failureCode, Instant now, Instant nextAttemptAt) { @@ -435,49 +385,6 @@ public final class JdbcOutboxRepository implements OutboxRepository { }); } - public void markPublishedUnfenced(MessageId messageId, Instant now) { - update( - "UPDATE messaging_outbox SET status = 'PUBLISHED', published_at = ?, " - + "lease_expires_at = NULL, attempts = attempts + 1 WHERE message_id = ?", - messageId, - now, - null); - } - - public void markAmbiguousUnfenced(MessageId messageId, String failureCode, Instant now) { - // The lease is released rather than held: an ambiguous row must become claimable again so the - // relay retries it under the same message id. - update( - "UPDATE messaging_outbox SET status = 'AMBIGUOUS', lease_expires_at = NULL, " - + "last_failure_code = ?, attempts = attempts + 1 WHERE message_id = ?", - messageId, - now, - failureCode); - } - - public void markFailedUnfenced(MessageId messageId, String failureCode, Instant now) { - update( - "UPDATE messaging_outbox SET status = 'FAILED', lease_expires_at = NULL, " - + "last_failure_code = ?, attempts = attempts + 1 WHERE message_id = ?", - messageId, - now, - failureCode); - } - - public void releaseLeaseUnfenced(MessageId messageId) { - withConnection( - connection -> { - try (PreparedStatement statement = - connection.prepareStatement( - "UPDATE messaging_outbox SET status = 'PENDING', lease_expires_at = NULL " - + "WHERE message_id = ? AND status = 'IN_FLIGHT'")) { - statement.setObject(1, messageId.value()); - statement.executeUpdate(); - } - return null; - }); - } - @Override public Optional find(MessageId messageId) { return withConnection( @@ -526,22 +433,6 @@ public final class JdbcOutboxRepository implements OutboxRepository { }); } - private void update(String sql, MessageId messageId, Instant now, String failureCode) { - withConnection( - connection -> { - try (PreparedStatement statement = connection.prepareStatement(sql)) { - if (failureCode == null) { - statement.setTimestamp(1, Timestamp.from(now)); - } else { - statement.setString(1, failureCode); - } - statement.setObject(2, messageId.value()); - statement.executeUpdate(); - } - return null; - }); - } - private static OutboxRecord read(ResultSet results) throws SQLException { Timestamp lease = results.getTimestamp("lease_expires_at"); return new OutboxRecord( @@ -551,7 +442,7 @@ public final class JdbcOutboxRepository implements OutboxRepository { new SchemaVersion(results.getInt("schema_version")), new ContentType(results.getString("content_type")), results.getBytes("payload"), - fromJson(results.getString("headers")), + headers(results.getArray("header_keys"), results.getArray("header_values")), readMetadata(results), results.getTimestamp("created_at").toInstant(), OutboxStatus.valueOf(results.getString("status")), @@ -597,119 +488,36 @@ public final class JdbcOutboxRepository implements OutboxRepository { } /** - * Serialises headers as a flat JSON object. + * The headers as one flat key, value, key, value array for {@code jsonb_object(text[])}. * - *

    Hand-rolled rather than pulled from a JSON library so this module keeps no codec dependency: - * outbox headers are always flat string pairs, validated by {@code MessageHeaders} before they - * ever reach here. + *

    PostgreSQL builds and escapes the JSON. The hand-rolled writer and reader this replaces got + * the escaping right one way and wrong the other: the reader took a quote after an escaped + * backslash for an escaped quote, so a value ending in a backslash ran on into the next header. */ - private static String toJson(Map headers) { - StringBuilder json = new StringBuilder("{"); - boolean first = true; + private static String[] flatten(Map headers) { + String[] flat = new String[headers.size() * 2]; + int index = 0; for (Map.Entry entry : headers.entrySet()) { - if (!first) { - json.append(','); - } - first = false; - json.append('"') - .append(escape(entry.getKey())) - .append("\":\"") - .append(escape(entry.getValue())) - .append('"'); + flat[index++] = entry.getKey(); + flat[index++] = entry.getValue(); } - return json.append('}').toString(); + return flat; } - private static Map fromJson(String json) { + /** Rebuilds the headers from the aligned key and value arrays the reads select. */ + private static Map headers(Array keys, Array values) throws SQLException { Map headers = new LinkedHashMap<>(); - if (json == null || json.length() <= 2) { + if (keys == null || values == null) { return headers; } - String body = json.substring(1, json.length() - 1); - int index = 0; - while (index < body.length()) { - int keyStart = body.indexOf('"', index); - if (keyStart < 0) { - break; - } - int keyEnd = findClosingQuote(body, keyStart + 1); - int valueStart = body.indexOf('"', body.indexOf(':', keyEnd)); - int valueEnd = findClosingQuote(body, valueStart + 1); - headers.put( - unescape(body.substring(keyStart + 1, keyEnd)), - unescape(body.substring(valueStart + 1, valueEnd))); - index = valueEnd + 1; + String[] names = (String[]) keys.getArray(); + String[] texts = (String[]) values.getArray(); + for (int index = 0; index < names.length; index++) { + headers.put(names[index], texts[index]); } return headers; } - private static int findClosingQuote(String text, int from) { - for (int index = from; index < text.length(); index++) { - if (text.charAt(index) == '"' && text.charAt(index - 1) != '\\') { - return index; - } - } - return text.length(); - } - - /** - * JSON string escaping, including the control characters. - * - *

    Only backslash and quote were escaped. A header value containing a newline or a NUL — which - * the value objects now refuse, but which older rows and other writers may still carry — produced - * a document PostgreSQL rejects as invalid JSONB, so the append failed at the database with an - * error naming neither the header nor the row. Control characters are the part of the JSON - * grammar that is easy to forget and impossible to get away with. - */ - private static String escape(String value) { - StringBuilder escaped = new StringBuilder(value.length() + 8); - for (int index = 0; index < value.length(); index++) { - char character = value.charAt(index); - switch (character) { - case '\\' -> escaped.append("\\\\"); - case '"' -> escaped.append("\\\""); - case '\n' -> escaped.append("\\n"); - case '\r' -> escaped.append("\\r"); - case '\t' -> escaped.append("\\t"); - case '\b' -> escaped.append("\\b"); - case '\f' -> escaped.append("\\f"); - default -> { - if (character < 0x20) { - escaped.append("\\u%04x".formatted((int) character)); - } else { - escaped.append(character); - } - } - } - } - return escaped.toString(); - } - - private static String unescape(String value) { - StringBuilder plain = new StringBuilder(value.length()); - for (int index = 0; index < value.length(); index++) { - char character = value.charAt(index); - if (character != '\\' || index == value.length() - 1) { - plain.append(character); - continue; - } - char next = value.charAt(++index); - switch (next) { - case 'n' -> plain.append('\n'); - case 'r' -> plain.append('\r'); - case 't' -> plain.append('\t'); - case 'b' -> plain.append('\b'); - case 'f' -> plain.append('\f'); - case 'u' -> { - plain.append((char) Integer.parseInt(value.substring(index + 1, index + 5), 16)); - index += 4; - } - default -> plain.append(next); - } - } - return plain.toString(); - } - /** A unit of work against a borrowed connection. */ @FunctionalInterface private interface ConnectionCallback { diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/resources/db/migration/messaging/V1001__messaging_outbox.sql b/src/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration/messaging/V1001__messaging_outbox.sql similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/resources/db/migration/messaging/V1001__messaging_outbox.sql rename to src/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration/messaging/V1001__messaging_outbox.sql diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/resources/db/migration/messaging/V1002__messaging_outbox_lease_fencing.sql b/src/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration/messaging/V1002__messaging_outbox_lease_fencing.sql similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/resources/db/migration/messaging/V1002__messaging_outbox_lease_fencing.sql rename to src/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration/messaging/V1002__messaging_outbox_lease_fencing.sql diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/resources/db/migration/messaging/V1003__messaging_admin_operation_journal.sql b/src/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration/messaging/V1003__messaging_admin_operation_journal.sql similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/resources/db/migration/messaging/V1003__messaging_admin_operation_journal.sql rename to src/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration/messaging/V1003__messaging_admin_operation_journal.sql diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/resources/db/migration/messaging/V1004__messaging_outbox_canonical_metadata.sql b/src/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration/messaging/V1004__messaging_outbox_canonical_metadata.sql similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/resources/db/migration/messaging/V1004__messaging_outbox_canonical_metadata.sql rename to src/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration/messaging/V1004__messaging_outbox_canonical_metadata.sql diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/resources/db/migration/messaging/V1005__messaging_outbox_ordering_key_index.sql b/src/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration/messaging/V1005__messaging_outbox_ordering_key_index.sql similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/resources/db/migration/messaging/V1005__messaging_outbox_ordering_key_index.sql rename to src/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration/messaging/V1005__messaging_outbox_ordering_key_index.sql diff --git a/src/messaging/messaging-inbox-jdbc-postgresql/src/main/resources/db/migration/messaging/V1101__messaging_inbox.sql b/src/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration/messaging/V1101__messaging_inbox.sql similarity index 100% rename from src/messaging/messaging-inbox-jdbc-postgresql/src/main/resources/db/migration/messaging/V1101__messaging_inbox.sql rename to src/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration/messaging/V1101__messaging_inbox.sql diff --git a/src/messaging/messaging-inbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/inbox/JdbcInboxTransactionRequirementTest.java b/src/messaging/messaging-reliability-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/inbox/JdbcInboxTransactionRequirementTest.java similarity index 100% rename from src/messaging/messaging-inbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/inbox/JdbcInboxTransactionRequirementTest.java rename to src/messaging/messaging-reliability-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/inbox/JdbcInboxTransactionRequirementTest.java diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/JdbcOutboxTransactionRequirementTest.java b/src/messaging/messaging-reliability-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/JdbcOutboxTransactionRequirementTest.java similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/JdbcOutboxTransactionRequirementTest.java rename to src/messaging/messaging-reliability-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/JdbcOutboxTransactionRequirementTest.java diff --git a/src/messaging/messaging-reliability/build.gradle b/src/messaging/messaging-reliability/build.gradle new file mode 100644 index 00000000..9c08eb50 --- /dev/null +++ b/src/messaging/messaging-reliability/build.gradle @@ -0,0 +1,19 @@ +plugins { + id 'ca.platform-module' +} + +// The outbox relay and the inbox consumer logic, framework-free. What they store and claim goes +// through the ports in messaging-reliability-api; the relational implementation of those ports is +// messaging-reliability-jdbc-postgresql. Split so a leaf's name says what it depends on: this one +// is Java stdlib plus the messaging APIs, the other is Spring JDBC and PostgreSQL SQL. +dependencies { + api project(':messaging:messaging-core-api') + api project(':messaging:messaging-reliability-api') + // The relay hands encoded rows to the publisher as EncodedMessage. + api project(':messaging:messaging-schema-api') + + // Test-only. The relay is also driven through the real DefaultMessagePublisher: a fake publisher + // accepted the pre-encoded rows the real one re-encoded and rejected. + testImplementation project(':messaging:messaging-runtime-core') + testImplementation project(':messaging:messaging-policy') +} diff --git a/src/messaging/messaging-reliability/gradle.lockfile b/src/messaging/messaging-reliability/gradle.lockfile new file mode 100644 index 00000000..58cc2a9c --- /dev/null +++ b/src/messaging/messaging-reliability/gradle.lockfile @@ -0,0 +1,89 @@ +# 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. +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.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.puppycrawl.tools:checkstyle:13.5.0=checkstyle +commons-beanutils:commons-beanutils:1.11.0=checkstyle +commons-collections:commons-collections:3.2.2=checkstyle +commons-io:commons-io:2.21.0=spotbugs +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=testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-core:1.16.7=testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=testCompileClasspath,testRuntimeClasspath +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +jaxen:jaxen:2.0.6=spotbugs +net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs +org.antlr:antlr4-runtime:4.13.2=checkstyle +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=spotbugs +org.apache.logging.log4j:log4j-core:2.25.5=spotbugs +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.xbean:xbean-reflect:3.7=checkstyle +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath +org.assertj:assertj-core:3.27.7=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.hdrhistogram:HdrHistogram:2.2.2=testRuntimeClasspath +org.javassist:javassist:3.28.0-GA=checkstyle +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,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.latencyutils:LatencyUtils:2.0.3=testRuntimeClasspath +org.mockito:mockito-core:5.20.0=mockitoAgent +org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath +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.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.reflections:reflections:0.10.2=checkstyle +org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j +org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j +org.slf4j:slf4j-simple:2.0.18=checkstyle +org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs +empty=compileClasspath,runtimeClasspath diff --git a/src/messaging/messaging-inbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/IdempotentConsumer.java b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/IdempotentConsumer.java similarity index 100% rename from src/messaging/messaging-inbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/IdempotentConsumer.java rename to src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/IdempotentConsumer.java diff --git a/src/messaging/messaging-inbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/InboxCleanupJob.java b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/InboxCleanupJob.java similarity index 100% rename from src/messaging/messaging-inbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/InboxCleanupJob.java rename to src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/InboxCleanupJob.java diff --git a/src/messaging/messaging-inbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/InboxOutcome.java b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/InboxOutcome.java similarity index 100% rename from src/messaging/messaging-inbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/InboxOutcome.java rename to src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/InboxOutcome.java diff --git a/src/messaging/messaging-inbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/InboxRetentionPolicy.java b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/InboxRetentionPolicy.java similarity index 100% rename from src/messaging/messaging-inbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/InboxRetentionPolicy.java rename to src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/InboxRetentionPolicy.java diff --git a/src/messaging/messaging-inbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/TransactionalInboxHandler.java b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/TransactionalInboxHandler.java similarity index 100% rename from src/messaging/messaging-inbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/inbox/TransactionalInboxHandler.java rename to src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/TransactionalInboxHandler.java diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxCleanupJob.java b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxCleanupJob.java similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxCleanupJob.java rename to src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxCleanupJob.java diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxEnvelopeFactory.java b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxEnvelopeFactory.java similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxEnvelopeFactory.java rename to src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxEnvelopeFactory.java diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxProperties.java b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxProperties.java similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxProperties.java rename to src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxProperties.java diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelay.java b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelay.java similarity index 99% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelay.java rename to src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelay.java index 52350c57..566f93c8 100644 --- a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelay.java +++ b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelay.java @@ -158,7 +158,7 @@ public final class OutboxRelay { */ public OutboxRelayReport runOnce(Instant now) { Objects.requireNonNull(now, "now must not be null"); - // claimBatch, not leaseBatch: the claim carries an owner and a fencing token, and every write + // The claim carries an owner and a fencing token, and every write // below is conditioned on them. Without that, a relay that stalled past its lease could record // AMBIGUOUS over the PUBLISHED another relay had already written, making a confirmed message // claimable again. diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelayReport.java b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelayReport.java similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelayReport.java rename to src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelayReport.java diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelayWorker.java b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelayWorker.java similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelayWorker.java rename to src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxRelayWorker.java diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxRetryScheduler.java b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxRetryScheduler.java similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/OutboxRetryScheduler.java rename to src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/outbox/OutboxRetryScheduler.java diff --git a/src/messaging/messaging-inbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/inbox/IdempotentConsumerTest.java b/src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/inbox/IdempotentConsumerTest.java similarity index 100% rename from src/messaging/messaging-inbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/inbox/IdempotentConsumerTest.java rename to src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/inbox/IdempotentConsumerTest.java diff --git a/src/messaging/messaging-inbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/inbox/InboxOperationsTest.java b/src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/inbox/InboxOperationsTest.java similarity index 100% rename from src/messaging/messaging-inbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/inbox/InboxOperationsTest.java rename to src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/inbox/InboxOperationsTest.java diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxEnvelopeFactoryTest.java b/src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/outbox/OutboxEnvelopeFactoryTest.java similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxEnvelopeFactoryTest.java rename to src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/outbox/OutboxEnvelopeFactoryTest.java diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxOperationsTest.java b/src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/outbox/OutboxOperationsTest.java similarity index 91% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxOperationsTest.java rename to src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/outbox/OutboxOperationsTest.java index 7eb3f0ac..2a52e0e1 100644 --- a/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxOperationsTest.java +++ b/src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/outbox/OutboxOperationsTest.java @@ -35,17 +35,6 @@ class OutboxOperationsTest { throw new UnsupportedOperationException(); } - @Override - public List leaseBatch(int batchSize, Duration leaseDuration, Instant now) { - throw new UnsupportedOperationException(); - } - - @Override - public java.util.List claimBatch( - String owner, int batchSize, Duration leaseDuration, Instant now) { - return java.util.List.of(); - } - @Override public java.util.List claimBatch( String owner, int batchSize, Duration leaseDuration, Instant now, int maxAttempts) { @@ -58,7 +47,7 @@ class OutboxOperationsTest { String failureCode, Instant now, Instant nextAttemptAt) { - return markAmbiguous(lease, failureCode, now); + throw new UnsupportedOperationException(); } @Override @@ -73,12 +62,6 @@ class OutboxOperationsTest { throw new UnsupportedOperationException(); } - @Override - public dev.caskeleton.messaging.reliability.OutboxTransitionResult markAmbiguous( - dev.caskeleton.messaging.reliability.OutboxLease lease, String failureCode, Instant now) { - throw new UnsupportedOperationException(); - } - @Override public dev.caskeleton.messaging.reliability.OutboxTransitionResult markFailed( dev.caskeleton.messaging.reliability.OutboxLease lease, String failureCode, Instant now) { diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayTest.java b/src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayTest.java similarity index 95% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayTest.java rename to src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayTest.java index 8749e0b6..fdc8591c 100644 --- a/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayTest.java +++ b/src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayTest.java @@ -199,15 +199,18 @@ class OutboxRelayTest { assertThat(repository.find(record.messageId()).orElseThrow().status()) .isEqualTo(OutboxStatus.FAILED); - assertThat(repository.leaseBatch(10, Duration.ofSeconds(30), NOW)).isEmpty(); + assertThat(repository.claimBatch("relay", 10, Duration.ofSeconds(30), NOW, Integer.MAX_VALUE)) + .isEmpty(); } @Test void aLeasedRowIsInvisibleToAnotherRelayInstance() { repository.append(OutboxFixtures.pending()); - List first = repository.leaseBatch(10, Duration.ofSeconds(30), NOW); - List second = repository.leaseBatch(10, Duration.ofSeconds(30), NOW); + List first = + repository.claimBatch("relay-a", 10, Duration.ofSeconds(30), NOW, Integer.MAX_VALUE); + List second = + repository.claimBatch("relay-b", 10, Duration.ofSeconds(30), NOW, Integer.MAX_VALUE); assertThat(first).hasSize(1); assertThat(second).isEmpty(); @@ -216,10 +219,11 @@ class OutboxRelayTest { @Test void anExpiredLeaseBecomesClaimableAgain() { repository.append(OutboxFixtures.pending()); - repository.leaseBatch(10, Duration.ofSeconds(30), NOW); + repository.claimBatch("relay-a", 10, Duration.ofSeconds(30), NOW, Integer.MAX_VALUE); - List reclaimed = - repository.leaseBatch(10, Duration.ofSeconds(30), NOW.plusSeconds(31)); + List reclaimed = + repository.claimBatch( + "relay-b", 10, Duration.ofSeconds(30), NOW.plusSeconds(31), Integer.MAX_VALUE); assertThat(reclaimed).hasSize(1); } @@ -352,8 +356,7 @@ final class InMemoryOutboxRepository implements OutboxRepository { * thing it stands in for hides exactly the defects it was written to catch, so this one follows * the same three-state rule. */ - @Override - public List leaseBatch(int batchSize, Duration leaseDuration, Instant now) { + private List lease(int batchSize, Duration leaseDuration, Instant now) { List leased = new ArrayList<>(); for (OutboxRecord record : List.copyOf(rows.values())) { if (leased.size() >= batchSize) { @@ -376,11 +379,10 @@ final class InMemoryOutboxRepository implements OutboxRepository { return List.copyOf(leased); } - @Override - public List claimBatch( + private List claimIgnoringBudget( String owner, int batchSize, Duration leaseDuration, Instant now) { List claimed = new ArrayList<>(); - for (OutboxRecord record : leaseBatch(batchSize, leaseDuration, now)) { + for (OutboxRecord record : lease(batchSize, leaseDuration, now)) { long token = tokens.merge(record.messageId(), 1L, Long::sum); owners.put(record.messageId(), owner); claimed.add(new OutboxLease(record, owner, token, now.plus(leaseDuration))); @@ -408,7 +410,7 @@ final class InMemoryOutboxRepository implements OutboxRepository { public List claimBatch( String owner, int batchSize, Duration leaseDuration, Instant now, int maxAttempts) { List claimed = new ArrayList<>(); - for (OutboxLease lease : claimBatch(owner, batchSize, leaseDuration, now)) { + for (OutboxLease lease : claimIgnoringBudget(owner, batchSize, leaseDuration, now)) { Instant nextAttempt = nextAttempts.get(lease.messageId()); boolean waiting = nextAttempt != null && now.isBefore(nextAttempt); if (waiting || lease.record().attempts() >= maxAttempts) { @@ -424,11 +426,13 @@ final class InMemoryOutboxRepository implements OutboxRepository { @Override public OutboxTransitionResult markAmbiguous( OutboxLease lease, String failureCode, Instant now, Instant nextAttemptAt) { - OutboxTransitionResult result = markAmbiguous(lease, failureCode, now); - if (result == OutboxTransitionResult.APPLIED) { - nextAttempts.put(lease.messageId(), nextAttemptAt); + if (!owns(lease)) { + return OutboxTransitionResult.STALE_LEASE; } - return result; + markAmbiguousUnfenced(lease.messageId(), failureCode); + owners.remove(lease.messageId()); + nextAttempts.put(lease.messageId(), nextAttemptAt); + return OutboxTransitionResult.APPLIED; } @Override @@ -452,16 +456,6 @@ final class InMemoryOutboxRepository implements OutboxRepository { return OutboxTransitionResult.APPLIED; } - @Override - public OutboxTransitionResult markAmbiguous(OutboxLease lease, String failureCode, Instant now) { - if (!owns(lease)) { - return OutboxTransitionResult.STALE_LEASE; - } - markAmbiguousUnfenced(lease.messageId(), failureCode); - owners.remove(lease.messageId()); - return OutboxTransitionResult.APPLIED; - } - @Override public OutboxTransitionResult markFailed(OutboxLease lease, String failureCode, Instant now) { if (!owns(lease)) { diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayWorkerTest.java b/src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayWorkerTest.java similarity index 100% rename from src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayWorkerTest.java rename to src/messaging/messaging-reliability/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayWorkerTest.java diff --git a/src/messaging/messaging-spring-boot-starter/build.gradle b/src/messaging/messaging-spring-boot-starter/build.gradle index acae04e6..88f47178 100644 --- a/src/messaging/messaging-spring-boot-starter/build.gradle +++ b/src/messaging/messaging-spring-boot-starter/build.gradle @@ -31,8 +31,9 @@ dependencies { // which is why MessagingCoreAutoConfiguration consumed a MessagePublisher that nothing in // reach could produce (MSG-INT-003). implementation project(':messaging:messaging-runtime-core') - implementation project(':messaging:messaging-outbox-jdbc-postgresql') - implementation project(':messaging:messaging-inbox-jdbc-postgresql') + // The relay and consumer logic, and the PostgreSQL stores behind their ports. + implementation project(':messaging:messaging-reliability') + implementation project(':messaging:messaging-reliability-jdbc-postgresql') implementation project(':messaging:messaging-admin-api') implementation project(':messaging:messaging-admin-runtime') diff --git a/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingOutboxRelayLifecycleTest.java b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingOutboxRelayLifecycleTest.java index 5c9e3b00..db68ef1d 100644 --- a/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingOutboxRelayLifecycleTest.java +++ b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingOutboxRelayLifecycleTest.java @@ -171,28 +171,11 @@ class MessagingOutboxRelayLifecycleTest { throw new UnsupportedOperationException("not used by this test"); } - @Override - public List leaseBatch(int batchSize, Duration leaseDuration, Instant now) { - throw new UnsupportedOperationException("not used by this test"); - } - - @Override - public List claimBatch( - String owner, int batchSize, Duration leaseDuration, Instant now) { - throw new UnsupportedOperationException("not used by this test"); - } - @Override public OutboxTransitionResult markPublished(OutboxLease lease, Instant now) { throw new UnsupportedOperationException("not used by this test"); } - @Override - public OutboxTransitionResult markAmbiguous( - OutboxLease lease, String failureCode, Instant now) { - throw new UnsupportedOperationException("not used by this test"); - } - @Override public OutboxTransitionResult markAmbiguous( OutboxLease lease, String failureCode, Instant now, Instant nextAttemptAt) { diff --git a/src/sample-portfolio/CLAUDE.md b/src/sample-portfolio/CLAUDE.md index 458de77c..76e3fc34 100644 --- a/src/sample-portfolio/CLAUDE.md +++ b/src/sample-portfolio/CLAUDE.md @@ -22,9 +22,11 @@ Package root: `dev.caskeleton.sample.portfolio`. `RepoStatsAclMapper`), `adapter/identifier` (`UuidWorkLogIdFactory`). - Contract-test fixtures the app-bootstrap verification suite analyses (`DomainExceptionHandler`, `PortfolioErrorCode`, wire/contract tests). -- Disposable messaging contract fixture: the exact `WorkLogReservedPayload` record, its static - application-core contract contribution, sample-owned schema/digest and golden vectors. It is not - runtime-discovered, and validator compatibility remains unproven until messaging Task 6. +- The sample's integration-event contracts: `WorkLogReservedPayload` with its contribution, + schema/digest and golden vectors, and the poster contracts in `PortfolioEventContracts`. Every + outbox append goes through `PortfolioEventOutbox` → the application's encoder → the canonical + `OutboxAppendPort`. The composition registers each contract as a bean; nothing is + classpath-discovered, and payloads are not validated against their JSON Schema. - Sample application collaborators consume invocation context through application-core ports and must not import SLF4J/MDC. diff --git a/src/sample-portfolio/README.md b/src/sample-portfolio/README.md index e52abe8c..e8efef76 100644 --- a/src/sample-portfolio/README.md +++ b/src/sample-portfolio/README.md @@ -125,7 +125,7 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ - "WorkLog 기간이 예약됨"이라는 도메인 사실을 표현하는 이벤트입니다. **전송(transport)과 무관**합니다 — 도메인 데이터(`WorkLogId`/`WorkCategory`/`LocalDate`)만 담고 broker/wire/HTTP 타입을 일절 참조하지 않습니다. 이것을 발행 가능한 integration 이벤트로 바꾸는 일은 application - 경계의 몫입니다(`application.event.WorkLogReservedIntegrationEvent` 와 그 매퍼 참고). + 경계의 몫입니다(`application.event.WorkLogReservedPayload` 와 `PortfolioEventOutbox` 참고). ### 포트 — WorkLogRepository / WorkLogIdFactory / OutboxEventIdFactory - **WorkLogRepository**: WorkLog 영속 아웃바운드 포트(구현은 adapter-persistence). `findPage` 는 @@ -134,8 +134,8 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ - **WorkLogIdFactory / OutboxEventIdFactory**: id 를 만들어 주는 도메인 포트. 둘을 **굳이 따로 둔 이유**는, 애그리거트 식별자 타입(`WorkLogId`)이 이벤트 id 모양을 묶어버리지 않게 하기 위해서입니다. 실제로는 둘 다 UUIDv7 기반이지만(identifier 어댑터가 구현), 도메인은 생성 방식을 모릅니다. - outbox 이벤트 id 는 outbox 봉투의 `eventId` 이자 `idempotencyKey` 로 쓰입니다(같은 값 → 이벤트 - 단위 중복 제거). + outbox 이벤트 id 는 envelope 의 `eventId` 이고, consumer 는 이 값으로 중복을 거릅니다(이벤트 단위 + 중복 제거). ### RepoStats - 외부 저장소 통계를 정규화한 결과 값입니다. 아웃바운드 ACL(B7)을 통과한 뒤에만 만들어집니다. @@ -154,17 +154,21 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ ### CreateWorkLogUseCase — 생성 + outbox 동시 기록 (dual-write 금지) - WorkLog 를 저장하면서 `WorkLogReserved` outbox 이벤트를 **같은 쓰기 트랜잭션 안에서** 함께 - 적재하는 예시입니다. 핵심은 `repository.save(...)` 와 `outboxAppendPort.append(...)` 가 같은 + 적재하는 예시입니다. 핵심은 `repository.save(...)` 와 outbox append 가 같은 `tx.inWrite { ... }` 블록 안에 있다는 점입니다. 저장이나 적재 중 하나라도 실패하면 트랜잭션 전체가 롤백됩니다 — "DB 한 번, 브로커 한 번" 식의 분리된 이중 쓰기(dual-write)를 막는 보장입니다. -- 순서: ① 저장된 애그리거트로 도메인 이벤트 생성 → ② 매퍼로 integration 이벤트로 변환(경계는 - application) → ③ 직접 만든 JSON 페이로드로 직렬화 → ④ 같은 트랜잭션에서 outbox 에 append. -- `eventId` 는 `OutboxEventIdFactory`(UUIDv7) 로 만들고, `idempotencyKey = eventId` 로 둡니다 - (이벤트 단위 중복 제거). +- 순서: ① 저장된 애그리거트로 도메인 이벤트 생성 → ② payload record(`WorkLogReservedPayload`)로 + 변환(경계는 application) → ③ `PortfolioEventOutbox` 가 draft 를 만들어 `IntegrationEventEncoderPort` + 로 encode → ④ 같은 트랜잭션에서 `OutboxAppendPort` 에 append. outbox append 모델은 canonical + 하나입니다(소유자 결정 7). 포스터 이벤트(`PosterEventPublisher`, `PosterImagePublicationEventPublisher`)도 + 같은 길로 갑니다. +- `eventId` 는 `OutboxEventIdFactory`(UUIDv7) 로 만듭니다(이벤트 단위 중복 제거 키). - `correlationId` 는 application-core의 `CorrelationIdPort`로 읽습니다. inbound web adapter가 sanitized MDC 값을 포트 뒤에서 제공하므로 sample application 코드는 SLF4J/MDC를 알지 않습니다. - 요청 밖에서 실행되거나 값이 blank면 `eventId`를 그대로 `correlationId`로 사용해 이벤트가 - 최소한 자신을 가리키게(self-correlation) 폴백합니다. + 요청 밖에서 실행되거나 값이 blank이거나 canonical identity 문법에 맞지 않으면 `eventId`를 그대로 + `correlationId`로 사용해 이벤트가 최소한 자신을 가리키게(self-correlation) 폴백합니다. +- aggregate 순서는 발생 시각(마이크로초)입니다. sample 애그리거트에는 event 카운터가 없고, 시간 + 순서는 옛 outbox 가 풀어 주던 순서와 같습니다. version 컬럼이 있는 서비스는 그것을 씁니다. - 쓰기 작업이라 `@RequiresPermission("worklog:write")` 로 권한을 요구합니다(이 권한은 `user`/`admin` 역할 묶음에 부여). @@ -207,22 +211,6 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ projection 도 저장소 기반이면 여전히 `READ_REPOSITORY` 입니다 — "projection 이냐 애그리거트냐"는 반환 *모양*의 축이고, 저장소 접근 *수준*과는 별개라서 새 capability enum 이 필요 없습니다. -### WorkLogReservedIntegrationEvent / …Mapper — integration(wire) 이벤트 -- **IntegrationEvent**: 도메인 이벤트와 달리 아웃바운드 어댑터가 실제로 발행할(예: Kafka) - 직렬화 가능한 경계 소유 형태입니다. 도메인 사실을 wire 계약으로 옮기는 일 — 값 객체를 원시 - 타입으로 평탄화, wire 표현 선택 — 은 application 의 관심사라서 application 계층에 둡니다. 도메인은 - wire 를 모릅니다. -- **Mapper**: 도메인 이벤트 → integration 이벤트 변환을 **application 경계에서** 수행하고, 트랜잭션 - outbox 용 JSON 페이로드 문자열로 직렬화합니다. - - JSON 직렬화(`toJson`)는 의존성을 늘리지 않으려고 RFC 8259 §7 이스케이프까지 직접 구현했습니다. - 실제 프로젝트라면 스키마 직렬화 계약(Avro/Protobuf, 스키마 레지스트리 붙은 Jackson)을 써야 - 합니다 — 샘플은 새 의존성 0을 유지합니다. 세 필드는 도메인 식별자와 enum 이름뿐이라 PII/토큰/ - 원문 본문이 없습니다. - - 이벤트 타입 이름 `"worklog.reserved"`: `도메인.동사` 패턴의 안정적인 점-구분 논리명입니다. - outbox relay 규약(`topic = eventType`)에 따라 그대로 브로커 토픽 이름이 됩니다. integration - 이벤트의 클래스 단순명을 쓰는 대안도 있지만, 클래스 이름을 바꾸면 토픽이 조용히 바뀌어 컨슈머가 - 깨질 수 있어, 안정적인 문자열 리터럴을 택했습니다(토픽 마이그레이션 계획 없이는 바꾸지 말 것). - ### WorkLogReservedPayload / …ContractContribution — canonical contract fixture - `WorkLogReservedPayload`는 새 closed contract SPI에 제공하는 exact final record다. v1은 @@ -233,12 +221,12 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ - contribution은 contract ID, exact payload type/component order, classpath resource ID, checked-in digest와 provider-neutral descriptor만 제공한다. JSON mapper, physical topic, Kafka 설정을 소유하지 않으며 매 호출 filesystem I/O도 하지 않는다. -- 기존 3-field `WorkLogReservedIntegrationEvent`/hand-rolled mapper는 현재 legacy outbox - characterization 경로에 남아 있다. 새 1-field canonical payload는 그 타입을 조용히 대체하지 않으며, - closed catalog와 encoder가 조립되기 전까지 양쪽은 서로 호출하거나 직렬화하지 않는다. -- 현재는 classpath scanning이나 runtime discovery가 없다. Task 5의 closed catalog 조립 전에는 - 자동 등록되지 않고, Task 6 validator qualification 전에는 Draft 2020-12 validator compatibility를 - 주장하지 않는다. +- `CreateWorkLogUseCase`가 이 contract로 발행한다. 예전의 3-field `WorkLogReservedIntegrationEvent`와 + 손으로 짠 JSON 매퍼는 outbox 를 canonical 로 통일하면서 삭제했다(2026-09-28). +- 포스터 이벤트의 contract 는 `PortfolioEventContracts`(schema 는 `contracts/messaging/poster.*`)에 + 있다. 조립(`SampleApplicationUseCaseConfig`)이 contract 마다 bean 을 등록하고, 템플릿 encoder 가 그 + bean 들로 닫힌 catalog 를 만든다. classpath scanning 은 없다. encoder 는 선언한 schema hash 를 schema + 파일과 대조하지만 Draft 2020-12 validator 로 payload 를 검증하지는 않는다. ### RepoStatsPort - 외부 저장소 통계를 가져오는 아웃바운드 포트(구현은 adapter-outbound). @@ -391,13 +379,14 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ ## bootstrap — 샘플 전용 구성 루트 -> **이 패키지가 왜 존재하는가 (공통 배경):** 프로덕션 조립은 `app-bootstrap` 모듈이 합니다. 그런데 +> **이 패키지가 왜 존재하는가 (공통 배경):** 프로덕션 조립은 `app-bootstrap` 모듈이 합니다. > `sample-portfolio` 는 일부러 `app-bootstrap` 에 의존하지 않습니다(샘플이 부트스트랩을 끌어오면 -> 안 됨). 그래서 스캔으로 자동 발견되지 않고 오직 `app-bootstrap` 에만 있는 구성 루트 빈들 -> (tracing/metrics/idempotency/privacy/management/domain-context 등)을, 여기 `bootstrap.*` 패키지가 -> **샘플 전용으로 동등하게 복제**해 제공합니다. 모두 일회용(disposable)입니다 — `sample-portfolio` -> 모듈을 지우면 함께 사라지고 프로덕션에는 영향이 없습니다. 프로덕션(`CaSkeletonApplication`)은 원래 -> `app-bootstrap` 빈들을 그대로 씁니다. +> 안 됨). 두 구성 루트가 함께 필요한 조립은 공용 `composition:*` 모듈이 하고, 샘플은 app-bootstrap과 +> 같은 `runtimeOnly` 한 줄로 받습니다 — tracing·metrics 계약 filter·domain context·user principal +> 가명화·actuator 보안 chain은 `composition:service-runtime`, 멱등성 executor는 +> `composition:idempotency`. 예전에는 이것들을 여기 `bootstrap.*` 패키지에 복사해 두었고, 복사본은 +> 이미 원본과 갈라져 있었습니다(런타임 어휘에 없는 `staging` 샘플 레이트, typed startup 실패 대신 +> `IllegalStateException`). 여기 남은 것은 샘플만의 결정입니다. ### SamplePortfolioApplication — 독립 실행 구성 루트 - 관계형 저장소는 다른 서비스와 똑같이 고른다: `build.gradle`의 @@ -429,35 +418,22 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ Flyway 위치는 persistence-jpa 모듈이 준다. 모듈의 `migrationStartupRunner`는 `@ConditionalOnMissingBean(FlywayMigrationStrategy)`라 이 전략이 있으면 물러난다. -### 분산 추적 복제본 — SampleTracingConfig / …Settings / …SampleRateResolver / …EnvironmentPostProcessor / SampleMicrometerSpanErrorRecorder -- `app-bootstrap` 의 tracing 구성 루트를 샘플 전용으로 옮긴 것들입니다(위 "공통 배경" 참고). tracing - 런타임(OTel/Micrometer 브리지)이 샘플 build.gradle 에 켜져 있지만, 그 빈들을 등록하는 조립 코드는 - `app-bootstrap` 에만 있어서 복제했습니다. -- **per-profile 기본 샘플 레이트(SampleRateResolver)**: `prod=0.01`, `staging=0.10`, `dev/local=1.0` - (그 외 프로파일도 1.0). 설정값(`APP_TRACING_SAMPLE_RATE`)이 `[0.0, 1.0]` 범위로 들어오면 그 값이 - per-profile 기본을 이깁니다. -- **EnvironmentPostProcessor**: 해소된 effective 레이트를 native 키 - `management.tracing.sampling.probability` 로 이어줘, 실제 OTel sampler 가 gauge 값과 일치하게 합니다. - 사용자가 native 키를 직접 지정했으면 그 값을 우선합니다. (이 PostProcessor 는 샘플 자신의 - `META-INF/spring.factories` 로 등록됩니다.) -- **SampleMicrometerSpanErrorRecorder**: 현재 span 에 예외를 `error.code` 태그와 함께 기록(D12). - Tracer 가 있으면 실제 recorder, 없으면 NOOP 로 동작합니다(adapter-web `GlobalExceptionHandler` 가 - `ObjectProvider` 로 집어 씀). +### 공용 runtime 배선 — `composition:service-runtime` +- tracing(`TracingConfig`, 샘플 레이트 resolver, sampling bridge `EnvironmentPostProcessor`, + `MicrometerSpanErrorRecorder`), metrics 계약 filter(`MetricsContractConfig`), domain context + propagator(`DomainContextConfig`), user principal 가명화(`PseudonymizationConfig`/`PrivacySettings`), + actuator 보안 chain(`ManagementSecurityConfig`)을 app-bootstrap과 같은 모듈에서 받습니다. + 설정 키(`ca-skeleton.tracing.*`, `ca-skeleton.privacy.*`)는 그대로입니다. +- 샘플 레이트 기본값은 공용 런타임 어휘(`RuntimeEnvironment`)를 따릅니다: `prod=0.01`, 그 밖은 1.0. + 샘플 복사본에만 있던 `staging=0.10` 분기는 삭제했습니다 — `staging` 프로파일은 이 템플릿에 없습니다. +- **SampleManagementSecurityConfig**: 샘플의 actuator chain은 복사본이 아니라 샘플만의 결정입니다 + (IdP 없이 둘러볼 수 있는 공개 데모라 모든 요청 허용). 공용 모듈의 chain과 같은 bean 이름 + `actuatorSecurityFilterChain` 으로 선언해, 공용 chain이 물러나게 합니다. 그래서 `loggers` 는 + 읽기 전용으로 둡니다(`SampleActuatorLoggersAccessTest`). -### 그 밖의 부트스트랩 복제본 -- **SampleMetricsContractConfig**: Micrometer `MeterFilter` 두 개를 meter 등록 전에 설치합니다 — - 고-cardinality 태그 키를 막는 필터(D8)와 SLO 기반 히스토그램 분포 필터(D9, 소유한 timer 이름에만 적용). -- **SampleIdempotencyConfig**: 샘플은 `ca-skeleton.capabilities.idempotency.provider=postgresql` - 로 `persistence-jpa` 의 PostgreSQL store 를 고릅니다. 샘플은 app-bootstrap 에 의존할 수 없으므로 - (`modules.json`) `IdempotencyExecutor` 는 이 설정이 한 번 만듭니다. app-bootstrap - `IdempotencySettings` 와 같은 prefix·같은 기본값에서 executor 가 쓰는 값만 읽고, provider 가 - `disabled` 면 만들지 않습니다. 예전 `SampleIdempotencySettings`(v1 `ca-skeleton.idempotency.ttl`)와 - `jdbc` provider 는 삭제됐습니다. -- **SamplePseudonymizationConfig / SamplePrivacySettings**: adapter-web `RequestLoggingFilter` 가 - `UserPrincipalPseudonymizerPort` 를 주입받으므로 그 포트를 채웁니다. salt 는 - `APP_PRIVACY_PSEUDONYMIZATION_SALT` 에서 오며, 비어 있으면 로컬/테스트가 시작은 되도록 dev 센티넬 - salt 로 폴백합니다(프로덕션 전엔 실제 시크릿 값을 넣을 것). -- **SampleDomainContextConfig**: `adapter-persistence-rdbms` 의 `DomainContextAuditContextPort` 가 - `DomainContextPropagator` 빈을 무조건 주입받으므로, 기본 `THREAD_LOCAL` 전략 구현 - (`ThreadLocalDomainContextPropagator`)을 제공합니다 — async 데코레이터를 안 켜는 WorkLog 데모에 - 적합합니다. +### 그 밖의 부트스트랩 구성 +- **멱등성 executor**: 샘플은 `ca-skeleton.capabilities.idempotency.provider=postgresql` + 로 `persistence-jpa` 의 PostgreSQL store 를 고르고, executor 는 app-bootstrap 과 같은 + `composition:idempotency` 모듈이 만듭니다(`runtimeOnly` 한 줄). 예전의 샘플 복사본 + `SampleIdempotencyConfig`(상한 검증 없이 `Binder`로 읽고 store 를 하나로 가정)는 삭제됐고, + `Clock` 과 `@EnableScheduling` 만 `bootstrap/runtime/SampleSchedulingConfig` 로 남았습니다. diff --git a/src/sample-portfolio/build.gradle b/src/sample-portfolio/build.gradle index 200d0d13..d93b6f37 100644 --- a/src/sample-portfolio/build.gradle +++ b/src/sample-portfolio/build.gradle @@ -56,6 +56,13 @@ dependencies { // Object storage adapter provides the canonical staged-publication ports (declared in // application-objectstorage) the poster image publication use cases run on. runtimeOnly project(':adapter:outbound:objectstorage') + // The request-idempotency executor, built by the same module app-bootstrap uses rather than a + // sample copy. It composes over the PostgreSQL store persistence-jpa contributes. + runtimeOnly project(':composition:idempotency') + // Tracing, the metrics contract filters, domain-context propagation and user-principal + // pseudonymization: the same module app-bootstrap uses, instead of the sample copies that had + // drifted from it. The sample's public actuator chain overrides the module's by bean name. + runtimeOnly project(':composition:service-runtime') implementation project(':adapter:inbound:web') implementation project(':shared-contract') implementation 'org.springframework.boot:spring-boot-starter' @@ -101,6 +108,8 @@ dependencies { testFixturesCompileOnly 'org.springframework.boot:spring-boot-autoconfigure' // Real PostgreSQL adapter/migration semantics. + // SampleIdempotencyReplayIntegrationTest composes the executor module over the real store. + integrationTestImplementation project(':composition:idempotency') integrationTestImplementation 'org.testcontainers:testcontainers-postgresql' integrationTestImplementation 'org.testcontainers:testcontainers-junit-jupiter' integrationTestImplementation 'org.springframework.boot:spring-boot-testcontainers' diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyReplayIntegrationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyReplayIntegrationTest.java index f40e488e..dfebda4e 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyReplayIntegrationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyReplayIntegrationTest.java @@ -7,10 +7,12 @@ import dev.caskeleton.application.idempotency.IdempotentAction; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; import dev.caskeleton.application.transaction.OperationId; +import dev.caskeleton.composition.idempotency.IdempotencyAutoConfiguration; import dev.caskeleton.sample.portfolio.adapter.outbound.identifier.HmacPosterImageIdempotencyScopeDigester; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationReservation; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationReservationCodec; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageSanitizedIdempotencyContextFactory; +import dev.caskeleton.sample.portfolio.bootstrap.runtime.SampleSchedulingConfig; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; import java.nio.charset.StandardCharsets; @@ -106,9 +108,9 @@ class SampleIdempotencyReplayIntegrationTest { DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, - FlywayAutoConfiguration.class)) - .withUserConfiguration( - Class.forName(POSTGRESQL_STORE_CONFIG), SampleIdempotencyConfig.class) + FlywayAutoConfiguration.class, + IdempotencyAutoConfiguration.class)) + .withUserConfiguration(Class.forName(POSTGRESQL_STORE_CONFIG), SampleSchedulingConfig.class) .withPropertyValues( // The sample's shipped default. "ca-skeleton.capabilities.idempotency.provider=postgresql", diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/EventJson.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/EventJson.java deleted file mode 100644 index 37785bb6..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/EventJson.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.sample.portfolio.application.event; - -/** - * The one JSON string writer the sample's event payloads use. - * - *

    Three publishers each carried their own copy, and one of them escaped only the reverse solidus - * and the quote — a value holding a control character would have produced a payload that is not - * JSON. The sample stays framework-free in its application layer, so this is a small RFC 8259 §7 - * writer rather than a Jackson dependency. - */ -final class EventJson { - - private EventJson() {} - - /** A {@code "key":"value"} member with the value escaped per RFC 8259 §7. */ - static String field(String key, String value) { - return "\"" + key + "\":\"" + escape(value) + "\""; - } - - /** A {@code "key":number} member. */ - static String number(String key, long value) { - return "\"" + key + "\":" + value; - } - - /** - * Escapes a string for a JSON string literal: reverse solidus, quotation mark and the C0 control - * characters (U+0000–U+001F), the escapes RFC 8259 §7 makes mandatory. {@code null} is written as - * the empty string. - */ - static String escape(String value) { - if (value == null) { - return ""; - } - StringBuilder escaped = new StringBuilder(value.length()); - for (int index = 0; index < value.length(); index++) { - char c = value.charAt(index); - if (c == '\\') { - escaped.append("\\\\"); - } else if (c == '"') { - escaped.append("\\\""); - } else if (c < 0x20) { - escaped.append(String.format("\\u%04x", (int) c)); - } else { - escaped.append(c); - } - } - return escaped.toString(); - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContract.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContract.java new file mode 100644 index 00000000..3540181c --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContract.java @@ -0,0 +1,80 @@ +package dev.caskeleton.sample.portfolio.application.event; + +import dev.caskeleton.application.messaging.contract.ContractDescriptor; +import dev.caskeleton.application.messaging.contract.ContractId; +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; +import dev.caskeleton.application.messaging.contract.IntegrationPayload; +import dev.caskeleton.application.messaging.contract.LogicalDestinationId; +import dev.caskeleton.application.messaging.contract.SchemaResourceId; +import dev.caskeleton.application.messaging.contract.Sha256; +import java.lang.reflect.RecordComponent; +import java.time.Duration; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; + +/** + * One portfolio integration-event contract: its id and payload version, the payload record, and the + * SHA-256 of its schema file under {@code contracts/messaging//v.schema.json}. + * + *

    Every portfolio event goes to the same logical destination under the same delivery descriptor, + * so only what differs between contracts is a component here. The encoder checks the declared hash + * against the schema file at startup; editing a schema without its hash fails the boot rather than + * stamping events with a hash of a schema that no longer exists. + * + * @param contractId the version-free contract id + * @param payloadVersion the payload schema version + * @param exactPayloadRecordType the payload record this contract carries + * @param payloadSchemaHash SHA-256 of the schema file's exact bytes + * @param

    the payload record type + */ +public record PortfolioEventContract

    ( + ContractId contractId, + int payloadVersion, + Class

    exactPayloadRecordType, + Sha256 payloadSchemaHash) + implements IntegrationEventContractContribution

    { + + /** Where every portfolio event goes; a deployment binds it to a broker destination. */ + public static final LogicalDestinationId DESTINATION = + new LogicalDestinationId("portfolio-domain-events"); + + private static final ContractDescriptor DESCRIPTOR = + new ContractDescriptor( + "sample-portfolio", + DESTINATION, + "json-envelope-v1", + true, + 64 * 1024, + 128 * 1024, + ContractDescriptor.SensitivityClassification.INTERNAL, + Duration.ofDays(7)); + + /** A contract whose schema hash is given as lower-case hex. */ + static

    PortfolioEventContract

    of( + String contractId, int payloadVersion, Class

    payloadType, String schemaSha256Hex) { + return new PortfolioEventContract<>( + new ContractId(contractId), + payloadVersion, + payloadType, + new Sha256(HexFormat.of().parseHex(schemaSha256Hex))); + } + + @Override + public List canonicalRecordComponentOrder() { + return Arrays.stream(exactPayloadRecordType.getRecordComponents()) + .map(RecordComponent::getName) + .toList(); + } + + @Override + public SchemaResourceId payloadSchemaResource() { + return new SchemaResourceId( + "contracts/messaging/" + contractId.value() + "/v" + payloadVersion + ".schema.json"); + } + + @Override + public ContractDescriptor descriptor() { + return DESCRIPTOR; + } +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContracts.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContracts.java new file mode 100644 index 00000000..580932b1 --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContracts.java @@ -0,0 +1,80 @@ +package dev.caskeleton.sample.portfolio.application.event; + +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; +import java.util.List; + +/** + * Every integration event the sample publishes, one constant per contract. + * + *

    The composition registers each as a bean, which is how the application's encoder learns the + * closed catalog. The hashes are of the schema files under {@code contracts/messaging/}; {@code + * PortfolioEventContractsTest} and the encoder at startup both hold them to those bytes. + */ +public final class PortfolioEventContracts { + + public static final PortfolioEventContract POSTER_CREATED = + PortfolioEventContract.of( + "poster.created", + 1, + PosterCreatedPayload.class, + "8be3a72b7b469d894d06bd30f79f565feb23fbf698674d5caee094de5a2300fb"); + + public static final PortfolioEventContract POSTER_IMAGE_ATTACHED = + PortfolioEventContract.of( + "poster.image-attached", + 1, + PosterImageAttachedPayload.class, + "8021e7676928d8cb0fd29edf052be8d37fb5e87284c3eb4b947942d395aedd99"); + + public static final PortfolioEventContract POSTER_PUBLISHED = + PortfolioEventContract.of( + "poster.published", + 1, + PosterIdPayload.class, + "d89954e3074fc015a20d616bf0ec1cb46c088fa417d78e006163f1c2dc61170c"); + + public static final PortfolioEventContract POSTER_ARCHIVED = + PortfolioEventContract.of( + "poster.archived", + 1, + PosterIdPayload.class, + "c71019a727f351aa26afbf6c9246b6cf1a7abcfd2b6bb3ee1185dfce6be504d8"); + + public static final PortfolioEventContract POSTER_DELETED = + PortfolioEventContract.of( + "poster.deleted", + 1, + PosterIdPayload.class, + "c5310821c338be5aa916d126008a0a0f4be6c6999775018ce29cbefc44c8a942"); + + public static final PortfolioEventContract + POSTER_IMAGE_ATTACHMENT_PREPARED = + PortfolioEventContract.of( + "poster.image-attachment-prepared", + 1, + PosterImageAttachmentPreparedPayload.class, + "179160ec458b710535c7846a47a1abceab1a743a3a5f11633c47c2115e82e2c4"); + + public static final PortfolioEventContract + POSTER_IMAGE_ATTACHMENT_READY = + PortfolioEventContract.of( + "poster.image-attachment-ready", + 2, + PosterImageAttachmentReadyPayload.class, + "1a256fa47c382a4900ed8f852da9256a01ef1ddb2dc5b0b75047f827ae81644e"); + + private PortfolioEventContracts() {} + + /** The closed catalog: every contract above plus {@code portfolio.worklog.reserved} v1. */ + public static List> all() { + return List.of( + POSTER_CREATED, + POSTER_IMAGE_ATTACHED, + POSTER_PUBLISHED, + POSTER_ARCHIVED, + POSTER_DELETED, + POSTER_IMAGE_ATTACHMENT_PREPARED, + POSTER_IMAGE_ATTACHMENT_READY, + new WorkLogReservedContractContribution()); + } +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutbox.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutbox.java new file mode 100644 index 00000000..c964db2a --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutbox.java @@ -0,0 +1,107 @@ +package dev.caskeleton.sample.portfolio.application.event; + +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; +import dev.caskeleton.application.messaging.contract.IntegrationPayload; +import dev.caskeleton.application.messaging.event.AggregateIdentity; +import dev.caskeleton.application.messaging.event.AggregateOrder; +import dev.caskeleton.application.messaging.event.EventId; +import dev.caskeleton.application.messaging.event.IntegrationEventDraft; +import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; +import dev.caskeleton.application.observability.CorrelationIdPort; +import dev.caskeleton.application.outbox.OutboxAppendPort; +import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory; +import java.time.Clock; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; +import java.util.regex.Pattern; + +/** + * Appends one portfolio integration event to the transactional outbox: build the draft, encode it, + * append it. MUST be called from within a use case's {@code TransactionPort.inWrite(...)} block, so + * the append joins the business write (no dual write). + * + *

    What the draft needs and a domain event does not carry is decided here, once: + * + *

      + *
    • The event id is a UUIDv7 from {@link OutboxEventIdFactory}; consumers deduplicate on it. + *
    • The correlation id is the request's, through {@link CorrelationIdPort}, when it fits the + * canonical identity grammar; otherwise — off-HTTP, or a caller-supplied header that does not + * fit — the event id. An unusable header must not fail the business write. + *
    • The aggregate order is the occurrence time in microseconds. The sample's aggregates keep no + * event counter, and time order is the order the pre-canonical outbox released them in; a + * service whose aggregate has a version column should use that instead. + *
    + */ +public final class PortfolioEventOutbox { + + /** The tenant every sample aggregate belongs to; the sample is single-tenant. */ + static final String TENANT_SCOPE = "portfolio"; + + private static final Pattern CORRELATION_GRAMMAR = + Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,95}"); + + private final OutboxAppendPort outbox; + private final IntegrationEventEncoderPort encoder; + private final OutboxEventIdFactory eventIds; + private final CorrelationIdPort correlations; + private final Clock clock; + + public PortfolioEventOutbox( + OutboxAppendPort outbox, + IntegrationEventEncoderPort encoder, + OutboxEventIdFactory eventIds, + CorrelationIdPort correlations, + Clock clock) { + this.outbox = Objects.requireNonNull(outbox, "outbox"); + this.encoder = Objects.requireNonNull(encoder, "encoder"); + this.eventIds = Objects.requireNonNull(eventIds, "eventIds"); + this.correlations = Objects.requireNonNull(correlations, "correlations"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + /** + * Appends an event of {@code contract} about one aggregate. + * + * @param contract the event's contract + * @param aggregateType the aggregate's type, e.g. {@code poster} + * @param aggregateId the aggregate's id + * @param payload the payload record + * @param

    the payload type + */ + public

    void append( + IntegrationEventContractContribution

    contract, + String aggregateType, + String aggregateId, + P payload) { + String eventId = eventIds.newEventId(); + Instant occurredAt = clock.instant(); + String correlationId = + correlations + .currentCorrelationId() + .filter(value -> CORRELATION_GRAMMAR.matcher(value).matches()) + .orElse(eventId); + outbox.append( + encoder.encode( + new IntegrationEventDraft<>( + new EventId(eventId), + contract.contractId(), + contract.payloadVersion(), + contract.descriptor().logicalDestination(), + new AggregateIdentity(TENANT_SCOPE, aggregateType, aggregateId), + new AggregateOrder(sequenceOf(occurredAt), 0), + occurredAt, + correlationId, + Optional.empty(), + payload))); + } + + /** Microseconds since the epoch, increasing with time; at least 1, as an aggregate order is. */ + static long sequenceOf(Instant occurredAt) { + return Math.max( + 1L, + Math.addExact( + Math.multiplyExact(occurredAt.getEpochSecond(), 1_000_000L), + occurredAt.getNano() / 1_000L)); + } +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterCreatedPayload.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterCreatedPayload.java new file mode 100644 index 00000000..bef00837 --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterCreatedPayload.java @@ -0,0 +1,11 @@ +package dev.caskeleton.sample.portfolio.application.event; + +import dev.caskeleton.application.messaging.contract.IntegrationPayload; + +/** + * Payload of {@code poster.created} v1. + * + * @param posterId the new poster + * @param title its title + */ +public record PosterCreatedPayload(String posterId, String title) implements IntegrationPayload {} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisher.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisher.java index 9193ee9c..d4cc5bb1 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisher.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisher.java @@ -1,87 +1,58 @@ package dev.caskeleton.sample.portfolio.application.event; -import dev.caskeleton.application.observability.CorrelationIdPort; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; import dev.caskeleton.sample.portfolio.domain.poster.PosterArchived; import dev.caskeleton.sample.portfolio.domain.poster.PosterCreated; import dev.caskeleton.sample.portfolio.domain.poster.PosterDeleted; import dev.caskeleton.sample.portfolio.domain.poster.PosterImageAttached; import dev.caskeleton.sample.portfolio.domain.poster.PosterPublished; -import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory; -import java.time.Clock; -import java.time.Instant; /** - * Publishes Poster lifecycle domain events to the transactional outbox. MUST be invoked from within - * a use case's {@code TransactionPort.inWrite(...)} block so the append participates in the same - * write transaction (no dual-write). Factors out the outbox plumbing shown once in {@code - * CreateWorkLogUseCase}, because Poster emits five lifecycle events. {@code eventId} (a UUIDv7 from - * {@link OutboxEventIdFactory}) doubles as the idempotency key; {@code correlationId} comes through - * {@link CorrelationIdPort}, falling back to {@code eventId} off-HTTP. + * Publishes Poster lifecycle domain events to the transactional outbox, one contract per event. + * MUST be invoked from within a use case's {@code TransactionPort.inWrite(...)} block so the append + * participates in the same write transaction (no dual-write). The identities every event needs are + * {@link PortfolioEventOutbox}'s; this class only maps a domain event to its payload. */ public class PosterEventPublisher { - private final LegacyOutboxAppendPort outbox; - private final OutboxEventIdFactory eventIdFactory; - private final CorrelationIdPort correlationIdPort; - private final Clock clock; + static final String AGGREGATE_TYPE = "poster"; - public PosterEventPublisher( - LegacyOutboxAppendPort outbox, - OutboxEventIdFactory eventIdFactory, - CorrelationIdPort correlationIdPort, - Clock clock) { + private final PortfolioEventOutbox outbox; + + public PosterEventPublisher(PortfolioEventOutbox outbox) { this.outbox = outbox; - this.eventIdFactory = eventIdFactory; - this.correlationIdPort = correlationIdPort; - this.clock = clock; } public void publishCreated(PosterCreated e) { - append( - "poster.created", - e.posterId().value(), - "{" - + EventJson.field("posterId", e.posterId().value()) - + "," - + EventJson.field("title", e.title()) - + "}"); + String posterId = e.posterId().value(); + outbox.append( + PortfolioEventContracts.POSTER_CREATED, + AGGREGATE_TYPE, + posterId, + new PosterCreatedPayload(posterId, e.title())); } public void publishImageAttached(PosterImageAttached e) { - append( - "poster.image-attached", - e.posterId().value(), - "{" - + EventJson.field("posterId", e.posterId().value()) - + "," - + EventJson.field("imageKey", e.imageKey()) - + "}"); + String posterId = e.posterId().value(); + outbox.append( + PortfolioEventContracts.POSTER_IMAGE_ATTACHED, + AGGREGATE_TYPE, + posterId, + new PosterImageAttachedPayload(posterId, e.imageKey())); } public void publishPublished(PosterPublished e) { - append("poster.published", e.posterId().value(), onlyId(e.posterId().value())); + publishIdOnly(PortfolioEventContracts.POSTER_PUBLISHED, e.posterId().value()); } public void publishArchived(PosterArchived e) { - append("poster.archived", e.posterId().value(), onlyId(e.posterId().value())); + publishIdOnly(PortfolioEventContracts.POSTER_ARCHIVED, e.posterId().value()); } public void publishDeleted(PosterDeleted e) { - append("poster.deleted", e.posterId().value(), onlyId(e.posterId().value())); + publishIdOnly(PortfolioEventContracts.POSTER_DELETED, e.posterId().value()); } - private void append(String eventType, String aggregateId, String payload) { - String eventId = eventIdFactory.newEventId(); - String correlationId = - correlationIdPort.currentCorrelationId().filter(value -> !value.isBlank()).orElse(eventId); - outbox.append( - new NewOutboxEvent( - eventId, eventType, aggregateId, payload, Instant.now(clock), correlationId, eventId)); - } - - private static String onlyId(String posterId) { - return "{" + EventJson.field("posterId", posterId) + "}"; + private void publishIdOnly(PortfolioEventContract contract, String posterId) { + outbox.append(contract, AGGREGATE_TYPE, posterId, new PosterIdPayload(posterId)); } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterIdPayload.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterIdPayload.java new file mode 100644 index 00000000..aed20555 --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterIdPayload.java @@ -0,0 +1,12 @@ +package dev.caskeleton.sample.portfolio.application.event; + +import dev.caskeleton.application.messaging.contract.IntegrationPayload; + +/** + * Payload of the poster lifecycle events that carry nothing but which poster: {@code + * poster.published}, {@code poster.archived} and {@code poster.deleted}, each v1. The contract id + * says what happened. + * + * @param posterId the poster + */ +public record PosterIdPayload(String posterId) implements IntegrationPayload {} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachedPayload.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachedPayload.java new file mode 100644 index 00000000..c2b572eb --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachedPayload.java @@ -0,0 +1,12 @@ +package dev.caskeleton.sample.portfolio.application.event; + +import dev.caskeleton.application.messaging.contract.IntegrationPayload; + +/** + * Payload of {@code poster.image-attached} v1, the legacy direct upload's announcement. + * + * @param posterId the poster + * @param imageKey the stored object's key + */ +public record PosterImageAttachedPayload(String posterId, String imageKey) + implements IntegrationPayload {} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentPreparedPayload.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentPreparedPayload.java new file mode 100644 index 00000000..7ac216e3 --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentPreparedPayload.java @@ -0,0 +1,16 @@ +package dev.caskeleton.sample.portfolio.application.event; + +import dev.caskeleton.application.messaging.contract.IntegrationPayload; + +/** + * Payload of {@code poster.image-attachment-prepared} v1: a staged upload committed PENDING. It + * carries no locator — the object is not published yet. + * + * @param posterId the poster + * @param operationId the upload operation + * @param mediaType the declared media type + * @param exactLength the exact content length in bytes + */ +public record PosterImageAttachmentPreparedPayload( + String posterId, String operationId, String mediaType, long exactLength) + implements IntegrationPayload {} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentReadyPayload.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentReadyPayload.java new file mode 100644 index 00000000..a54e7719 --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentReadyPayload.java @@ -0,0 +1,18 @@ +package dev.caskeleton.sample.portfolio.application.event; + +import dev.caskeleton.application.messaging.contract.IntegrationPayload; + +/** + * Payload of {@code poster.image-attachment-ready} v2: the published image reference. Version 2 + * because {@code poster.image-attached} v1, which carried the raw object key, came first and still + * exists for the legacy upload. + * + * @param posterId the poster + * @param operationId the upload operation + * @param reference the published image reference + * @param mediaType the media type + * @param exactLength the exact content length in bytes + */ +public record PosterImageAttachmentReadyPayload( + String posterId, String operationId, String reference, String mediaType, long exactLength) + implements IntegrationPayload {} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImagePublicationEventPublisher.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImagePublicationEventPublisher.java index af26ced5..39596a11 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImagePublicationEventPublisher.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImagePublicationEventPublisher.java @@ -1,67 +1,41 @@ package dev.caskeleton.sample.portfolio.application.event; -import dev.caskeleton.application.observability.CorrelationIdPort; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; -import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory; -import java.time.Clock; - -/** Transactional locator-free publication integration notifications. */ +/** + * Transactional, locator-free publication notifications for the Poster image workflow. Called + * inside the use case's write transaction; see {@link PortfolioEventOutbox}. + */ public final class PosterImagePublicationEventPublisher { - private final LegacyOutboxAppendPort outbox; - private final OutboxEventIdFactory ids; - private final CorrelationIdPort correlations; - private final Clock clock; + private final PortfolioEventOutbox outbox; - public PosterImagePublicationEventPublisher( - LegacyOutboxAppendPort outbox, - OutboxEventIdFactory ids, - CorrelationIdPort correlations, - Clock clock) { + public PosterImagePublicationEventPublisher(PortfolioEventOutbox outbox) { this.outbox = outbox; - this.ids = ids; - this.correlations = correlations; - this.clock = clock; } public void publishPrepared(PosterImageAttachmentPrepared event) { - append( - "poster.image-attachment-prepared.v1", - event.posterId().value(), - "{" - + EventJson.field("posterId", event.posterId().value()) - + "," - + EventJson.field("operationId", event.operationId().value()) - + "," - + EventJson.field("mediaType", event.mediaType().canonicalText()) - + "," - + EventJson.number("exactLength", event.contentIdentity().exactLength()) - + "}"); + String posterId = event.posterId().value(); + outbox.append( + PortfolioEventContracts.POSTER_IMAGE_ATTACHMENT_PREPARED, + PosterEventPublisher.AGGREGATE_TYPE, + posterId, + new PosterImageAttachmentPreparedPayload( + posterId, + event.operationId().value(), + event.mediaType().canonicalText(), + event.contentIdentity().exactLength())); } public void publishReady(PosterImageAttachmentReadyV2 event) { - append( - "poster.image-attachment-ready.v2", - event.posterId().value(), - "{" - + EventJson.field("posterId", event.posterId().value()) - + "," - + EventJson.field("operationId", event.operationId().value()) - + "," - + EventJson.field("reference", event.reference().value()) - + "," - + EventJson.field("mediaType", event.mediaType().canonicalText()) - + "," - + EventJson.number("exactLength", event.contentIdentity().exactLength()) - + "}"); - } - - private void append(String type, String aggregate, String payload) { - String id = ids.newEventId(); - String correlation = - correlations.currentCorrelationId().filter(value -> !value.isBlank()).orElse(id); + String posterId = event.posterId().value(); outbox.append( - new NewOutboxEvent(id, type, aggregate, payload, clock.instant(), correlation, id)); + PortfolioEventContracts.POSTER_IMAGE_ATTACHMENT_READY, + PosterEventPublisher.AGGREGATE_TYPE, + posterId, + new PosterImageAttachmentReadyPayload( + posterId, + event.operationId().value(), + event.reference().value(), + event.mediaType().canonicalText(), + event.contentIdentity().exactLength())); } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEvent.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEvent.java deleted file mode 100644 index 90bcb746..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEvent.java +++ /dev/null @@ -1,10 +0,0 @@ -package dev.caskeleton.sample.portfolio.application.event; - -/** - * Integration (wire) event derived from the {@code WorkLogReserved} domain event: the - * boundary-owned, serialisable shape an outbound adapter would publish (e.g. to Kafka). It lives in - * the application layer because translating a domain fact into a wire contract is an application - * concern; the domain stays unaware of the wire. See README. - */ -public record WorkLogReservedIntegrationEvent( - String workLogId, String category, String occurredOn) {} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapper.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapper.java deleted file mode 100644 index 19400c7c..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapper.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.sample.portfolio.application.event; - -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogReserved; - -/** - * Maps the transport-free {@code WorkLogReserved} domain event to a {@link - * WorkLogReservedIntegrationEvent} at the application boundary, and serialises it to a hand-rolled - * JSON payload string for the transactional outbox. See README. - */ -public final class WorkLogReservedIntegrationEventMapper { - - /** Stable logical event type name; becomes the broker topic. See README. */ - public static final String EVENT_TYPE = "worklog.reserved"; - - private WorkLogReservedIntegrationEventMapper() {} - - /** - * Maps a {@link WorkLogReserved} domain event to its integration event form, flattening value - * objects to primitive strings. - * - * @param event the domain event; must not be {@code null} - * @return the integration event record - */ - public static WorkLogReservedIntegrationEvent toIntegrationEvent(WorkLogReserved event) { - return new WorkLogReservedIntegrationEvent( - event.workLogId().value(), event.category().name(), event.periodStart().toString()); - } - - /** - * Serialises a {@link WorkLogReservedIntegrationEvent} to a JSON string for the outbox {@code - * payload} field (hand-rolled, no Jackson/Gson dependency). See README. - * - * @param event the integration event to serialise; must not be {@code null} - * @return a JSON object string, e.g. {@code - * {"workLogId":"0190bd6e-7c3e-7abc-8def-0123456789ab","category":"BACKEND","occurredOn":"2025-01-01"}} - */ - public static String toJson(WorkLogReservedIntegrationEvent event) { - return "{" - + EventJson.field("workLogId", event.workLogId()) - + "," - + EventJson.field("category", event.category()) - + "," - + EventJson.field("occurredOn", event.occurredOn()) - + "}"; - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogUseCase.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogUseCase.java index d1208d85..1123eaed 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogUseCase.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogUseCase.java @@ -3,31 +3,25 @@ package dev.caskeleton.sample.portfolio.application.worklog; import dev.caskeleton.application.capability.Idempotency; import dev.caskeleton.application.capability.RepositoryAccess; import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.observability.CorrelationIdPort; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; import dev.caskeleton.application.security.RequiresPermission; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.usecase.CommandUseCase; import dev.caskeleton.sample.portfolio.application.command.CreateWorkLogCommand; -import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedIntegrationEvent; -import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedIntegrationEventMapper; -import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory; +import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; +import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedContractContribution; +import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedPayload; import dev.caskeleton.sample.portfolio.domain.worklog.Period; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogIdFactory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogOwner; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogReserved; -import java.time.Clock; -import java.time.Instant; /** - * Creates a new {@link WorkLog} and appends a {@link WorkLogReserved} outbox event in the same - * write transaction, demonstrating the dual-write prohibition. {@code eventId} is the UUIDv7 from - * {@link OutboxEventIdFactory} and doubles as the idempotency key; {@code correlationId} comes - * through {@link CorrelationIdPort}. See README. + * Creates a new {@link WorkLog} and appends a {@link WorkLogReserved} integration event ({@code + * portfolio.worklog.reserved} v1) in the same write transaction, demonstrating the dual-write + * prohibition. The event's identities come from {@link PortfolioEventOutbox}. See README. */ @RequiresPermission("worklog:write") @UseCaseCapability( @@ -36,28 +30,22 @@ import java.time.Instant; repositoryAccess = RepositoryAccess.WRITE_REPOSITORY) public class CreateWorkLogUseCase implements CommandUseCase { + private static final WorkLogReservedContractContribution RESERVED = + new WorkLogReservedContractContribution(); + private final WorkLogRepository repository; private final WorkLogIdFactory idFactory; - private final OutboxEventIdFactory eventIdFactory; - private final LegacyOutboxAppendPort outboxAppendPort; - private final CorrelationIdPort correlationIdPort; - private final Clock clock; + private final PortfolioEventOutbox events; private final TransactionPort tx; public CreateWorkLogUseCase( WorkLogRepository repository, WorkLogIdFactory idFactory, - OutboxEventIdFactory eventIdFactory, - LegacyOutboxAppendPort outboxAppendPort, - CorrelationIdPort correlationIdPort, - Clock clock, + PortfolioEventOutbox events, TransactionPort tx) { this.repository = repository; this.idFactory = idFactory; - this.eventIdFactory = eventIdFactory; - this.outboxAppendPort = outboxAppendPort; - this.correlationIdPort = correlationIdPort; - this.clock = clock; + this.events = events; this.tx = tx; } @@ -87,33 +75,14 @@ public class CreateWorkLogUseCase implements CommandUseCase !value.isBlank()).orElse(eventId); - - outboxAppendPort.append( - new NewOutboxEvent( - eventId, - WorkLogReservedIntegrationEventMapper.EVENT_TYPE, - saved.id().value(), - payload, - occurredAt, - correlationId, - eventId // idempotencyKey = eventId - )); + String workLogId = domainEvent.workLogId().value(); + events.append(RESERVED, "worklog", workLogId, new WorkLogReservedPayload(workLogId)); } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/application/SampleApplicationUseCaseConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/application/SampleApplicationUseCaseConfig.java index 4cdfc289..b492d1b4 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/application/SampleApplicationUseCaseConfig.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/application/SampleApplicationUseCaseConfig.java @@ -1,10 +1,20 @@ package dev.caskeleton.sample.portfolio.bootstrap.application; +import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; import dev.caskeleton.application.observability.CorrelationIdPort; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.sample.portfolio.application.event.PortfolioEventContract; +import dev.caskeleton.sample.portfolio.application.event.PortfolioEventContracts; +import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; +import dev.caskeleton.sample.portfolio.application.event.PosterCreatedPayload; import dev.caskeleton.sample.portfolio.application.event.PosterEventPublisher; +import dev.caskeleton.sample.portfolio.application.event.PosterIdPayload; +import dev.caskeleton.sample.portfolio.application.event.PosterImageAttachedPayload; +import dev.caskeleton.sample.portfolio.application.event.PosterImageAttachmentPreparedPayload; +import dev.caskeleton.sample.portfolio.application.event.PosterImageAttachmentReadyPayload; import dev.caskeleton.sample.portfolio.application.event.PosterImagePublicationEventPublisher; +import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedContractContribution; import dev.caskeleton.sample.portfolio.application.port.RepoStatsPort; import dev.caskeleton.sample.portfolio.application.port.WorkLogSummaryQueryPort; import dev.caskeleton.sample.portfolio.application.poster.ArchivePosterUseCase; @@ -43,22 +53,70 @@ import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class SampleApplicationUseCaseConfig { + /** + * The closed integration-event catalog, one bean per contract. The application's encoder is built + * over every contribution bean in the context, which is how it learns these. + */ @Bean - PosterEventPublisher posterEventPublisher( - LegacyOutboxAppendPort outbox, + PortfolioEventContract posterCreatedContract() { + return PortfolioEventContracts.POSTER_CREATED; + } + + @Bean + PortfolioEventContract posterImageAttachedContract() { + return PortfolioEventContracts.POSTER_IMAGE_ATTACHED; + } + + @Bean + PortfolioEventContract posterPublishedContract() { + return PortfolioEventContracts.POSTER_PUBLISHED; + } + + @Bean + PortfolioEventContract posterArchivedContract() { + return PortfolioEventContracts.POSTER_ARCHIVED; + } + + @Bean + PortfolioEventContract posterDeletedContract() { + return PortfolioEventContracts.POSTER_DELETED; + } + + @Bean + PortfolioEventContract + posterImageAttachmentPreparedContract() { + return PortfolioEventContracts.POSTER_IMAGE_ATTACHMENT_PREPARED; + } + + @Bean + PortfolioEventContract posterImageAttachmentReadyContract() { + return PortfolioEventContracts.POSTER_IMAGE_ATTACHMENT_READY; + } + + @Bean + WorkLogReservedContractContribution workLogReservedContract() { + return new WorkLogReservedContractContribution(); + } + + @Bean + PortfolioEventOutbox portfolioEventOutbox( + OutboxAppendPort outbox, + IntegrationEventEncoderPort encoder, OutboxEventIdFactory eventIds, CorrelationIdPort correlations, Clock clock) { - return new PosterEventPublisher(outbox, eventIds, correlations, clock); + return new PortfolioEventOutbox(outbox, encoder, eventIds, correlations, clock); + } + + @Bean + PosterEventPublisher posterEventPublisher(PortfolioEventOutbox events) { + return new PosterEventPublisher(events); } @Bean PosterImagePublicationEventPublisher posterImagePublicationEventPublisher( - LegacyOutboxAppendPort outbox, - OutboxEventIdFactory eventIds, - CorrelationIdPort correlations, - Clock clock) { - return new PosterImagePublicationEventPublisher(outbox, eventIds, correlations, clock); + PortfolioEventOutbox events) { + return new PosterImagePublicationEventPublisher(events); } @Bean @@ -117,13 +175,9 @@ public class SampleApplicationUseCaseConfig { CreateWorkLogUseCase createWorkLogUseCase( WorkLogRepository repository, WorkLogIdFactory workLogIds, - OutboxEventIdFactory eventIds, - LegacyOutboxAppendPort outbox, - CorrelationIdPort correlations, - Clock clock, + PortfolioEventOutbox events, TransactionPort transactions) { - return new CreateWorkLogUseCase( - repository, workLogIds, eventIds, outbox, correlations, clock, transactions); + return new CreateWorkLogUseCase(repository, workLogIds, events, transactions); } @Bean diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/context/SampleDomainContextConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/context/SampleDomainContextConfig.java deleted file mode 100644 index 90f98949..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/context/SampleDomainContextConfig.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.sample.portfolio.bootstrap.context; - -import dev.caskeleton.shared.concurrency.DomainContextPropagator; -import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Sample-local substitute for {@code app-bootstrap}'s {@code DomainContextConfig}: provides the - * {@link DomainContextPropagator} bean (default {@code THREAD_LOCAL} strategy) that the scanned - * {@code DomainContextAuditContextPort} requires. Disposable. See README. - */ -@Configuration -public class SampleDomainContextConfig { - - @Bean - public DomainContextPropagator domainContextPropagator() { - return new ThreadLocalDomainContextPropagator(); - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java deleted file mode 100644 index 647baabc..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.sample.portfolio.bootstrap.idempotency; - -import dev.caskeleton.application.idempotency.IdempotencyExecutor; -import dev.caskeleton.application.idempotency.IdempotencyStorePort; -import java.time.Clock; -import java.time.Duration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.scheduling.annotation.EnableScheduling; - -/** - * Sample-local stand-in for {@code app-bootstrap}'s {@code IdempotencyProviderSelectionConfig}. The - * sample is its own composition root and must not depend on {@code app-bootstrap}, so it builds the - * one executor itself, over the {@link IdempotencyStorePort} the persistence-jpa provider - * contributes, from the same {@code ca-skeleton.capabilities.idempotency} keys and defaults. Also - * supplies the {@code Clock} and turns on scheduling for the sample's jobs. Disposable. See README. - */ -@Configuration -@EnableScheduling -public class SampleIdempotencyConfig { - - private static final String PREFIX = "ca-skeleton.capabilities.idempotency."; - - @Bean - public Clock systemClock() { - return Clock.systemUTC(); - } - - @Bean - @ConditionalOnExpression( - "!'${ca-skeleton.capabilities.idempotency.provider:disabled}'.trim()" - + ".equalsIgnoreCase('disabled')") - public IdempotencyExecutor idempotencyExecutor( - IdempotencyStorePort store, Environment environment) { - Binder binder = Binder.get(environment); - return new IdempotencyExecutor( - store, - binder.bind(PREFIX + "processing-lease", Duration.class).orElse(Duration.ofSeconds(30)), - binder.bind(PREFIX + "replay-ttl", Duration.class).orElse(Duration.ofHours(24)), - binder.bind(PREFIX + "failure-retention", Duration.class).orElse(Duration.ofHours(24)), - binder.bind(PREFIX + "response-codec-id", String.class).orElse("json-v2"), - binder.bind(PREFIX + "policy-revision", Integer.class).orElse(2)); - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/logging/SamplePseudonymizationConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/logging/SamplePseudonymizationConfig.java deleted file mode 100644 index 3fe94843..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/logging/SamplePseudonymizationConfig.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.sample.portfolio.bootstrap.logging; - -import dev.caskeleton.adapter.outbound.identifier.HmacUserPrincipalPseudonymizer; -import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort; -import dev.caskeleton.sample.portfolio.bootstrap.settings.SamplePrivacySettings; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Sample-local copy of {@code app-bootstrap}'s {@code PseudonymizationConfig}: supplies the {@code - * UserPrincipalPseudonymizerPort} that adapter-web's {@code RequestLoggingFilter} injects. - * Disposable. See README. - */ -@Configuration -@EnableConfigurationProperties(SamplePrivacySettings.class) -public class SamplePseudonymizationConfig { - - @Bean - @ConditionalOnMissingBean - UserPrincipalPseudonymizerPort userPrincipalPseudonymizer(SamplePrivacySettings privacySettings) { - return new HmacUserPrincipalPseudonymizer(privacySettings.saltBytes()); - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/management/SampleManagementSecurityConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/management/SampleManagementSecurityConfig.java index 46fdbede..2905046e 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/management/SampleManagementSecurityConfig.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/management/SampleManagementSecurityConfig.java @@ -10,8 +10,12 @@ import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.SecurityFilterChain; /** - * Sample-local actuator chain. The standalone sample is intentionally public so the demo can be - * inspected without a configured IdP; production actuator posture remains in app-bootstrap. + * The sample's actuator posture, which differs from the template's on purpose: the standalone + * sample is public so the demo can be inspected without a configured IdP. + * + *

    Not a copy of the shared chain. {@code composition:service-runtime} ships the template's chain + * as {@code actuatorSecurityFilterChain} and steps aside when a composition root declares a bean of + * that name, which this class does; production actuator posture stays in that module. */ @Configuration @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @@ -20,7 +24,7 @@ public class SampleManagementSecurityConfig { /** Actuator security chain ordered at {@code 0} to run BEFORE the main app chain. */ @Bean @Order(0) - public SecurityFilterChain sampleActuatorSecurityFilterChain(HttpSecurity http) throws Exception { + public SecurityFilterChain actuatorSecurityFilterChain(HttpSecurity http) throws Exception { http.securityMatcher(EndpointRequest.toAnyEndpoint()) .csrf(csrf -> csrf.disable()) .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/metrics/SampleMetricsContractConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/metrics/SampleMetricsContractConfig.java deleted file mode 100644 index 55c26800..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/metrics/SampleMetricsContractConfig.java +++ /dev/null @@ -1,89 +0,0 @@ -package dev.caskeleton.sample.portfolio.bootstrap.metrics; - -import dev.caskeleton.shared.metrics.ForbiddenMetricTags; -import io.micrometer.core.instrument.Meter; -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.core.instrument.Tag; -import io.micrometer.core.instrument.config.MeterFilter; -import io.micrometer.core.instrument.config.MeterFilterReply; -import io.micrometer.core.instrument.distribution.DistributionStatisticConfig; -import java.time.Duration; -import java.util.Set; -import org.springframework.boot.micrometer.metrics.autoconfigure.MeterRegistryCustomizer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; - -/** - * Sample-local copy of {@code app-bootstrap}'s {@code MetricsContractConfig}: installs the - * cardinality and SLO-distribution {@code MeterFilter}s onto the {@link MeterRegistry} before any - * meters register. Disposable. See README. - * - *

    A {@link MeterRegistryCustomizer}, for the same reason the original is: a - * {@code @PostConstruct} ran after earlier beans had already registered meters, so the filters - * missed them and Micrometer said so. Changed in step with the original — fixing one composition - * root and leaving the other would have left the warning reproducible from the sample. - */ -@Configuration -public class SampleMetricsContractConfig { - - /** - * Applies both filters at registry construction. - * - * @return the customizer Boot applies to every registry it creates - */ - @Bean - @Order(Ordered.HIGHEST_PRECEDENCE) - public MeterRegistryCustomizer sampleMetricsContractMeterFilters() { - return registry -> - registry - .config() - .meterFilter(new CardinalityFilter()) - .meterFilter(new DistributionFilter()); - } - - /** Deny meters with high-cardinality tag keys. */ - private static final class CardinalityFilter implements MeterFilter { - @Override - public MeterFilterReply accept(Meter.Id id) { - for (Tag tag : id.getTags()) { - if (ForbiddenMetricTags.isForbidden(tag.getKey())) { - return MeterFilterReply.DENY; - } - } - return MeterFilterReply.NEUTRAL; - } - } - - /** SLO-driven histogram config for owned timer names. */ - private static final class DistributionFilter implements MeterFilter { - - private static final Set SLO_DRIVEN_TIMERS = - Set.of( - "http.server.requests", - "http.server.requests.latency", - "dependency.client.requests", - "db.query.duration", - "jvm.gc.pause"); - - @Override - public DistributionStatisticConfig configure(Meter.Id id, DistributionStatisticConfig config) { - if (!SLO_DRIVEN_TIMERS.contains(id.getName())) { - return config; - } - return DistributionStatisticConfig.builder() - .percentilesHistogram(true) - .percentiles(0.5, 0.9, 0.95, 0.99) - .serviceLevelObjectives( - (double) Duration.ofMillis(100).toNanos(), - (double) Duration.ofMillis(500).toNanos(), - (double) Duration.ofSeconds(1).toNanos(), - (double) Duration.ofSeconds(5).toNanos()) - .minimumExpectedValue((double) Duration.ofMillis(1).toNanos()) - .maximumExpectedValue((double) Duration.ofSeconds(10).toNanos()) - .build() - .merge(config); - } - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/runtime/SampleSchedulingConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/runtime/SampleSchedulingConfig.java new file mode 100644 index 00000000..00eb7a16 --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/runtime/SampleSchedulingConfig.java @@ -0,0 +1,24 @@ +package dev.caskeleton.sample.portfolio.bootstrap.runtime; + +import java.time.Clock; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** + * The sample's clock, and scheduling for its jobs (the Poster image retirement job, the idempotency + * reaper of the PostgreSQL store). + * + *

    The idempotency executor is not built here any more. It comes from {@code + * composition:idempotency}, the module app-bootstrap uses too, so the sample no longer carries a + * copy that read the lifecycle keys without their bounds and assumed exactly one store. + */ +@Configuration +@EnableScheduling +public class SampleSchedulingConfig { + + @Bean + public Clock systemClock() { + return Clock.systemUTC(); + } +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/settings/SamplePrivacySettings.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/settings/SamplePrivacySettings.java deleted file mode 100644 index f9d419c6..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/settings/SamplePrivacySettings.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.sample.portfolio.bootstrap.settings; - -import java.nio.charset.StandardCharsets; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * Sample-local copy of {@code app-bootstrap}'s {@code PrivacySettings}, bound from {@code - * ca-skeleton.privacy.*}. Supplies the HMAC salt; a blank salt falls back to a dev sentinel so - * local/test runs start. Disposable. See README. - */ -@ConfigurationProperties(prefix = "ca-skeleton.privacy") -public record SamplePrivacySettings(String pseudonymizationSalt) { - - private static final Logger log = LoggerFactory.getLogger(SamplePrivacySettings.class); - - static final String DEV_SENTINEL_SALT = "__LOCAL_DEV_pseudonymization_salt"; - - public SamplePrivacySettings { - if (pseudonymizationSalt == null || pseudonymizationSalt.isBlank()) { - log.warn( - "APP_PRIVACY_PSEUDONYMIZATION_SALT is blank; using a dev sentinel salt. " - + "Set a real secret-manager value before production."); - pseudonymizationSalt = DEV_SENTINEL_SALT; - } - } - - /** The salt as UTF-8 bytes for the HMAC key. */ - public byte[] saltBytes() { - return pseudonymizationSalt.getBytes(StandardCharsets.UTF_8); - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleMicrometerSpanErrorRecorder.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleMicrometerSpanErrorRecorder.java deleted file mode 100644 index 9cb62c88..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleMicrometerSpanErrorRecorder.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.sample.portfolio.bootstrap.tracing; - -import dev.caskeleton.shared.tracing.SpanErrorRecorder; -import io.micrometer.tracing.Span; -import io.micrometer.tracing.Tracer; - -/** - * Sample-local copy of {@code app-bootstrap}'s {@code MicrometerSpanErrorRecorder}: records an - * exception on the current span with an {@code error.code} tag. Disposable. See README. - */ -public final class SampleMicrometerSpanErrorRecorder implements SpanErrorRecorder { - - private final Tracer tracer; - - public SampleMicrometerSpanErrorRecorder(Tracer tracer) { - this.tracer = tracer; - } - - @Override - public void recordException(Throwable error, String errorCode) { - if (error == null) { - return; - } - Span span = tracer.currentSpan(); - if (span == null) { - return; - } - span.error(error); - if (errorCode != null) { - span.tag("error.code", errorCode); - } - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingConfig.java deleted file mode 100644 index a8e16bae..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingConfig.java +++ /dev/null @@ -1,83 +0,0 @@ -package dev.caskeleton.sample.portfolio.bootstrap.tracing; - -import dev.caskeleton.shared.tracing.SpanErrorRecorder; -import io.micrometer.core.instrument.Gauge; -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.tracing.Tracer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -/** - * Sample-local copy of {@code app-bootstrap}'s {@code TracingConfig}: registers the {@link - * SpanErrorRecorder} bean and the sampling-rate gauge. Disposable. See README. - */ -@Configuration -@EnableConfigurationProperties(SampleTracingSettings.class) -public class SampleTracingConfig { - - private static final Logger log = LoggerFactory.getLogger(SampleTracingConfig.class); - - private final SampleTracingSettings properties; - private final Environment environment; - private final ObjectProvider meterRegistryProvider; - - public SampleTracingConfig( - SampleTracingSettings properties, - Environment environment, - ObjectProvider meterRegistryProvider) { - this.properties = properties; - this.environment = environment; - this.meterRegistryProvider = meterRegistryProvider; - } - - /** Registers the {@code tracing.sampling.rate} gauge on startup. */ - @Bean - public SampleTracingSamplingRateGaugeRegistrar sampleTracingSamplingRateGaugeRegistrar() { - String activeProfile = resolveActiveProfile(); - double effectiveRate = - new SampleTracingSampleRateResolver().resolve(activeProfile, properties.sampleRate()); - registerGauge(activeProfile, effectiveRate); - return new SampleTracingSamplingRateGaugeRegistrar(activeProfile, effectiveRate); - } - - /** Real {@link SpanErrorRecorder} bean when a Tracer is present; NOOP otherwise. */ - @Bean - @ConditionalOnMissingBean(SpanErrorRecorder.class) - SpanErrorRecorder sampleSpanErrorRecorder(ObjectProvider tracerProvider) { - Tracer tracer = tracerProvider.getIfAvailable(); - if (tracer == null) { - return SpanErrorRecorder.NOOP; - } - return new SampleMicrometerSpanErrorRecorder(tracer); - } - - private String resolveActiveProfile() { - String[] profiles = environment.getActiveProfiles(); - return (profiles != null && profiles.length > 0) ? profiles[0] : "local"; - } - - private void registerGauge(String activeProfile, double effectiveRate) { - MeterRegistry registry = meterRegistryProvider.getIfAvailable(); - if (registry == null) { - return; - } - try { - Gauge.builder("tracing.sampling.rate", () -> effectiveRate) - .tag("profile", activeProfile != null ? activeProfile : "unknown") - .description("Effective distributed-tracing sample rate for the active profile") - .register(registry); - } catch (RuntimeException ex) { - log.warn("sample tracing: failed to register gauge tracing.sampling.rate", ex); - } - } - - /** Value holder exposing the active profile and resolved rate for test inspection. */ - public record SampleTracingSamplingRateGaugeRegistrar( - String activeProfile, double effectiveSampleRate) {} -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingSampleRateResolver.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingSampleRateResolver.java deleted file mode 100644 index be612fae..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingSampleRateResolver.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.sample.portfolio.bootstrap.tracing; - -import java.util.Locale; - -/** - * Sample-local copy of {@code app-bootstrap}'s {@code TracingSampleRateResolver}: applies the - * per-profile default sample rate (prod=0.01, staging=0.10, dev/local=1.0). Disposable. See README. - */ -final class SampleTracingSampleRateResolver { - - /** - * Returns the per-profile default sample rate (D6 SSOT). - * - * @param profile Spring active profile name; {@code null}/blank treated as "anything else" - * @return effective default rate for the profile - */ - static double defaultRateForProfile(String profile) { - if (profile == null) { - return 1.0; - } - return switch (profile.trim().toLowerCase(Locale.ROOT)) { - case "prod" -> 0.01; - case "staging" -> 0.10; - case "dev" -> 1.0; - case "local" -> 1.0; - default -> 1.0; - }; - } - - /** - * Resolves the effective sample rate, letting a configured override win over the per-profile - * default. - * - * @param profile active Spring profile - * @param configuredRate raw string from {@code APP_TRACING_SAMPLE_RATE}; may be blank - * @return effective sample rate in [0.0, 1.0] - */ - double resolve(String profile, String configuredRate) { - if (configuredRate != null && !configuredRate.isBlank()) { - try { - double v = Double.parseDouble(configuredRate.trim()); - if (v >= 0.0 && v <= 1.0) { - return v; - } - } catch (NumberFormatException ignored) { - // fall through to profile default - } - } - return defaultRateForProfile(profile); - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingSamplingEnvironmentPostProcessor.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingSamplingEnvironmentPostProcessor.java deleted file mode 100644 index a31e9eb5..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingSamplingEnvironmentPostProcessor.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.sample.portfolio.bootstrap.tracing; - -import java.util.Map; -import org.springframework.boot.EnvironmentPostProcessor; -import org.springframework.boot.SpringApplication; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.MapPropertySource; - -/** - * Sample-local copy of {@code app-bootstrap}'s {@code TracingSamplingEnvironmentPostProcessor}: - * bridges the resolved sample rate to {@code management.tracing.sampling.probability} so the OTel - * sampler matches the gauge. Disposable. See README. - */ -public class SampleTracingSamplingEnvironmentPostProcessor implements EnvironmentPostProcessor { - - private static final String NATIVE_KEY = "management.tracing.sampling.probability"; - private static final String CA_SAMPLE_RATE_KEY = "ca-skeleton.tracing.sample-rate"; - - private final SampleTracingSampleRateResolver resolver = new SampleTracingSampleRateResolver(); - - @Override - public void postProcessEnvironment( - ConfigurableEnvironment environment, SpringApplication application) { - // User-explicit setting takes priority. - if (environment.containsProperty(NATIVE_KEY)) { - return; - } - String[] profiles = environment.getActiveProfiles(); - String profile = (profiles != null && profiles.length > 0) ? profiles[0] : "local"; - String configured = environment.getProperty(CA_SAMPLE_RATE_KEY); - double rate = resolver.resolve(profile, configured); - environment - .getPropertySources() - .addLast( - new MapPropertySource( - "sampleTracingSamplingBridge", Map.of(NATIVE_KEY, String.valueOf(rate)))); - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingSettings.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingSettings.java deleted file mode 100644 index f1763584..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/tracing/SampleTracingSettings.java +++ /dev/null @@ -1,76 +0,0 @@ -package dev.caskeleton.sample.portfolio.bootstrap.tracing; - -import java.net.URI; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.validation.annotation.Validated; - -/** - * Sample-local copy of {@code app-bootstrap}'s {@code TracingSettings}, bound from {@code - * ca-skeleton.tracing.*}. Blank sampleRate = per-profile default; non-blank must be a float in - * [0.0, 1.0]; blank otlpEndpoint = exporter off, non-blank must be a valid URL. Disposable. See - * README. - */ -@ConfigurationProperties(prefix = "ca-skeleton.tracing") -@Validated -public record SampleTracingSettings(boolean enabled, String sampleRate, Exporter exporter) { - - /** Nested properties for the exporter seam. */ - public record Exporter(String otlpEndpoint) { - - public Exporter { - if (otlpEndpoint == null) { - otlpEndpoint = ""; - } - } - - /** {@code true} when an exporter endpoint is configured (non-blank). */ - public boolean isConfigured() { - return otlpEndpoint != null && !otlpEndpoint.isBlank(); - } - } - - /** Compact canonical constructor — validation: float_between_0_and_1 + url_or_empty. */ - public SampleTracingSettings { - if (sampleRate == null) { - sampleRate = ""; - } - if (exporter == null) { - exporter = new Exporter(""); - } - // blank = "per-profile default" signal - if (!sampleRate.isBlank()) { - validateSampleRate(sampleRate); - } - validateOtlpEndpoint(exporter.otlpEndpoint()); - } - - private static void validateSampleRate(String raw) { - try { - double v = Double.parseDouble(raw.trim()); - if (v < 0.0 || v > 1.0) { - throw new IllegalStateException( - "APP_TRACING_SAMPLE_RATE must be a float in [0.0, 1.0]; got: " + raw); - } - } catch (NumberFormatException ex) { - throw new IllegalStateException( - "APP_TRACING_SAMPLE_RATE must be a float in [0.0, 1.0]; got: " + raw, ex); - } - } - - private static void validateOtlpEndpoint(String endpoint) { - if (endpoint == null || endpoint.isBlank()) { - return; - } - try { - URI uri = URI.create(endpoint.trim()); - String scheme = uri.getScheme(); - if (scheme == null || scheme.isBlank()) { - throw new IllegalStateException( - "OTEL_EXPORTER_OTLP_ENDPOINT must be a valid URL with a scheme; got: " + endpoint); - } - } catch (IllegalArgumentException ex) { - throw new IllegalStateException( - "OTEL_EXPORTER_OTLP_ENDPOINT must be a valid URL or empty; got: " + endpoint, ex); - } - } -} diff --git a/src/sample-portfolio/src/main/resources/META-INF/spring.factories b/src/sample-portfolio/src/main/resources/META-INF/spring.factories deleted file mode 100644 index f660ca1b..00000000 --- a/src/sample-portfolio/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.EnvironmentPostProcessor=\ -dev.caskeleton.sample.portfolio.bootstrap.tracing.SampleTracingSamplingEnvironmentPostProcessor diff --git a/src/sample-portfolio/src/main/resources/application.yml b/src/sample-portfolio/src/main/resources/application.yml index 34bca6e5..3b9de0a6 100644 --- a/src/sample-portfolio/src/main/resources/application.yml +++ b/src/sample-portfolio/src/main/resources/application.yml @@ -173,8 +173,8 @@ ca-skeleton: generation-recheck-interval: ${APP_CACHE_REDIS_L1_GENERATION_RECHECK_INTERVAL:5s} invalidation-queue-capacity: ${APP_CACHE_REDIS_L1_INVALIDATION_QUEUE_CAPACITY:1024} # The only IdempotencyStorePort this composition can produce is persistence-jpa's PostgreSQL - # store, which applies its own migration stream when selected. SampleIdempotencyConfig builds - # the executor over it; `disabled` builds neither. + # store, which applies its own migration stream when selected. composition:idempotency builds + # the executor over it (the same module app-bootstrap uses); `disabled` builds neither. idempotency: provider: ${APP_IDEMPOTENCY_PROVIDER:postgresql} bootstrap: @@ -279,8 +279,6 @@ app: invalidation-queue-capacity: ${APP_CACHE_REDIS_L1_INVALIDATION_QUEUE_CAPACITY:1024} messaging: broker: ${APP_MESSAGING_BROKER:} - kafka: - brokers: ${APP_MESSAGING_KAFKA_BROKERS:} notification: slack-webhook: enabled: ${APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED:false} diff --git a/src/sample-portfolio/src/main/resources/contracts/messaging/poster.archived/v1.schema.json b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.archived/v1.schema.json new file mode 100644 index 00000000..5c48678c --- /dev/null +++ b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.archived/v1.schema.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:dev-caskeleton:contracts:messaging:poster.archived:v1", + "title": "PosterArchived payload v1", + "type": "object", + "required": [ + "posterId" + ], + "properties": { + "posterId": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" + } + }, + "unevaluatedProperties": false +} diff --git a/src/sample-portfolio/src/main/resources/contracts/messaging/poster.created/v1.schema.json b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.created/v1.schema.json new file mode 100644 index 00000000..b0d80890 --- /dev/null +++ b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.created/v1.schema.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:dev-caskeleton:contracts:messaging:poster.created:v1", + "title": "PosterCreated payload v1", + "type": "object", + "required": [ + "posterId", + "title" + ], + "properties": { + "posterId": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" + }, + "title": { + "type": "string", + "minLength": 1 + } + }, + "unevaluatedProperties": false +} diff --git a/src/sample-portfolio/src/main/resources/contracts/messaging/poster.deleted/v1.schema.json b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.deleted/v1.schema.json new file mode 100644 index 00000000..f90fcc4d --- /dev/null +++ b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.deleted/v1.schema.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:dev-caskeleton:contracts:messaging:poster.deleted:v1", + "title": "PosterDeleted payload v1", + "type": "object", + "required": [ + "posterId" + ], + "properties": { + "posterId": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" + } + }, + "unevaluatedProperties": false +} diff --git a/src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attached/v1.schema.json b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attached/v1.schema.json new file mode 100644 index 00000000..d315308d --- /dev/null +++ b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attached/v1.schema.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:dev-caskeleton:contracts:messaging:poster.image-attached:v1", + "title": "PosterImageAttached payload v1", + "type": "object", + "required": [ + "posterId", + "imageKey" + ], + "properties": { + "posterId": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" + }, + "imageKey": { + "type": "string", + "minLength": 1 + } + }, + "unevaluatedProperties": false +} diff --git a/src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attachment-prepared/v1.schema.json b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attachment-prepared/v1.schema.json new file mode 100644 index 00000000..d0811367 --- /dev/null +++ b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attachment-prepared/v1.schema.json @@ -0,0 +1,33 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:dev-caskeleton:contracts:messaging:poster.image-attachment-prepared:v1", + "title": "PosterImageAttachmentPrepared payload v1", + "type": "object", + "required": [ + "posterId", + "operationId", + "mediaType", + "exactLength" + ], + "properties": { + "posterId": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" + }, + "operationId": { + "type": "string", + "minLength": 1 + }, + "mediaType": { + "type": "string", + "minLength": 1 + }, + "exactLength": { + "type": "integer", + "minimum": 0 + } + }, + "unevaluatedProperties": false +} diff --git a/src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attachment-ready/v2.schema.json b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attachment-ready/v2.schema.json new file mode 100644 index 00000000..bd2c2067 --- /dev/null +++ b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attachment-ready/v2.schema.json @@ -0,0 +1,38 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:dev-caskeleton:contracts:messaging:poster.image-attachment-ready:v2", + "title": "PosterImageAttachmentReady payload v2", + "type": "object", + "required": [ + "posterId", + "operationId", + "reference", + "mediaType", + "exactLength" + ], + "properties": { + "posterId": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" + }, + "operationId": { + "type": "string", + "minLength": 1 + }, + "reference": { + "type": "string", + "minLength": 1 + }, + "mediaType": { + "type": "string", + "minLength": 1 + }, + "exactLength": { + "type": "integer", + "minimum": 0 + } + }, + "unevaluatedProperties": false +} diff --git a/src/sample-portfolio/src/main/resources/contracts/messaging/poster.published/v1.schema.json b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.published/v1.schema.json new file mode 100644 index 00000000..75a1987c --- /dev/null +++ b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.published/v1.schema.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:dev-caskeleton:contracts:messaging:poster.published:v1", + "title": "PosterPublished payload v1", + "type": "object", + "required": [ + "posterId" + ], + "properties": { + "posterId": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" + } + }, + "unevaluatedProperties": false +} diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContractsTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContractsTest.java new file mode 100644 index 00000000..23612bdc --- /dev/null +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContractsTest.java @@ -0,0 +1,44 @@ +package dev.caskeleton.sample.portfolio.application.event; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; +import dev.caskeleton.application.messaging.contract.Sha256; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +class PortfolioEventContractsTest { + + static Stream> contracts() { + return PortfolioEventContracts.all().stream(); + } + + /** + * The encoder refuses the same mismatch at startup; this says which contract, before anything + * boots. + */ + @ParameterizedTest + @MethodSource("contracts") + void everyContractDeclaresTheHashOfTheSchemaItShips( + IntegrationEventContractContribution contract) { + // when + Sha256 shipped = sha256Of(contract.payloadSchemaResource().value()); + + // then + assertThat(contract.payloadSchemaHash()).isEqualTo(shipped); + } + + private static Sha256 sha256Of(String resource) { + try (InputStream in = + PortfolioEventContractsTest.class.getClassLoader().getResourceAsStream(resource)) { + assertThat(in).as(resource).isNotNull(); + return Sha256.of(in.readAllBytes()); + } catch (IOException unreadable) { + throw new UncheckedIOException(unreadable); + } + } +} diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutboxTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutboxTest.java new file mode 100644 index 00000000..48b43d66 --- /dev/null +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutboxTest.java @@ -0,0 +1,85 @@ +package dev.caskeleton.sample.portfolio.application.event; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.messaging.event.AggregateIdentity; +import dev.caskeleton.application.messaging.event.AggregateOrder; +import dev.caskeleton.application.messaging.event.IntegrationEventDraft; +import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; +import dev.caskeleton.application.observability.CorrelationIdPort; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +class PortfolioEventOutboxTest { + + private static final String EVENT_ID = "0190bd6e-7c3e-7abc-8def-0123456789ff"; + private static final Instant NOW = Instant.parse("2025-06-01T10:00:00.123456Z"); + + private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder(); + + @Test + void usesTheCurrentCorrelationIdWhenItFitsTheCanonicalGrammar() { + // when + append(() -> Optional.of("corr-123")); + + // then + assertThat(encoder.drafts()) + .singleElement() + .extracting(IntegrationEventDraft::correlationId) + .isEqualTo("corr-123"); + } + + /** + * A correlation id the canonical grammar refuses — a header with a space in it, say — must not + * fail the business write the event announces. Before, the pre-canonical outbox accepted any + * non-blank value; the canonical draft would throw. + */ + @ParameterizedTest + @NullSource + @ValueSource(strings = {"", " ", "not canonical", "-leading-dash"}) + void fallsBackToTheEventIdWhenTheCorrelationIdIsAbsentBlankOrNotCanonical(String correlationId) { + // when + append(() -> Optional.ofNullable(correlationId)); + + // then + assertThat(encoder.drafts()) + .singleElement() + .extracting(IntegrationEventDraft::correlationId) + .isEqualTo(EVENT_ID); + } + + @Test + void theEventBelongsToThePortfolioTenantAndIsOrderedByItsOccurrenceMicrosecond() { + // when + append(Optional::empty); + + // then + assertThat(encoder.drafts()) + .singleElement() + .extracting(IntegrationEventDraft::aggregate, IntegrationEventDraft::order) + .containsExactly( + new AggregateIdentity("portfolio", "poster", "poster-1"), + new AggregateOrder(1_748_772_000_123_456L, 0)); + } + + private void append(CorrelationIdPort correlations) { + new PortfolioEventOutbox( + new InMemoryOutboxStore(), + encoder, + () -> EVENT_ID, + correlations, + Clock.fixed(NOW, ZoneOffset.UTC)) + .append( + PortfolioEventContracts.POSTER_PUBLISHED, + "poster", + "poster-1", + new PosterIdPayload("poster-1")); + } +} diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisherTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisherTest.java index 8a6d7495..b5dee5da 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisherTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisherTest.java @@ -2,20 +2,17 @@ package dev.caskeleton.sample.portfolio.application.event; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.application.observability.CorrelationIdPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.messaging.event.IntegrationEventDraft; +import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; import dev.caskeleton.sample.portfolio.domain.poster.PosterCreated; +import dev.caskeleton.sample.portfolio.domain.poster.PosterDeleted; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.NullSource; -import org.junit.jupiter.params.provider.ValueSource; class PosterEventPublisherTest { @@ -24,37 +21,50 @@ class PosterEventPublisherTest { private static final Clock CLOCK = Clock.fixed(Instant.parse("2025-06-01T10:00:00Z"), ZoneOffset.UTC); - // LegacyOutboxAppendPort is owned by application-core; a recording method reference is enough. - private final List appended = new ArrayList<>(); + private final InMemoryOutboxStore outbox = new InMemoryOutboxStore(); + private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder(); + private final PosterEventPublisher publisher = + new PosterEventPublisher( + new PortfolioEventOutbox(outbox, encoder, () -> EVENT_ID, Optional::empty, CLOCK)); @Test - void usesTheCurrentCorrelationIdWhenOneIsPresent() { + void aCreatedPosterIsAnnouncedAsPosterCreatedAboutThatPoster() { // when - publishCreated(() -> Optional.of("corr-123")); + publisher.publishCreated(new PosterCreated(POSTER_ID, "title")); // then - assertThat(appended) + assertThat(encoder.drafts()) .singleElement() - .extracting(NewOutboxEvent::correlationId) - .isEqualTo("corr-123"); + .extracting( + draft -> draft.contractId().value(), + draft -> draft.aggregate().aggregateId(), + IntegrationEventDraft::featurePayload) + .containsExactly( + "poster.created", + POSTER_ID.value(), + new PosterCreatedPayload(POSTER_ID.value(), "title")); } - @ParameterizedTest - @NullSource - @ValueSource(strings = {"", " "}) - void fallsBackToTheEventIdWhenTheCorrelationIdIsAbsentOrBlank(String correlationId) { + @Test + void aDeletedPosterIsAnnouncedWithItsIdOnly() { // when - publishCreated(() -> Optional.ofNullable(correlationId)); + publisher.publishDeleted(new PosterDeleted(POSTER_ID)); // then - assertThat(appended) + assertThat(encoder.drafts()) .singleElement() - .extracting(NewOutboxEvent::correlationId) - .isEqualTo(EVENT_ID); + .extracting(draft -> draft.contractId().value(), IntegrationEventDraft::featurePayload) + .containsExactly("poster.deleted", new PosterIdPayload(POSTER_ID.value())); } - private void publishCreated(CorrelationIdPort correlationIdPort) { - new PosterEventPublisher(appended::add, () -> EVENT_ID, correlationIdPort, CLOCK) - .publishCreated(new PosterCreated(POSTER_ID, "title")); + @Test + void theEncodedEventIsAppendedToTheOutbox() { + // when + publisher.publishCreated(new PosterCreated(POSTER_ID, "title")); + + // then + assertThat(outbox.appended()) + .extracting(event -> event.eventId().value()) + .containsExactly(EVENT_ID); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedConsumerDedupeContractTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedConsumerDedupeContractTest.java index ab3f7a9e..12003aff 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedConsumerDedupeContractTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedConsumerDedupeContractTest.java @@ -2,7 +2,8 @@ package dev.caskeleton.sample.portfolio.application.event; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; @@ -15,9 +16,9 @@ import org.junit.jupiter.api.Test; * Contract test (spec D7) — at-least-once delivery consumer dedupe obligation. * *

    This test demonstrates the executable contract that any consumer of {@code - * worklog.reserved} events MUST honour: given identical {@code idempotencyKey} envelopes delivered - * multiple times (at-least-once delivery is the structural guarantee of the polling outbox), - * exactly one processing side-effect must occur. + * portfolio.worklog.reserved} events MUST honour: given the same event delivered multiple times + * (at-least-once delivery is the structural guarantee of the polling outbox), exactly one + * processing side-effect must occur. * *

    Scope

    * @@ -25,15 +26,12 @@ import org.junit.jupiter.api.Test; *
  • The dedupe mechanism (in-memory {@link Set} below) is intentionally minimal — a * real consumer uses a persistent store with TTL. Storage and TTL policy is owned by the * consumer implementation branch (out of scope here). - *
  • This test exercises the shape of the contract: same {@code idempotencyKey} → skip, - * different key → process. It does not test distributed consistency or TTL expiry. + *
  • This test exercises the shape of the contract: same event id → skip, different id + * → process. It does not test distributed consistency or TTL expiry. * * - *

    Relationship to I12

    - * - *

    {@code idempotencyKey = eventId} by default (I12 — per-event deduplication). A consumer that - * keys dedupe on the envelope's {@code idempotencyKey} therefore deduplicates at the event level, - * not the use-case call level. + *

    The event id is the deduplication key: the outbox stores and republishes the exact validated + * envelope, so a redelivery carries the id of the first delivery. */ class WorkLogReservedConsumerDedupeContractTest { @@ -44,21 +42,21 @@ class WorkLogReservedConsumerDedupeContractTest { private final FakeWorkLogReservedConsumer consumer = new FakeWorkLogReservedConsumer(); @Test - void sameIdempotencyKeyDeliveredFiveTimesProducesExactlyOneEffect() { + void sameEventDeliveredFiveTimesProducesExactlyOneEffect() { // given - NewOutboxEvent envelope = sampleEnvelope(KEY_A); + ValidatedIntegrationEvent envelope = sampleEnvelope(KEY_A); // when Collections.nCopies(5, envelope).forEach(consumer::consume); // then assertThat(consumer.processedEventIds) - .as("same idempotencyKey delivered 5 times must produce exactly 1 processing effect (D7)") + .as("the same event delivered 5 times must produce exactly 1 processing effect (D7)") .containsExactly(KEY_A); } @Test - void distinctIdempotencyKeysAreEachProcessedOnce() { + void distinctEventsAreEachProcessedOnce() { // when deliver(KEY_A, KEY_B, KEY_C); @@ -67,7 +65,7 @@ class WorkLogReservedConsumerDedupeContractTest { } @Test - void mixedDeliveryOnlyDeduplicatesTheRepeatedKey() { + void mixedDeliveryOnlyDeduplicatesTheRepeatedEvent() { // when deliver(KEY_A, KEY_A, KEY_B); @@ -75,36 +73,19 @@ class WorkLogReservedConsumerDedupeContractTest { assertThat(consumer.processedEventIds).containsExactly(KEY_A, KEY_B); } - @Test - void envelopeIdempotencyKeyEqualsEventIdPerI12() { - // when - NewOutboxEvent envelope = sampleEnvelope(KEY_A); - - // then - assertThat(envelope.idempotencyKey()).isEqualTo(envelope.eventId()); - } - - private void deliver(String... idempotencyKeys) { - for (String key : idempotencyKeys) { - consumer.consume(sampleEnvelope(key)); + private void deliver(String... eventIds) { + for (String eventId : eventIds) { + consumer.consume(sampleEnvelope(eventId)); } } - private static NewOutboxEvent sampleEnvelope(String id) { - return new NewOutboxEvent( - id, - WorkLogReservedIntegrationEventMapper.EVENT_TYPE, - "0190bd6e-7c3e-7abc-8def-0123456789ab", // aggregateId - "{\"workLogId\":\"" + id + "\",\"category\":\"BACKEND\",\"occurredOn\":\"2025-01-01\"}", - Instant.parse("2025-01-01T00:00:00Z"), - id, // correlationId - id // idempotencyKey = eventId (I12) - ); + private static ValidatedIntegrationEvent sampleEnvelope(String eventId) { + return OutboxEvents.event(eventId, Instant.parse("2025-01-01T00:00:00Z")); } /** - * Minimal consumer with in-memory idempotencyKey tracking — the subject of this contract, not a - * port double. + * Minimal consumer with in-memory event-id tracking — the subject of this contract, not a port + * double. * *

    Real implementations replace the {@link HashSet} with a persistent store (Redis / DB {@code * idempotency_record}) and a configurable TTL. The dedupe logic shape ({@code if (seen.add(key)) @@ -115,13 +96,11 @@ class WorkLogReservedConsumerDedupeContractTest { private final Set processedKeys = new HashSet<>(); private final List processedEventIds = new ArrayList<>(); - /** - * Processes the envelope. If {@code idempotencyKey} was already seen, the message is silently - * skipped (at-least-once → exactly-once effect). - */ - void consume(NewOutboxEvent envelope) { - if (processedKeys.add(envelope.idempotencyKey())) { - processedEventIds.add(envelope.eventId()); + /** Processes the envelope unless its event id was already seen. */ + void consume(ValidatedIntegrationEvent envelope) { + String eventId = envelope.eventId().value(); + if (processedKeys.add(eventId)) { + processedEventIds.add(eventId); } } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperJsonTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperJsonTest.java deleted file mode 100644 index 0efd5d22..00000000 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperJsonTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.sample.portfolio.application.event; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.params.provider.Arguments.argumentSet; - -import com.fasterxml.jackson.databind.ObjectMapper; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogReserved; -import java.io.IOException; -import java.time.LocalDate; -import java.util.Locale; -import java.util.Map; -import java.util.stream.Stream; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * Verifies the JSON serialisation produced by {@link WorkLogReservedIntegrationEventMapper#toJson} - * (feature-domain-event-outbox-contract D11 + D12). - * - *

    Hand-rolled serialisation: no Jackson dependency in main code. Checks field presence, - * ordering, and RFC 8259 §7 escape correctness. - */ -class WorkLogReservedIntegrationEventMapperJsonTest { - - private static final WorkLogReservedIntegrationEvent SAMPLE_EVENT = - WorkLogReservedIntegrationEventMapper.toIntegrationEvent( - new WorkLogReserved( - WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"), - WorkCategory.BACKEND, - LocalDate.of(2025, 1, 1))); - - @Test - void toJsonWritesWorkLogIdCategoryAndOccurredOnInThatOrder() { - assertThat(WorkLogReservedIntegrationEventMapper.toJson(SAMPLE_EVENT)) - .isEqualTo( - "{\"workLogId\":\"0190bd6e-7c3e-7abc-8def-0123456789ab\"," - + "\"category\":\"BACKEND\"," - + "\"occurredOn\":\"2025-01-01\"}"); - } - - @Test - void toJsonIsAParseableObjectWithExactlyTheThreeFields() throws IOException { - // when - String json = WorkLogReservedIntegrationEventMapper.toJson(SAMPLE_EVENT); - - // then - assertThat(json).startsWith("{").endsWith("}"); - assertThat(new ObjectMapper().readTree(json).properties()) - .extracting(Map.Entry::getKey) - .containsExactly("workLogId", "category", "occurredOn"); - } - - @ParameterizedTest - @MethodSource("escapeCases") - void escapeProducesRfc8259EscapedText(String input, String expected) { - assertThat(EventJson.escape(input)).isEqualTo(expected); - } - - static Stream escapeCases() { - return Stream.of( - argumentSet("backslash and double quote", "path\\to\"value", "path\\\\to\\\"value"), - // Tab (0x09) and newline (0x0A) are below 0x20, so they become \\u escapes. - argumentSet("control characters", "a\tb\nc", "a\\u0009b\\u000ac"), - argumentSet("null becomes the empty string", null, "")); - } - - @Test - void eventTypeConstantIsStable() { - // I9: eventType becomes the broker topic — must not change silently - assertThat(WorkLogReservedIntegrationEventMapper.EVENT_TYPE).isEqualTo("worklog.reserved"); - } - - @Test - void toJsonContainsNoPiiFieldNames() { - // EventPayloadPiiContractTest (Task E) also enforces this statically; - // this test makes it explicit for the sample payload shape. - assertThat(WorkLogReservedIntegrationEventMapper.toJson(SAMPLE_EVENT).toLowerCase(Locale.ROOT)) - .doesNotContain("email", "password", "token", "secret"); - } -} diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperTest.java deleted file mode 100644 index 12035829..00000000 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.sample.portfolio.application.event; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogReserved; -import java.time.LocalDate; -import org.junit.jupiter.api.Test; - -/** - * Verifies the Claims-To-Verify flow: a transport-free domain event is convertible to an - * integration event at the application boundary (feature-domain-modeling-guardrails D4/D8). - */ -class WorkLogReservedIntegrationEventMapperTest { - - @Test - void mapsDomainEventToIntegrationEventFlatteningValueObjects() { - // given - WorkLogReserved domainEvent = - new WorkLogReserved( - WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"), - WorkCategory.BACKEND, - LocalDate.of(2025, 1, 1)); - - // when - WorkLogReservedIntegrationEvent integrationEvent = - WorkLogReservedIntegrationEventMapper.toIntegrationEvent(domainEvent); - - // then - assertThat(integrationEvent) - .isEqualTo( - new WorkLogReservedIntegrationEvent( - "0190bd6e-7c3e-7abc-8def-0123456789ab", "BACKEND", "2025-01-01")); - } -} diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImageAbortReconcileRaceTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImageAbortReconcileRaceTest.java index 7dc6c3b1..1836691a 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImageAbortReconcileRaceTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImageAbortReconcileRaceTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; @@ -37,6 +38,7 @@ import dev.caskeleton.application.outbound.CallBudget; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.sample.portfolio.application.command.AbortPosterImageUploadCommand; import dev.caskeleton.sample.portfolio.application.command.ReconcilePosterImageUploadCommand; +import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; import dev.caskeleton.sample.portfolio.application.event.PosterImagePublicationEventPublisher; import dev.caskeleton.sample.portfolio.application.exception.PosterImageAlreadyPublishedException; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageAttachmentCompareAndSetPort; @@ -212,7 +214,12 @@ class PosterImageAbortReconcileRaceTest { new PosterImageOperationIdFactory.AllocatedOperation( UUID.randomUUID(), ObjectOperationId.of(UUID.randomUUID().toString())), new PosterImagePublicationEventPublisher( - event -> {}, () -> "0190bd6e-7c3e-7abc-8def-0123456789ff", Optional::empty, CLOCK), + new PortfolioEventOutbox( + event -> {}, + new FakeIntegrationEventEncoder(), + () -> "0190bd6e-7c3e-7abc-8def-0123456789ff", + Optional::empty, + CLOCK)), transactions, publications, handoffs, diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImagePublicationWorkflowTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImagePublicationWorkflowTest.java index 1681338e..3e01caa5 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImagePublicationWorkflowTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImagePublicationWorkflowTest.java @@ -7,6 +7,7 @@ import static org.mockito.Mockito.when; import dev.caskeleton.application.idempotency.IdempotencyExecutor; import dev.caskeleton.application.idempotency.testkit.InMemoryIdempotencyStore; +import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; import dev.caskeleton.application.objectstorage.content.ObjectContentProductionContext; @@ -33,6 +34,7 @@ import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import dev.caskeleton.sample.portfolio.adapter.outbound.identifier.HmacPosterImageIdempotencyScopeDigester; import dev.caskeleton.sample.portfolio.application.command.PublishPosterImageCommand; +import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; import dev.caskeleton.sample.portfolio.application.event.PosterImagePublicationEventPublisher; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageIdempotencyScopeDigest; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageOperationIdFactory; @@ -148,7 +150,7 @@ class PosterImagePublicationWorkflowTest { // then assertThat(appendedInsideTransaction) - .containsExactly(Map.entry("poster.image-attachment-prepared.v1", true)); + .containsExactly(Map.entry("poster.image-attachment-prepared", true)); } @Test @@ -225,11 +227,14 @@ class PosterImagePublicationWorkflowTest { publications, handoffs, new PosterImagePublicationEventPublisher( - event -> - appendedInsideTransaction.add(Map.entry(event.eventType(), transactions.active())), - () -> "0190bd6e-7c3e-7abc-8def-0123456789ff", - Optional::empty, - CLOCK), + new PortfolioEventOutbox( + event -> + appendedInsideTransaction.add( + Map.entry(event.contractId().value(), transactions.active())), + new FakeIntegrationEventEncoder(), + () -> "0190bd6e-7c3e-7abc-8def-0123456789ff", + Optional::empty, + CLOCK)), new PosterImagePublicationPolicy(1024), new PosterImagePublicationParameters( ObjectDestinationId.of("poster"), diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogOutboxTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogOutboxTest.java index d09f3ab0..055236d6 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogOutboxTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogOutboxTest.java @@ -1,15 +1,16 @@ package dev.caskeleton.sample.portfolio.application.worklog; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.tuple; -import dev.caskeleton.application.observability.CorrelationIdPort; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.messaging.event.IntegrationEventDraft; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import dev.caskeleton.sample.portfolio.application.command.CreateWorkLogCommand; -import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedIntegrationEventMapper; +import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; +import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedPayload; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; @@ -24,8 +25,8 @@ import java.util.Optional; import org.junit.jupiter.api.Test; /** - * {@link CreateWorkLogUseCase} appends a {@code WorkLogReserved} outbox event in the same {@code - * tx.inWrite} as the aggregate save (feature-domain-event-outbox-contract D2). + * {@link CreateWorkLogUseCase} appends a {@code portfolio.worklog.reserved} integration event in + * the same {@code tx.inWrite} as the aggregate save (feature-domain-event-outbox-contract D2). */ class CreateWorkLogOutboxTest { @@ -34,126 +35,75 @@ class CreateWorkLogOutboxTest { private static final Instant NOW = Instant.parse("2025-06-01T10:00:00Z"); private final DirectTransactionPort tx = new DirectTransactionPort(); - private final List appended = new ArrayList<>(); + private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder(); + private final List appended = new ArrayList<>(); private final List appendedInsideTransaction = new ArrayList<>(); - /** application-core's in-memory outbox does not expose appended events, so record them here. */ - private final LegacyOutboxAppendPort outbox = + private final OutboxAppendPort outbox = event -> { appended.add(event); appendedInsideTransaction.add(tx.active()); }; @Test - void appendsOneEventOfTheWorkLogReservedType() { + void appendsOneWorkLogReservedEventAboutTheCreatedWorkLog() { // when - createWith(Optional::empty); + WorkLog created = create(); // then - assertThat(appended) - .extracting(NewOutboxEvent::eventType) - .containsExactly(WorkLogReservedIntegrationEventMapper.EVENT_TYPE); + assertThat(encoder.drafts()) + .singleElement() + .extracting( + draft -> draft.contractId().value(), + draft -> draft.aggregate().aggregateId(), + IntegrationEventDraft::featurePayload) + .containsExactly( + "portfolio.worklog.reserved", + created.id().value(), + new WorkLogReservedPayload(FIXED_ID.value())); } @Test void appendsTheEventInsideTheTransaction() { // when - createWith(Optional::empty); + create(); // then assertThat(appendedInsideTransaction) - .as("LegacyOutboxAppendPort.append must run inside tx.inWrite (D2)") + .as("OutboxAppendPort.append must run inside tx.inWrite (D2)") .containsExactly(true); } @Test void savesAndAppendsInOneWriteTransaction() { // when - createWith(Optional::empty); + create(); // then assertThat(tx.committed()).containsExactly(Boundary.WRITE); } @Test - void usesTheCreatedWorkLogIdAsTheAggregateId() { + void stampsTheEventIdAndOccurredAtItWasGiven() { // when - WorkLog created = createWith(Optional::empty); + create(); // then assertThat(appended) - .extracting(NewOutboxEvent::aggregateId) - .containsExactly(created.id().value()); + .extracting(event -> event.eventId().value(), ValidatedIntegrationEvent::occurredAt) + .containsExactly(org.assertj.core.groups.Tuple.tuple(FIXED_EVENT_ID, NOW)); } - @Test - void usesTheEventIdAsTheIdempotencyKey() { - // when - createWith(Optional::empty); - - // then - assertThat(appended) - .as("idempotencyKey must equal eventId (I12)") - .extracting(NewOutboxEvent::eventId, NewOutboxEvent::idempotencyKey) - .containsExactly(tuple(FIXED_EVENT_ID, FIXED_EVENT_ID)); - } - - @Test - void stampsOccurredAtFromTheInjectedClock() { - // when - createWith(Optional::empty); - - // then - assertThat(appended).extracting(NewOutboxEvent::occurredAt).containsExactly(NOW); - } - - @Test - void writesTheWorkLogIdAndCategoryIntoThePayload() { - // when - createWith(Optional::empty); - - // then - assertThat(appended.get(0).payload()).contains(FIXED_ID.value(), "BACKEND"); - } - - @Test - void fallsBackToTheEventIdAsCorrelationIdWhenNoneIsInContext() { - // when - createWith(Optional::empty); - - // then - assertThat(appended) - .as("self-correlation fallback: correlationId = eventId when context is absent") - .extracting(NewOutboxEvent::correlationId) - .containsExactly(FIXED_EVENT_ID); - } - - @Test - void usesTheCorrelationIdFromContextWhenPresent() { - // when - createWith(() -> Optional.of("test-corr-123")); - - // then - assertThat(appended).extracting(NewOutboxEvent::correlationId).containsExactly("test-corr-123"); - } - - @Test - void fallsBackToTheEventIdAsCorrelationIdWhenTheContextValueIsBlank() { - // when - createWith(() -> Optional.of(" ")); - - // then - assertThat(appended).extracting(NewOutboxEvent::correlationId).containsExactly(FIXED_EVENT_ID); - } - - private WorkLog createWith(CorrelationIdPort correlation) { + private WorkLog create() { return new CreateWorkLogUseCase( new InMemoryWorkLogRepository(), () -> FIXED_ID, - () -> FIXED_EVENT_ID, - outbox, - correlation, - Clock.fixed(NOW, ZoneOffset.UTC), + new PortfolioEventOutbox( + outbox, + encoder, + () -> FIXED_EVENT_ID, + Optional::empty, + Clock.fixed(NOW, ZoneOffset.UTC)), tx) .handle( new CreateWorkLogCommand( diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java index 97aaed3b..dd6583c0 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java @@ -7,14 +7,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import com.github.f4b6a3.uuid.UuidCreator; +import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.observability.CorrelationIdPort; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import dev.caskeleton.sample.portfolio.application.command.BatchCreateWorkLogsCommand; import dev.caskeleton.sample.portfolio.application.command.CreateWorkLogCommand; import dev.caskeleton.sample.portfolio.application.command.DeleteWorkLogCommand; import dev.caskeleton.sample.portfolio.application.command.UpdateWorkLogCommand; +import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; import dev.caskeleton.sample.portfolio.application.exception.WorkLogNotFoundException; import dev.caskeleton.sample.portfolio.application.exception.WorkLogVersionMismatchException; import dev.caskeleton.sample.portfolio.application.query.GetWorkLogQuery; @@ -46,7 +48,7 @@ class WorkLogUseCasesTest { private static final WorkLogIdFactory IDS = () -> WorkLogId.of(UuidCreator.getTimeOrderedEpochPlus1().toString()); - private static final LegacyOutboxAppendPort NO_OP_OUTBOX = event -> {}; + private static final OutboxAppendPort NO_OP_OUTBOX = event -> {}; private static final CorrelationIdPort NO_CORRELATION = Optional::empty; private final InMemoryWorkLogRepository repository = new InMemoryWorkLogRepository(); @@ -55,10 +57,12 @@ class WorkLogUseCasesTest { new CreateWorkLogUseCase( repository, IDS, - () -> "01FAKEEVENTIDTSV4RRFFQ6900", - NO_OP_OUTBOX, - NO_CORRELATION, - Clock.systemUTC(), + new PortfolioEventOutbox( + NO_OP_OUTBOX, + new FakeIntegrationEventEncoder(), + () -> "01FAKEEVENTIDTSV4RRFFQ6900", + NO_CORRELATION, + Clock.systemUTC()), tx); private final UpdateWorkLogUseCase update = new UpdateWorkLogUseCase(repository, tx); diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationContractTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationContractTest.java index 9d8a9bf6..26217927 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationContractTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationContractTest.java @@ -9,13 +9,14 @@ import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter; import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig; import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy; import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry; +import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.observability.CorrelationIdPort; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.sample.portfolio.application.command.CreateWorkLogCommand; import dev.caskeleton.sample.portfolio.application.command.DeleteWorkLogCommand; +import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; import dev.caskeleton.sample.portfolio.application.worklog.CreateWorkLogUseCase; import dev.caskeleton.sample.portfolio.application.worklog.DeleteWorkLogUseCase; import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory; @@ -219,9 +220,9 @@ class WorkLogAuthorizationContractTest { } @Bean - LegacyOutboxAppendPort outboxAppendPort() { + OutboxAppendPort outboxAppendPort() { // No-op for authorization tests — the contract under test is auth, not outbox. - return (NewOutboxEvent e) -> {}; + return event -> {}; } @Bean @@ -239,12 +240,20 @@ class WorkLogAuthorizationContractTest { WorkLogRepository repository, WorkLogIdFactory idFactory, OutboxEventIdFactory eventIdFactory, - LegacyOutboxAppendPort outboxAppendPort, + OutboxAppendPort outboxAppendPort, CorrelationIdPort correlationIdPort, Clock clock, TransactionPort tx) { return new CreateWorkLogUseCase( - repository, idFactory, eventIdFactory, outboxAppendPort, correlationIdPort, clock, tx); + repository, + idFactory, + new PortfolioEventOutbox( + outboxAppendPort, + new FakeIntegrationEventEncoder(), + eventIdFactory, + correlationIdPort, + clock), + tx); } @Bean diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfigTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfigTest.java index db55d545..e6cf50b7 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfigTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfigTest.java @@ -48,7 +48,11 @@ import org.springframework.test.web.servlet.ResultActions; // The slice excludes the data layer; persistence-jpa is on while present, so it is switched off. @SpringBootTest( classes = SamplePublicAccessSecurityConfigTest.TestBootstrap.class, - properties = "ca-skeleton.persistence-jpa.enabled=false") + properties = { + "ca-skeleton.persistence-jpa.enabled=false", + // The PostgreSQL idempotency store needs the relational module this test leaves off. + "ca-skeleton.capabilities.idempotency.provider=disabled" + }) @AutoConfigureMockMvc class SamplePublicAccessSecurityConfigTest { diff --git a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/contract/OpenApiDriftContractTest.java b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/contract/OpenApiDriftContractTest.java index a811c52a..5edbed62 100644 --- a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/contract/OpenApiDriftContractTest.java +++ b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/contract/OpenApiDriftContractTest.java @@ -62,7 +62,11 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean; classes = OpenApiDriftContractTest.OpenApiDriftTestApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, // The app excludes the data layer; persistence-jpa is on while present, so it is switched off. - properties = {"management.server.port=0", "ca-skeleton.persistence-jpa.enabled=false"}) + properties = { + "management.server.port=0", + "ca-skeleton.persistence-jpa.enabled=false", + "ca-skeleton.capabilities.idempotency.provider=disabled" + }) @AutoConfigureTestRestTemplate class OpenApiDriftContractTest { diff --git a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/date/DateHeaderContractTest.java b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/date/DateHeaderContractTest.java index 60b5fac6..e60b92be 100644 --- a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/date/DateHeaderContractTest.java +++ b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/date/DateHeaderContractTest.java @@ -34,7 +34,11 @@ import org.springframework.web.bind.annotation.RestController; classes = DateHeaderContractTest.DateProbeApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, // The app excludes the data layer; persistence-jpa is on while present, so it is switched off. - properties = {"management.server.port=0", "ca-skeleton.persistence-jpa.enabled=false"}) + properties = { + "management.server.port=0", + "ca-skeleton.persistence-jpa.enabled=false", + "ca-skeleton.capabilities.idempotency.provider=disabled" + }) @AutoConfigureTestRestTemplate class DateHeaderContractTest { diff --git a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcE2ETest.java b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcE2ETest.java index e0ae0fff..57eaf1ff 100644 --- a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcE2ETest.java +++ b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcE2ETest.java @@ -64,7 +64,8 @@ import org.springframework.web.bind.annotation.RestController; "spring.jackson.deserialization.fail-on-unknown-properties=true", "management.server.port=0", // The app excludes the data layer; persistence-jpa is on while present, so it is off here. - "ca-skeleton.persistence-jpa.enabled=false" + "ca-skeleton.persistence-jpa.enabled=false", + "ca-skeleton.capabilities.idempotency.provider=disabled" }) @AutoConfigureTestRestTemplate class VirtualThreadMdcE2ETest { diff --git a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/openapi/OpenApiSnapshotTest.java b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/openapi/OpenApiSnapshotTest.java index 8b3d75ab..95fb392d 100644 --- a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/openapi/OpenApiSnapshotTest.java +++ b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/openapi/OpenApiSnapshotTest.java @@ -44,7 +44,11 @@ import tools.jackson.databind.ObjectMapper; classes = OpenApiSnapshotTest.OpenApiTestApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, // The app excludes the data layer; persistence-jpa is on while present, so it is switched off. - properties = {"management.server.port=0", "ca-skeleton.persistence-jpa.enabled=false"}) + properties = { + "management.server.port=0", + "ca-skeleton.persistence-jpa.enabled=false", + "ca-skeleton.capabilities.idempotency.provider=disabled" + }) @AutoConfigureTestRestTemplate class OpenApiSnapshotTest { diff --git a/src/shared-contract/README.md b/src/shared-contract/README.md index 125119e6..244bcd2e 100644 --- a/src/shared-contract/README.md +++ b/src/shared-contract/README.md @@ -459,7 +459,7 @@ virtual-thread 와 `StructuredTaskScope.fork()` 경계 너머로 전파하는 virtual-thread 안전, `InheritableThreadLocal` 미사용). - **`DomainContextKey`** — 도메인이 공급하는 per-value 확장점(키), `RateLimitKeyResolver` 와 유사. -Spring 배선(`DomainContextConfig`)은 `app-bootstrap` 에 있고 `ThreadLocalDomainContextPropagator` 를 +Spring 배선(`DomainContextConfig`)은 `composition:service-runtime` 에 있고 `ThreadLocalDomainContextPropagator` 를 직접 만든다. 구현이 하나뿐이라 strategy enum·factory·선택 설정은 두지 않는다. ### 무엇을 일부러 ship 하지 않았나 (그리고 왜) diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/package-info.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/package-info.java index 24d8b596..152a4872 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/package-info.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/package-info.java @@ -4,8 +4,8 @@ * *

    The package ships one implementation ({@link * dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator}) behind the {@link - * dev.caskeleton.shared.concurrency.DomainContextPropagator} port; {@code app-bootstrap}'s {@code - * DomainContextConfig} constructs it directly. + * dev.caskeleton.shared.concurrency.DomainContextPropagator} port; {@code + * composition:service-runtime}'s {@code DomainContextConfig} constructs it directly. * *

    See the module README for the full design: what stays unshipped (domain keys, the {@code * ScopedValue} strategy) and why, and the boundary → mechanism delegation map.