review-followup Wave 3 라운드 3(P19): 3-D 공통 유틸 — Sha256·HmacSha256·Backoff·MdcKeys·TenantId, caller 트랜잭션 guard 하나

- shared-contract `Sha256`(약 65벌 흡수, notification `MessageDigestPort` 삭제), `HmacSha256`(서명 헬퍼), `Backoff`("full jitter" 뜻 하나),
  `MdcKeys`(gRPC·STOMP에도 상관관계), registry edge application-notification → shared-contract
- application-core `TenantId` 하나로 web·GraphQL tenant 문법 통일, web operation 경로에 tenant 해석(JWT `tenant_id`)
- persistence-jpa `CallerTransaction` 하나(복사본 4벌 + `JpaStreamScope` 흡수), 범위 없는 멱등성·outbox 리포지토리 메서드 제거(E-6b)
- 주입된 `Clock` 우회 제거(objectstorage·websocket·mongo·web stream), GraphQL 오류가 HTTP request id 사용, notification UUIDv7은 uuid-creator
- 호출처 없는 `WebRequestContext`·argument resolver 삭제
- 결함 수정: `WebStreamRegistry` 상한 경합(ORCH-new-3 — bin 하나만 잠그는 lock 안에서 크기 확인, 원자 카운터로 슬롯 예약)
- 현황표: 소유자 결정 33(persistence-notification·fileserver → persistence-jpa edge), 34(id 포트 domain 전환 보류), 35(X2-P2-6b 나머지 보류)

