feat(notification): implement the notification delivery platform
Maps the 31-module plan onto the registry's 19 leaves as packages; the two edges the registry forbids (provider->httpclient, inbox->messaging) are replaced by application-owned ports. See docs/notification/module-mapping.md. Acceptance is not delivery: ProviderSubmissionResult refuses to carry a delivery outcome, and AMBIGUOUS is a first-class terminal state that blocks automatic retry and fallback until reconciliation resolves it. Providers: SES (SigV4 + SNS callback), Twilio (X-Twilio-Signature + reconciliation), FCM (FID-primary batch), APNs, Web Push (RFC 8030/8291/8292), SMTP and webhook. Contact points are AES-256-GCM encrypted with a separate HMAC lookup fingerprint; nothing raw reaches a log, metric tag or exception. Dispatch commits the attempt row, calls the provider with no transaction open, then records the outcome; the durable queue uses FOR UPDATE SKIP LOCKED. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
3b5aee50e3
commit
701ba67456
@@ -160,6 +160,10 @@ def contractRegistriesDirectory = rootProject.projectDir.parentFile.toPath()
|
||||
.resolve('docs/registries').toFile()
|
||||
tasks.withType(Test).configureEach {
|
||||
systemProperty 'ca.repository.root', repositoryRootForContractTests
|
||||
// This module's tests hold whole-repository ArchUnit class graphs. Gradle's 512m default runs
|
||||
// out once more than one @AnalyzeClasses suite is resident, and the failure surfaces as an
|
||||
// executor crash rather than as a named failing test — which is a bad afternoon to debug.
|
||||
maxHeapSize = '2g'
|
||||
}
|
||||
|
||||
// Pin UTC for the TEST JVM so timestamp tests are host-locale-independent (production UTC owned elsewhere). See README.
|
||||
|
||||
@@ -215,6 +215,7 @@ jakarta.activation:jakarta.activation-api:2.1.4=productionRuntimeClasspath,runti
|
||||
jakarta.annotation:jakarta.annotation-api:2.1.1=sampleFixture
|
||||
jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,conditionalTransportTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
jakarta.inject:jakarta.inject-api:2.0.1=productionRuntimeClasspath,runtimeClasspath,sampleFixture,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
jakarta.mail:jakarta.mail-api:2.1.5=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
jakarta.persistence:jakarta.persistence-api:3.1.0=sampleFixture
|
||||
jakarta.persistence:jakarta.persistence-api:3.2.0=productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
jakarta.transaction:jakarta.transaction-api:2.0.1=productionRuntimeClasspath,runtimeClasspath,sampleFixture,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
@@ -234,6 +235,7 @@ net.logstash.logback:logstash-logback-encoder:8.0=compileClasspath,productionRun
|
||||
net.minidev:accessors-smart:2.6.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
net.minidev:json-smart:2.6.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
|
||||
ognl:ognl:3.3.4=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
org.antlr:antlr4-runtime:4.13.2=checkstyle,productionRuntimeClasspath,runtimeClasspath,sampleFixture,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.apache.bcel:bcel:6.12.0=spotbugs
|
||||
org.apache.commons:commons-compress:1.28.0=sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
@@ -266,6 +268,7 @@ org.apiguardian:apiguardian-api:1.1.2=conditionalTransportTestCompileClasspath,f
|
||||
org.aspectj:aspectjweaver:1.9.25=productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.aspectj:aspectjweaver:1.9.25.1=sampleFixture
|
||||
org.assertj:assertj-core:3.27.6=conditionalTransportTestCompileClasspath,conditionalTransportTestRuntimeClasspath,functionalTestCompileClasspath,functionalTestRuntimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.attoparser:attoparser:2.0.7.RELEASE=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
org.awaitility:awaitility:4.3.0=sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.checkerframework:checker-qual:3.42.0=conditionalTransportTestRuntimeClasspath
|
||||
org.checkerframework:checker-qual:3.49.5=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
@@ -276,6 +279,7 @@ 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=productionRuntimeClasspath,runtimeClasspath,sampleFixture,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
org.eclipse.angus:angus-mail:2.0.5=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
org.eclipse.jetty.compression:jetty-compression-common:12.1.4=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
org.eclipse.jetty.compression:jetty-compression-gzip:12.1.4=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
org.eclipse.jetty:jetty-alpn-client:12.1.4=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
@@ -302,6 +306,7 @@ org.hibernate.orm:hibernate-core:7.1.8.Final=productionRuntimeClasspath,runtimeC
|
||||
org.hibernate.validator:hibernate-validator:8.0.3.Final=sampleFixture
|
||||
org.hibernate.validator:hibernate-validator:9.0.1.Final=compileClasspath,conditionalTransportTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.javassist:javassist:3.28.0-GA=checkstyle
|
||||
org.javassist:javassist:3.29.0-GA=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
org.jboss.logging:jboss-logging:3.6.1.Final=compileClasspath,conditionalTransportTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.jboss.logging:jboss-logging:3.6.3.Final=sampleFixture
|
||||
org.jetbrains.kotlin:kotlin-stdlib-common:1.9.25=sampleFixture
|
||||
@@ -375,6 +380,7 @@ org.springframework.boot:spring-boot-jdbc-test:4.0.0=sampleOffTestCompileClasspa
|
||||
org.springframework.boot:spring-boot-jdbc:4.0.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.springframework.boot:spring-boot-jpa-test:4.0.0=sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.springframework.boot:spring-boot-jpa:4.0.0=productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.springframework.boot:spring-boot-mail:4.0.0=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
org.springframework.boot:spring-boot-micrometer-metrics:4.0.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.springframework.boot:spring-boot-micrometer-observation:4.0.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.springframework.boot:spring-boot-persistence:4.0.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
@@ -398,6 +404,7 @@ org.springframework.boot:spring-boot-starter-json:3.5.16=sampleFixture
|
||||
org.springframework.boot:spring-boot-starter-json:4.0.0=productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.springframework.boot:spring-boot-starter-logging:3.5.16=sampleFixture
|
||||
org.springframework.boot:spring-boot-starter-logging:4.0.0=compileClasspath,conditionalTransportTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.springframework.boot:spring-boot-starter-mail:4.0.0=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
org.springframework.boot:spring-boot-starter-micrometer-metrics:4.0.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.springframework.boot:spring-boot-starter-oauth2-resource-server:3.5.16=sampleFixture
|
||||
org.springframework.boot:spring-boot-starter-oauth2-resource-server:4.0.0=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
@@ -461,6 +468,7 @@ org.springframework:spring-aspects:6.2.19=sampleFixture
|
||||
org.springframework:spring-aspects:7.0.1=productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.springframework:spring-beans:6.2.19=sampleFixture
|
||||
org.springframework:spring-beans:7.0.1=compileClasspath,conditionalTransportTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.springframework:spring-context-support:7.0.1=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
org.springframework:spring-context:6.2.19=sampleFixture
|
||||
org.springframework:spring-context:7.0.1=compileClasspath,conditionalTransportTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.springframework:spring-core:6.2.19=sampleFixture
|
||||
@@ -488,6 +496,8 @@ org.testcontainers:testcontainers-jdbc:2.0.2=sampleOffTestCompileClasspath,sampl
|
||||
org.testcontainers:testcontainers-junit-jupiter:2.0.2=sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.testcontainers:testcontainers-postgresql:2.0.2=sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.testcontainers:testcontainers:2.0.2=sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.thymeleaf:thymeleaf:3.1.3.RELEASE=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
org.unbescape:unbescape:1.1.6.RELEASE=productionRuntimeClasspath,runtimeClasspath,sampleOffTestRuntimeClasspath,testRuntimeClasspath
|
||||
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
|
||||
org.xmlunit:xmlunit-core:2.10.4=sampleOffTestCompileClasspath,sampleOffTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
org.yaml:snakeyaml:2.4=sampleFixture
|
||||
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
package dev.caskeleton.bootstrap.notification;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.ContactPointJpaRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.DeliveryAttemptJpaRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaAdminOperationStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaContactPointStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaDeliveryAttemptStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationRequestStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationSideEffectStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaPolicyStores;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaProviderEventLedger;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientDeliveryStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientLeaseStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaSuppressionStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaTemplateRegistry;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.NotificationPolicyJpaRepositories;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.NotificationRecordMapper;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.NotificationRequestJpaRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.ProviderEventJpaRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.RecipientDeliveryJpaRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.SuppressionJpaRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.InboxCommitEventPublisher;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.InboxItemJpaRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.JpaNotificationInbox;
|
||||
import dev.caskeleton.application.notification.platform.admin.AdminOperationStorePort;
|
||||
import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptResolverPort;
|
||||
import dev.caskeleton.application.notification.platform.callback.DeliveryProjectionStorePort;
|
||||
import dev.caskeleton.application.notification.platform.callback.NotificationSideEffectPort;
|
||||
import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.NotificationRoutingPlanCodecPort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.NotificationVariablesCodecPort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.TenantContextPort;
|
||||
import dev.caskeleton.application.notification.platform.inbox.InboxContentCodecPort;
|
||||
import dev.caskeleton.application.notification.platform.inbox.NotificationInbox;
|
||||
import dev.caskeleton.application.notification.platform.inbox.NotificationInboxSignalPort;
|
||||
import dev.caskeleton.application.notification.platform.policy.ConsentStorePort;
|
||||
import dev.caskeleton.application.notification.platform.policy.DeduplicationStorePort;
|
||||
import dev.caskeleton.application.notification.platform.policy.PreferenceStorePort;
|
||||
import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort;
|
||||
import dev.caskeleton.application.notification.platform.template.TemplateContentCodecPort;
|
||||
import dev.caskeleton.application.notification.platform.template.TemplateRegistry;
|
||||
import java.time.Clock;
|
||||
import java.util.Locale;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Binds the notification application ports to their JPA implementations.
|
||||
*
|
||||
* <p>This is the only place that sees both the application ports and the persistence adapter, which
|
||||
* is what keeps application-core free of JPA and the persistence leaf free of use-case policy.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(
|
||||
prefix = "ca-skeleton.notification.platform",
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
public class NotificationPlatformPersistenceConfig {
|
||||
|
||||
/** Entity/record mapping. */
|
||||
@Bean
|
||||
public NotificationRecordMapper notificationRecordMapper(
|
||||
NotificationRoutingPlanCodecPort routingPlans, NotificationVariablesCodecPort variables) {
|
||||
return new NotificationRecordMapper(routingPlans, variables);
|
||||
}
|
||||
|
||||
/** Request and recipient persistence. */
|
||||
@Bean
|
||||
public NotificationRequestStorePort notificationRequestStore(
|
||||
NotificationRequestJpaRepository requests,
|
||||
RecipientDeliveryJpaRepository recipients,
|
||||
NotificationRecordMapper mapper,
|
||||
Clock clock) {
|
||||
return new JpaNotificationRequestStore(requests, recipients, mapper, clock);
|
||||
}
|
||||
|
||||
/** Single recipient job persistence. */
|
||||
@Bean
|
||||
public RecipientDeliveryStorePort recipientDeliveryStore(
|
||||
RecipientDeliveryJpaRepository recipients, NotificationRecordMapper mapper, Clock clock) {
|
||||
return new JpaRecipientDeliveryStore(recipients, mapper, clock);
|
||||
}
|
||||
|
||||
/** Durable queue claim. */
|
||||
@Bean
|
||||
public RecipientLeaseStorePort recipientLeaseStore(
|
||||
RecipientDeliveryJpaRepository recipients, Clock clock) {
|
||||
return new JpaRecipientLeaseStore(recipients, clock);
|
||||
}
|
||||
|
||||
/** Attempt persistence, which also serves the resolver and projection ports. */
|
||||
@Bean
|
||||
public JpaDeliveryAttemptStore deliveryAttemptStore(
|
||||
DeliveryAttemptJpaRepository attempts,
|
||||
RecipientDeliveryJpaRepository recipients,
|
||||
ProviderRequestIdHasherPort hasher,
|
||||
Clock clock) {
|
||||
return new JpaDeliveryAttemptStore(attempts, recipients, hasher, clock);
|
||||
}
|
||||
|
||||
/** Attempt store as its application port. */
|
||||
@Bean
|
||||
public DeliveryAttemptStorePort deliveryAttemptStorePort(JpaDeliveryAttemptStore store) {
|
||||
return store;
|
||||
}
|
||||
|
||||
/** Attempt resolution for incoming provider events. */
|
||||
@Bean
|
||||
public DeliveryAttemptResolverPort deliveryAttemptResolverPort(JpaDeliveryAttemptStore store) {
|
||||
return store;
|
||||
}
|
||||
|
||||
/** Projection persistence. */
|
||||
@Bean
|
||||
public DeliveryProjectionStorePort deliveryProjectionStorePort(JpaDeliveryAttemptStore store) {
|
||||
return store;
|
||||
}
|
||||
|
||||
/** Append-only provider event ledger. */
|
||||
@Bean
|
||||
public ProviderEventLedger providerEventLedger(
|
||||
ProviderEventJpaRepository events,
|
||||
DeliveryAttemptResolverPort resolver,
|
||||
ProviderRequestIdHasherPort hasher,
|
||||
NotificationVariablesCodecPort attributes,
|
||||
NotificationIdGeneratorPort ids) {
|
||||
return new JpaProviderEventLedger(events, resolver, hasher, attributes, ids);
|
||||
}
|
||||
|
||||
/** Contact point persistence. */
|
||||
@Bean
|
||||
public ContactPointStorePort contactPointStore(
|
||||
ContactPointJpaRepository contactPoints, Clock clock) {
|
||||
return new JpaContactPointStore(contactPoints, clock);
|
||||
}
|
||||
|
||||
/** Suppression persistence. */
|
||||
@Bean
|
||||
public SuppressionStorePort suppressionStore(
|
||||
SuppressionJpaRepository suppressions, NotificationIdGeneratorPort ids, Clock clock) {
|
||||
return new JpaSuppressionStore(suppressions, ids, clock);
|
||||
}
|
||||
|
||||
/** Contact-point and suppression side effects of a projected event. */
|
||||
@Bean
|
||||
public NotificationSideEffectPort notificationSideEffectPort(
|
||||
ContactPointStorePort contactPoints, SuppressionStorePort suppressions, Clock clock) {
|
||||
return new JpaNotificationSideEffectStore(contactPoints, suppressions, clock);
|
||||
}
|
||||
|
||||
/** Preference persistence. */
|
||||
@Bean
|
||||
public PreferenceStorePort preferenceStore(
|
||||
NotificationPolicyJpaRepositories.PreferenceJpaRepository preferences,
|
||||
NotificationIdGeneratorPort ids,
|
||||
Clock clock) {
|
||||
return new JpaPolicyStores.Preferences(preferences, ids, clock);
|
||||
}
|
||||
|
||||
/** Consent persistence. */
|
||||
@Bean
|
||||
public ConsentStorePort consentStore(
|
||||
NotificationPolicyJpaRepositories.ConsentJpaRepository consents,
|
||||
NotificationIdGeneratorPort ids) {
|
||||
return new JpaPolicyStores.Consents(consents, ids);
|
||||
}
|
||||
|
||||
/** Deduplication window claims. */
|
||||
@Bean
|
||||
public DeduplicationStorePort deduplicationStore(
|
||||
NotificationPolicyJpaRepositories.DeduplicationClaimJpaRepository claims,
|
||||
NotificationIdGeneratorPort ids,
|
||||
Clock clock) {
|
||||
return new JpaPolicyStores.DeduplicationClaims(claims, ids, clock);
|
||||
}
|
||||
|
||||
/** Operator action idempotency and audit. */
|
||||
@Bean
|
||||
public AdminOperationStorePort adminOperationStore(
|
||||
NotificationPolicyJpaRepositories.AdminAuditJpaRepository audits,
|
||||
NotificationIdGeneratorPort ids,
|
||||
Clock clock) {
|
||||
return new JpaAdminOperationStore(audits, ids, clock);
|
||||
}
|
||||
|
||||
/** Durable template registry. */
|
||||
@Bean
|
||||
public TemplateRegistry templateRegistry(
|
||||
NotificationPolicyJpaRepositories.TemplateVersionJpaRepository versions,
|
||||
TemplateContentCodecPort contentCodec,
|
||||
TenantContextPort tenants,
|
||||
NotificationIdGeneratorPort ids,
|
||||
Clock clock) {
|
||||
return new JpaTemplateRegistry(versions, contentCodec, tenants, ids, clock, Locale.ENGLISH);
|
||||
}
|
||||
|
||||
/** Post-commit inbox signal. */
|
||||
@Bean
|
||||
public InboxCommitEventPublisher inboxCommitEventPublisher(NotificationInboxSignalPort signals) {
|
||||
return new InboxCommitEventPublisher(signals);
|
||||
}
|
||||
|
||||
/** Durable in-app inbox. */
|
||||
@Bean
|
||||
public NotificationInbox notificationInbox(
|
||||
InboxItemJpaRepository items,
|
||||
InboxContentCodecPort contentCodec,
|
||||
InboxCommitEventPublisher publisher,
|
||||
NotificationIdGeneratorPort ids,
|
||||
Clock clock) {
|
||||
return new JpaNotificationInbox(items, contentCodec, publisher, ids, clock);
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package dev.caskeleton.bootstrap.notification;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.autoconfigure.NotificationPlatformSettings;
|
||||
import dev.caskeleton.application.notification.platform.api.ProviderId;
|
||||
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
|
||||
import dev.caskeleton.application.notification.platform.callback.CallbackLimits;
|
||||
import dev.caskeleton.application.notification.platform.callback.ProviderCallbackAdapter;
|
||||
import dev.caskeleton.application.notification.platform.callback.ProviderCallbackAdapterRegistry;
|
||||
import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector;
|
||||
import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectorRegistry;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Registries assembled from whatever provider beans the deployment actually declared.
|
||||
*
|
||||
* <p>Both registries are built from the bean list rather than a hard-coded switch, so adding a
|
||||
* provider is a matter of contributing a bean — the plan's requirement that a new adapter needs no
|
||||
* change to the core.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(
|
||||
prefix = "ca-skeleton.notification.platform",
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
public class NotificationPlatformRegistriesConfig {
|
||||
|
||||
/** Projector lookup by provider family. */
|
||||
@Bean
|
||||
public ProviderEventProjectorRegistry providerEventProjectorRegistry(
|
||||
List<ProviderEventProjector> projectors) {
|
||||
Map<ProviderId, ProviderEventProjector> byProvider = new HashMap<>();
|
||||
projectors.forEach(projector -> byProvider.put(projector.providerId(), projector));
|
||||
Map<ProviderId, ProviderEventProjector> frozen = Map.copyOf(byProvider);
|
||||
return providerId -> Optional.ofNullable(frozen.get(providerId));
|
||||
}
|
||||
|
||||
/** Callback adapter lookup by configured profile. */
|
||||
@Bean
|
||||
public ProviderCallbackAdapterRegistry providerCallbackAdapterRegistry(
|
||||
List<ProviderCallbackAdapter> adapters, NotificationPlatformSettings settings) {
|
||||
Map<String, ProviderCallbackAdapter> byProvider = new HashMap<>();
|
||||
adapters.forEach(adapter -> byProvider.put(adapter.providerId().value(), adapter));
|
||||
|
||||
Map<ProviderProfileId, ProviderCallbackAdapter> byProfile = new HashMap<>();
|
||||
settings
|
||||
.providers()
|
||||
.forEach(
|
||||
(profileId, provider) -> {
|
||||
ProviderCallbackAdapter adapter =
|
||||
byProvider.get(provider.type().toLowerCase(java.util.Locale.ROOT));
|
||||
if (adapter != null) {
|
||||
byProfile.put(new ProviderProfileId(profileId), adapter);
|
||||
}
|
||||
});
|
||||
|
||||
Map<ProviderProfileId, ProviderCallbackAdapter> frozen = Map.copyOf(byProfile);
|
||||
CallbackLimits limits =
|
||||
new CallbackLimits(
|
||||
settings.callbacks().maxBodyBytes(),
|
||||
Set.of("application/json", "text/plain", "application/x-www-form-urlencoded"));
|
||||
|
||||
return new ProviderCallbackAdapterRegistry() {
|
||||
|
||||
@Override
|
||||
public ProviderCallbackAdapter require(ProviderProfileId profileId) {
|
||||
Objects.requireNonNull(profileId, "profileId");
|
||||
ProviderCallbackAdapter adapter = frozen.get(profileId);
|
||||
if (adapter == null) {
|
||||
// Refusing an unknown profile is a security property: an endpoint that accepted any
|
||||
// profile name would let a caller pick which signature check runs.
|
||||
throw new IllegalStateException("no callback adapter registered for the profile");
|
||||
}
|
||||
return adapter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CallbackLimits limitsFor(ProviderProfileId profileId) {
|
||||
return limits;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+506
@@ -0,0 +1,506 @@
|
||||
package dev.caskeleton.bootstrap.notification;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.autoconfigure.NotificationPlatformSettings;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.CapabilityReconciliationGateway;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ConfiguredRoutePlanner;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.JacksonRoutingPlanCodec;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.LoggingInboxSignalPublisher;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.MapTemplateRendererRegistry;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationDispatchProperties;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationSchedulerWorker;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderRuntimeRegistry;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.RegistryProviderDispatchGateway;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.SingleTenantContext;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.UuidV7Generator;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.observation.LoggingNotificationAudit;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.observation.LoggingNotificationMetrics;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.observation.NotificationHealthReporter;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmCallbackPayloadProtection;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.security.HmacProviderRequestIdHasher;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.template.CanonicalNotificationRenderer;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.template.JacksonInboxContentCodec;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.template.JacksonTemplateContentCodec;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationTemplateEngine;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.template.ThymeleafNotificationRenderer;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.template.ThymeleafStringTemplateEngine;
|
||||
import dev.caskeleton.application.notification.platform.api.NotificationOrchestrator;
|
||||
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
|
||||
import dev.caskeleton.application.notification.platform.api.routing.Channel;
|
||||
import dev.caskeleton.application.notification.platform.callback.CallbackPayloadProtectionPort;
|
||||
import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptResolverPort;
|
||||
import dev.caskeleton.application.notification.platform.callback.DeliveryProjectionStorePort;
|
||||
import dev.caskeleton.application.notification.platform.callback.NotificationSideEffectPort;
|
||||
import dev.caskeleton.application.notification.platform.callback.ProviderCallbackAdapterRegistry;
|
||||
import dev.caskeleton.application.notification.platform.callback.ProviderCallbackIngestionService;
|
||||
import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger;
|
||||
import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService;
|
||||
import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectorRegistry;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.CanonicalNotificationPlanWriter;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFactory;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.DispatchOutcomeRecorder;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.DispatchPipeline;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.NotificationDispatchService;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.NotificationRoutePlannerPort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.NotificationRoutingPlanCodecPort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.NotificationSubmissionService;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.NotificationVariablesCodecPort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.ProviderDispatchGatewayPort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.RequestFingerprint;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.TemplateRendererRegistry;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.TenantContextPort;
|
||||
import dev.caskeleton.application.notification.platform.inbox.InboxContentCodecPort;
|
||||
import dev.caskeleton.application.notification.platform.inbox.NotificationInboxSignalPort;
|
||||
import dev.caskeleton.application.notification.platform.observation.CardinalityGuard;
|
||||
import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort;
|
||||
import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort;
|
||||
import dev.caskeleton.application.notification.platform.observation.NotificationSecurityAuditPort;
|
||||
import dev.caskeleton.application.notification.platform.policy.CompositeNotificationEligibilityPolicy;
|
||||
import dev.caskeleton.application.notification.platform.policy.DefaultNotificationRetryPolicy;
|
||||
import dev.caskeleton.application.notification.platform.policy.JitterSource;
|
||||
import dev.caskeleton.application.notification.platform.policy.NotificationEligibilityPolicy;
|
||||
import dev.caskeleton.application.notification.platform.policy.NotificationRetryPolicy;
|
||||
import dev.caskeleton.application.notification.platform.policy.PreferenceStorePort;
|
||||
import dev.caskeleton.application.notification.platform.policy.RetryBackoff;
|
||||
import dev.caskeleton.application.notification.platform.policy.RoutingDecisionEngine;
|
||||
import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort;
|
||||
import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider;
|
||||
import dev.caskeleton.application.notification.platform.template.NotificationTemplateRenderer;
|
||||
import dev.caskeleton.application.notification.platform.template.TemplateContentCodecPort;
|
||||
import dev.caskeleton.application.notification.platform.template.TemplateRegistry;
|
||||
import dev.caskeleton.application.notification.platform.template.TemplateVariableValidator;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.bootstrap.notification.observation.MicrometerNotificationMetrics;
|
||||
import dev.caskeleton.bootstrap.notification.observation.NotificationHealthEndpoint;
|
||||
import dev.caskeleton.bootstrap.notification.observation.NotificationObservationConvention;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Composition root for the notification platform.
|
||||
*
|
||||
* <p>Only this class sees every leaf at once, which is what lets application-core stay free of
|
||||
* Spring and every adapter stay unaware of the others.
|
||||
*
|
||||
* <p>The provider runtime registry starts empty on purpose. Registering a provider requires
|
||||
* credentials and a profile, so a deployment that has not configured one gets a platform that
|
||||
* accepts and stores notifications and reports no eligible route — a visible, diagnosable state
|
||||
* rather than a startup failure or a silent drop.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(
|
||||
prefix = "ca-skeleton.notification.platform",
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
public class NotificationPlatformRuntimeConfig {
|
||||
|
||||
/** Time-ordered identifiers for every notification row. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public NotificationIdGeneratorPort notificationIdGenerator(Clock clock) {
|
||||
return new UuidV7Generator(clock);
|
||||
}
|
||||
|
||||
/** Single-tenant context; a multi-tenant deployment replaces this bean. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public TenantContextPort notificationTenantContext() {
|
||||
return new SingleTenantContext("default");
|
||||
}
|
||||
|
||||
/** Frozen route plan encoding. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public NotificationRoutingPlanCodecPort notificationRoutingPlanCodec() {
|
||||
return new JacksonRoutingPlanCodec();
|
||||
}
|
||||
|
||||
/** Template content encoding. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public TemplateContentCodecPort notificationTemplateContentCodec() {
|
||||
return new JacksonTemplateContentCodec();
|
||||
}
|
||||
|
||||
/** Inbox content encoding. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public InboxContentCodecPort notificationInboxContentCodec() {
|
||||
return new JacksonInboxContentCodec();
|
||||
}
|
||||
|
||||
/** Keyed hash of provider request identifiers. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public ProviderRequestIdHasherPort providerRequestIdHasher(SecretMaterialProvider secrets) {
|
||||
return new HmacProviderRequestIdHasher(secrets);
|
||||
}
|
||||
|
||||
/** Bounded, encrypted raw callback retention. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public CallbackPayloadProtectionPort callbackPayloadProtection(
|
||||
SecretMaterialProvider secrets, NotificationPlatformSettings settings) {
|
||||
return new AesGcmCallbackPayloadProtection(
|
||||
secrets, (int) Math.min(settings.callbacks().maxBodyBytes(), Integer.MAX_VALUE));
|
||||
}
|
||||
|
||||
/** Metric tag guard. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public CardinalityGuard notificationCardinalityGuard() {
|
||||
return new CardinalityGuard();
|
||||
}
|
||||
|
||||
/**
|
||||
* Metrics sink.
|
||||
*
|
||||
* <p>Chosen here rather than through two competing {@code @ConditionalOnMissingBean} definitions:
|
||||
* which of the two wins would then depend on configuration ordering, and the failure mode is a
|
||||
* deployment that silently logs its metrics instead of exporting them.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public NotificationMetricsPort notificationMetrics(
|
||||
CardinalityGuard guard, ObjectProvider<io.micrometer.core.instrument.MeterRegistry> meters) {
|
||||
io.micrometer.core.instrument.MeterRegistry registry = meters.getIfAvailable();
|
||||
return registry == null
|
||||
? new LoggingNotificationMetrics(guard)
|
||||
: new MicrometerNotificationMetrics(registry, guard);
|
||||
}
|
||||
|
||||
/** Naming and tagging convention shared by dispatch and callback observations. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public NotificationObservationConvention notificationObservationConvention(
|
||||
CardinalityGuard guard) {
|
||||
return new NotificationObservationConvention(guard);
|
||||
}
|
||||
|
||||
/** Operational snapshot source for the actuator endpoint. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public NotificationHealthReporter notificationHealthReporter(
|
||||
ProviderRuntimeRegistry runtimes, NotificationPlatformSettings settings) {
|
||||
return new NotificationHealthReporter(
|
||||
runtimes, settings.providers().keySet().stream().map(ProviderProfileId::new).toList());
|
||||
}
|
||||
|
||||
/** Actuator endpoint and health indicator for the platform. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public NotificationHealthEndpoint notificationHealthEndpoint(
|
||||
NotificationHealthReporter reporter) {
|
||||
return new NotificationHealthEndpoint(reporter);
|
||||
}
|
||||
|
||||
/** Audit sink, which also serves the security audit port. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public LoggingNotificationAudit notificationAudit() {
|
||||
return new LoggingNotificationAudit();
|
||||
}
|
||||
|
||||
/** Audit port. */
|
||||
@Bean
|
||||
public NotificationAuditPort notificationAuditPort(LoggingNotificationAudit audit) {
|
||||
return audit;
|
||||
}
|
||||
|
||||
/** Security audit port. */
|
||||
@Bean
|
||||
public NotificationSecurityAuditPort notificationSecurityAuditPort(
|
||||
LoggingNotificationAudit audit) {
|
||||
return audit;
|
||||
}
|
||||
|
||||
/** Inbox signal sink. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public NotificationInboxSignalPort notificationInboxSignalPort() {
|
||||
return new LoggingInboxSignalPublisher();
|
||||
}
|
||||
|
||||
/**
|
||||
* Channel renderers built on the configured engine and the shared validator.
|
||||
*
|
||||
* <p>Every channel gets the same engine on purpose. Rendering the email body with one engine and
|
||||
* the push body with another would mean two escaping policies for the same variable, and the
|
||||
* content digest — which a retry uses to prove it sent the same thing — would depend on which
|
||||
* channel rendered it.
|
||||
*/
|
||||
@Bean
|
||||
public TemplateRendererRegistry notificationTemplateRendererRegistry(
|
||||
TemplateRegistry templates,
|
||||
TemplateVariableValidator validator,
|
||||
NotificationTemplateEngine engine) {
|
||||
List<NotificationTemplateRenderer> renderers =
|
||||
List.of(Channel.values()).stream()
|
||||
.map(channel -> renderer(channel, templates, validator, engine))
|
||||
.toList();
|
||||
return new MapTemplateRendererRegistry(renderers);
|
||||
}
|
||||
|
||||
private static NotificationTemplateRenderer renderer(
|
||||
Channel channel,
|
||||
TemplateRegistry templates,
|
||||
TemplateVariableValidator validator,
|
||||
NotificationTemplateEngine engine) {
|
||||
// Named types rather than one generic renderer, so a stack trace and a bean name say which
|
||||
// engine actually produced the content.
|
||||
return engine instanceof ThymeleafStringTemplateEngine thymeleaf
|
||||
? new ThymeleafNotificationRenderer(channel, templates, validator, thymeleaf)
|
||||
: new CanonicalNotificationRenderer(channel, templates, validator, engine);
|
||||
}
|
||||
|
||||
/** Empty registry until a provider profile is configured. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public ProviderRuntimeRegistry providerRuntimeRegistry() {
|
||||
return new ProviderRuntimeRegistry();
|
||||
}
|
||||
|
||||
/** Outbound provider call with permit and health handling. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public ProviderDispatchGatewayPort providerDispatchGateway(ProviderRuntimeRegistry runtimes) {
|
||||
return new RegistryProviderDispatchGateway(runtimes);
|
||||
}
|
||||
|
||||
/** Provider status query routing. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public ReconciliationGatewayPort reconciliationGateway(ProviderRuntimeRegistry runtimes) {
|
||||
return new CapabilityReconciliationGateway(Map.of(), runtimes);
|
||||
}
|
||||
|
||||
/** Route planning from the configured channel-to-profile map. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public NotificationRoutePlannerPort notificationRoutePlanner() {
|
||||
return new ConfiguredRoutePlanner(Map.of());
|
||||
}
|
||||
|
||||
/** Eligibility: mandatory suppression first, injected business policy last. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public NotificationEligibilityPolicy notificationEligibilityPolicy(
|
||||
SuppressionStorePort suppressions,
|
||||
PreferenceStorePort preferences,
|
||||
ObjectProvider<NotificationEligibilityPolicy> injected) {
|
||||
return new CompositeNotificationEligibilityPolicy(
|
||||
suppressions,
|
||||
preferences,
|
||||
Optional.ofNullable(injected.getIfUnique())
|
||||
.orElseGet(NotificationEligibilityPolicy::permitAll));
|
||||
}
|
||||
|
||||
/** Evidence-aware retry policy. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public NotificationRetryPolicy notificationRetryPolicy() {
|
||||
SecureRandom random = new SecureRandom();
|
||||
JitterSource jitter = bound -> bound <= 1 ? 0 : Math.floorMod(random.nextLong(), bound);
|
||||
return new DefaultNotificationRetryPolicy(RetryBackoff.DEFAULT, jitter, Duration.ofMinutes(1));
|
||||
}
|
||||
|
||||
/** Stable routing engine. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public RoutingDecisionEngine routingDecisionEngine() {
|
||||
return new RoutingDecisionEngine();
|
||||
}
|
||||
|
||||
/** Canonical request fingerprint. */
|
||||
@Bean
|
||||
public RequestFingerprint requestFingerprint(MessageDigestPort digest) {
|
||||
return new RequestFingerprint(digest);
|
||||
}
|
||||
|
||||
/** Durable row factory for a submission. */
|
||||
@Bean
|
||||
public CanonicalNotificationPlanWriter canonicalNotificationPlanWriter(
|
||||
NotificationIdGeneratorPort ids,
|
||||
NotificationRoutePlannerPort routePlanner,
|
||||
NotificationVariablesCodecPort variables) {
|
||||
return new CanonicalNotificationPlanWriter(ids, routePlanner, variables);
|
||||
}
|
||||
|
||||
/** N2 orchestration. */
|
||||
@Bean
|
||||
public NotificationOrchestrator notificationOrchestrator(
|
||||
NotificationRequestStorePort requests,
|
||||
RecipientDeliveryStorePort recipients,
|
||||
DeliveryAttemptStorePort attempts,
|
||||
TemplateRegistry templates,
|
||||
RequestFingerprint fingerprints,
|
||||
CanonicalNotificationPlanWriter writer,
|
||||
TransactionPort transactions,
|
||||
TenantContextPort tenants,
|
||||
NotificationMetricsPort metrics,
|
||||
Clock clock) {
|
||||
return new NotificationSubmissionService(
|
||||
requests,
|
||||
recipients,
|
||||
attempts,
|
||||
templates,
|
||||
fingerprints,
|
||||
writer,
|
||||
transactions,
|
||||
tenants,
|
||||
metrics,
|
||||
clock);
|
||||
}
|
||||
|
||||
/** Pre-provider guard chain. */
|
||||
@Bean
|
||||
public DispatchPipeline dispatchPipeline(
|
||||
ContactPointStorePort contactPoints,
|
||||
NotificationEligibilityPolicy eligibility,
|
||||
NotificationMetricsPort metrics) {
|
||||
return new DispatchPipeline(contactPoints, eligibility, metrics);
|
||||
}
|
||||
|
||||
/** Attempt row factory. */
|
||||
@Bean
|
||||
public DeliveryAttemptFactory deliveryAttemptFactory(NotificationIdGeneratorPort ids) {
|
||||
return new DeliveryAttemptFactory(ids);
|
||||
}
|
||||
|
||||
/** Outcome recorder. */
|
||||
@Bean
|
||||
public DispatchOutcomeRecorder dispatchOutcomeRecorder(
|
||||
DeliveryAttemptStorePort attempts,
|
||||
RecipientDeliveryStorePort recipients,
|
||||
NotificationMetricsPort metrics) {
|
||||
return new DispatchOutcomeRecorder(attempts, recipients, metrics);
|
||||
}
|
||||
|
||||
/** Dispatch runtime bounds. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public NotificationDispatchProperties notificationDispatchProperties(
|
||||
NotificationPlatformSettings settings) {
|
||||
return new NotificationDispatchProperties(
|
||||
settings.dispatch().claimBatchSize(),
|
||||
settings.dispatch().leaseDuration(),
|
||||
settings.dispatch().pollInterval(),
|
||||
settings.dispatch().maxGlobalConcurrency(),
|
||||
settings.dispatch().maxAdditionalAttempts(),
|
||||
Duration.ofSeconds(2),
|
||||
settings.dispatch().maxQueueAge(),
|
||||
Duration.ofSeconds(20));
|
||||
}
|
||||
|
||||
/** Dispatch orchestration. */
|
||||
@Bean
|
||||
public NotificationDispatchService notificationDispatchService(
|
||||
NotificationRequestStorePort requests,
|
||||
RecipientDeliveryStorePort recipients,
|
||||
DeliveryAttemptStorePort attempts,
|
||||
DispatchPipeline pipeline,
|
||||
RoutingDecisionEngine routing,
|
||||
NotificationRetryPolicy retryPolicy,
|
||||
DeliveryAttemptFactory attemptFactory,
|
||||
DispatchOutcomeRecorder recorder,
|
||||
ProviderDispatchGatewayPort gateway,
|
||||
TemplateRendererRegistry renderers,
|
||||
NotificationVariablesCodecPort variables,
|
||||
RecipientLeaseStorePort leases,
|
||||
TransactionPort transactions,
|
||||
Clock clock,
|
||||
NotificationDispatchProperties properties) {
|
||||
return new NotificationDispatchService(
|
||||
requests,
|
||||
recipients,
|
||||
attempts,
|
||||
pipeline,
|
||||
routing,
|
||||
retryPolicy,
|
||||
attemptFactory,
|
||||
recorder,
|
||||
gateway,
|
||||
renderers,
|
||||
variables,
|
||||
leases,
|
||||
transactions,
|
||||
clock,
|
||||
properties.maxAdditionalAttempts(),
|
||||
properties.estimatedDispatchDuration());
|
||||
}
|
||||
|
||||
/** Ledger projection. */
|
||||
@Bean
|
||||
public ProviderEventProjectionService providerEventProjectionService(
|
||||
ProviderEventLedger ledger,
|
||||
ProviderEventProjectorRegistry projectors,
|
||||
DeliveryAttemptResolverPort resolver,
|
||||
DeliveryProjectionStorePort projections,
|
||||
NotificationSideEffectPort sideEffects,
|
||||
TransactionPort transactions,
|
||||
NotificationMetricsPort metrics) {
|
||||
return new ProviderEventProjectionService(
|
||||
ledger, projectors, resolver, projections, sideEffects, transactions, metrics);
|
||||
}
|
||||
|
||||
/** Callback ingestion. */
|
||||
@Bean
|
||||
public ProviderCallbackIngestionService providerCallbackIngestionService(
|
||||
ProviderCallbackAdapterRegistry adapters,
|
||||
ProviderEventLedger ledger,
|
||||
ProviderEventProjectionService projection,
|
||||
CallbackPayloadProtectionPort payloadProtection,
|
||||
NotificationSecurityAuditPort securityAudit,
|
||||
NotificationMetricsPort metrics,
|
||||
Clock clock) {
|
||||
return new ProviderCallbackIngestionService(
|
||||
adapters, ledger, projection, payloadProtection, securityAudit, metrics, clock);
|
||||
}
|
||||
|
||||
/** Provider status correction. */
|
||||
@Bean
|
||||
public ReconciliationService reconciliationService(
|
||||
DeliveryAttemptStorePort attempts,
|
||||
RecipientDeliveryStorePort recipients,
|
||||
ReconciliationGatewayPort gateway,
|
||||
ProviderEventLedger ledger,
|
||||
ProviderEventProjectionService projection,
|
||||
NotificationAuditPort audit,
|
||||
NotificationMetricsPort metrics,
|
||||
Clock clock) {
|
||||
return new ReconciliationService(
|
||||
attempts, recipients, gateway, ledger, projection, audit, metrics, clock);
|
||||
}
|
||||
|
||||
/** Queue worker. Started by the application lifecycle, stopped on shutdown. */
|
||||
@Bean(destroyMethod = "close")
|
||||
public NotificationSchedulerWorker notificationSchedulerWorker(
|
||||
RecipientLeaseStorePort leases,
|
||||
NotificationDispatchService dispatcher,
|
||||
NotificationMetricsPort metrics,
|
||||
NotificationDispatchProperties properties) {
|
||||
NotificationSchedulerWorker worker =
|
||||
new NotificationSchedulerWorker(
|
||||
leases, dispatcher, metrics, properties, "notification-worker-1");
|
||||
worker.start();
|
||||
return worker;
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package dev.caskeleton.bootstrap.notification;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.security.SettingsSecretMaterialProvider;
|
||||
import dev.caskeleton.application.notification.platform.security.SecretKeyMaterial;
|
||||
import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider;
|
||||
import dev.caskeleton.application.notification.platform.security.SecretPurpose;
|
||||
import java.util.Base64;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Key material for the notification platform.
|
||||
*
|
||||
* <p>Values arrive base64-encoded from the environment. The startup check is deliberately strict:
|
||||
* two distinct keys, and the contact encryption key exactly 256 bits. A platform that boots with a
|
||||
* weak or shared key would encrypt every contact point wrongly and only reveal it under audit.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(
|
||||
prefix = "ca-skeleton.notification.platform",
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
public class NotificationPlatformSecretsConfig {
|
||||
|
||||
/** Base64 key material bound from the environment. */
|
||||
@ConfigurationProperties("ca-skeleton.notification.platform.secrets")
|
||||
public record NotificationSecretsSettings(
|
||||
String contactEncryptionKey,
|
||||
String contactLookupHmacKey,
|
||||
String callbackSigningKey,
|
||||
String providerCredentialKey,
|
||||
String payloadEncryptionKey,
|
||||
String vapidSigningKey) {}
|
||||
|
||||
/** Secret provider assembled from the bound settings. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public SecretMaterialProvider notificationSecretMaterialProvider(
|
||||
NotificationSecretsSettings settings) {
|
||||
Objects.requireNonNull(settings, "settings");
|
||||
Map<SecretPurpose, SecretKeyMaterial> active = new EnumMap<>(SecretPurpose.class);
|
||||
put(active, SecretPurpose.CONTACT_ENCRYPTION, "contact-enc", settings.contactEncryptionKey());
|
||||
put(active, SecretPurpose.CONTACT_LOOKUP_HMAC, "contact-mac", settings.contactLookupHmacKey());
|
||||
put(active, SecretPurpose.CALLBACK_SIGNING, "callback-sign", settings.callbackSigningKey());
|
||||
put(
|
||||
active,
|
||||
SecretPurpose.PROVIDER_CREDENTIAL,
|
||||
"provider-cred",
|
||||
settings.providerCredentialKey());
|
||||
put(active, SecretPurpose.PAYLOAD_ENCRYPTION, "payload-enc", settings.payloadEncryptionKey());
|
||||
put(active, SecretPurpose.VAPID_SIGNING, "vapid-sign", settings.vapidSigningKey());
|
||||
return new SettingsSecretMaterialProvider(active, Map.of());
|
||||
}
|
||||
|
||||
private static void put(
|
||||
Map<SecretPurpose, SecretKeyMaterial> target,
|
||||
SecretPurpose purpose,
|
||||
String keyId,
|
||||
String base64) {
|
||||
if (base64 == null || base64.isBlank()) {
|
||||
return;
|
||||
}
|
||||
target.put(purpose, new SecretKeyMaterial(keyId, purpose, Base64.getDecoder().decode(base64)));
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package dev.caskeleton.bootstrap.notification.observation;
|
||||
|
||||
import dev.caskeleton.application.notification.platform.observation.CardinalityGuard;
|
||||
import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
/**
|
||||
* Micrometer-backed metric sink, living in the composition root because the registry does.
|
||||
*
|
||||
* <p>Every tag map is validated before a meter is created. Validating after registration would be
|
||||
* too late: Micrometer creates the time series on first use, so a rejected tag would already have
|
||||
* cost the series it was supposed to prevent.
|
||||
*
|
||||
* <p>Gauges are held through a strong reference deliberately. Micrometer's gauge holds its source
|
||||
* weakly, so a locally-created holder is collected and the gauge silently reports NaN forever after
|
||||
* — a failure mode that looks like a broken exporter rather than a bug here.
|
||||
*/
|
||||
public final class MicrometerNotificationMetrics implements NotificationMetricsPort {
|
||||
|
||||
private final MeterRegistry registry;
|
||||
private final CardinalityGuard guard;
|
||||
private final Map<String, AtomicReference<Double>> gauges = new ConcurrentHashMap<>();
|
||||
|
||||
public MicrometerNotificationMetrics(MeterRegistry registry, CardinalityGuard guard) {
|
||||
this.registry = Objects.requireNonNull(registry, "registry");
|
||||
this.guard = Objects.requireNonNull(guard, "guard");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void increment(String metricName, Map<String, String> tags) {
|
||||
guard.validate(tags);
|
||||
registry.counter(metricName, tags(tags)).increment();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void record(String metricName, Map<String, String> tags, Duration value) {
|
||||
guard.validate(tags);
|
||||
registry.timer(metricName, tags(tags)).record(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void gauge(String metricName, Map<String, String> tags, double value) {
|
||||
guard.validate(tags);
|
||||
Tags meterTags = tags(tags);
|
||||
gauges
|
||||
.computeIfAbsent(
|
||||
metricName + meterTags,
|
||||
key -> {
|
||||
AtomicReference<Double> holder = new AtomicReference<>(value);
|
||||
registry.gauge(metricName, meterTags, holder, AtomicReference::get);
|
||||
return holder;
|
||||
})
|
||||
.set(value);
|
||||
}
|
||||
|
||||
private static Tags tags(Map<String, String> tags) {
|
||||
return Tags.of(tags.entrySet().stream().map(e -> Tag.of(e.getKey(), e.getValue())).toList());
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package dev.caskeleton.bootstrap.notification.observation;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.observation.NotificationHealthReporter;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.observation.NotificationHealthSnapshot;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
|
||||
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
|
||||
import org.springframework.boot.health.contributor.Health;
|
||||
import org.springframework.boot.health.contributor.HealthIndicator;
|
||||
|
||||
/**
|
||||
* Actuator surface for the delivery platform.
|
||||
*
|
||||
* <p>Two things an operator needs are genuinely invisible from process-level health: a provider
|
||||
* whose credentials were rejected, and a queue whose oldest entry is aging. Both leave the JVM
|
||||
* perfectly healthy while nothing is being delivered, which is why they get their own indicator
|
||||
* rather than being inferred from liveness.
|
||||
*
|
||||
* <p>What is exposed is provider state, credential generation, in-flight attempt count and queue
|
||||
* age. What is not: sender addresses, endpoints, key ids, credential references, template content.
|
||||
* A health endpoint is one of the least protected surfaces an application has — often reachable by
|
||||
* anything that can route to the management port — so the safe assumption is that everything here
|
||||
* is public.
|
||||
*/
|
||||
@Endpoint(id = "notifications")
|
||||
public class NotificationHealthEndpoint implements HealthIndicator {
|
||||
|
||||
private final NotificationHealthReporter reporter;
|
||||
|
||||
public NotificationHealthEndpoint(NotificationHealthReporter reporter) {
|
||||
this.reporter = Objects.requireNonNull(reporter, "reporter");
|
||||
}
|
||||
|
||||
/** Full operational snapshot, non-sensitive by construction. */
|
||||
@ReadOperation
|
||||
public Map<String, Object> notifications() {
|
||||
NotificationHealthSnapshot snapshot = reporter.snapshot();
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("healthy", snapshot.healthy());
|
||||
body.put("providers", providers(snapshot));
|
||||
body.put("queue", new java.util.TreeMap<>(snapshot.queue()));
|
||||
return body;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Health health() {
|
||||
NotificationHealthSnapshot snapshot = reporter.snapshot();
|
||||
Health.Builder builder = snapshot.healthy() ? Health.up() : Health.down();
|
||||
// Detail on the indicator too: an operator paged at 03:00 should see which profile is down
|
||||
// without needing a second, differently-authorized endpoint.
|
||||
return builder.withDetail("providers", providers(snapshot)).build();
|
||||
}
|
||||
|
||||
private static List<Map<String, Object>> providers(NotificationHealthSnapshot snapshot) {
|
||||
return snapshot.providers().stream()
|
||||
.map(
|
||||
provider -> {
|
||||
Map<String, Object> entry = new LinkedHashMap<>();
|
||||
entry.put("profileId", provider.profileId());
|
||||
entry.put("state", provider.state());
|
||||
entry.put("credentialGeneration", provider.credentialGeneration());
|
||||
entry.put("activeAttempts", provider.activeAttempts());
|
||||
return Map.copyOf(entry);
|
||||
})
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package dev.caskeleton.bootstrap.notification.observation;
|
||||
|
||||
import io.micrometer.observation.Observation;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* What one notification observation is allowed to know about itself.
|
||||
*
|
||||
* <p>The identifiers an operator actually needs during an incident — notification id, recipient id,
|
||||
* attempt id, provider request id — are deliberately absent from this type rather than merely
|
||||
* excluded from the tag list. A field that exists is a field somebody eventually tags with, and one
|
||||
* high-cardinality tag is enough to make a metric backend unusable and to put a recipient address
|
||||
* into a metrics store that was never designed to hold one. Those identifiers belong in structured
|
||||
* logs, which are queryable and have a retention policy.
|
||||
*
|
||||
* <p>{@code templateId} is optional because it is only bounded when it came from the registry. A
|
||||
* caller-supplied template name is unbounded by construction, so an unregistered one is dropped
|
||||
* rather than tagged.
|
||||
*/
|
||||
public final class NotificationObservationContext extends Observation.Context {
|
||||
|
||||
private final String channel;
|
||||
private final String provider;
|
||||
private final Optional<String> registeredTemplateId;
|
||||
private final String status;
|
||||
private final Optional<String> failureCategory;
|
||||
private final String attemptBucket;
|
||||
private final String sizeBucket;
|
||||
|
||||
private NotificationObservationContext(Builder builder) {
|
||||
this.channel = builder.channel;
|
||||
this.provider = builder.provider;
|
||||
this.registeredTemplateId = Optional.ofNullable(builder.registeredTemplateId);
|
||||
this.status = builder.status;
|
||||
this.failureCategory = Optional.ofNullable(builder.failureCategory);
|
||||
this.attemptBucket = builder.attemptBucket;
|
||||
this.sizeBucket = builder.sizeBucket;
|
||||
}
|
||||
|
||||
/** Start describing an observation. */
|
||||
public static Builder builder(String channel, String provider, String status) {
|
||||
return new Builder(channel, provider, status);
|
||||
}
|
||||
|
||||
/** Bounded tag map, in a stable order. */
|
||||
public Map<String, String> boundedTags() {
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
tags.put("channel", channel);
|
||||
tags.put("provider", provider);
|
||||
tags.put("status", status);
|
||||
tags.put("attemptBucket", attemptBucket);
|
||||
tags.put("sizeBucket", sizeBucket);
|
||||
registeredTemplateId.ifPresent(value -> tags.put("templateId", value));
|
||||
failureCategory.ifPresent(value -> tags.put("failureCategory", value));
|
||||
return Map.copyOf(tags);
|
||||
}
|
||||
|
||||
/** Builder that refuses blank bounded values rather than emitting an empty tag. */
|
||||
public static final class Builder {
|
||||
|
||||
private final String channel;
|
||||
private final String provider;
|
||||
private final String status;
|
||||
private String registeredTemplateId;
|
||||
private String failureCategory;
|
||||
private String attemptBucket = "1";
|
||||
private String sizeBucket = "small";
|
||||
|
||||
private Builder(String channel, String provider, String status) {
|
||||
this.channel = require(channel, "channel");
|
||||
this.provider = require(provider, "provider");
|
||||
this.status = require(status, "status");
|
||||
}
|
||||
|
||||
/** Template id, only when the registry recognised it. */
|
||||
public Builder registeredTemplateId(String value) {
|
||||
this.registeredTemplateId = require(value, "templateId");
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Normalized failure category. */
|
||||
public Builder failureCategory(String value) {
|
||||
this.failureCategory = require(value, "failureCategory");
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Bucketed attempt number — never the raw count, which is unbounded. */
|
||||
public Builder attemptBucket(int attemptNumber) {
|
||||
this.attemptBucket =
|
||||
switch (Math.max(attemptNumber, 1)) {
|
||||
case 1 -> "1";
|
||||
case 2 -> "2";
|
||||
case 3, 4 -> "3-4";
|
||||
default -> "5+";
|
||||
};
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Bucketed payload size. */
|
||||
public Builder sizeBucket(long bytes) {
|
||||
this.sizeBucket =
|
||||
bytes <= 1024L
|
||||
? "small"
|
||||
: bytes <= 65_536L ? "medium" : bytes <= 1_048_576L ? "large" : "xlarge";
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Build the context. */
|
||||
public NotificationObservationContext build() {
|
||||
return new NotificationObservationContext(this);
|
||||
}
|
||||
|
||||
private static String require(String value, String name) {
|
||||
Objects.requireNonNull(value, name);
|
||||
if (value.isBlank()) {
|
||||
throw new IllegalArgumentException(name);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package dev.caskeleton.bootstrap.notification.observation;
|
||||
|
||||
import dev.caskeleton.application.notification.platform.observation.CardinalityGuard;
|
||||
import io.micrometer.common.KeyValue;
|
||||
import io.micrometer.common.KeyValues;
|
||||
import io.micrometer.observation.Observation;
|
||||
import io.micrometer.observation.ObservationConvention;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* How a notification observation is named and tagged.
|
||||
*
|
||||
* <p>Two decisions are worth stating, because both look like omissions:
|
||||
*
|
||||
* <p><b>High-cardinality key values are empty.</b> Micrometer routes them to the tracing backend
|
||||
* rather than the metric backend, which makes them look safe for a notification id or a recipient
|
||||
* address. They are not: spans are exported to a third-party collector and are exactly the place a
|
||||
* contact point must never appear. Correlation belongs in structured logs, which stay inside the
|
||||
* retention and access controls the platform already applies to them.
|
||||
*
|
||||
* <p><b>A callback is a linked observation, not a child span.</b> A provider callback can arrive
|
||||
* seconds or days after the dispatch that caused it. Modelling it as a child would keep the
|
||||
* dispatch span open across that gap — an unbounded in-flight span per notification, which no
|
||||
* tracing backend handles gracefully and which reports a p99 latency measuring the provider's
|
||||
* callback schedule rather than anything the platform did. {@link #callbackObservation} therefore
|
||||
* starts a root observation and records the originating trace as a link.
|
||||
*/
|
||||
public final class NotificationObservationConvention
|
||||
implements ObservationConvention<NotificationObservationContext> {
|
||||
|
||||
/** Observation name for a dispatch attempt. */
|
||||
public static final String DISPATCH_NAME = "notification.dispatch";
|
||||
|
||||
/** Observation name for an inbound provider callback. */
|
||||
public static final String CALLBACK_NAME = "notification.callback";
|
||||
|
||||
/** Key carrying the originating dispatch trace on a callback observation. */
|
||||
public static final String LINK_KEY = "link.notification.dispatch";
|
||||
|
||||
private final CardinalityGuard guard;
|
||||
|
||||
public NotificationObservationConvention(CardinalityGuard guard) {
|
||||
this.guard = Objects.requireNonNull(guard, "guard");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsContext(Observation.Context context) {
|
||||
return context instanceof NotificationObservationContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return DISPATCH_NAME;
|
||||
}
|
||||
|
||||
@Override
|
||||
public KeyValues getLowCardinalityKeyValues(NotificationObservationContext context) {
|
||||
var tags = Objects.requireNonNull(context, "context").boundedTags();
|
||||
// The guard is the same one the metric port uses, so a tag added here and forgotten there
|
||||
// cannot diverge into a shape only one of the two backends rejects.
|
||||
guard.validate(tags);
|
||||
return KeyValues.of(
|
||||
tags.entrySet().stream()
|
||||
.map(entry -> KeyValue.of(entry.getKey(), entry.getValue()))
|
||||
.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public KeyValues getHighCardinalityKeyValues(NotificationObservationContext context) {
|
||||
return KeyValues.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a root observation for a callback, linked to the dispatch that caused it.
|
||||
*
|
||||
* @param registry observation registry
|
||||
* @param context bounded callback context
|
||||
* @param originatingTraceId trace id of the dispatch, as a link rather than a parent
|
||||
*/
|
||||
public Observation callbackObservation(
|
||||
io.micrometer.observation.ObservationRegistry registry,
|
||||
NotificationObservationContext context,
|
||||
String originatingTraceId) {
|
||||
Objects.requireNonNull(registry, "registry");
|
||||
Objects.requireNonNull(context, "context");
|
||||
Objects.requireNonNull(originatingTraceId, "originatingTraceId");
|
||||
return Observation.createNotStarted(CALLBACK_NAME, () -> context, registry)
|
||||
// Explicitly detached: inheriting whatever is on the callback thread would silently
|
||||
// reparent the callback under the HTTP request that delivered it.
|
||||
.parentObservation(null)
|
||||
.highCardinalityKeyValue(LINK_KEY, originatingTraceId);
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
package dev.caskeleton.bootstrap.architecture;
|
||||
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
|
||||
|
||||
import com.tngtech.archunit.junit.AnalyzeClasses;
|
||||
import com.tngtech.archunit.junit.ArchTest;
|
||||
import com.tngtech.archunit.lang.ArchRule;
|
||||
|
||||
/**
|
||||
* Structural boundaries of the notification delivery platform.
|
||||
*
|
||||
* <p>These rules exist because the failure they prevent is invisible in review. A provider SDK type
|
||||
* that reaches the application contract does not break anything on the day it is added — it breaks
|
||||
* the day a second provider has to satisfy the same interface, by which point the shape is load
|
||||
* bearing and the migration is a rewrite. The same is true of a transport type in a policy class
|
||||
* and of a persistence entity in a contract: each is cheap to add and expensive to remove.
|
||||
*/
|
||||
// Scoped to the notification packages rather than all of dev.caskeleton. Every rule here is about
|
||||
// what notification code may depend on, and the forbidden targets are matched by package name
|
||||
// whether or not those classes were imported — so a whole-repository import would buy nothing and
|
||||
// cost another full class graph in a JVM that already holds two.
|
||||
@AnalyzeClasses(
|
||||
packages = {
|
||||
"dev.caskeleton.application.notification",
|
||||
"dev.caskeleton.adapter.outbound.notification"
|
||||
},
|
||||
importOptions = ProductionClassImportOption.class)
|
||||
class NotificationArchitectureTest {
|
||||
|
||||
private static final String[] PROVIDER_SDK_PACKAGES = {
|
||||
"com.google.firebase..",
|
||||
"com.google.auth..",
|
||||
"com.twilio..",
|
||||
"software.amazon.awssdk..",
|
||||
"com.amazonaws..",
|
||||
"jakarta.mail..",
|
||||
"org.apache.hc..",
|
||||
"com.eatthepath.pushy.."
|
||||
};
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule NOTIFICATION_APPLICATION_CONTRACT_HAS_NO_PROVIDER_SDK =
|
||||
noClasses()
|
||||
.that()
|
||||
.resideInAPackage("dev.caskeleton.application.notification..")
|
||||
.should()
|
||||
.dependOnClassesThat()
|
||||
.resideInAnyPackage(PROVIDER_SDK_PACKAGES)
|
||||
.because(
|
||||
"a provider SDK type in the application contract makes every other provider adapt to"
|
||||
+ " that one vendor's shape; the platform would have an FCM interface with an"
|
||||
+ " APNs implementation bolted on");
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule NOTIFICATION_APPLICATION_CONTRACT_HAS_NO_TRANSPORT_OR_PERSISTENCE =
|
||||
noClasses()
|
||||
.that()
|
||||
.resideInAPackage("dev.caskeleton.application.notification..")
|
||||
.should()
|
||||
.dependOnClassesThat()
|
||||
.resideInAnyPackage(
|
||||
"jakarta.persistence..",
|
||||
"org.hibernate..",
|
||||
"org.springframework.data..",
|
||||
"org.springframework.web..",
|
||||
"org.springframework.http..",
|
||||
"jakarta.servlet..",
|
||||
"tools.jackson..",
|
||||
"com.fasterxml.jackson..")
|
||||
.because(
|
||||
"the notification contract is the one type set every adapter shares; a JPA entity or"
|
||||
+ " an HTTP status in it makes the contract untestable without a container and"
|
||||
+ " ties the platform's vocabulary to whichever adapter was written first");
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule NOTIFICATION_CONTRACT_HAS_NO_DIAGNOSTIC_FRAMEWORK =
|
||||
noClasses()
|
||||
.that()
|
||||
.resideInAPackage("dev.caskeleton.application.notification..")
|
||||
.should()
|
||||
.dependOnClassesThat()
|
||||
.resideInAnyPackage(
|
||||
"org.slf4j..", "io.micrometer..", "ch.qos.logback..", "org.apache.logging..")
|
||||
.because(
|
||||
"diagnostic intent is expressed through the audit and metric ports, so the same"
|
||||
+ " redaction and cardinality rules apply to every emission instead of depending"
|
||||
+ " on which class happened to hold a logger");
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule NOTIFICATION_ADAPTER_DOES_NOT_REACH_INTO_PERSISTENCE_OR_TRANSPORT =
|
||||
noClasses()
|
||||
.that()
|
||||
.resideInAPackage("dev.caskeleton.adapter.outbound.notification..")
|
||||
.should()
|
||||
.dependOnClassesThat()
|
||||
.resideInAnyPackage(
|
||||
"dev.caskeleton.adapter.outbound.persistence..",
|
||||
"dev.caskeleton.adapter.inbound..",
|
||||
"dev.caskeleton.bootstrap..")
|
||||
.because(
|
||||
"the outbound notification adapter is reachable from the composition root only; a"
|
||||
+ " dependency on persistence or on a controller inverts that and makes the"
|
||||
+ " provider layer unusable in a deployment that wires storage differently");
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule CONTACT_POINT_VALUES_ARE_IMMUTABLE_RECORDS =
|
||||
classes()
|
||||
.that()
|
||||
.implement("dev.caskeleton.application.notification.platform.contact.ContactPointValue")
|
||||
.should()
|
||||
.beRecords()
|
||||
.because(
|
||||
"a contact point that can be mutated after construction defeats its own validation:"
|
||||
+ " the address checked at admission is not necessarily the address dispatched to");
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule ONLY_THE_SECURITY_PACKAGE_HANDLES_KEY_MATERIAL =
|
||||
noClasses()
|
||||
.that()
|
||||
.resideInAPackage("dev.caskeleton.adapter.outbound.notification.platform.provider..")
|
||||
.and()
|
||||
.haveSimpleNameNotEndingWith("Signer")
|
||||
.and()
|
||||
.haveSimpleNameNotEndingWith("Encryptor")
|
||||
.and()
|
||||
.haveSimpleNameNotEndingWith("Validator")
|
||||
.and()
|
||||
.haveSimpleNameNotEndingWith("Verifier")
|
||||
.and()
|
||||
.haveSimpleNameNotEndingWith("Registry")
|
||||
.and()
|
||||
// WebhookSignatureStrategy is the webhook channel's signing primitive; the suffix names
|
||||
// its role because a webhook's scheme is per-subscription, not per-provider.
|
||||
.haveSimpleNameNotEndingWith("SignatureStrategy")
|
||||
.should()
|
||||
.dependOnClassesThat()
|
||||
.haveFullyQualifiedName("javax.crypto.spec.SecretKeySpec")
|
||||
.because(
|
||||
"raw key material belongs in the small set of classes that were reviewed for it;"
|
||||
+ " a request mapper holding a SecretKeySpec is how a key ends up in a log line");
|
||||
}
|
||||
+18
@@ -12,4 +12,22 @@ public final class ProductionClassImportOption implements ImportOption {
|
||||
public boolean includes(Location location) {
|
||||
return defaultTestExclusion.includes(location) && !location.contains("/sampleOffTest/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Value equality so ArchUnit's class cache is shared across the suites that use this option.
|
||||
*
|
||||
* <p>The cache is keyed on (locations, import options). Without equality, each
|
||||
* {@code @AnalyzeClasses} suite gets its own instance, its own cache entry, and its own full copy
|
||||
* of the class graph in the same JVM — which is how a third suite turns this task into an
|
||||
* OutOfMemoryError rather than a slower run.
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
return other instanceof ProductionClassImportOption;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return ProductionClassImportOption.class.hashCode();
|
||||
}
|
||||
}
|
||||
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
package dev.caskeleton.bootstrap.notification;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.notification.platform.callback.NotificationCallbackMvcController;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.autoconfigure.NotificationPlatformAutoConfiguration;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.autoconfigure.NotificationPlatformSettings;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpGateway;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmContactPointProtector;
|
||||
import dev.caskeleton.application.notification.platform.admin.NotificationAdminService;
|
||||
import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort;
|
||||
import dev.caskeleton.application.notification.platform.security.ContactPointProtector;
|
||||
import dev.caskeleton.application.notification.platform.security.SecretKeyMaterial;
|
||||
import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider;
|
||||
import dev.caskeleton.application.notification.platform.security.SecretPurpose;
|
||||
import dev.caskeleton.application.notification.platform.template.TemplateVariableValidator;
|
||||
import java.util.Arrays;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner;
|
||||
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Startup guardrails of the platform's conditional wiring.
|
||||
*
|
||||
* <p>The theme is that a misconfiguration must fail the boot, not the first delivery. A platform
|
||||
* that starts happily and then refuses every notification at 02:00 is strictly worse than one that
|
||||
* refuses to start at deploy time, when someone is watching.
|
||||
*/
|
||||
class NotificationAutoConfigurationTest {
|
||||
|
||||
private final ApplicationContextRunner runner =
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(NotificationPlatformAutoConfiguration.class));
|
||||
|
||||
@Test
|
||||
void thePlatformContributesNothingUntilItIsExplicitlyEnabled() {
|
||||
runner.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
assertThat(context).doesNotHaveBean(MessageDigestPort.class);
|
||||
assertThat(context).doesNotHaveBean(TemplateVariableValidator.class);
|
||||
assertThat(context).doesNotHaveBean(NotificationHttpGateway.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void enablingThePlatformContributesItsDefaultRuntimeBeans() {
|
||||
enabled()
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasSingleBean(MessageDigestPort.class);
|
||||
assertThat(context).hasSingleBean(TemplateVariableValidator.class);
|
||||
assertThat(context).hasSingleBean(NotificationHttpGateway.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void contactPointProtectionAppearsOnlyOnceKeyMaterialExists() {
|
||||
enabled().run(context -> assertThat(context).doesNotHaveBean(ContactPointProtector.class));
|
||||
|
||||
enabled()
|
||||
.withUserConfiguration(SecretsConfiguration.class)
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasSingleBean(ContactPointProtector.class);
|
||||
assertThat(context.getBean(ContactPointProtector.class))
|
||||
.isInstanceOf(AesGcmContactPointProtector.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminOperationsAreAbsentByDefaultRatherThanPresentAndUnguarded() {
|
||||
enabled().run(context -> assertThat(context).doesNotHaveBean(NotificationAdminService.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWebPushProfileWithoutAVapidKeyFailsStartup() {
|
||||
enabled()
|
||||
.withPropertyValues(
|
||||
"ca-skeleton.notification.platform.providers.webpush.type=WEB_PUSH",
|
||||
"ca-skeleton.notification.platform.providers.webpush.enabled=true",
|
||||
"ca-skeleton.notification.platform.providers.webpush.environment=PRODUCTION",
|
||||
"ca-skeleton.notification.platform.providers.webpush.credential-profile=default",
|
||||
"ca-skeleton.notification.platform.providers.webpush.timeout=5s",
|
||||
"ca-skeleton.notification.platform.providers.webpush.max-concurrency=4",
|
||||
"ca-skeleton.notification.platform.providers.webpush.rate-per-second=10")
|
||||
.run(
|
||||
context ->
|
||||
// The validation failure is wrapped by the binder, so assert on the whole chain.
|
||||
assertThat(context).getFailure().hasStackTraceContaining("VAPID"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ambiguousFallbackCannotBeTurnedOnByConfiguration() {
|
||||
enabled()
|
||||
.withPropertyValues(
|
||||
"ca-skeleton.notification.platform.dispatch.allow-ambiguous-fallback=true",
|
||||
"ca-skeleton.notification.platform.dispatch.claim-batch-size=100",
|
||||
"ca-skeleton.notification.platform.dispatch.lease-duration=30s",
|
||||
"ca-skeleton.notification.platform.dispatch.poll-interval=250ms",
|
||||
"ca-skeleton.notification.platform.dispatch.max-global-concurrency=8",
|
||||
"ca-skeleton.notification.platform.dispatch.max-additional-attempts=3",
|
||||
"ca-skeleton.notification.platform.dispatch.max-queue-age=1h")
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context)
|
||||
.getFailure()
|
||||
.hasStackTraceContaining("allow-ambiguous-fallback"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnboundedClaimBatchIsRefusedAtStartup() {
|
||||
enabled()
|
||||
.withPropertyValues(
|
||||
"ca-skeleton.notification.platform.dispatch.claim-batch-size=100000",
|
||||
"ca-skeleton.notification.platform.dispatch.lease-duration=30s",
|
||||
"ca-skeleton.notification.platform.dispatch.poll-interval=250ms",
|
||||
"ca-skeleton.notification.platform.dispatch.max-global-concurrency=8",
|
||||
"ca-skeleton.notification.platform.dispatch.max-additional-attempts=3",
|
||||
"ca-skeleton.notification.platform.dispatch.max-queue-age=1h")
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context).getFailure().hasStackTraceContaining("claim-batch-size"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theServletCallbackControllerIsAbsentWhileCallbacksAreDisabled() {
|
||||
new WebApplicationContextRunner()
|
||||
.withUserConfiguration(MvcCallbackConfiguration.class)
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context).doesNotHaveBean(NotificationCallbackMvcController.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theServletControllerNeverRegistersInAReactiveApplication() {
|
||||
// Annotated controllers are honoured by WebFlux too, so without the servlet condition a
|
||||
// reactive deployment would map both transports onto the same callback path.
|
||||
new ReactiveWebApplicationContextRunner()
|
||||
.withUserConfiguration(MvcCallbackConfiguration.class)
|
||||
.withPropertyValues("ca-skeleton.notification.platform.callbacks.enabled=true")
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context).doesNotHaveBean(NotificationCallbackMvcController.class));
|
||||
}
|
||||
|
||||
private ApplicationContextRunner enabled() {
|
||||
return runner.withPropertyValues("ca-skeleton.notification.platform.enabled=true");
|
||||
}
|
||||
|
||||
/** Registers the servlet controller as a candidate so its conditions are actually evaluated. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@org.springframework.context.annotation.Import(NotificationCallbackMvcController.class)
|
||||
static class MvcCallbackConfiguration {}
|
||||
|
||||
/** Deterministic key material so the protector has something to bind to. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
static class SecretsConfiguration {
|
||||
|
||||
@Bean
|
||||
SecretMaterialProvider secrets() {
|
||||
return new SecretMaterialProvider() {
|
||||
|
||||
@Override
|
||||
public SecretKeyMaterial activeKey(SecretPurpose purpose) {
|
||||
return key(purpose);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SecretKeyMaterial keyById(String keyId) {
|
||||
return key(SecretPurpose.CONTACT_ENCRYPTION);
|
||||
}
|
||||
|
||||
private SecretKeyMaterial key(SecretPurpose purpose) {
|
||||
byte[] material = new byte[32];
|
||||
Arrays.fill(material, (byte) 0x2A);
|
||||
return new SecretKeyMaterial(
|
||||
purpose.name().toLowerCase(java.util.Locale.ROOT), purpose, material);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Referenced so the settings type is loaded by this test's compilation unit. */
|
||||
static Class<?> settingsType() {
|
||||
return NotificationPlatformSettings.class;
|
||||
}
|
||||
}
|
||||
+263
@@ -0,0 +1,263 @@
|
||||
package dev.caskeleton.bootstrap.notification.observation;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderAttemptLimiter;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderRuntime;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderRuntimeRegistry;
|
||||
import dev.caskeleton.adapter.outbound.notification.platform.observation.NotificationHealthReporter;
|
||||
import dev.caskeleton.application.notification.platform.api.ProviderId;
|
||||
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
|
||||
import dev.caskeleton.application.notification.platform.api.routing.Channel;
|
||||
import dev.caskeleton.application.notification.platform.observation.CardinalityGuard;
|
||||
import dev.caskeleton.application.notification.platform.observation.IllegalMetricTagException;
|
||||
import dev.caskeleton.application.notification.platform.observation.NotificationMetricName;
|
||||
import dev.caskeleton.application.notification.platform.provider.NotificationProviderAdapter;
|
||||
import dev.caskeleton.application.notification.platform.provider.ProviderCapabilities;
|
||||
import dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot;
|
||||
import dev.caskeleton.application.notification.platform.provider.ProviderSubmission;
|
||||
import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import io.micrometer.observation.ObservationRegistry;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.health.contributor.Status;
|
||||
|
||||
/**
|
||||
* The Micrometer half of notification observability.
|
||||
*
|
||||
* <p>These assertions are about what must <em>not</em> reach a metric or trace backend. A metric
|
||||
* store is not access-controlled the way the application's own data is, and spans leave the process
|
||||
* entirely — so a recipient address or a notification id arriving here is both an unbounded time
|
||||
* series and a disclosure.
|
||||
*/
|
||||
class NotificationObservationTest {
|
||||
|
||||
private static final Clock CLOCK =
|
||||
Clock.fixed(Instant.parse("2026-08-14T00:00:00Z"), ZoneOffset.UTC);
|
||||
private static final ProviderProfileId PROFILE = new ProviderProfileId("ses-primary");
|
||||
|
||||
@Test
|
||||
void aHighCardinalityTagIsRejectedBeforeTheTimeSeriesIsEverCreated() {
|
||||
var meters = new SimpleMeterRegistry();
|
||||
var metrics = new MicrometerNotificationMetrics(meters, new CardinalityGuard());
|
||||
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
metrics.increment(
|
||||
NotificationMetricName.DISPATCH,
|
||||
Map.of(
|
||||
"channel",
|
||||
"EMAIL",
|
||||
"notificationId",
|
||||
"01920000-0000-7000-8000-000000000000")))
|
||||
.isInstanceOf(IllegalMetricTagException.class);
|
||||
// Rejecting after registration would already have cost the series it was meant to prevent.
|
||||
assertThat(meters.getMeters()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void boundedTagsAreAcceptedAndRecordedOnEachMeterKind() {
|
||||
var meters = new SimpleMeterRegistry();
|
||||
var metrics = new MicrometerNotificationMetrics(meters, new CardinalityGuard());
|
||||
Map<String, String> tags = Map.of("channel", "EMAIL", "provider", "ses", "status", "ACCEPTED");
|
||||
|
||||
metrics.increment(NotificationMetricName.PROVIDER_ACCEPTED, tags);
|
||||
metrics.record(NotificationMetricName.DISPATCH, tags, Duration.ofMillis(120));
|
||||
metrics.gauge(NotificationMetricName.QUEUE_DEPTH, Map.of("channel", "EMAIL"), 7d);
|
||||
|
||||
assertThat(meters.counter(NotificationMetricName.PROVIDER_ACCEPTED, tagArray(tags)).count())
|
||||
.isEqualTo(1d);
|
||||
assertThat(
|
||||
meters
|
||||
.timer(NotificationMetricName.DISPATCH, tagArray(tags))
|
||||
.totalTime(java.util.concurrent.TimeUnit.MILLISECONDS))
|
||||
.isEqualTo(120d);
|
||||
assertThat(meters.get(NotificationMetricName.QUEUE_DEPTH).gauge().value()).isEqualTo(7d);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGaugeKeepsReportingAfterGarbageCollectionInsteadOfDecayingToNaN() {
|
||||
var meters = new SimpleMeterRegistry();
|
||||
var metrics = new MicrometerNotificationMetrics(meters, new CardinalityGuard());
|
||||
|
||||
metrics.gauge(NotificationMetricName.QUEUE_AGE, Map.of("channel", "SMS"), 3d);
|
||||
System.gc();
|
||||
metrics.gauge(NotificationMetricName.QUEUE_AGE, Map.of("channel", "SMS"), 9d);
|
||||
|
||||
assertThat(meters.get(NotificationMetricName.QUEUE_AGE).gauge().value()).isEqualTo(9d);
|
||||
}
|
||||
|
||||
@Test
|
||||
void observationTagsCarryNoIdentifierThatCouldIdentifyARecipientOrAMessage() {
|
||||
var convention = new NotificationObservationConvention(new CardinalityGuard());
|
||||
var context =
|
||||
NotificationObservationContext.builder("EMAIL", "ses", "ACCEPTED")
|
||||
.registeredTemplateId("welcome-v3")
|
||||
.attemptBucket(7)
|
||||
.sizeBucket(2048)
|
||||
.failureCategory("NONE")
|
||||
.build();
|
||||
|
||||
var low = convention.getLowCardinalityKeyValues(context);
|
||||
var keys = low.stream().map(io.micrometer.common.KeyValue::getKey).toList();
|
||||
|
||||
assertThat(keys)
|
||||
.doesNotContain(
|
||||
"notificationId",
|
||||
"recipientId",
|
||||
"attemptId",
|
||||
"providerRequestId",
|
||||
"email",
|
||||
"phone",
|
||||
"token",
|
||||
"endpoint");
|
||||
assertThat(keys)
|
||||
.containsExactlyInAnyOrder(
|
||||
"channel",
|
||||
"provider",
|
||||
"status",
|
||||
"attemptBucket",
|
||||
"sizeBucket",
|
||||
"templateId",
|
||||
"failureCategory");
|
||||
// High-cardinality values are routed to the tracing backend, which is exported off-host.
|
||||
assertThat(convention.getHighCardinalityKeyValues(context)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void attemptCountAndPayloadSizeAreBucketedRatherThanTaggedRaw() {
|
||||
var convention = new NotificationObservationConvention(new CardinalityGuard());
|
||||
|
||||
assertThat(tag(convention, 1, 100L, "attemptBucket")).isEqualTo("1");
|
||||
assertThat(tag(convention, 4, 100L, "attemptBucket")).isEqualTo("3-4");
|
||||
assertThat(tag(convention, 99, 100L, "attemptBucket")).isEqualTo("5+");
|
||||
assertThat(tag(convention, 1, 100L, "sizeBucket")).isEqualTo("small");
|
||||
assertThat(tag(convention, 1, 70_000L, "sizeBucket")).isEqualTo("large");
|
||||
assertThat(tag(convention, 1, 5_000_000L, "sizeBucket")).isEqualTo("xlarge");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCallbackIsALinkedRootObservationRatherThanALongRunningChildSpan() {
|
||||
var convention = new NotificationObservationConvention(new CardinalityGuard());
|
||||
var registry = ObservationRegistry.create();
|
||||
// Without a handler Micrometer hands back a no-op observation that discards everything, so the
|
||||
// assertion below would pass for the wrong reason.
|
||||
registry.observationConfig().observationHandler(handled -> true);
|
||||
var context = NotificationObservationContext.builder("EMAIL", "ses", "DELIVERED").build();
|
||||
|
||||
var observation = convention.callbackObservation(registry, context, "trace-abc");
|
||||
|
||||
// A child span would stay open for however long the provider takes to call back — hours, in the
|
||||
// normal case for email — and would report the provider's schedule as platform latency.
|
||||
assertThat(observation.getContextView().getParentObservation()).isNull();
|
||||
assertThat(
|
||||
observation
|
||||
.getContextView()
|
||||
.getHighCardinalityKeyValue(NotificationObservationConvention.LINK_KEY))
|
||||
.isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void healthEndpointExposesProviderStateAndGenerationButNoCredentialOrAddress() {
|
||||
var registry = new ProviderRuntimeRegistry();
|
||||
registry.register(runtime(3));
|
||||
var endpoint =
|
||||
new NotificationHealthEndpoint(new NotificationHealthReporter(registry, List.of(PROFILE)));
|
||||
|
||||
Map<String, Object> body = endpoint.notifications();
|
||||
|
||||
assertThat(body).containsEntry("healthy", true);
|
||||
assertThat(body.toString()).contains("ses-primary", "HEALTHY", "credentialGeneration=3");
|
||||
assertThat(body.toString()).doesNotContain("@", "key", "secret", "token");
|
||||
assertThat(endpoint.health().getStatus()).isEqualTo(Status.UP);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRejectedCredentialTakesTheIndicatorDownWhileTheProcessStaysFine() {
|
||||
var registry = new ProviderRuntimeRegistry();
|
||||
var runtime = runtime(1);
|
||||
registry.register(runtime);
|
||||
runtime.markAuthenticationFailed("INVALID_CREDENTIAL");
|
||||
var endpoint =
|
||||
new NotificationHealthEndpoint(new NotificationHealthReporter(registry, List.of(PROFILE)));
|
||||
|
||||
assertThat(endpoint.health().getStatus()).isEqualTo(Status.DOWN);
|
||||
assertThat(endpoint.notifications()).containsEntry("healthy", false);
|
||||
// The reason code is deliberately absent from the endpoint body; it names a credential.
|
||||
assertThat(endpoint.notifications().toString()).doesNotContain("INVALID_CREDENTIAL");
|
||||
}
|
||||
|
||||
private static String tag(
|
||||
NotificationObservationConvention convention, int attempt, long bytes, String key) {
|
||||
return convention
|
||||
.getLowCardinalityKeyValues(
|
||||
NotificationObservationContext.builder("EMAIL", "ses", "ACCEPTED")
|
||||
.attemptBucket(attempt)
|
||||
.sizeBucket(bytes)
|
||||
.build())
|
||||
.stream()
|
||||
.filter(keyValue -> keyValue.getKey().equals(key))
|
||||
.findFirst()
|
||||
.orElseThrow()
|
||||
.getValue();
|
||||
}
|
||||
|
||||
private static String[] tagArray(Map<String, String> tags) {
|
||||
return tags.entrySet().stream()
|
||||
.flatMap(entry -> java.util.stream.Stream.of(entry.getKey(), entry.getValue()))
|
||||
.toArray(String[]::new);
|
||||
}
|
||||
|
||||
private static ProviderRuntime runtime(long generation) {
|
||||
return new ProviderRuntime(
|
||||
new ProviderProfileSnapshot(
|
||||
PROFILE,
|
||||
new ProviderId("ses"),
|
||||
Channel.EMAIL,
|
||||
"PRODUCTION",
|
||||
generation,
|
||||
capabilities(),
|
||||
Map.of("senderDomain", "example.com")),
|
||||
new StubAdapter(),
|
||||
new ProviderAttemptLimiter(4, 100, CLOCK));
|
||||
}
|
||||
|
||||
private static ProviderCapabilities capabilities() {
|
||||
return new ProviderCapabilities(
|
||||
true, false, false, false, false, false, false, true, 50, 10_000_000L, Duration.ofDays(1));
|
||||
}
|
||||
|
||||
/** Never invoked; the runtime tests here never dispatch. */
|
||||
private static final class StubAdapter implements NotificationProviderAdapter {
|
||||
|
||||
@Override
|
||||
public ProviderId providerId() {
|
||||
return new ProviderId("ses");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Channel> channels() {
|
||||
return Set.of(Channel.EMAIL);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProviderCapabilities capabilities() {
|
||||
return NotificationObservationTest.capabilities();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletionStage<ProviderSubmissionResult> submit(ProviderSubmission submission) {
|
||||
return CompletableFuture.failedFuture(new UnsupportedOperationException());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user