diff --git a/config/spotbugs/exclude.xml b/config/spotbugs/exclude.xml index 2ee07473..26570e65 100644 --- a/config/spotbugs/exclude.xml +++ b/config/spotbugs/exclude.xml @@ -208,12 +208,19 @@ Annotation matcher covers every class annotated at class level, including ones added later. A class that annotates only some methods is proxied all the same but is not matched here; name it when one appears. A @Configuration class is CGLIB-subclassed for its @Bean - methods for the same reason. --> + methods for the same reason. Every use case carries @UseCaseCapability and is not final by + the use-case contract (src/application/core/AGENTS.md), @SystemInvoked and query use cases + included, so the annotation matches them too; together with the *UseCase name, so a class + that is not a use case does not hide a finding behind the annotation. --> + + + + diff --git a/docs/manual/05-idempotency.md b/docs/manual/05-idempotency.md index fce96ff2..8c8cd538 100644 --- a/docs/manual/05-idempotency.md +++ b/docs/manual/05-idempotency.md @@ -44,6 +44,27 @@ DB 커밋 중 연결 끊김 ───────────────── executor 조립과 실제 PostgreSQL 저장소 왕복은 `PostgreSqlIdempotencyProviderIntegrationTest`(app-bootstrap `integrationTest`)다. KEYED 유스케이스를 HTTP부터 끝까지 이은 업무 기능 예는 템플릿에 없다. +### executor를 쓰지 않는 중복 판정 둘 (2026-11-13 결정) + +템플릿에는 `IdempotencyExecutor` 말고 중복을 판정하는 곳이 둘 더 있다. 둘 다 일부러 executor로 옮기지 않는다. +executor는 **응답을 다시 돌려주는 기록**이다: HTTP `Idempotency-Key` 헤더로 들어오고, 원본 키 대신 scope digest만 +저장하고, 기록은 TTL이 지나면 지운다. 아래 둘은 **업무 행 자체의 정체성**이라 수명과 판정 대상이 다르다. + +| 어디 | 키 | 같은 키·같은 요청 | 같은 키·다른 요청 | 수명 | +| --- | --- | --- | --- | --- | +| executor(KEYED 유스케이스) | `Idempotency-Key` 헤더의 scope digest | 저장된 응답 재생 | 422 `IDEMPOTENT_REQUEST_MISMATCH` | TTL | +| 알림 받기(`AcceptNotificationApplicationUseCase`) | 본문의 `idempotencyKey`. 없으면 알림 plan 지문 | 처음 만든 알림의 receipt | `IDEMPOTENCY_CONFLICT`(요청 지문 비교) | 알림 행과 같다 | +| durable operation 제출(`SubmitDurableOperationUseCase`) | 제출 scope(tenant·principal·operation 이름)와 payload 지문 | 처음 받은 operation | 지문이 키에 들어 있어 다른 키다. 새 operation | operation 보존 기간 | + +- 알림: 키는 tenant 안에서 같은 알림을 한 번만 만드는 업무 키다. 저장소의 유일 제약이 동시 제출을 막고, 진 쪽은 이긴 행을 + 읽어 같은 receipt로 수렴한다. 키를 주지 않은 호출자도 중복을 막도록 plan 지문으로 키를 만든다. executor로 옮기면 TTL + 뒤 같은 알림을 다시 만들고, 키 없는 호출은 중복을 막지 못한다. 저장한 키 값을 어떻게 다룰지(원본 저장)는 보안 검토 + 항목이다. +- durable operation: 결정 15·26(서버가 id를 만들고 payload 지문으로 재제출을 판정)이 정한다. capability의 `KEYED`는 + "같은 scope·같은 payload로 다시 보내면 같은 작업"이라는 뜻이고, 그 판정은 operation 저장소의 scope 유일성이 한다. +- 새 기능이 이 둘을 따라 할 일은 거의 없다. 클라이언트가 응답을 못 받아 다시 보내는 쓰기는 위 순서대로 executor를 쓴다. + 업무 행 자체가 영구히 하나여야 하면(04장 유일 제약) 그 행의 키로 판정한다. + ## 클라이언트에게 무엇을 약속하나 | 응답 | 의미 | 클라이언트 행동 | diff --git a/docs/notification/api-surface-snapshot.txt b/docs/notification/api-surface-snapshot.txt index 691f0444..f5622441 100644 --- a/docs/notification/api-surface-snapshot.txt +++ b/docs/notification/api-surface-snapshot.txt @@ -2,7 +2,7 @@ # Every top-level public type under the platform packages. Growth is a reviewed change. # Update only after review with: # ./gradlew :adapter:outbound:notification:updateNotificationApiSurface -PapproveNotificationApiSurfaceChange -# types: 364 +# types: 359 dev.caskeleton.adapter.outbound.notification.NotificationConfig dev.caskeleton.adapter.outbound.notification.NotificationRoutesSettings dev.caskeleton.adapter.outbound.notification.core.FailOpenNotificationProvider @@ -136,7 +136,6 @@ dev.caskeleton.application.notification.platform.api.NotificationPlan dev.caskeleton.application.notification.platform.api.NotificationReceipt dev.caskeleton.application.notification.platform.api.NotificationSnapshot dev.caskeleton.application.notification.platform.api.NotificationVariable -dev.caskeleton.application.notification.platform.api.ProviderEventId dev.caskeleton.application.notification.platform.api.ProviderId dev.caskeleton.application.notification.platform.api.ProviderProfileId dev.caskeleton.application.notification.platform.api.RecipientDeliveryId @@ -168,7 +167,6 @@ dev.caskeleton.application.notification.platform.api.error.CallbackValidationExc dev.caskeleton.application.notification.platform.api.error.FailureCategory dev.caskeleton.application.notification.platform.api.error.IdempotencyConflictException dev.caskeleton.application.notification.platform.api.error.NotificationException -dev.caskeleton.application.notification.platform.api.error.NotificationExpiredException dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor dev.caskeleton.application.notification.platform.api.error.NotificationValidationException @@ -329,14 +327,11 @@ dev.caskeleton.application.notification.platform.port.in.SubmitNotificationComma dev.caskeleton.application.notification.platform.port.in.SubmitNotificationUseCase dev.caskeleton.application.notification.platform.provider.AttachmentAccessContext dev.caskeleton.application.notification.platform.provider.AttachmentResolver -dev.caskeleton.application.notification.platform.provider.BatchNotificationProviderAdapter -dev.caskeleton.application.notification.platform.provider.CollapseCapability dev.caskeleton.application.notification.platform.provider.EvidenceCertainty dev.caskeleton.application.notification.platform.provider.EvidenceFact dev.caskeleton.application.notification.platform.provider.NotificationProviderAdapter dev.caskeleton.application.notification.platform.provider.ProviderCallNotStartedException dev.caskeleton.application.notification.platform.provider.ProviderCapabilities -dev.caskeleton.application.notification.platform.provider.ProviderCollapseMapping dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence dev.caskeleton.application.notification.platform.provider.ProviderFailure dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot diff --git a/docs/upgrade/2026-11-round9-application.md b/docs/upgrade/2026-11-round9-application.md new file mode 100644 index 00000000..e985b88c --- /dev/null +++ b/docs/upgrade/2026-11-round9-application.md @@ -0,0 +1,22 @@ +# 업그레이드 안내 — 2026-11 application 구조와 작은 정리 + +- 범위: durable operation 제출이 id를 유스케이스에서 만들고 tenant를 타입으로 받게 한 변경, 쓰지 않던 공개 타입 일곱의 + 삭제, 그 밖의 작은 정리. 공개 타입과 생성자가 바뀐 곳이 있다. 아래 표가 그 목록이다. +- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 application 작은 것(B15b) 발견 + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 durable operation을 직접 제출·조회하는 +서비스와 아래 표의 지운 타입을 쓴 서비스다. + +## 2. 할 일 + +| # | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | +| 1 | `OperationCommand`에서 operation id 인자를 지우고, tenant를 `Optional`(`application.tenant.TenantId`)로 넘긴다. `GetDurableOperationQuery`·`CancelDurableOperationCommand`의 tenant도 같다. `SubmitDurableOperationUseCase`는 생성자에 `DurableOperationIdFactory`를 받아 id를 직접 만든다. `DurableOperationController`는 id factory를 받지 않는다 | 컴파일이 실패한다 | durable operation을 직접 제출·조회하거나 그 use case를 조립한 서비스 | +| 2 | 쓰는 곳이 없던 공개 타입 일곱을 지웠다: `application.transaction.ReadConsistency`, `FileserverSpans`, 알림의 `ProviderEventId`·`NotificationExpiredException`·`BatchNotificationProviderAdapter`·`CollapseCapability`·`ProviderCollapseMapping` | 그 타입을 쓴 코드는 컴파일이 실패한다. 템플릿 안에는 쓰는 곳이 없었다 | 그 타입을 쓴 서비스 | + +## 3. 바뀐 동작 (따라 할 일 없음) + +- `GetDurableOperationUseCase`·`PublishPendingOutboxEventsUseCase`가 final이 아니다. +- 알림 받기의 `idempotencyKey`가 `IdempotencyExecutor`와 다른 이유는 manual 05 「executor를 쓰지 않는 중복 판정 둘」에 있다. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java index cdf7a8ab..c58d7e53 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java @@ -7,7 +7,6 @@ import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.operation.CancelDurableOperationCommand; import dev.caskeleton.application.operation.CancelDurableOperationUseCase; import dev.caskeleton.application.operation.DurableOperationId; -import dev.caskeleton.application.operation.DurableOperationIdFactory; import dev.caskeleton.application.operation.GetDurableOperationQuery; import dev.caskeleton.application.operation.GetDurableOperationUseCase; import dev.caskeleton.application.operation.OperationAcceptance; @@ -19,6 +18,7 @@ import jakarta.validation.Valid; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Objects; +import java.util.Optional; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; @@ -51,7 +51,6 @@ public final class DurableOperationController { private final SubmitDurableOperationUseCase submit; private final GetDurableOperationUseCase get; private final CancelDurableOperationUseCase cancel; - private final DurableOperationIdFactory operationIds; /** * A controller over the three operation use cases. @@ -59,15 +58,12 @@ public final class DurableOperationController { * @param submit accepts work * @param get reads one operation * @param cancel requests cancellation - * @param operationIds mints the id of a new operation (a UUIDv7: it is also the event id) */ public DurableOperationController( SubmitDurableOperationUseCase submit, GetDurableOperationUseCase get, - CancelDurableOperationUseCase cancel, - DurableOperationIdFactory operationIds) { + CancelDurableOperationUseCase cancel) { this.submit = Objects.requireNonNull(submit, "submit"); - this.operationIds = Objects.requireNonNull(operationIds, "operationIds"); this.get = Objects.requireNonNull(get, "get"); this.cancel = Objects.requireNonNull(cancel, "cancel"); } @@ -75,10 +71,9 @@ public final class DurableOperationController { /** * Accepts an operation. * - *