검증: ./gradlew check architectureCheck verifyDependencyLocks verifyPublicPathSnapshot :app-bootstrap:verifyEnvKeys configContractCheck
:app-bootstrap:integrationTest :sample-portfolio:integrationTest :sample-portfolio:systemTest graphql·websocket systemTest
persistence-jpa jpaPlatformContractTest·postgresql{Idempotency,Outbox*}IntegrationTest --continue 통과(695 task)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
donghyeon-ka
2026-09-29 14:17:48 +09:00
co-authored by Claude Opus 5.5
parent 4f4bd1fd34
commit 09e2dd63d6
163 changed files with 2216 additions and 1389 deletions
@@ -6,4 +6,5 @@ plugins {
// application-core; this leaf contains the notification platform policy/use cases only.
dependencies {
implementation project(':application-core')
implementation project(':shared-contract')
}
@@ -1,8 +1,6 @@
package dev.caskeleton.application.notification.platform.admin;
import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
import dev.caskeleton.shared.digest.Sha256;
import java.util.Objects;
/**
@@ -14,12 +12,6 @@ import java.util.Objects;
*/
final class AdminOperationCommandFingerprint {
private final MessageDigestPort digests;
AdminOperationCommandFingerprint(MessageDigestPort digests) {
this.digests = Objects.requireNonNull(digests, "digests");
}
String of(RedriveCommand command) {
Objects.requireNonNull(command, "command");
StringBuilder canonical = action("REDRIVE");
@@ -65,8 +57,7 @@ final class AdminOperationCommandFingerprint {
}
private String digest(StringBuilder canonical) {
byte[] bytes = canonical.toString().getBytes(StandardCharsets.UTF_8);
return HexFormat.of().formatHex(digests.sha256(bytes));
return Sha256.ofUtf8(canonical.toString()).hex();
}
private static StringBuilder action(String action) {
@@ -8,7 +8,6 @@ import dev.caskeleton.application.notification.platform.api.error.NotificationFa
import dev.caskeleton.application.notification.platform.api.error.ProviderConfigurationException;
import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot;
import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort;
import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort;
import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService;
import dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent;
@@ -74,7 +73,6 @@ public final class NotificationAdminApplicationService implements NotificationAd
NotificationAuditPort audit,
TransactionPort transactions,
dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort ids,
MessageDigestPort digests,
Clock clock) {
this.authorization = Objects.requireNonNull(authorization, "authorization");
this.duplicateRiskGuard = Objects.requireNonNull(duplicateRiskGuard, "duplicateRiskGuard");
@@ -86,8 +84,7 @@ public final class NotificationAdminApplicationService implements NotificationAd
this.operations = Objects.requireNonNull(operations, "operations");
this.transactions = Objects.requireNonNull(transactions, "transactions");
this.operationExecutor = new AdminOperationExecutor(this.operations, this.transactions);
this.commandFingerprints =
new AdminOperationCommandFingerprint(Objects.requireNonNull(digests, "digests"));
this.commandFingerprints = new AdminOperationCommandFingerprint();
this.audit = Objects.requireNonNull(audit, "audit");
this.ids = Objects.requireNonNull(ids, "ids");
this.clock = Objects.requireNonNull(clock, "clock");
@@ -71,7 +71,7 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU
new IdempotencyKey("derived-key-placeholder");
private final NotificationIdGeneratorPort ids;
private final RequestFingerprint fingerprints;
private final PlanFingerprint fingerprints;
private final CanonicalNotificationPlanEncoder planEncoder =
new CanonicalNotificationPlanEncoder();
private final TransactionPort transactions;
@@ -98,7 +98,7 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU
ContactPointProtector protector,
TenantContextPort tenants,
NotificationIdGeneratorPort ids,
RequestFingerprint fingerprints,
PlanFingerprint fingerprints,
TransactionPort transactions,
Clock clock,
Locale defaultLocale) {
@@ -1,8 +0,0 @@
package dev.caskeleton.application.notification.platform.dispatch;
/** Hashing boundary so application-core stays free of a concrete crypto provider. */
public interface MessageDigestPort {
/** SHA-256 of the given bytes. */
byte[] sha256(byte[] input);
}
@@ -40,7 +40,7 @@ public final class NotificationSubmissionService {
private final RecipientDeliveryStorePort recipients;
private final DeliveryAttemptStorePort attempts;
private final TemplateRegistry templates;
private final RequestFingerprint fingerprints;
private final PlanFingerprint fingerprints;
private final CanonicalNotificationPlanEncoder planEncoder =
new CanonicalNotificationPlanEncoder();
private final CanonicalNotificationPlanWriter writer;
@@ -56,7 +56,7 @@ public final class NotificationSubmissionService {
RecipientDeliveryStorePort recipients,
DeliveryAttemptStorePort attempts,
TemplateRegistry templates,
RequestFingerprint fingerprints,
PlanFingerprint fingerprints,
CanonicalNotificationPlanWriter writer,
TransactionPort transactions,
TenantContextPort tenants,
@@ -1,7 +1,7 @@
package dev.caskeleton.application.notification.platform.dispatch;
import dev.caskeleton.application.notification.platform.api.EncodedNotificationPlan;
import java.util.HexFormat;
import dev.caskeleton.shared.digest.Sha256;
import java.util.Objects;
/**
@@ -11,14 +11,11 @@ import java.util.Objects;
* fingerprint covers — the whole fallback order, the channel override, the deduplication action,
* the collapse spec, the schedule, the metadata, the typed variables — is a question about {@link
* CanonicalNotificationPlanEncoder}, which is the single place a plan becomes bytes.
*
* <p>Named for what it fingerprints: application-core's {@code RequestFingerprint} is the HTTP
* request-body fingerprint of the idempotency executor, a different value.
*/
public final class RequestFingerprint {
private final MessageDigestPort digest;
public RequestFingerprint(MessageDigestPort digest) {
this.digest = Objects.requireNonNull(digest, "digest");
}
public final class PlanFingerprint {
/**
* Fingerprint of one encoded plan.
@@ -33,6 +30,6 @@ public final class RequestFingerprint {
*/
public String of(EncodedNotificationPlan encoded) {
Objects.requireNonNull(encoded, "encoded");
return HexFormat.of().formatHex(digest.sha256(encoded.bytes()));
return Sha256.of(encoded.bytes()).hex();
}
}
@@ -14,8 +14,7 @@ import dev.caskeleton.application.notification.platform.template.VariableSchema;
import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
import dev.caskeleton.shared.digest.Sha256;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -36,7 +35,9 @@ import java.util.Objects;
* prefixed. Concatenating slot sources in map order would hash {@code SUBJECT="ab", BODY="c"} and
* {@code SUBJECT="a", BODY="bc"} alike, which is a content change the digest would call identical.
*/
// externalOutboundAllowed because MessageDigestPort is adapter-bound and called from here; see
// externalOutboundAllowed although the hashing port is gone: the D7 architecture rule treats any
// interface an outbound adapter implements as an outbound port, and this use case calls
// java.util.Map (the command's slot map), which an adapter class implements. See
// AcceptNotificationApplicationUseCase for why the flag states the reach rather than the distance.
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
@@ -48,20 +49,17 @@ public class PublishNotificationTemplateApplicationUseCase
implements PublishNotificationTemplateUseCase {
private final TemplateRegistry templates;
private final MessageDigestPort digests;
private final TransactionPort transactions;
/**
* Creates the use case.
*
* @param templates the registry this publishes into
* @param digests the hashing boundary, so application-core names no crypto provider
* @param transactions the write boundary this use case owns
*/
public PublishNotificationTemplateApplicationUseCase(
TemplateRegistry templates, MessageDigestPort digests, TransactionPort transactions) {
TemplateRegistry templates, TransactionPort transactions) {
this.templates = Objects.requireNonNull(templates, "templates");
this.digests = Objects.requireNonNull(digests, "digests");
this.transactions = Objects.requireNonNull(transactions, "transactions");
}
@@ -117,7 +115,6 @@ public class PublishNotificationTemplateApplicationUseCase
.append(source)
.append('\n');
}
return HexFormat.of()
.formatHex(digests.sha256(canonical.toString().getBytes(StandardCharsets.UTF_8)));
return Sha256.ofUtf8(canonical.toString()).hex();
}
}
@@ -3,8 +3,7 @@ package dev.caskeleton.application.notification.platform.dispatch;
import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId;
import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent;
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
import dev.caskeleton.shared.digest.Sha256;
import java.util.Objects;
/**
@@ -36,12 +35,6 @@ public final class SyntheticEventFingerprint {
*/
private static final String VERSION = "1";
private final MessageDigestPort digest;
public SyntheticEventFingerprint(MessageDigestPort digest) {
this.digest = Objects.requireNonNull(digest, "digest");
}
/**
* Fingerprint of one synthesised reconciliation event.
*
@@ -57,11 +50,7 @@ public final class SyntheticEventFingerprint {
Objects.requireNonNull(providerProfileId, "providerProfileId");
Objects.requireNonNull(attemptId, "attemptId");
Objects.requireNonNull(event, "event");
return HexFormat.of()
.formatHex(
digest.sha256(
canonicalForm(providerProfileId, attemptId, event)
.getBytes(StandardCharsets.UTF_8)));
return Sha256.ofUtf8(canonicalForm(providerProfileId, attemptId, event)).hex();
}
/**
@@ -1,20 +1,30 @@
package dev.caskeleton.application.notification.platform.policy;
import dev.caskeleton.shared.retry.Backoff;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;
import java.util.random.RandomGenerator;
/**
* Exponential backoff with full jitter and a hard ceiling.
* Full jitter over the shared exponential {@link Backoff}, never shorter than the base, with a hard
* ceiling.
*
* <p>"Full jitter" is the shared-contract word: uniform in {@code [0, ceiling]}. Delivery retries
* then raise it to at least {@code base}, so a provider that just failed is not called again in the
* same instant.
*
* <p>A provider-supplied {@code Retry-After} always wins over the computed value, but never over
* the configured maximum: a provider asking for an hour must not silently extend a delivery
* deadline.
*
* @param base the first attempt's ceiling and the shortest delay
* @param max the longest delay, {@code Retry-After} included
*/
public record RetryBackoff(Duration base, Duration max, double multiplier) {
public record RetryBackoff(Duration base, Duration max) {
public static final RetryBackoff DEFAULT =
new RetryBackoff(Duration.ofSeconds(1), Duration.ofMinutes(5), 2.0d);
new RetryBackoff(Duration.ofSeconds(1), Duration.ofMinutes(5));
public RetryBackoff {
Objects.requireNonNull(base, "base");
@@ -25,9 +35,6 @@ public record RetryBackoff(Duration base, Duration max, double multiplier) {
if (max.compareTo(base) < 0) {
throw new IllegalArgumentException("max must not be smaller than base");
}
if (multiplier < 1.0d) {
throw new IllegalArgumentException("multiplier");
}
}
/** Delay before attempt number {@code attemptNumber + 1}. */
@@ -37,11 +44,23 @@ public record RetryBackoff(Duration base, Duration max, double multiplier) {
if (attemptNumber < 1) {
throw new IllegalArgumentException("attemptNumber");
}
double exponential = base.toMillis() * Math.pow(multiplier, attemptNumber - 1d);
long ceilingMillis = (long) Math.min(exponential, (double) max.toMillis());
long jittered = ceilingMillis <= 0 ? 0 : jitter.nextLong(ceilingMillis + 1);
Duration computed = Duration.ofMillis(Math.max(jittered, base.toMillis()));
Duration jittered = new Backoff(base, max).fullJitter(attemptNumber, asRandom(jitter));
Duration computed = jittered.compareTo(base) < 0 ? base : jittered;
Duration chosen = retryAfter.filter(hint -> hint.compareTo(computed) > 0).orElse(computed);
return chosen.compareTo(max) > 0 ? max : chosen;
}
private static RandomGenerator asRandom(JitterSource jitter) {
return new RandomGenerator() {
@Override
public long nextLong() {
throw new UnsupportedOperationException("only bounded draws are used");
}
@Override
public long nextLong(long bound) {
return jitter.nextLong(bound);
}
};
}
}
@@ -3,8 +3,6 @@ package dev.caskeleton.application.notification.platform.admin;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.Test;
@@ -12,7 +10,7 @@ import org.junit.jupiter.api.Test;
class AdminOperationCommandFingerprintTest {
private final AdminOperationCommandFingerprint fingerprints =
new AdminOperationCommandFingerprint(AdminOperationCommandFingerprintTest::sha256);
new AdminOperationCommandFingerprint();
@Test
void fingerprintIsStableSha256AndChangesWithCommandMeaning() {
@@ -40,12 +38,4 @@ class AdminOperationCommandFingerprintTest {
assertThat(fingerprints.of(ordered)).isEqualTo(fingerprints.of(reversed));
}
private static byte[] sha256(byte[] bytes) {
try {
return MessageDigest.getInstance("SHA-256").digest(bytes);
} catch (NoSuchAlgorithmException impossible) {
throw new IllegalStateException(impossible);
}
}
}
@@ -244,7 +244,6 @@ class NotificationAdminApplicationServiceTest {
audit,
transactions,
new PlatformFakes.SequentialIds(),
NotificationAdminApplicationServiceTest::sha256,
CLOCK);
}
}
@@ -322,12 +321,4 @@ class NotificationAdminApplicationServiceTest {
return Optional.empty();
}
}
private static byte[] sha256(byte[] bytes) {
try {
return java.security.MessageDigest.getInstance("SHA-256").digest(bytes);
} catch (java.security.NoSuchAlgorithmException impossible) {
throw new IllegalStateException(impossible);
}
}
}
@@ -63,7 +63,7 @@ public final class NotificationPlatformNoops {
projection(ledger),
audit(),
metrics(),
new SyntheticEventFingerprint(NotificationPlatformNoops::sha256),
new SyntheticEventFingerprint(),
new PlatformFakes.RecordingTransactions(),
clock);
}
@@ -166,14 +166,6 @@ public final class NotificationPlatformNoops {
metrics());
}
private static byte[] sha256(byte[] bytes) {
try {
return java.security.MessageDigest.getInstance("SHA-256").digest(bytes);
} catch (java.security.NoSuchAlgorithmException impossible) {
throw new IllegalStateException(impossible);
}
}
private static final class NoopLedger implements ProviderEventLedger {
@Override
public AppendEventResult append(VerifiedProviderEvent event) {
@@ -29,7 +29,7 @@ import org.junit.jupiter.api.Test;
*/
class RequestFingerprintTest {
private final RequestFingerprint fingerprint = PlatformFakes.fingerprints();
private final PlanFingerprint fingerprint = PlatformFakes.fingerprints();
@Test
@DisplayName("a different fallback tail is a different request")
@@ -403,16 +403,8 @@ public final class PlatformFakes {
* <p>The canonical form is production code and is exactly what decides whether a repeated
* idempotency key converges or conflicts, so it is not stubbed out here.
*/
public static RequestFingerprint fingerprints() {
return new RequestFingerprint(PlatformFakes::sha256);
}
private static byte[] sha256(byte[] input) {
try {
return java.security.MessageDigest.getInstance("SHA-256").digest(input);
} catch (java.security.NoSuchAlgorithmException absent) {
throw new IllegalStateException(absent);
}
public static PlanFingerprint fingerprints() {
return new PlanFingerprint();
}
/** Tenant context pinned to one tenant. */
@@ -21,8 +21,7 @@ class PublishNotificationTemplateApplicationUseCaseTest {
RecordingTemplates templates = new RecordingTemplates();
PlatformFakes.RecordingTransactions transactions = new PlatformFakes.RecordingTransactions();
PublishNotificationTemplateApplicationUseCase useCase =
new PublishNotificationTemplateApplicationUseCase(
templates, PublishNotificationTemplateApplicationUseCaseTest::sha256, transactions);
new PublishNotificationTemplateApplicationUseCase(templates, transactions);
PublishNotificationTemplateCommand command =
new PublishNotificationTemplateCommand(
"payment-receipt",
@@ -46,9 +45,7 @@ class PublishNotificationTemplateApplicationUseCaseTest {
// given
PublishNotificationTemplateApplicationUseCase useCase =
new PublishNotificationTemplateApplicationUseCase(
new RecordingTemplates(),
PublishNotificationTemplateApplicationUseCaseTest::sha256,
new PlatformFakes.RecordingTransactions());
new RecordingTemplates(), new PlatformFakes.RecordingTransactions());
PublishNotificationTemplateCommand command =
new PublishNotificationTemplateCommand(
"payment-receipt",
@@ -67,14 +64,6 @@ class PublishNotificationTemplateApplicationUseCaseTest {
assertThat(published.version()).isEqualTo(NotificationTemplateVersion.FIRST_VERSION);
}
private static byte[] sha256(byte[] bytes) {
try {
return java.security.MessageDigest.getInstance("SHA-256").digest(bytes);
} catch (java.security.NoSuchAlgorithmException impossible) {
throw new IllegalStateException(impossible);
}
}
private static final class RecordingTemplates implements TemplateRegistry {
private NotificationTemplateVersion published;
@@ -6,8 +6,6 @@ import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId;
import dev.caskeleton.application.notification.platform.api.NormalizedEventType;
import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent;
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.Map;
@@ -31,8 +29,7 @@ class SyntheticEventFingerprintTest {
private static final DeliveryAttemptId ATTEMPT =
new DeliveryAttemptId(UUID.fromString("0198f1a2-3b4c-7d8e-9f01-234567890abc"));
private final SyntheticEventFingerprint fingerprints =
new SyntheticEventFingerprint(SyntheticEventFingerprintTest::sha256);
private final SyntheticEventFingerprint fingerprints = new SyntheticEventFingerprint();
@Test
@DisplayName("accepted and delivered for the same attempt are different events")
@@ -173,12 +170,4 @@ class SyntheticEventFingerprintTest {
Optional.of(occurredAt),
Map.of());
}
private static byte[] sha256(byte[] input) {
try {
return MessageDigest.getInstance("SHA-256").digest(input);
} catch (NoSuchAlgorithmException unavailable) {
throw new IllegalStateException("SHA-256 is required by every Java platform", unavailable);
}
}
}