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
+1
View File
@@ -73,6 +73,7 @@ Package root: `dev.caskeleton.application`.
| `messaging.event.ValidatedIntegrationEvent` | Stable semantic identities plus immutable exact encoded bytes and hashes, ready for a later durable append boundary. |
| `messaging.event.IntegrationEventEncoderPort` | Framework-free local draft-to-validated-event boundary implemented by an outbound adapter (the template's: `adapter:outbound:support` `JsonIntegrationEventEncoder`). |
| `outbox.OutboxAppendPort` | The one outbox append: a `ValidatedIntegrationEvent`, in the caller's write transaction. |
| `tenant.TenantId` | The tenant identifier and its one grammar (`[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`); the web and GraphQL transport contexts both carry it. Built by a transport from verified authentication data only. |
## Notification (NOTIF-ADR-005)
+9 -6
View File
@@ -397,16 +397,19 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장.
### OutboxBackoffPolicy
- relay 재시도 스케줄링용 exponential-backoff-with-full-jitter 정책(I10).
- 공식: `base = 30s`, `maxAttempts = 3`, `delay = base × 2^(attemptCount-1) + jitter(0..base)`,
`nextAttemptAt = now + delay`. 여기서 `attemptCount` 는 방금 실패한 시도의 1-based 번호다.
- full jitter 는 주입된 `RandomGenerator` 로 `[0, base]` 균등 분포에서 뽑는다. 고정 시드/0 을
반환하는 generator 를 주면 테스트가 결정적이 된다(I10).
- relay 재시도 스케줄링 정책(I10). 이름과 달리 "full jitter" 가 아니다 — full jitter 는 0 을 고를
수 있고, relay 재시도가 실패한 그 순간에 다시 due 가 되면 안 된다.
- 공식: `base = 30s`, `maxAttempts = 3`, `delay = ceiling(attemptCount) + U[0, base]`,
`nextAttemptAt = now + delay`. `ceiling` 은 shared-contract `Backoff` 의
`base × 2^(attemptCount-1)` 이고 마지막 시도 값(120s)에서 멈춘다. `attemptCount` 는 방금 실패한
시도의 1-based 번호다.
- 더하는 spread 는 한 base 짜리 full jitter(`Backoff#fullJitter`, `[0, base]` 균등)이며 주입된
`RandomGenerator` 로 뽑는다. 0 을 반환하는 generator 를 주면 테스트가 결정적이 된다(I10).
- **상수는 고정이다(I10)**: `BASE_DELAY`·`MAX_ATTEMPTS`·jitter 범위는 설정 프로퍼티가 아니다.
외부화하면 registry alert 임계치(`error-codes.yaml` 의 `retry_after_seconds=30`)와
`outbox-publish-failed` runbook 이 실제 런타임 값과 어긋난다. 이 상수는 registry·runbook
업데이트와 **함께만** 바꾼다.
- 지수 계산은 overflow 방지를 위해 `2^30` 에서 cap 한다(`2^30 × 30s > 30년` 이라 안전).
- 지수 계산의 overflow 는 `Backoff` 가 포화 연산으로 막는다.
### outbox 값/상태 타입 (Status · ClaimedOutboxEvent · RelayResult · Command)
+1
View File
@@ -13,6 +13,7 @@ dependencies {
implementation project(':shared-contract')
// Port contracts (`*Contract`) are abstract JUnit classes that fakes and adapters both extend.
testFixturesImplementation project(':shared-contract')
testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api'
testFixturesImplementation 'org.assertj:assertj-core'
}
@@ -1,8 +1,6 @@
package dev.caskeleton.application.idempotency;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import dev.caskeleton.shared.digest.Sha256;
import java.util.Objects;
/**
@@ -27,12 +25,6 @@ public record RequestFingerprint(String hex) {
/** Compute the SHA-256 fingerprint of the raw request body bytes. */
public static RequestFingerprint ofSha256(byte[] body) {
byte[] payload = body == null ? new byte[0] : body;
try {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(payload);
return new RequestFingerprint(HexFormat.of().formatHex(digest));
} catch (NoSuchAlgorithmException e) {
// SHA-256 is mandated by every JDK — unreachable.
throw new IllegalStateException("SHA-256 algorithm unavailable", e);
}
return new RequestFingerprint(Sha256.of(payload).hex());
}
}
@@ -1,5 +1,6 @@
package dev.caskeleton.application.messaging.contract;
import dev.caskeleton.shared.digest.Sha256;
import java.util.List;
/**
@@ -1,50 +0,0 @@
package dev.caskeleton.application.messaging.contract;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HexFormat;
/** Immutable SHA-256 digest value. */
@SuppressWarnings("ArrayRecordComponent")
public record Sha256(byte[] bytes) {
public static final int BYTE_LENGTH = 32;
public Sha256 {
if (bytes == null || bytes.length != BYTE_LENGTH) {
throw new IllegalArgumentException("SHA-256 digest must contain exactly 32 bytes");
}
bytes = bytes.clone();
}
/** The SHA-256 digest of {@code content}. */
public static Sha256 of(byte[] content) {
try {
return new Sha256(MessageDigest.getInstance("SHA-256").digest(content));
} catch (NoSuchAlgorithmException e) {
// SHA-256 is mandated by every JDK — unreachable.
throw new IllegalStateException("SHA-256 algorithm unavailable", e);
}
}
@Override
public byte[] bytes() {
return bytes.clone();
}
@Override
public boolean equals(Object other) {
return this == other || (other instanceof Sha256 sha256 && Arrays.equals(bytes, sha256.bytes));
}
@Override
public int hashCode() {
return Arrays.hashCode(bytes);
}
@Override
public String toString() {
return HexFormat.of().formatHex(bytes);
}
}
@@ -2,7 +2,7 @@ package dev.caskeleton.application.messaging.event;
import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
@@ -5,7 +5,7 @@ import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.SchemaResourceId;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.shared.digest.Sha256;
import java.util.HexFormat;
import java.util.List;
@@ -13,11 +13,8 @@ import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import dev.caskeleton.shared.digest.Sha256;
import java.time.Clock;
import java.util.HexFormat;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
@@ -172,12 +169,6 @@ public class SubmitDurableOperationUseCase
if (value.length() <= MAXIMUM_EVENT_ID_LENGTH && EVENT_ID_GRAMMAR.matcher(value).matches()) {
return value;
}
try {
byte[] digest =
MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
return "operation-" + HexFormat.of().formatHex(digest);
} catch (NoSuchAlgorithmException unreachable) {
throw new IllegalStateException("Java runtime does not provide SHA-256", unreachable);
}
return "operation-" + Sha256.ofUtf8(value).hex();
}
}
@@ -1,16 +1,22 @@
package dev.caskeleton.application.outbox;
import dev.caskeleton.shared.retry.Backoff;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import java.util.random.RandomGenerator;
/**
* Exponential-backoff-with-full-jitter policy for outbox relay retry scheduling: {@code delay =
* base × 2^(attemptCount-1) + jitter(0..base)} with {@code base = 30s}, {@code maxAttempts = 3};
* {@code attemptCount} is the 1-based just-failed attempt. Full jitter uses the injected {@link
* RandomGenerator} (deterministic in tests with a fixed-seed generator). The constants are fixed,
* not configurable — see README for why.
* Retry scheduling for the outbox relay: {@code delay = ceiling(attemptCount) + U[0, base]}, where
* the ceiling is the shared {@link Backoff} exponential {@code base × 2^(attemptCount-1)} capped at
* the last attempt's value, {@code base = 30s} and {@code maxAttempts = 3}; {@code attemptCount} is
* the 1-based just-failed attempt.
*
* <p>This is not "full jitter", although it used to be called that: full jitter ({@link
* Backoff#fullJitter}) may choose zero, and a relay retry must never be due at the instant it
* failed. The spread added on top of the exponential ceiling is a full jitter of one base, drawn
* from the injected {@link RandomGenerator} (deterministic in tests). The constants are fixed, not
* configurable — see README for why.
*/
public final class OutboxBackoffPolicy {
@@ -20,6 +26,13 @@ public final class OutboxBackoffPolicy {
/** Maximum delivery attempts before a row is DEAD-lettered. */
public static final int MAX_ATTEMPTS = 3;
/** The exponential part, capped where the last attempt already is. */
private static final Backoff SCHEDULE =
new Backoff(BASE_DELAY, BASE_DELAY.multipliedBy(1L << (MAX_ATTEMPTS - 1)));
/** The spread: a full jitter of one base. */
private static final Backoff SPREAD = new Backoff(BASE_DELAY, BASE_DELAY);
private final RandomGenerator random;
/**
@@ -56,16 +69,6 @@ public final class OutboxBackoffPolicy {
"attemptCount must be >= 1 (1-based), was " + attemptCount);
}
Objects.requireNonNull(now, "now must not be null");
// Exponential base: base * 2^(attemptCount-1)
// Capped to avoid overflow for very large attemptCount values.
long exponent = Math.min(attemptCount - 1, 30); // 2^30 * 30s > 30 years — safe cap
long baseSeconds = BASE_DELAY.toSeconds() * (1L << exponent);
// Full jitter: uniform in [0, base]
double jitterSeconds = random.nextDouble() * BASE_DELAY.toSeconds();
long totalSeconds = baseSeconds + (long) jitterSeconds;
return now.plusSeconds(totalSeconds);
return now.plus(SCHEDULE.ceiling(attemptCount)).plus(SPREAD.fullJitter(1, random));
}
}
@@ -0,0 +1,46 @@
package dev.caskeleton.application.tenant;
import java.util.Optional;
import java.util.regex.Pattern;
/**
* A tenant identifier, with the one grammar every transport accepts.
*
* <p>Opaque, short and safe to place in a log field: {@code [A-Za-z0-9][A-Za-z0-9_.-]{0,63}}. The
* web and GraphQL transports each held a {@code TenantContext} with its own rule — web this
* grammar, GraphQL "non-blank, at most 128 characters" — so the same tenant passed one transport
* and was refused by the other (review X2-P2-6a, S5-lead-3). Both now carry this type.
*
* <p>A tenant is a security boundary, so where one comes from matters more than its shape: a
* transport builds it from verified authentication data, never from a request parameter.
*
* @param value the identifier
*/
public record TenantId(String value) {
/** The grammar, for a transport that has to explain a refusal. */
public static final String GRAMMAR = "[A-Za-z0-9][A-Za-z0-9_.-]{0,63}";
private static final Pattern PATTERN = Pattern.compile(GRAMMAR);
public TenantId {
if (value == null || !PATTERN.matcher(value).matches()) {
throw new IllegalArgumentException("tenant identifier must match " + GRAMMAR);
}
}
/**
* The tenant named by an optional value: empty for {@code null} or blank.
*
* @throws IllegalArgumentException when a non-blank value breaks the grammar — a malformed tenant
* is never read as "no tenant", which would widen what the caller sees
*/
public static Optional<TenantId> optional(String value) {
return value == null || value.isBlank() ? Optional.empty() : Optional.of(new TenantId(value));
}
@Override
public String toString() {
return value;
}
}
@@ -3,6 +3,7 @@ package dev.caskeleton.application.messaging.contract;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.shared.digest.Sha256;
import java.lang.reflect.Modifier;
import java.time.Duration;
import java.util.Arrays;
@@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
@@ -0,0 +1,64 @@
package dev.caskeleton.application.tenant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import java.util.Optional;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class TenantIdTest {
@ParameterizedTest
@ValueSource(strings = {"acme", "Acme-01", "a", "tenant_a.eu-1"})
void aTenantInTheGrammarIsAccepted(String value) {
assertThat(new TenantId(value).value()).isEqualTo(value);
}
@ParameterizedTest
@ValueSource(strings = {"", " ", "-acme", ".acme", "ac me", "acme\n", "../public", "테넌트"})
@DisplayName("문법 밖의 tenant(선행 구분자, 공백, 줄바꿈, 경로, 비ASCII)는 거부한다")
void aTenantOutsideTheGrammarIsRefused(String value) {
// when
Throwable thrown = catchThrowable(() -> new TenantId(value));
// then
assertThat(thrown)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("tenant identifier must match " + TenantId.GRAMMAR);
}
@Test
@DisplayName("65자 tenant는 거부한다")
void aTenantLongerThanSixtyFourCharactersIsRefused() {
// when
Throwable thrown = catchThrowable(() -> new TenantId("a".repeat(65)));
// then
assertThat(thrown).isInstanceOf(IllegalArgumentException.class);
}
@Test
void anAbsentOptionalTenantIsEmpty() {
assertThat(TenantId.optional(null)).isEmpty();
}
@Test
void aPresentOptionalTenantIsParsed() {
assertThat(TenantId.optional("acme")).isEqualTo(Optional.of(new TenantId("acme")));
}
@Test
@DisplayName("형식이 틀린 tenant는 '없음'으로 읽지 않고 거부한다")
void aMalformedOptionalTenantIsRefusedRatherThanReadAsAbsent() {
// when
Throwable thrown = catchThrowable(() -> TenantId.optional("ac me"));
// then
assertThat(thrown)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("tenant identifier must match " + TenantId.GRAMMAR);
}
}
@@ -1,9 +1,9 @@
package dev.caskeleton.application.messaging.event.testkit;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.application.messaging.event.IntegrationEventDraft;
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HexFormat;
@@ -2,13 +2,13 @@ package dev.caskeleton.application.outbox.testkit;
import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.application.messaging.event.AggregateIdentity;
import dev.caskeleton.application.messaging.event.AggregateOrder;
import dev.caskeleton.application.messaging.event.EventId;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import dev.caskeleton.application.outbox.ClaimedOutboxEvent;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.HexFormat;