{@code 202} with the operation's {@code Location}. The id is minted here, by {@link - * DurableOperationIdFactory}; a resubmission of the same work by the same caller is recognised by - * its payload fingerprint and answered with the operation that already exists, {@code - * alreadyAccepted} true and the same {@code Location}. + *

{@code 202} with the operation's {@code Location}. The use case mints the id; a resubmission + * of the same work by the same caller is recognised by its payload fingerprint and answered with + * the operation that already exists, {@code alreadyAccepted} true and the same {@code Location}. */ @PostMapping public ResponseEntity> submit( @@ -88,7 +83,6 @@ public final class DurableOperationController { OperationAcceptance acceptance = submit.handle( new OperationCommand( - operationIds.newOperationId(), request.operationName(), principalId(principal), tenantOf(principal), @@ -155,9 +149,9 @@ public final class DurableOperationController { return principal.idpUserId(); } - // The operation use cases take the tenant as a plain string; null means "not tenant scoped". - private static String tenantOf(AuthenticatedPrincipal principal) { - return principal == null ? null : principal.tenant().map(TenantId::value).orElse(null); + // Empty means "not tenant scoped", the same as a token without a tenant claim. + private static Optional tenantOf(AuthenticatedPrincipal principal) { + return principal == null ? Optional.empty() : principal.tenant(); } private static ResponseEntity> notFound() { diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java index 4039ff1a..ae20c86d 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java @@ -70,10 +70,10 @@ class DurableOperationControllerTest { outbox, new FakeIntegrationEventEncoder(new DurableOperationSubmittedContract()), transactions, + new UuidV7DurableOperationIdFactory(), clock), new GetDurableOperationUseCase(operations, transactions, clock), - new CancelDurableOperationUseCase(operations, transactions, clock), - new UuidV7DurableOperationIdFactory()); + new CancelDurableOperationUseCase(operations, transactions, clock)); mvc = MockMvcBuilders.standaloneSetup(controller) .setControllerAdvice( @@ -141,10 +141,14 @@ class DurableOperationControllerTest { MockMvcBuilders.standaloneSetup( new DurableOperationController( new SubmitDurableOperationUseCase( - operations, outbox, new FakeIntegrationEventEncoder(), transactions, clock), + operations, + outbox, + new FakeIntegrationEventEncoder(), + transactions, + new UuidV7DurableOperationIdFactory(), + clock), new GetDurableOperationUseCase(operations, transactions, clock), - new CancelDurableOperationUseCase(operations, transactions, clock), - new UuidV7DurableOperationIdFactory())) + new CancelDurableOperationUseCase(operations, transactions, clock))) .setControllerAdvice( new GlobalExceptionHandler(SpanErrorRecorder.NOOP), new EnvelopeBodyAdvice()) .setCustomArgumentResolvers(new AuthenticationPrincipalArgumentResolver()) diff --git a/src/adapter/outbound/identifier/README.md b/src/adapter/outbound/identifier/README.md index 4ad90bb5..c4c13f0a 100644 --- a/src/adapter/outbound/identifier/README.md +++ b/src/adapter/outbound/identifier/README.md @@ -37,7 +37,8 @@ leaf에 둔다. 그때 이 절을 고친다. 만든다. operation id는 제출 이벤트의 event id가 되고, messaging platform `MessageId`는 UUIDv7만 받는다. 예전에는 web controller가 `UUID.randomUUID()`(v4)로 만들어 모든 제출 이벤트가 발행 시점에 거부되어 DEAD가 됐다(리뷰 2026-11-01 06-06, Kafka relay lane이 발견). -`composition:durable-operation`이 bean으로 조립한다. +`composition:durable-operation`이 bean으로 조립하고, `SubmitDurableOperationUseCase`가 제출마다 부른다. 2026-11-13 +전에는 controller가 불러 그 id를 command에 실었다. ## 조립 diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStore.java index 44caf0a3..b6fd27c0 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStore.java @@ -46,8 +46,8 @@ public class JpaDurableOperationStore implements DurableOperationStorePort { // Insert-or-nothing on the scope, then read whichever row holds it. Catching the unique // violation instead does not work on PostgreSQL: the violation aborts the caller's transaction // (25P02), and the read of the winning row is refused along with everything after it. The - // inserted count is the only thing that tells a retry under the same operation id from a - // creation. + // inserted count is the only thing that tells a resubmission, which finds the scope already + // held by an earlier call's operation, from a creation. int inserted = repository.submitIfAbsent( submission.operationId().value(), diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java index 55db6eb9..77366f9f 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java @@ -31,6 +31,7 @@ import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Optional; import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.AfterAll; @@ -151,10 +152,9 @@ class DurableOperationSubmissionOutboxIntegrationTest { private static OperationCommand command() { return new OperationCommand( - ID, "reports.generate", "alice", - null, + Optional.empty(), new RequestFingerprint("a".repeat(64)), "{\"range\":\"2026-08\"}", Duration.ofDays(1)); @@ -224,6 +224,9 @@ class DurableOperationSubmissionOutboxIntegrationTest { new JpaOutboxStore(outbox, (now, limit) -> List.of()), new JsonIntegrationEventEncoder(List.of(new DurableOperationSubmittedContract())), transactions, + // One id every time: a resubmission's minted id is discarded, so the tests read the + // first submission's id back whichever call they make. + () -> ID, Clock.fixed(NOW, ZoneOffset.UTC)); } } diff --git a/src/application/core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimAttempt.java b/src/application/core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimAttempt.java index aeff40dc..35885ba0 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimAttempt.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimAttempt.java @@ -13,6 +13,10 @@ import java.util.regex.Pattern; * until the record expired (round6 RR6-02-01, {@code IdempotencyStoreContract}). One attempt is one * sender at a time: a handle from before a takeover is stale, but two calls sending the same * attempt at once are not told apart — retry after the call has returned, not beside it. + * + *

The owner token is the store's: 32 secure-random bytes as 64 lower-case hex characters, which + * both stores compare as a fixed-width value. It is not a lease owner token (Base64URL, chosen by + * the lease caller); the transaction {@code OperationId} Javadoc compares the identities. */ public record IdempotencyClaimAttempt(String ownerToken, OperationId operationId) { diff --git a/src/application/core/src/main/java/dev/caskeleton/application/lease/LeaseValidation.java b/src/application/core/src/main/java/dev/caskeleton/application/lease/LeaseValidation.java index 4618c613..6d32894d 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/lease/LeaseValidation.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/lease/LeaseValidation.java @@ -11,6 +11,11 @@ final class LeaseValidation { private LeaseValidation() {} + /** + * A lease's operation id or owner token: 16..128 Base64URL characters, so it fits a header and a + * Redis key without escaping and is long enough to be unguessable. Narrower than the transaction + * {@code OperationId}, whose Javadoc compares the operation-shaped ids and why they differ. + */ static String opaqueToken(String value, String field) { if (value == null || value.length() < 16 diff --git a/src/application/core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationIdentity.java b/src/application/core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationIdentity.java index adc509c3..b4958ab6 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationIdentity.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationIdentity.java @@ -1,5 +1,9 @@ package dev.caskeleton.application.messaging.event; +import dev.caskeleton.shared.digest.Sha256; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; import java.util.regex.Pattern; /** @@ -73,6 +77,35 @@ public final class IntegrationIdentity { return value != null && UUID_V7.matcher(value).matches(); } + /** + * A canonical lower-case UUIDv7 derived from {@code value}: the same value and instant always + * give the same id. + * + *

For an event whose id must follow from something that is not itself a UUIDv7 — an operation + * id a client chose, say — so a retry drafts the same event. The time field is {@code at}, so the + * id orders like a minted one; the other 74 bits are the SHA-256 of {@code value}. Kept here, + * with the grammar it must satisfy, rather than in each use case that needs one: the derivation + * is messaging identity, not the use case's own rule. + * + * @param value what the id is derived from + * @param at the instant its time field carries + * @return a canonical lower-case UUIDv7 + */ + public static String uuidV7Derived(String value, Instant at) { + Objects.requireNonNull(value, "value"); + Objects.requireNonNull(at, "at"); + byte[] digest = Sha256.ofUtf8(value).bytes(); + long millis = at.toEpochMilli() & 0xFFFF_FFFF_FFFFL; + long randA = ((digest[0] & 0x0FL) << 8) | (digest[1] & 0xFFL); + long mostSignificant = (millis << 16) | (0x7L << 12) | randA; + long randB = 0; + for (int i = 2; i < 10; i++) { + randB = (randB << 8) | (digest[i] & 0xFFL); + } + long leastSignificant = (randB & 0x3FFF_FFFF_FFFF_FFFFL) | 0x8000_0000_0000_0000L; + return new UUID(mostSignificant, leastSignificant).toString(); + } + /** Refuses a correlation or causation id outside the grammar or the bound. */ static void requireCorrelation(String field, String value) { if (!isCanonical(value, CORRELATION_MAX_LENGTH)) { diff --git a/src/application/core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationCommand.java b/src/application/core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationCommand.java index aa9fc88e..6b4e0a6b 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationCommand.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationCommand.java @@ -1,19 +1,23 @@ package dev.caskeleton.application.operation; import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.tenant.TenantId; import java.util.Objects; +import java.util.Optional; /** * A caller asking to cancel one operation. * * @param operationId the identity to cancel * @param principal the authenticated caller, or null when the caller is not authenticated - * @param tenantId the caller's tenant, or null when the request is not tenant scoped + * @param tenant the caller's tenant, empty when the request is not tenant scoped */ public record CancelDurableOperationCommand( - DurableOperationId operationId, String principal, String tenantId) implements Command { + DurableOperationId operationId, String principal, Optional tenant) + implements Command { public CancelDurableOperationCommand { Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(tenant, "tenant"); } } diff --git a/src/application/core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationUseCase.java b/src/application/core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationUseCase.java index 6c3c2449..9aa35d16 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationUseCase.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationUseCase.java @@ -63,7 +63,7 @@ public class CancelDurableOperationUseCase .filter( operation -> DurableOperationAccessPolicy.mayAccess( - operation, command.principal(), command.tenantId())) + operation, command.principal(), command.tenant())) .map(visible -> operations.cancel(command.operationId(), command.principal(), now)); }); } diff --git a/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationAccessPolicy.java b/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationAccessPolicy.java index 6674f707..3e799bf6 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationAccessPolicy.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationAccessPolicy.java @@ -1,6 +1,8 @@ package dev.caskeleton.application.operation; +import dev.caskeleton.application.tenant.TenantId; import java.util.Objects; +import java.util.Optional; /** * Who may read or cancel an operation: the principal that submitted it, in the tenant it was @@ -20,10 +22,21 @@ final class DurableOperationAccessPolicy { * * @param operation the stored operation * @param principal the authenticated caller, or null when the caller is not authenticated - * @param tenantId the caller's tenant, or null when the request is not tenant scoped + * @param tenant the caller's tenant, empty when the request is not tenant scoped */ - static boolean mayAccess(DurableOperation operation, String principal, String tenantId) { + static boolean mayAccess( + DurableOperation operation, String principal, Optional tenant) { return operation.principal().equals(principal) - && Objects.equals(operation.tenantId(), tenantId); + && Objects.equals(operation.tenantId(), storedForm(tenant)); + } + + /** + * The tenant as the operation row holds it: its value, or null when not tenant scoped. + * + * @param tenant the caller's tenant + * @return the stored form + */ + static String storedForm(Optional tenant) { + return tenant.map(TenantId::value).orElse(null); } } diff --git a/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationId.java b/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationId.java index 573e0135..f8c85981 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationId.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationId.java @@ -10,9 +10,10 @@ import java.util.regex.Pattern; */ public record DurableOperationId(String value) { - // Bounded and free of anything that needs escaping. The identifier travels to whatever transport - // published the operation and is handed back to callers, so a value that one encoding mangles is - // a defect that only appears for some clients. + // Bounded and free of anything that needs escaping: RFC 3986 unreserved characters, because the + // identifier is a URL path segment (/operations/{id}) and is handed back to callers, so a value + // that one encoding mangles is a defect that only appears for some clients. Narrower than the + // transaction OperationId for that reason (its Javadoc compares the operation-shaped ids). private static final Pattern GRAMMAR = Pattern.compile("[A-Za-z0-9._~-]{1,128}"); public DurableOperationId { diff --git a/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationStorePort.java b/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationStorePort.java index 66c718b2..887f5c72 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationStorePort.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationStorePort.java @@ -27,8 +27,8 @@ public interface DurableOperationStorePort { * rather than a second one is what makes a resubmission safe while the first is still running. * * @param submission what was accepted - * @return the operation, and whether this call created it; a retry under the same operation id is - * not a creation + * @return the operation, and whether this call created it; a resubmission that finds the + * operation an earlier call created, under its own fresh id, is not a creation */ DurableOperationSubmitResult submit(DurableOperationSubmission submission); diff --git a/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmitResult.java b/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmitResult.java index 1d43820a..2c0edd5d 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmitResult.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmitResult.java @@ -5,10 +5,10 @@ import java.util.Objects; /** * What a store did with a submission. * - *

{@code created} comes from the store's own write, not from comparing identifiers afterwards. A - * retry under the same operation id finds the operation it created itself, and an identifier - * comparison cannot tell that retry from the first call — which is how a retry appended its outbox - * event a second time. + *

{@code created} comes from the store's own write, not from comparing identifiers afterwards. + * Every call mints a fresh operation id, and a resubmission is found by scope and fingerprint as + * the operation the first call created; only the store's write tells that resubmission from the + * first call, which is what keeps it from appending its outbox event a second time. * * @param operation the operation holding the submission's scope * @param created whether this call inserted it diff --git a/src/application/core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationQuery.java b/src/application/core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationQuery.java index e6ce2ae6..afb85f8f 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationQuery.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationQuery.java @@ -1,19 +1,22 @@ package dev.caskeleton.application.operation; import dev.caskeleton.application.query.Query; +import dev.caskeleton.application.tenant.TenantId; import java.util.Objects; +import java.util.Optional; /** * A caller asking to read one operation. * * @param operationId the identity being polled * @param principal the authenticated caller, or null when the caller is not authenticated - * @param tenantId the caller's tenant, or null when the request is not tenant scoped + * @param tenant the caller's tenant, empty when the request is not tenant scoped */ public record GetDurableOperationQuery( - DurableOperationId operationId, String principal, String tenantId) implements Query { + DurableOperationId operationId, String principal, Optional tenant) implements Query { public GetDurableOperationQuery { Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(tenant, "tenant"); } } diff --git a/src/application/core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationUseCase.java b/src/application/core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationUseCase.java index 3fb1bfed..4a66ef81 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationUseCase.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationUseCase.java @@ -15,7 +15,7 @@ import java.util.Optional; transactionMode = TransactionMode.READ_ONLY, idempotency = Idempotency.IDEMPOTENT, repositoryAccess = RepositoryAccess.READ_REPOSITORY) -public final class GetDurableOperationUseCase +public class GetDurableOperationUseCase implements QueryUseCase> { private final DurableOperationStorePort operations; @@ -47,6 +47,6 @@ public final class GetDurableOperationUseCase .filter( operation -> DurableOperationAccessPolicy.mayAccess( - operation, query.principal(), query.tenantId())); + operation, query.principal(), query.tenant())); } } diff --git a/src/application/core/src/main/java/dev/caskeleton/application/operation/OperationCommand.java b/src/application/core/src/main/java/dev/caskeleton/application/operation/OperationCommand.java index 0d401654..d56f22bb 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/operation/OperationCommand.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/operation/OperationCommand.java @@ -2,34 +2,34 @@ package dev.caskeleton.application.operation; import dev.caskeleton.application.command.Command; import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.tenant.TenantId; import java.time.Duration; import java.util.Objects; +import java.util.Optional; /** * A request to run work asynchronously. * - *

The caller supplies the operation id rather than the store minting one. That is what lets the - * transport hand back a {@code Location} it already knows, and it makes the whole submission one - * value the caller can retry: a generated id would differ on every attempt, so a retry after an - * ambiguous failure would create a second operation. + *

No operation id: {@link SubmitDurableOperationUseCase} mints one with {@link + * DurableOperationIdFactory}, and a resubmission of the same work by the same caller is recognised + * by its scope and payload fingerprint, not by an id the caller kept. The transport used to mint it + * and hand it in (round9 review 2026-11-12, RR9-05-13). * *

There is no event type to choose. Every accepted operation announces itself with the one * {@link DurableOperationSubmittedContract} event, which only wakes a worker; letting a caller name * the type would let it publish any event the broker carries. * - * @param operationId the identity to use * @param operationName what work this is * @param principal who is asking - * @param tenantId the tenant, or null when the operation is not tenant scoped + * @param tenant the tenant, empty when the operation is not tenant scoped * @param fingerprint the semantic fingerprint of the request * @param payload the serialized request a worker will execute * @param timeToLive how long the record and its result stay available */ public record OperationCommand( - DurableOperationId operationId, String operationName, String principal, - String tenantId, + Optional tenant, RequestFingerprint fingerprint, String payload, Duration timeToLive) @@ -39,8 +39,8 @@ public record OperationCommand( public static final Duration DEFAULT_TIME_TO_LIVE = Duration.ofDays(1); public OperationCommand { - Objects.requireNonNull(operationId, "operationId"); Objects.requireNonNull(operationName, "operationName"); + Objects.requireNonNull(tenant, "tenant"); Objects.requireNonNull(fingerprint, "fingerprint"); Objects.requireNonNull(payload, "payload"); Objects.requireNonNull(timeToLive, "timeToLive"); diff --git a/src/application/core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java b/src/application/core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java index e5d8719c..45471cef 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java @@ -15,12 +15,10 @@ import dev.caskeleton.application.security.RequiresPermission; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.usecase.CommandUseCase; -import dev.caskeleton.shared.digest.Sha256; import java.time.Clock; import java.time.Instant; import java.util.Objects; import java.util.Optional; -import java.util.UUID; /** * Accepts long-running work: one transaction that writes the operation row and the outbox row. @@ -49,8 +47,9 @@ import java.util.UUID; @RequiresPermission("operation:submit") @UseCaseCapability( transactionMode = TransactionMode.WRITE, - // KEYED, not IDEMPOTENT. Re-running this use case is only safe because the caller supplies the - // operation id and the fingerprint scope; without a key it would accept the same work twice. + // KEYED, not IDEMPOTENT. Re-running this use case is only safe because the store recognises the + // submission scope and the payload fingerprint; without that key it would accept the same work + // twice. idempotency = Idempotency.KEYED, repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, // False, and load-bearing. Nothing here reaches the broker: the outbox row is the publish @@ -72,6 +71,7 @@ public class SubmitDurableOperationUseCase private final OutboxAppendPort outbox; private final IntegrationEventEncoderPort encoder; private final TransactionPort transactions; + private final DurableOperationIdFactory operationIds; private final Clock clock; /** @@ -82,6 +82,7 @@ public class SubmitDurableOperationUseCase * @param encoder turns the submission event into the validated event the outbox stores; it must * know {@link DurableOperationSubmittedContract} * @param transactions opens the write transaction both share + * @param operationIds mints the id of a new submission * @param clock the submission clock */ public SubmitDurableOperationUseCase( @@ -89,8 +90,10 @@ public class SubmitDurableOperationUseCase OutboxAppendPort outbox, IntegrationEventEncoderPort encoder, TransactionPort transactions, + DurableOperationIdFactory operationIds, Clock clock) { this.operations = Objects.requireNonNull(operations, "operations"); + this.operationIds = Objects.requireNonNull(operationIds, "operationIds"); this.outbox = Objects.requireNonNull(outbox, "outbox"); this.encoder = Objects.requireNonNull(encoder, "encoder"); this.transactions = Objects.requireNonNull(transactions, "transactions"); @@ -110,18 +113,20 @@ public class SubmitDurableOperationUseCase () -> { DurableOperationSubmission submission = new DurableOperationSubmission( - command.operationId(), + // Minted per call. A resubmission's id is never stored: the store answers with + // the operation the first submission created. + operationIds.newOperationId(), command.operationName(), command.principal(), - command.tenantId(), + DurableOperationAccessPolicy.storedForm(command.tenant()), command.fingerprint(), command.payload(), clock.instant(), command.timeToLive()); DurableOperationSubmitResult submitted = operations.submit(submission); DurableOperation operation = submitted.operation(); - // The store's answer, not an id comparison: a retry under the same operation id finds - // the operation it created itself, and the ids match. + // The store's answer, not an id comparison: every call mints a fresh id, and a retry of + // the same submission is found by the store as the operation the first call created. boolean alreadyAccepted = !submitted.created(); if (!alreadyAccepted) { @@ -147,8 +152,8 @@ public class SubmitDurableOperationUseCase // Single-tenant scope even when the command names a tenant: the event only wakes a worker, the // tenant travels in the stored operation, and mapping a TenantId into the lower-case scope // grammar is the messaging platform's decision, not this use case's. - // No request correlation: the event correlates to the operation itself, so a retry under the - // same operation id produces the same event. + // No request correlation: the event correlates to the operation itself, so a retry that the + // store resolves to the same operation produces the same event. return IntegrationEventDrafts.draft( CONTRACT, new EventId(identity), @@ -160,15 +165,15 @@ public class SubmitDurableOperationUseCase } /** - * The operation id itself when it is a canonical lower-case UUIDv7 — every id the HTTP adapter - * mints is — and otherwise a UUIDv7 derived from it. + * The operation id itself when it is a canonical lower-case UUIDv7 — every id the shipped {@code + * DurableOperationIdFactory} mints is — and otherwise a UUIDv7 derived from it. * *

The event id is the messaging platform's message id, which is a canonical lower-case UUIDv7; - * the draft refuses anything else, so an operation id a client chose ({@code ~report}, a v4, an - * upper-case spelling) cannot be the event id. The derived id keeps the event deterministic for - * the operation — the same id and submission time always give the same event id — and the payload - * carries the operation id unchanged for the worker. Its time field is the submission time, so it - * orders like a minted one; its other 74 bits are the SHA-256 of the operation id. + * the draft refuses anything else, so an id a deployment's own factory mints ({@code ~report}, a + * v4, an upper-case spelling) cannot be the event id. The derived id keeps the event + * deterministic for the operation — the same id and submission time always give the same event id + * — and the payload carries the operation id unchanged for the worker. The derivation is {@link + * IntegrationIdentity#uuidV7Derived}, with the submission time as its time field. * *

It replaced an {@code operation-} digest, which fit the stored identity grammar and * passed the append, and which the bridge then refused, parking the committed event (review @@ -179,15 +184,6 @@ public class SubmitDurableOperationUseCase if (IntegrationIdentity.isCanonicalUuidV7(value)) { return value; } - byte[] digest = Sha256.ofUtf8(value).bytes(); - long millis = submittedAt.toEpochMilli() & 0xFFFF_FFFF_FFFFL; - long randA = ((digest[0] & 0x0FL) << 8) | (digest[1] & 0xFFL); - long mostSignificant = (millis << 16) | (0x7L << 12) | randA; - long randB = 0; - for (int i = 2; i < 10; i++) { - randB = (randB << 8) | (digest[i] & 0xFFL); - } - long leastSignificant = (randB & 0x3FFF_FFFF_FFFF_FFFFL) | 0x8000_0000_0000_0000L; - return new UUID(mostSignificant, leastSignificant).toString(); + return IntegrationIdentity.uuidV7Derived(value, submittedAt); } } diff --git a/src/application/core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java b/src/application/core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java index 68ae05cf..0425030a 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java @@ -40,7 +40,7 @@ import java.util.function.Supplier; idempotency = Idempotency.IDEMPOTENT, repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, externalOutboundAllowed = true) -public final class PublishPendingOutboxEventsUseCase +public class PublishPendingOutboxEventsUseCase implements CommandUseCase { /** The failure code of a thrown failure whose type has no simple name. */ diff --git a/src/application/core/src/main/java/dev/caskeleton/application/transaction/OperationId.java b/src/application/core/src/main/java/dev/caskeleton/application/transaction/OperationId.java index f9704f17..6e230d94 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/transaction/OperationId.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/transaction/OperationId.java @@ -7,6 +7,15 @@ import java.util.Objects; * *

The value is intentionally opaque. Adapters may use it for reconciliation, but must not invent * a replacement identity after an uncertain commit. + * + *

The widest of the operation-shaped identities, on purpose: the caller chooses it and it is + * only ever compared, never put in a URL or a key, so any printable ASCII is allowed. The others + * are narrower because of where they travel — a {@link + * dev.caskeleton.application.operation.DurableOperationId} is a URL path segment, a lease's + * operation id and owner token are Base64URL so they fit a header and a Redis key unescaped, and an + * idempotency owner token is the 32 random bytes the store mints, as 64 hex characters. One value + * type for all four would either let a path segment carry {@code /} or refuse caller ids that are + * valid today (round9 review 2026-11-12, RR9-05-11). */ public record OperationId(String value) { diff --git a/src/application/core/src/main/java/dev/caskeleton/application/transaction/ReadConsistency.java b/src/application/core/src/main/java/dev/caskeleton/application/transaction/ReadConsistency.java deleted file mode 100644 index 23912c34..00000000 --- a/src/application/core/src/main/java/dev/caskeleton/application/transaction/ReadConsistency.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.transaction; - -/** Application-owned read consistency vocabulary. */ -public enum ReadConsistency { - STRONG, - READ_YOUR_WRITES, - EVENTUAL, - BOUNDED_STALENESS -} diff --git a/src/application/core/src/test/java/dev/caskeleton/application/operation/CancelDurableOperationUseCaseTest.java b/src/application/core/src/test/java/dev/caskeleton/application/operation/CancelDurableOperationUseCaseTest.java index 8c845cac..69219b0a 100644 --- a/src/application/core/src/test/java/dev/caskeleton/application/operation/CancelDurableOperationUseCaseTest.java +++ b/src/application/core/src/test/java/dev/caskeleton/application/operation/CancelDurableOperationUseCaseTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStore; +import dev.caskeleton.application.tenant.TenantId; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.time.Clock; import java.time.Duration; @@ -28,7 +29,8 @@ class CancelDurableOperationUseCaseTest { operations.submit(submission("t-1")); // when - useCase.handle(new CancelDurableOperationCommand(ID, "alice", "t-1")); + useCase.handle( + new CancelDurableOperationCommand(ID, "alice", Optional.of(new TenantId("t-1")))); // then assertThat(operations.find(ID, "alice", NOW).orElseThrow().state()) @@ -45,7 +47,7 @@ class CancelDurableOperationUseCaseTest { // when Optional canceled = - useCase.handle(new CancelDurableOperationCommand(ID, "alice", null)); + useCase.handle(new CancelDurableOperationCommand(ID, "alice", Optional.empty())); // then assertThat(canceled).contains(false); @@ -58,7 +60,8 @@ class CancelDurableOperationUseCaseTest { // when Optional canceled = - useCase.handle(new CancelDurableOperationCommand(ID, "alice", "t-2")); + useCase.handle( + new CancelDurableOperationCommand(ID, "alice", Optional.of(new TenantId("t-2")))); // then assertThat(canceled).isEmpty(); @@ -70,7 +73,8 @@ class CancelDurableOperationUseCaseTest { operations.submit(submission(null)); // when - Optional canceled = useCase.handle(new CancelDurableOperationCommand(ID, null, null)); + Optional canceled = + useCase.handle(new CancelDurableOperationCommand(ID, null, Optional.empty())); // then assertThat(canceled).isEmpty(); diff --git a/src/application/core/src/test/java/dev/caskeleton/application/operation/DurableOperationAccessPolicyTest.java b/src/application/core/src/test/java/dev/caskeleton/application/operation/DurableOperationAccessPolicyTest.java index 44c66954..7be18cc6 100644 --- a/src/application/core/src/test/java/dev/caskeleton/application/operation/DurableOperationAccessPolicyTest.java +++ b/src/application/core/src/test/java/dev/caskeleton/application/operation/DurableOperationAccessPolicyTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.application.operation; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.application.tenant.TenantId; import java.time.Instant; import java.util.Optional; import org.junit.jupiter.params.ParameterizedTest; @@ -33,7 +34,7 @@ class DurableOperationAccessPolicyTest { String owner, String ownerTenant, String caller, String callerTenant, boolean expected) { assertThat( DurableOperationAccessPolicy.mayAccess( - operation(owner, ownerTenant), caller, callerTenant)) + operation(owner, ownerTenant), caller, TenantId.optional(callerTenant))) .isEqualTo(expected); } diff --git a/src/application/core/src/test/java/dev/caskeleton/application/operation/GetDurableOperationUseCaseTest.java b/src/application/core/src/test/java/dev/caskeleton/application/operation/GetDurableOperationUseCaseTest.java index 292cce01..3cb19a13 100644 --- a/src/application/core/src/test/java/dev/caskeleton/application/operation/GetDurableOperationUseCaseTest.java +++ b/src/application/core/src/test/java/dev/caskeleton/application/operation/GetDurableOperationUseCaseTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStore; +import dev.caskeleton.application.tenant.TenantId; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.time.Clock; import java.time.Duration; @@ -29,7 +30,7 @@ class GetDurableOperationUseCaseTest { // when Optional read = - useCase.handle(new GetDurableOperationQuery(ID, "alice", "t-1")); + useCase.handle(new GetDurableOperationQuery(ID, "alice", Optional.of(new TenantId("t-1")))); // then assertThat(read).contains(submitted); @@ -42,7 +43,7 @@ class GetDurableOperationUseCaseTest { // when Optional read = - useCase.handle(new GetDurableOperationQuery(ID, "alice", "t-2")); + useCase.handle(new GetDurableOperationQuery(ID, "alice", Optional.of(new TenantId("t-2")))); // then assertThat(read).isEmpty(); @@ -54,7 +55,8 @@ class GetDurableOperationUseCaseTest { operations.submit(submission(null)); // when - Optional read = useCase.handle(new GetDurableOperationQuery(ID, null, null)); + Optional read = + useCase.handle(new GetDurableOperationQuery(ID, null, Optional.empty())); // then assertThat(read).isEmpty(); diff --git a/src/application/core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java b/src/application/core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java index ac469e2d..9053cfab 100644 --- a/src/application/core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java +++ b/src/application/core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java @@ -16,7 +16,10 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; +import java.util.ArrayDeque; +import java.util.Deque; import java.util.List; +import java.util.Optional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -34,7 +37,7 @@ class SubmitDurableOperationUseCaseTest { private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - /** An id the HTTP adapter mints: a canonical lower-case UUIDv7, used as the event id itself. */ + /** An id the factory mints: a canonical lower-case UUIDv7, used as the event id itself. */ private static final String OPERATION_UUID = "01994e11-4d88-7000-8000-0000000000a1"; private static final DurableOperationId ID = new DurableOperationId(OPERATION_UUID); @@ -48,16 +51,25 @@ class SubmitDurableOperationUseCaseTest { private final FailingOutbox outbox = new FailingOutbox(transactions); private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder(new DurableOperationSubmittedContract()); + + /** What the id factory mints, in order: one id per submission, kept or not. */ + private final Deque mintable = + new ArrayDeque<>(List.of(ID, new DurableOperationId("op-2"), new DurableOperationId("op-3"))); + private final CommandUseCase useCase = new SubmitDurableOperationUseCase( - operations, outbox, encoder, transactions, Clock.fixed(NOW, ZoneOffset.UTC)); + operations, + outbox, + encoder, + transactions, + mintable::removeFirst, + Clock.fixed(NOW, ZoneOffset.UTC)); - private static OperationCommand command(DurableOperationId id, String hash) { + private static OperationCommand command(String hash) { return new OperationCommand( - id, "reports.generate", "alice", - null, + Optional.empty(), new RequestFingerprint(hash), "{\"range\":\"2026-08\"}", Duration.ofHours(6)); @@ -66,7 +78,7 @@ class SubmitDurableOperationUseCaseTest { @Test @DisplayName("an accepted submission writes both the operation and the outbox event") void submissionWritesBoth() { - OperationAcceptance acceptance = useCase.handle(command(ID, "a".repeat(64))); + OperationAcceptance acceptance = useCase.handle(command("a".repeat(64))); assertThat(acceptance.operationId()).isEqualTo(ID); assertThat(acceptance.alreadyAccepted()).isFalse(); @@ -74,10 +86,20 @@ class SubmitDurableOperationUseCaseTest { assertThat(outbox.appended()).hasSize(1); } + @Test + @DisplayName("operation id는 호출자가 아니라 use case가 id factory로 만든다") + void theOperationIdIsMintedByTheUseCase() { + // when + OperationAcceptance acceptance = useCase.handle(command("d".repeat(64))); + + // then + assertThat(List.of(acceptance.operationId(), mintable.size())).containsExactly(ID, 2); + } + @Test @DisplayName("both writes happen inside one transaction") void bothWritesShareOneTransaction() { - useCase.handle(command(ID, "a".repeat(64))); + useCase.handle(command("a".repeat(64))); // Not an implementation detail. Outside one transaction the two writes can commit // independently, and every failure mode this use case exists to prevent comes back. The @@ -92,7 +114,7 @@ class SubmitDurableOperationUseCaseTest { void rollbackLeavesNothing() { outbox.failNext = true; - assertThatThrownBy(() -> useCase.handle(command(ID, "a".repeat(64)))) + assertThatThrownBy(() -> useCase.handle(command("a".repeat(64)))) .isInstanceOf(IllegalStateException.class); assertThat(operations.size()).isZero(); @@ -102,10 +124,9 @@ class SubmitDurableOperationUseCaseTest { @Test @DisplayName("an identical resubmission returns the first operation and publishes nothing new") void resubmissionReusesTheFirstOperation() { - useCase.handle(command(ID, "a".repeat(64))); + useCase.handle(command("a".repeat(64))); - OperationAcceptance repeat = - useCase.handle(command(new DurableOperationId("op-2"), "a".repeat(64))); + OperationAcceptance repeat = useCase.handle(command("a".repeat(64))); // The client is pointed at the work that is actually running. Starting a second operation // would run the same report twice and hand back an id for the copy. @@ -116,12 +137,12 @@ class SubmitDurableOperationUseCaseTest { } @Test - void retryUnderTheSameOperationIdAppendsTheOutboxEventOnlyOnce() { + void aRetriedSubmissionAppendsTheOutboxEventOnlyOnce() { // given - useCase.handle(command(ID, "a".repeat(64))); + useCase.handle(command("a".repeat(64))); // when - OperationAcceptance retry = useCase.handle(command(ID, "a".repeat(64))); + OperationAcceptance retry = useCase.handle(command("a".repeat(64))); // then assertThat(List.of(retry.alreadyAccepted(), outbox.appended().size())).containsExactly(true, 1); @@ -130,10 +151,9 @@ class SubmitDurableOperationUseCaseTest { @Test @DisplayName("a different request under the same principal is a different operation") void differentRequestsAreDifferentOperations() { - useCase.handle(command(ID, "a".repeat(64))); + useCase.handle(command("a".repeat(64))); - OperationAcceptance second = - useCase.handle(command(new DurableOperationId("op-2"), "b".repeat(64))); + OperationAcceptance second = useCase.handle(command("b".repeat(64))); assertThat(second.alreadyAccepted()).isFalse(); assertThat(operations.size()).isEqualTo(2); @@ -143,7 +163,7 @@ class SubmitDurableOperationUseCaseTest { @Test void theOutboxEventIsTheSubmittedContractAnchoredToTheOperation() { // given - useCase.handle(command(ID, "a".repeat(64))); + useCase.handle(command("a".repeat(64))); // when ValidatedIntegrationEvent event = outbox.appended().get(0); @@ -167,7 +187,7 @@ class SubmitDurableOperationUseCaseTest { @Test void theSubmittedEventNamesTheOperationAndNotTheRequest() { // when - useCase.handle(command(ID, "a".repeat(64))); + useCase.handle(command("a".repeat(64))); // then // The worker reads what to run from the submission it claims; the request never travels. @@ -200,13 +220,13 @@ class SubmitDurableOperationUseCaseTest { } @Test - @DisplayName("UUIDv7이 아닌 operation id로 받은 작업도 outbox에 발행할 수 있는 event로 남는다") - void aSubmissionUnderAClientChosenIdStillAppendsAPublishableEvent() { + @DisplayName("id factory가 UUIDv7이 아닌 id를 만들어도 outbox에 발행할 수 있는 event로 남는다") + void aSubmissionUnderANonUuidV7IdStillAppendsAPublishableEvent() { // given - DurableOperationId clientChosen = new DurableOperationId("~report"); + mintable.addFirst(new DurableOperationId("~report")); // when - useCase.handle(command(clientChosen, "c".repeat(64))); + useCase.handle(command("c".repeat(64))); // then assertThat(outbox.appended()) diff --git a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/FileMetadataPort.java b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/FileMetadataPort.java index 1b5e7b0d..fa5ffde3 100644 --- a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/FileMetadataPort.java +++ b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/FileMetadataPort.java @@ -10,14 +10,36 @@ import java.util.Optional; * Authoritative file metadata port. * *

Every transition is conditional on both the expected version and the expected state, so two - * writers racing on the same record produce exactly one winner and one optimistic conflict. + * writers racing on the same record produce exactly one winner and one optimistic conflict. How + * each write fails is part of the contract, because the use cases decide from the failure whether + * to retry, report a conflict or treat the file as gone. A record that does not exist fails as a + * lost precondition, like one that moved on. */ public interface FileMetadataPort { + /** + * Records a new file in {@code CREATED}. + * + * @return the stored record, version 0 + * @throws RuntimeException the store's own refusal when a record already exists under {@code + * draft.fileId()}; file ids are server-minted, so that is a defect, not a race to recover + * from + */ FileRecord insert(FileRecordDraft draft); Optional find(FileId fileId); + /** + * Moves a record from {@code expectedState} at {@code expectedVersion} to {@code targetState}. + * + * @return the record as stored after the move + * @throws IllegalStateException when {@code expectedState} may never move to {@code targetState} + * — a caller defect, refused before anything is written + * @throws dev.caskeleton.application.fileserver.api.error.FileserverException with {@code + * CONCURRENT_MODIFICATION} when the record is no longer at that version and state + * @throws dev.caskeleton.application.fileserver.api.error.FileNotFoundException with {@code + * FILE_NOT_FOUND} when the record disappeared during the move + */ FileRecord transition( FileId fileId, long expectedVersion, @@ -25,6 +47,16 @@ public interface FileMetadataPort { FileState targetState, FileRecordMutation mutation); + /** + * Moves a record at {@code expectedVersion} in a deletable state to {@code DELETING}. + * + * @return the record as stored after the move + * @throws dev.caskeleton.application.fileserver.api.error.FileserverException with {@code + * CONCURRENT_MODIFICATION} when the record is no longer at that version or not in a deletable + * state + * @throws dev.caskeleton.application.fileserver.api.error.FileNotFoundException with {@code + * FILE_NOT_FOUND} when the record disappeared during the move + */ FileRecord markDeleting(FileId fileId, long expectedVersion); /** @@ -33,6 +65,12 @@ public interface FileMetadataPort { *

A namespace is a metadata grouping, so this changes one column and never touches the * immutable physical object. Copying gigabytes to express an ownership change would also break * every strong validator already handed to clients. + * + * @return the record as stored after the move + * @throws dev.caskeleton.application.fileserver.api.error.FileserverException with {@code + * CONCURRENT_MODIFICATION} when the record is no longer {@code READY} at that version + * @throws dev.caskeleton.application.fileserver.api.error.FileNotFoundException with {@code + * FILE_NOT_FOUND} when the record disappeared during the move */ FileRecord relocate(FileId fileId, long expectedVersion, StorageNamespace targetNamespace); diff --git a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/UploadSessionPort.java b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/UploadSessionPort.java index 9116e18f..42062eeb 100644 --- a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/UploadSessionPort.java +++ b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/UploadSessionPort.java @@ -18,6 +18,14 @@ public interface UploadSessionPort { Optional find(UploadId uploadId); + /** + * Takes the writer lease on an upload that holds none, or whose lease has lapsed. + * + * @return the new lease, with a fresh token and the session version after the claim + * @throws dev.caskeleton.application.fileserver.api.error.FileserverException with {@code + * CONCURRENT_MODIFICATION} when another owner holds an unexpired lease, the session is no + * longer at {@code expectedVersion}, or the upload has expired (then not retryable) + */ WriterLease acquireLease( UploadId uploadId, String owner, Instant now, Duration leaseDuration, long expectedVersion); @@ -34,6 +42,15 @@ public interface UploadSessionPort { */ WriterLease renewLease(WriterLease lease, Instant now, Duration leaseDuration); + /** + * Advances the committed offset from {@code expectedOffset} to {@code committedOffset} for the + * holder of {@code lease}. + * + * @return the session as stored after the commit + * @throws dev.caskeleton.application.fileserver.api.error.FileserverException with {@code + * CONCURRENT_MODIFICATION} when the lease token no longer holds the session or the stored + * offset is not {@code expectedOffset}; nothing is committed + */ UploadSession commitOffset( UploadId uploadId, WriterLease lease, long expectedOffset, long committedOffset); diff --git a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/observability/FileserverSpans.java b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/observability/FileserverSpans.java deleted file mode 100644 index ab6fd5df..00000000 --- a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/observability/FileserverSpans.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.application.fileserver.observability; - -/** - * The exact span names the design fixes. - * - *

Naming them once means a dashboard or an alert built on one of these keeps working when the - * code that emits it moves. A span name invented at a call site would silently break both. - */ -public final class FileserverSpans { - - public static final String UPLOAD_CREATE = "upload.create"; - public static final String UPLOAD_APPEND = "upload.append"; - public static final String UPLOAD_FINALIZE = "upload.finalize"; - public static final String VERIFY_DIGEST = "verify.digest"; - public static final String VERIFY_MEDIA_TYPE = "verify.media-type"; - public static final String VERIFY_MALWARE = "verify.malware"; - public static final String STORAGE_PUBLISH = "storage.publish"; - public static final String STORAGE_STAT = "storage.stat"; - public static final String METADATA_TRANSITION = "metadata.transition"; - public static final String DOWNLOAD_AUTHORIZE = "download.authorize"; - public static final String DOWNLOAD_RESOLVE_RANGE = "download.resolve-range"; - public static final String DOWNLOAD_OPEN = "download.open"; - public static final String DOWNLOAD_DELEGATE = "download.delegate"; - public static final String CLEANUP_ITEM = "cleanup.item"; - public static final String RECONCILE_FILE = "reconcile.file"; - - private FileserverSpans() {} -} diff --git a/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/api/security/OriginalFilenamePolicyTest.java b/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/api/security/OriginalFilenamePolicyTest.java index 05357b59..0bd7a4c9 100644 Binary files a/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/api/security/OriginalFilenamePolicyTest.java and b/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/api/security/OriginalFilenamePolicyTest.java differ diff --git a/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/observability/FileserverObservabilityTest.java b/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/observability/FileserverObservabilityTest.java index affc9182..6a240a63 100644 --- a/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/observability/FileserverObservabilityTest.java +++ b/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/observability/FileserverObservabilityTest.java @@ -76,30 +76,6 @@ class FileserverObservabilityTest { } } - @Test - void everyDesignSpanNameIsDeclaredExactlyOnce() { - List spans = - List.of( - FileserverSpans.UPLOAD_CREATE, - FileserverSpans.UPLOAD_APPEND, - FileserverSpans.UPLOAD_FINALIZE, - FileserverSpans.VERIFY_DIGEST, - FileserverSpans.VERIFY_MEDIA_TYPE, - FileserverSpans.VERIFY_MALWARE, - FileserverSpans.STORAGE_PUBLISH, - FileserverSpans.STORAGE_STAT, - FileserverSpans.METADATA_TRANSITION, - FileserverSpans.DOWNLOAD_AUTHORIZE, - FileserverSpans.DOWNLOAD_RESOLVE_RANGE, - FileserverSpans.DOWNLOAD_OPEN, - FileserverSpans.DOWNLOAD_DELEGATE, - FileserverSpans.CLEANUP_ITEM, - FileserverSpans.RECONCILE_FILE); - - assertThat(spans).doesNotHaveDuplicates().hasSize(15); - assertThat(spans).allSatisfy(name -> assertThat(name).matches("[a-z]+\\.[a-z-]+")); - } - @Test void anAuditEventCarriesFingerprintsRatherThanNames() { SafeFileFingerprint fingerprint = new SafeFileFingerprint(KEY); diff --git a/src/application/notification/AGENTS.md b/src/application/notification/AGENTS.md index 9c163f4d..0dce0cb1 100644 --- a/src/application/notification/AGENTS.md +++ b/src/application/notification/AGENTS.md @@ -12,7 +12,7 @@ ## 책임 - 알림 플랫폼의 업무 흐름: 제출·예약·취소·조회, template 게시, provider callback 수집, 발송 판정과 재시도 정책. -- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`), 나가는 포트(쓰는 흐름의 패키지에 있다: `platform.dispatch`·`platform.callback`·`platform.policy`·`platform.observation`·`platform.admin`·`platform.inbox`·`platform.template`·`platform.provider`·`platform.security`), 오류 어휘(`platform.api.error`). `port.out` 패키지는 따로 없다. 나가는 포트 이름은 대개 `*Port`지만 아닌 것도 있다: `provider.NotificationProviderAdapter`·`BatchNotificationProviderAdapter`·`AttachmentResolver`, `security.SecretMaterialProvider`·`ContactPointProtector`, `template.TemplateRegistry`, `callback.ProviderEventLedger`. 새 포트를 만들기 전에 이 이름들도 찾는다. +- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`), 나가는 포트(쓰는 흐름의 패키지에 있다: `platform.dispatch`·`platform.callback`·`platform.policy`·`platform.observation`·`platform.admin`·`platform.inbox`·`platform.template`·`platform.provider`·`platform.security`), 오류 어휘(`platform.api.error`). `port.out` 패키지는 따로 없다. 나가는 포트 이름은 대개 `*Port`지만 아닌 것도 있다: `provider.NotificationProviderAdapter`·`AttachmentResolver`, `security.SecretMaterialProvider`·`ContactPointProtector`, `template.TemplateRegistry`, `callback.ProviderEventLedger`. 새 포트를 만들기 전에 이 이름들도 찾는다. - testFixtures(흐름 패키지의 `testkit`): 저장 포트의 in-memory fake와 공유 계약(`*Contract`), provider adapter 계약(`ProviderAdapterContract`). 모든 포트에 있지는 않다. adapter의 시험이 같은 계약을 상속한다. ## 규칙 diff --git a/src/application/notification/README.md b/src/application/notification/README.md index 682a0357..b1372fc9 100644 --- a/src/application/notification/README.md +++ b/src/application/notification/README.md @@ -5,7 +5,7 @@ ## 책임과 소유하지 않는 것 - 알림 플랫폼의 업무 흐름: 제출·예약·취소·조회, template 게시, provider callback 수집, 발송 판정과 재시도 정책. -- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`), 나가는 포트(쓰는 흐름의 패키지에 있다: `platform.dispatch`·`platform.callback`·`platform.policy`·`platform.observation`·`platform.admin`·`platform.inbox`·`platform.template`·`platform.provider`·`platform.security`), 오류 어휘(`platform.api.error`). `port.out` 패키지는 따로 없다. 나가는 포트 이름은 대개 `*Port`지만 아닌 것도 있다: `provider.NotificationProviderAdapter`·`BatchNotificationProviderAdapter`·`AttachmentResolver`, `security.SecretMaterialProvider`·`ContactPointProtector`, `template.TemplateRegistry`, `callback.ProviderEventLedger`. 새 포트를 만들기 전에 이 이름들도 찾는다. +- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`), 나가는 포트(쓰는 흐름의 패키지에 있다: `platform.dispatch`·`platform.callback`·`platform.policy`·`platform.observation`·`platform.admin`·`platform.inbox`·`platform.template`·`platform.provider`·`platform.security`), 오류 어휘(`platform.api.error`). `port.out` 패키지는 따로 없다. 나가는 포트 이름은 대개 `*Port`지만 아닌 것도 있다: `provider.NotificationProviderAdapter`·`AttachmentResolver`, `security.SecretMaterialProvider`·`ContactPointProtector`, `template.TemplateRegistry`, `callback.ProviderEventLedger`. 새 포트를 만들기 전에 이 이름들도 찾는다. - testFixtures(흐름 패키지의 `testkit`): 저장 포트의 in-memory fake와 공유 계약(`*Contract`), provider adapter 계약(`ProviderAdapterContract`). 모든 포트에 있지는 않다. adapter의 시험이 같은 계약을 상속한다. - 소유하지 않는 것: HTTP 모양(`adapter:inbound:web-notification`), provider 호출·설정(`adapter:outbound:notification`), 저장(`adapter:outbound:persistence-notification`), 조립(`composition:notification-platform`). diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/ProviderEventId.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/ProviderEventId.java deleted file mode 100644 index 56924a78..00000000 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/ProviderEventId.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.application.notification.platform.api; - -/** - * Provider-assigned event identity. Absent for providers that do not emit one; the ledger then - * falls back to a deterministic fingerprint. - */ -public record ProviderEventId(String value) { - - private static final int MAX_LENGTH = 300; - - public ProviderEventId { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException("value"); - } - if (value.length() > MAX_LENGTH) { - throw new IllegalArgumentException("value exceeds " + MAX_LENGTH + " characters"); - } - } -} diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationExpiredException.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationExpiredException.java deleted file mode 100644 index ba926e17..00000000 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationExpiredException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.api.error; - -/** The delivery expiry passed before a new attempt could start. */ -public class NotificationExpiredException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public NotificationExpiredException(NotificationFailureDescriptor descriptor) { - super(descriptor); - } -} diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCase.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCase.java index d8ed77b3..3107e0ac 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCase.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCase.java @@ -137,6 +137,9 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU command.templateVersion().orElse(NotificationTemplateVersion.FIRST_VERSION), command.locale().orElse(defaultLocale)); CorrelationId correlationId = new CorrelationId(ids.nextId().toString()); + // Not the HTTP Idempotency-Key the executor replays: a business key that makes the + // notification itself one per tenant and lives as long as it does, derived from the plan when + // the caller gave none (manual 05 「executor를 쓰지 않는 중복 판정 둘」). IdempotencyKey idempotencyKey = command .idempotencyKey() diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/CanonicalNotificationPlanEncoder.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/CanonicalNotificationPlanEncoder.java index 9ca2b512..0204482e 100644 Binary files a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/CanonicalNotificationPlanEncoder.java and b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/CanonicalNotificationPlanEncoder.java differ diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/provider/BatchNotificationProviderAdapter.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/provider/BatchNotificationProviderAdapter.java deleted file mode 100644 index 43fb9527..00000000 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/provider/BatchNotificationProviderAdapter.java +++ /dev/null @@ -1,16 +0,0 @@ -package dev.caskeleton.application.notification.platform.provider; - -import java.util.List; -import java.util.concurrent.CompletionStage; - -/** - * Optional batching extension. - * - *

One transport call may carry many submissions, but the result list is positional: every - * recipient keeps its own attempt and its own outcome. - */ -public interface BatchNotificationProviderAdapter extends NotificationProviderAdapter { - - /** Submit a batch and return one result per input, in input order. */ - CompletionStage> submitBatch(List submissions); -} diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/provider/CollapseCapability.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/provider/CollapseCapability.java deleted file mode 100644 index a5ba086c..00000000 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/provider/CollapseCapability.java +++ /dev/null @@ -1,10 +0,0 @@ -package dev.caskeleton.application.notification.platform.provider; - -import dev.caskeleton.application.notification.platform.api.CollapseSpec; - -/** Maps a platform collapse hint onto a provider-native key, validating provider limits first. */ -public interface CollapseCapability { - - /** Translate the spec, or fail when the key violates a provider limit. */ - ProviderCollapseMapping map(CollapseSpec spec); -} diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/provider/ProviderCollapseMapping.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/provider/ProviderCollapseMapping.java deleted file mode 100644 index 121c940a..00000000 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/provider/ProviderCollapseMapping.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.application.notification.platform.provider; - -import java.util.Objects; - -/** - * Provider-native collapse key. - * - *

{@code guaranteesSingleUserNotification} is always false: collapse replaces an undelivered - * message inside the provider, it cannot recall one the device already showed. - */ -public record ProviderCollapseMapping(String nativeKey, String headerOrFieldName) { - - public ProviderCollapseMapping { - Objects.requireNonNull(nativeKey, "nativeKey"); - Objects.requireNonNull(headerOrFieldName, "headerOrFieldName"); - if (nativeKey.isBlank() || headerOrFieldName.isBlank()) { - throw new IllegalArgumentException("collapse mapping must not be blank"); - } - } - - /** Collapse never promises the user sees exactly one notification. */ - public boolean guaranteesSingleUserNotification() { - return false; - } -} diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/DeduplicationAndCollapseTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/DeduplicationAndCollapseTest.java index ecc03283..904b0a0a 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/DeduplicationAndCollapseTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/DeduplicationAndCollapseTest.java @@ -2,14 +2,10 @@ package dev.caskeleton.application.notification.platform.policy; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.application.notification.platform.api.CollapseScope; -import dev.caskeleton.application.notification.platform.api.CollapseSpec; import dev.caskeleton.application.notification.platform.api.DeduplicationAction; import dev.caskeleton.application.notification.platform.api.DeduplicationSpec; import dev.caskeleton.application.notification.platform.api.NotificationId; import dev.caskeleton.application.notification.platform.policy.testkit.InMemoryDeduplicationStore; -import dev.caskeleton.application.notification.platform.provider.CollapseCapability; -import dev.caskeleton.application.notification.platform.provider.ProviderCollapseMapping; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -55,14 +51,4 @@ class DeduplicationAndCollapseTest { assertThat(other.duplicate()).isFalse(); } - - @Test - void collapseDoesNotReportExactlyOnceOrDelivered() { - CollapseCapability capability = - spec -> new ProviderCollapseMapping(spec.key(), "apns-collapse-id"); - var mapped = capability.map(new CollapseSpec("feed:user-1", CollapseScope.RECIPIENT)); - - assertThat(mapped.guaranteesSingleUserNotification()).isFalse(); - assertThat(mapped.nativeKey()).isEqualTo("feed:user-1"); - } } diff --git a/src/bootstrap/durable-operation/src/main/java/dev/caskeleton/composition/operation/DurableOperationAutoConfiguration.java b/src/bootstrap/durable-operation/src/main/java/dev/caskeleton/composition/operation/DurableOperationAutoConfiguration.java index cab63f22..c1133358 100644 --- a/src/bootstrap/durable-operation/src/main/java/dev/caskeleton/composition/operation/DurableOperationAutoConfiguration.java +++ b/src/bootstrap/durable-operation/src/main/java/dev/caskeleton/composition/operation/DurableOperationAutoConfiguration.java @@ -71,8 +71,10 @@ public class DurableOperationAutoConfiguration { OutboxAppendPort outbox, IntegrationEventEncoderPort encoder, TransactionPort transactions, + DurableOperationIdFactory operationIds, Clock clock) { - return new SubmitDurableOperationUseCase(operations, outbox, encoder, transactions, clock); + return new SubmitDurableOperationUseCase( + operations, outbox, encoder, transactions, operationIds, clock); } /** Reads one operation for the caller that submitted it. */