review-followup Wave 3 라운드 2(P18): outbox canonical 통일, composition 모듈, legacy Kafka seam 삭제
- 결정 7: `LegacyOutboxAppendPort`·legacy 저장 모델·relay·Kafka R0 seam 삭제, 템플릿 JSON encoder(`JsonIntegrationEventEncoder`),
durable operation·sample 이벤트가 `OutboxAppendPort` + encoder로, persistence-jpa V19(pre-canonical 미발행 row 거부)
- 결정 3: outbox relay·멱등성 executor 조립을 `composition:outbox-relay`·`composition:idempotency`로,
sample이 복사한 bootstrap 인프라를 `composition:service-runtime`으로(sample `SampleIdempotencyConfig` 복사본 삭제)
- persistence-jpa outbox·멱등성 패키지 feature 기준 이동, messaging outbox·inbox leaf를 reliability / reliability-jdbc-postgresql로
- messaging outbox header를 jsonb로(P18-new-1 — `\`로 끝나는 값이 다음 header를 삼키던 결함)
- 통합(충돌 22건): P25 A-10c(전략 선택 설정 삭제)를 service-runtime `DomainContextConfig`에 적용, P25 startup 예외 통합을
composition 설정 테스트에, P25 `CommandUseCase.handle` 이름을 PG 통합 테스트에, P15 `EventJson`은 호출자 0이 되어 삭제
- root CLAUDE.md의 legacy seam 문장 수정(P18-new-2)
검증: ./gradlew check architectureCheck verifyDependencyLocks verifyPublicPathSnapshot :app-bootstrap:verifyEnvKeys
configContractCheck :app-bootstrap:integrationTest :sample-portfolio:integrationTest :sample-portfolio:systemTest
persistence-jpa jpaPlatformContractTest·postgresql{Idempotency,OutboxAppendTransactional,OutboxConcurrentRelay,OutboxRowLifecycle}IntegrationTest
:messaging:messaging-reliability-jdbc-postgresql:integrationTest --continue 통과(700 task)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
25de288ab4
commit
423a29c46f
@@ -71,7 +71,8 @@ Package root: `dev.caskeleton.application`.
|
||||
| `messaging.contract.IntegrationEventContractContribution<P>` | Closed exact-record payload type, canonical component order, local schema identity/hash and provider-neutral descriptor contribution. |
|
||||
| `messaging.event.IntegrationEventDraft<P>` | Typed semantic event before local encoding; never JSON, Kafka or persistence state. |
|
||||
| `messaging.event.ValidatedIntegrationEvent` | Stable semantic identities plus immutable exact encoded bytes and hashes, ready for a later durable append boundary. |
|
||||
| `messaging.event.IntegrationEventEncoderPort` | Framework-free local draft-to-validated-event boundary implemented by an outbound adapter. |
|
||||
| `messaging.event.IntegrationEventEncoderPort` | Framework-free local draft-to-validated-event boundary implemented by an outbound adapter (the template's: `adapter:outbound:support` `JsonIntegrationEventEncoder`). |
|
||||
| `outbox.OutboxAppendPort` | The one outbox append: a `ValidatedIntegrationEvent`, in the caller's write transaction. |
|
||||
|
||||
## Notification (NOTIF-ADR-005)
|
||||
|
||||
@@ -161,7 +162,7 @@ generation; the V1 `IdempotencyScope`/`tryBegin` API is gone.
|
||||
- **Store**: `IdempotencyStorePort`, contributed by exactly one provider selected with
|
||||
`ca-skeleton.capabilities.idempotency.provider` (`redis` → `cache-redis`, `postgresql` →
|
||||
`persistence-jpa`; default `disabled`). In-memory prod storage is forbidden.
|
||||
- **Executor**: built once by app-bootstrap `IdempotencyProviderSelectionConfig` from
|
||||
- **Executor**: built once by `composition:idempotency` `IdempotencyAutoConfiguration` from
|
||||
`IdempotencySettings` (processing lease 30s, replay TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h,
|
||||
failure retention 24h). Do not construct it in a use case or a sample config.
|
||||
- The action returns `IdempotentAction.Outcome` (`Success` / `RetryableNoEffect` /
|
||||
|
||||
@@ -33,8 +33,10 @@ Cache도 같은 원칙을 따른다. `cache` 패키지에는 cache-redis가 구
|
||||
보유한다. tenant가 없는 모드도 null 대신 canonical system tenant scope를
|
||||
`AggregateIdentity`에 넣어 dedupe/order identity가 PostgreSQL nullable uniqueness에 기대지
|
||||
않게 한다.
|
||||
- `IntegrationEventEncoderPort` 뒤의 adapter가 deterministic encoding과 schema validation을
|
||||
수행하고 `ValidatedIntegrationEvent`를 돌려준다. 결과는 logical destination, exact US-ASCII
|
||||
- `IntegrationEventEncoderPort` 뒤의 adapter가 deterministic encoding을 수행하고
|
||||
`ValidatedIntegrationEvent`를 돌려준다. 템플릿의 구현은 `adapter:outbound:support`의
|
||||
`JsonIntegrationEventEncoder`다(envelope v1 + payload record의 결정적 JSON, 선언한 schema hash를
|
||||
classpath 파일과 대조). 결과는 logical destination, exact US-ASCII
|
||||
partition key, exact encoded envelope bytes, schema/envelope hash와 catalog/binding revision을
|
||||
defensive copy로 보존한다.
|
||||
- `ContractDescriptor`는 owner module, logical destination, serializer ID, ordering requirement,
|
||||
@@ -372,7 +374,7 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장.
|
||||
못한다.
|
||||
- **안전한 allowlist report**: `OutboxRelayFailureReport`는
|
||||
`code/eventId/eventType/aggregateId/correlationId/attemptCount/nextAttemptAt/cause`만 가진다.
|
||||
payload, idempotency key, whole `OutboxEvent`, severity/template, arbitrary map은 타입 수준에서
|
||||
payload, envelope bytes, whole `ClaimedOutboxEvent`, severity/template, arbitrary map은 타입 수준에서
|
||||
전달할 수 없다. retry factory는 `OUTBOX_PUBLISH_FAILED`와 필수 `nextAttemptAt`, dead factory는
|
||||
`OUTBOX_DEAD_LETTER`와 null retry time을 고정한다.
|
||||
- **상태 갱신 실패는 시끄럽게 전파한다**: 발행 성공 후의 `markPublished` 실패는 store/인프라
|
||||
@@ -406,17 +408,18 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장.
|
||||
업데이트와 **함께만** 바꾼다.
|
||||
- 지수 계산은 overflow 방지를 위해 `2^30` 에서 cap 한다(`2^30 × 30s > 30년` 이라 안전).
|
||||
|
||||
### outbox 값/상태 타입 (Status · Event · NewOutboxEvent · RelayResult · Command)
|
||||
### outbox 값/상태 타입 (Status · ClaimedOutboxEvent · RelayResult · Command)
|
||||
|
||||
- `OutboxEventStatus` — 행 상태 머신(D5). `PENDING → IN_FLIGHT → {PUBLISHED | FAILED | DEAD}`,
|
||||
`FAILED → IN_FLIGHT`(재claim), `IN_FLIGHT 고아 → IN_FLIGHT`(I6). `DEAD` 는 FIFO 형제를 막는다 —
|
||||
같은 aggregate 의 뒤 행 claim 을 차단하므로 runbook 개입이 필요하다.
|
||||
- `OutboxEvent` — `claimBatch` 가 반환하는 claim-result 읽기 모델. `NewOutboxEvent` 필드 + 현재
|
||||
`status` + `attemptCount`. relay 가 `attemptCount` 로 다음 실패 시 dead-letter 여부를 결정한다.
|
||||
- `NewOutboxEvent` — caller 의 write 트랜잭션 안에서 append 할 새 이벤트 값 객체. 모든 필드가
|
||||
필수이고 null/blank 면 생성 시점에 거부한다(D12). caller 가 `eventId`·`idempotencyKey` 를
|
||||
공급한다(I12 — outbox core 는 ID 생성에 비의존). 권장 기본값은 `idempotencyKey = eventId`
|
||||
(per-event dedup, CloudEvents-C2).
|
||||
- append 는 `OutboxAppendPort.append(ValidatedIntegrationEvent)` 하나다(2026-09-28, 소유자 결정 7).
|
||||
use case 가 `IntegrationEventDraft` 를 만들고 `IntegrationEventEncoderPort` 로 encode 한 뒤 같은
|
||||
write 트랜잭션 안에서 append 한다. consumer 의 중복 제거 키는 event id 다.
|
||||
- `ClaimedOutboxEvent` — `claimBatch` 가 반환하는 claim-result 읽기 모델. append 된 validated event
|
||||
(저장된 exact envelope bytes 에서 복원) + 현재 `status` + `attemptCount`. relay 가 `attemptCount` 로
|
||||
다음 실패 시 dead-letter 여부를 결정한다. 옛 `OutboxEvent`/`NewOutboxEvent`/`LegacyOutboxAppendPort`
|
||||
(free-text payload 모델)는 삭제됐다.
|
||||
- `OutboxRelayResult` — relay 한 사이클의 결과. `claimedCount` + per-event outcome 목록. 내부
|
||||
`Outcome` enum 이 `OutboxEventStatus` 의 5값을 재사용하지 않고 4값(PUBLISHED/FAILED/DEAD/
|
||||
STALE — 마지막은 lease 를 잃어 결과를 쓰지 못한 경우)을
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package dev.caskeleton.application.operation;
|
||||
|
||||
import dev.caskeleton.application.messaging.contract.IntegrationPayload;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The payload of the event that wakes a worker for an accepted operation.
|
||||
*
|
||||
* <p>Which operation, and what kind of work it is — nothing more. The worker reads what to run from
|
||||
* the submission it claims, so the request itself never travels through the broker and a worker
|
||||
* never acts on a copy that could disagree with the stored one.
|
||||
*
|
||||
* @param operationId the operation to claim
|
||||
* @param operationName what kind of work it is, so a worker can ignore work it does not run
|
||||
*/
|
||||
public record DurableOperationSubmitted(String operationId, String operationName)
|
||||
implements IntegrationPayload {
|
||||
|
||||
public DurableOperationSubmitted {
|
||||
Objects.requireNonNull(operationId, "operationId");
|
||||
Objects.requireNonNull(operationName, "operationName");
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package dev.caskeleton.application.operation;
|
||||
|
||||
import dev.caskeleton.application.messaging.contract.ContractDescriptor;
|
||||
import dev.caskeleton.application.messaging.contract.ContractId;
|
||||
import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution;
|
||||
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
|
||||
import dev.caskeleton.application.messaging.contract.SchemaResourceId;
|
||||
import dev.caskeleton.application.messaging.contract.Sha256;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The {@code durable-operation.submitted} v1 contract: the one event a durable-operation submission
|
||||
* appends, whichever transport accepted it.
|
||||
*
|
||||
* <p>One type for every operation. The event only wakes a worker, and letting a caller choose the
|
||||
* type would let it publish any event the broker carries. The composition that turns durable
|
||||
* operations on registers this contribution, so the encoder knows the contract.
|
||||
*/
|
||||
public final class DurableOperationSubmittedContract
|
||||
implements IntegrationEventContractContribution<DurableOperationSubmitted> {
|
||||
|
||||
/** The contract id every submission event carries. */
|
||||
public static final ContractId CONTRACT_ID = new ContractId("durable-operation.submitted");
|
||||
|
||||
/** Where submission events go; a deployment binds it to a broker destination. */
|
||||
public static final LogicalDestinationId DESTINATION =
|
||||
new LogicalDestinationId("durable-operations");
|
||||
|
||||
private static final SchemaResourceId SCHEMA_RESOURCE =
|
||||
new SchemaResourceId("contracts/messaging/durable-operation.submitted/v1.schema.json");
|
||||
|
||||
// SHA-256 of the schema file's exact bytes. The encoder recomputes it at startup and refuses a
|
||||
// mismatch, so editing the schema without updating this fails the boot, not the consumer.
|
||||
private static final Sha256 SCHEMA_HASH =
|
||||
new Sha256(
|
||||
HexFormat.of()
|
||||
.parseHex("4d2f780bf6c23fa548fc2b0e6ef02302" + "e17fca44a20f21ebf5ba07aaac11a245"));
|
||||
|
||||
private static final ContractDescriptor DESCRIPTOR =
|
||||
new ContractDescriptor(
|
||||
"application-core",
|
||||
DESTINATION,
|
||||
"json-envelope-v1",
|
||||
false,
|
||||
16 * 1024,
|
||||
32 * 1024,
|
||||
ContractDescriptor.SensitivityClassification.INTERNAL,
|
||||
OperationCommand.DEFAULT_TIME_TO_LIVE);
|
||||
|
||||
@Override
|
||||
public ContractId contractId() {
|
||||
return CONTRACT_ID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int payloadVersion() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<DurableOperationSubmitted> exactPayloadRecordType() {
|
||||
return DurableOperationSubmitted.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> canonicalRecordComponentOrder() {
|
||||
return List.of("operationId", "operationName");
|
||||
}
|
||||
|
||||
@Override
|
||||
public SchemaResourceId payloadSchemaResource() {
|
||||
return SCHEMA_RESOURCE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Sha256 payloadSchemaHash() {
|
||||
return SCHEMA_HASH;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ContractDescriptor descriptor() {
|
||||
return DESCRIPTOR;
|
||||
}
|
||||
}
|
||||
+4
-17
@@ -13,13 +13,16 @@ import java.util.Objects;
|
||||
* value the caller can retry: a generated id would differ on every attempt, so a retry after an
|
||||
* ambiguous failure would create a second operation.
|
||||
*
|
||||
* <p>There is no event type to choose. Every accepted operation announces itself with the one
|
||||
* {@link DurableOperationSubmittedContract} event, which only wakes a worker; letting a caller name
|
||||
* the type would let it publish any event the broker carries.
|
||||
*
|
||||
* @param operationId the identity to use
|
||||
* @param operationName what work this is
|
||||
* @param principal who is asking
|
||||
* @param tenantId the tenant, or null when the operation is not tenant scoped
|
||||
* @param fingerprint the semantic fingerprint of the request
|
||||
* @param payload the serialized request a worker will execute
|
||||
* @param eventType the outbox event type a worker subscribes to
|
||||
* @param timeToLive how long the record and its result stay available
|
||||
*/
|
||||
public record OperationCommand(
|
||||
@@ -29,20 +32,9 @@ public record OperationCommand(
|
||||
String tenantId,
|
||||
RequestFingerprint fingerprint,
|
||||
String payload,
|
||||
String eventType,
|
||||
Duration timeToLive)
|
||||
implements Command {
|
||||
|
||||
/**
|
||||
* The outbox event type for an operation whose caller does not publish an event of its own, such
|
||||
* as the HTTP operation endpoint.
|
||||
*
|
||||
* <p>One type for all of them: the event only wakes a worker, and the worker reads what to run
|
||||
* from the submission it claims. Letting such a caller choose the type would let it publish any
|
||||
* event the broker carries.
|
||||
*/
|
||||
public static final String SUBMITTED_EVENT_TYPE = "DurableOperationSubmitted";
|
||||
|
||||
/** How long an operation submitted without a caller-specific lifetime stays pollable. */
|
||||
public static final Duration DEFAULT_TIME_TO_LIVE = Duration.ofDays(1);
|
||||
|
||||
@@ -58,10 +50,5 @@ public record OperationCommand(
|
||||
if (operationName.isBlank()) {
|
||||
throw new IllegalArgumentException("an operation command needs the operation it is for");
|
||||
}
|
||||
if (eventType == null || eventType.isBlank()) {
|
||||
throw new IllegalArgumentException(
|
||||
"an operation command needs an event type; without one the outbox row reaches no worker"
|
||||
+ " and the operation is accepted into silence");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+69
-13
@@ -3,14 +3,24 @@ package dev.caskeleton.application.operation;
|
||||
import dev.caskeleton.application.capability.Idempotency;
|
||||
import dev.caskeleton.application.capability.RepositoryAccess;
|
||||
import dev.caskeleton.application.capability.UseCaseCapability;
|
||||
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
|
||||
import dev.caskeleton.application.outbox.NewOutboxEvent;
|
||||
import dev.caskeleton.application.messaging.event.AggregateIdentity;
|
||||
import dev.caskeleton.application.messaging.event.AggregateOrder;
|
||||
import dev.caskeleton.application.messaging.event.EventId;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventDraft;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
|
||||
import dev.caskeleton.application.outbox.OutboxAppendPort;
|
||||
import dev.caskeleton.application.security.RequiresPermission;
|
||||
import dev.caskeleton.application.transaction.TransactionMode;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.application.usecase.CommandUseCase;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Accepts long-running work: one transaction that writes the operation row and the outbox row.
|
||||
@@ -54,8 +64,15 @@ import java.util.Objects;
|
||||
public class SubmitDurableOperationUseCase
|
||||
implements CommandUseCase<OperationCommand, OperationAcceptance> {
|
||||
|
||||
private static final String TENANT_SCOPE = "global";
|
||||
private static final String AGGREGATE_TYPE = "durable-operation";
|
||||
private static final AggregateOrder FIRST_EVENT = new AggregateOrder(1, 0);
|
||||
private static final int MAXIMUM_EVENT_ID_LENGTH = 96;
|
||||
private static final Pattern EVENT_ID_GRAMMAR = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]*");
|
||||
|
||||
private final DurableOperationStorePort operations;
|
||||
private final LegacyOutboxAppendPort outbox;
|
||||
private final OutboxAppendPort outbox;
|
||||
private final IntegrationEventEncoderPort encoder;
|
||||
private final TransactionPort transactions;
|
||||
private final Clock clock;
|
||||
|
||||
@@ -64,16 +81,20 @@ public class SubmitDurableOperationUseCase
|
||||
*
|
||||
* @param operations where operations are recorded
|
||||
* @param outbox where the publish intent is recorded
|
||||
* @param encoder turns the submission event into the validated event the outbox stores; it must
|
||||
* know {@link DurableOperationSubmittedContract}
|
||||
* @param transactions opens the write transaction both share
|
||||
* @param clock the submission clock
|
||||
*/
|
||||
public SubmitDurableOperationUseCase(
|
||||
DurableOperationStorePort operations,
|
||||
LegacyOutboxAppendPort outbox,
|
||||
OutboxAppendPort outbox,
|
||||
IntegrationEventEncoderPort encoder,
|
||||
TransactionPort transactions,
|
||||
Clock clock) {
|
||||
this.operations = Objects.requireNonNull(operations, "operations");
|
||||
this.outbox = Objects.requireNonNull(outbox, "outbox");
|
||||
this.encoder = Objects.requireNonNull(encoder, "encoder");
|
||||
this.transactions = Objects.requireNonNull(transactions, "transactions");
|
||||
this.clock = Objects.requireNonNull(clock, "clock");
|
||||
}
|
||||
@@ -110,18 +131,53 @@ public class SubmitDurableOperationUseCase
|
||||
// operation would have a worker claim it, find it already RUNNING or finished, and
|
||||
// discard the message — harmless but indistinguishable in the logs from a real
|
||||
// duplicate, which is exactly the signal an operator needs to stay trustworthy.
|
||||
outbox.append(
|
||||
new NewOutboxEvent(
|
||||
operation.operationId().value(),
|
||||
command.eventType(),
|
||||
operation.operationId().value(),
|
||||
command.payload(),
|
||||
operation.submittedAt(),
|
||||
operation.operationId().value(),
|
||||
operation.operationId().value()));
|
||||
outbox.append(encoder.encode(submittedEvent(operation)));
|
||||
}
|
||||
return new OperationAcceptance(
|
||||
operation.operationId(), operation.submittedAt(), alreadyAccepted);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The event for a new operation, anchored to it: the operation is its own aggregate, so its id is
|
||||
* the event id, the aggregate id and the correlation id, and a worker that receives the message
|
||||
* twice can tell it is the same work.
|
||||
*/
|
||||
private static IntegrationEventDraft<DurableOperationSubmitted> submittedEvent(
|
||||
DurableOperation operation) {
|
||||
String identity = canonicalIdentity(operation.operationId());
|
||||
return new IntegrationEventDraft<>(
|
||||
new EventId(identity),
|
||||
DurableOperationSubmittedContract.CONTRACT_ID,
|
||||
1,
|
||||
DurableOperationSubmittedContract.DESTINATION,
|
||||
new AggregateIdentity(TENANT_SCOPE, AGGREGATE_TYPE, identity),
|
||||
FIRST_EVENT,
|
||||
operation.submittedAt(),
|
||||
identity,
|
||||
Optional.empty(),
|
||||
new DurableOperationSubmitted(operation.operationId().value(), operation.operationName()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The operation id itself when it fits the integration-event identity grammar — every id the HTTP
|
||||
* adapter mints does — and otherwise a digest of it.
|
||||
*
|
||||
* <p>An operation id may contain {@code ~} or run to 128 characters, and an event id may do
|
||||
* neither. The digest keeps the event deterministic for the operation, so a retry still produces
|
||||
* the same event, and the payload carries the id unchanged for the worker.
|
||||
*/
|
||||
static String canonicalIdentity(DurableOperationId operationId) {
|
||||
String value = operationId.value();
|
||||
if (value.length() <= MAXIMUM_EVENT_ID_LENGTH && EVENT_ID_GRAMMAR.matcher(value).matches()) {
|
||||
return value;
|
||||
}
|
||||
try {
|
||||
byte[] digest =
|
||||
MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
|
||||
return "operation-" + HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException unreachable) {
|
||||
throw new IllegalStateException("Java runtime does not provide SHA-256", unreachable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
package dev.caskeleton.application.outbox;
|
||||
|
||||
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Claimed legacy-authority row whose immutable payload is a complete canonical integration event.
|
||||
*/
|
||||
public record CanonicalClaimedOutboxEvent(
|
||||
ValidatedIntegrationEvent event, OutboxEventStatus status, int attemptCount)
|
||||
implements ClaimedOutboxEvent {
|
||||
|
||||
public CanonicalClaimedOutboxEvent {
|
||||
Objects.requireNonNull(event, "event must not be null");
|
||||
Objects.requireNonNull(status, "status must not be null");
|
||||
if (attemptCount < 0) {
|
||||
throw new IllegalArgumentException("attemptCount must be >= 0, was " + attemptCount);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String eventId() {
|
||||
return event.eventId().value();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String eventType() {
|
||||
return event.contractId().value();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String aggregateId() {
|
||||
return event.aggregate().aggregateId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String correlationId() {
|
||||
return event.correlationId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant occurredAt() {
|
||||
return event.occurredAt();
|
||||
}
|
||||
}
|
||||
+36
-12
@@ -1,26 +1,50 @@
|
||||
package dev.caskeleton.application.outbox;
|
||||
|
||||
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Relay-facing claimed row identity shared by legacy and canonical outbox generations.
|
||||
* One outbox row as a claim returns it: the validated integration event that was appended, plus
|
||||
* where the row stands in the relay state machine.
|
||||
*
|
||||
* <p>Only fields needed by the legacy relay state machine and diagnostics live here. Payload and
|
||||
* canonical envelope data remain on their concrete subtype.
|
||||
* <p>The event is restored from the exact envelope bytes and hashes the append stored, so the relay
|
||||
* publishes the bytes that were validated rather than a re-rendering of them. The accessors below
|
||||
* name the few identities the relay and its diagnostics read without reaching into the envelope.
|
||||
*
|
||||
* @param event the appended event
|
||||
* @param status the row's lifecycle status; {@link OutboxEventStatus#IN_FLIGHT} right after a claim
|
||||
* @param attemptCount delivery attempts made, counting the claim that returned this row
|
||||
*/
|
||||
public sealed interface ClaimedOutboxEvent permits OutboxEvent, CanonicalClaimedOutboxEvent {
|
||||
public record ClaimedOutboxEvent(
|
||||
ValidatedIntegrationEvent event, OutboxEventStatus status, int attemptCount) {
|
||||
|
||||
String eventId();
|
||||
public ClaimedOutboxEvent {
|
||||
Objects.requireNonNull(event, "event must not be null");
|
||||
Objects.requireNonNull(status, "status must not be null");
|
||||
if (attemptCount < 0) {
|
||||
throw new IllegalArgumentException("attemptCount must be >= 0, was " + attemptCount);
|
||||
}
|
||||
}
|
||||
|
||||
String eventType();
|
||||
public String eventId() {
|
||||
return event.eventId().value();
|
||||
}
|
||||
|
||||
String aggregateId();
|
||||
/** The contract id; the outbox's event type is the contract the event was validated against. */
|
||||
public String eventType() {
|
||||
return event.contractId().value();
|
||||
}
|
||||
|
||||
String correlationId();
|
||||
public String aggregateId() {
|
||||
return event.aggregate().aggregateId();
|
||||
}
|
||||
|
||||
Instant occurredAt();
|
||||
public String correlationId() {
|
||||
return event.correlationId();
|
||||
}
|
||||
|
||||
OutboxEventStatus status();
|
||||
|
||||
int attemptCount();
|
||||
public Instant occurredAt() {
|
||||
return event.occurredAt();
|
||||
}
|
||||
}
|
||||
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package dev.caskeleton.application.outbox;
|
||||
|
||||
/**
|
||||
* Compatibility-only append boundary for the pre-canonical outbox payload model.
|
||||
*
|
||||
* <p>New integration-event code must use {@link OutboxAppendPort}. This port remains only while
|
||||
* legacy/sample producers still persist {@link NewOutboxEvent} rows through the transport-only
|
||||
* cutover window.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface LegacyOutboxAppendPort {
|
||||
|
||||
void append(NewOutboxEvent event);
|
||||
}
|
||||
-53
@@ -1,53 +0,0 @@
|
||||
package dev.caskeleton.application.outbox;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Value object for a new outbox event, appended within the caller's write transaction. All fields
|
||||
* are required (null/blank is rejected at construction). Callers supply {@code eventId} and {@code
|
||||
* idempotencyKey} (the outbox core is ID-generation-agnostic); the recommended default is {@code
|
||||
* idempotencyKey = eventId}. See README.
|
||||
*
|
||||
* @param eventId unique identifier for this event (e.g. a UUIDv7 string)
|
||||
* @param eventType logical event type name (e.g. {@code "UserCreated"})
|
||||
* @param aggregateId the aggregate that emitted this event; used as the message routing key and
|
||||
* FIFO-gate anchor
|
||||
* @param payload serialised event payload (pre-serialised JSON string)
|
||||
* @param occurredAt wall-clock time at which the domain event occurred
|
||||
* @param correlationId trace / correlation identifier for log correlation
|
||||
* @param idempotencyKey consumer-side deduplication key (D12 / I12)
|
||||
*/
|
||||
public record NewOutboxEvent(
|
||||
String eventId,
|
||||
String eventType,
|
||||
String aggregateId,
|
||||
String payload,
|
||||
Instant occurredAt,
|
||||
String correlationId,
|
||||
String idempotencyKey) {
|
||||
|
||||
public NewOutboxEvent {
|
||||
requireNonBlank(eventId, "eventId");
|
||||
requireNonBlank(eventType, "eventType");
|
||||
requireNonBlank(aggregateId, "aggregateId");
|
||||
requireNonBlank(payload, "payload");
|
||||
// Validated here, on the append side, and not only on the read model.
|
||||
//
|
||||
// OutboxEvent — the type the relay maps a stored row into — already applied this policy, so a
|
||||
// malformed or oversized payload was accepted at write and first threw when the relay read it
|
||||
// back. And it threw out of `claimBatch`, which maps a whole batch in one stream: one poisoned
|
||||
// row failed every subsequent relay pass rather than the single transaction that could still
|
||||
// have refused it. The append boundary is where the caller is still there to be told.
|
||||
OutboxPayloadPolicy.requireValidPayload(payload);
|
||||
Objects.requireNonNull(occurredAt, "occurredAt must not be null");
|
||||
requireNonBlank(correlationId, "correlationId");
|
||||
requireNonBlank(idempotencyKey, "idempotencyKey");
|
||||
}
|
||||
|
||||
private static void requireNonBlank(String value, String field) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new IllegalArgumentException(field + " must not be null or blank");
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -3,11 +3,13 @@ package dev.caskeleton.application.outbox;
|
||||
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
|
||||
|
||||
/**
|
||||
* Canonical durable append boundary for a fully validated integration event.
|
||||
* The one outbox append boundary: a fully validated integration event, written in the caller's
|
||||
* write transaction.
|
||||
*
|
||||
* <p>The implementation participates in the caller's existing write transaction and persists the
|
||||
* exact validated envelope bytes. Raw legacy payload append is intentionally separated into {@link
|
||||
* LegacyOutboxAppendPort}.
|
||||
* exact validated envelope bytes; it never opens a transaction of its own, because a row committed
|
||||
* apart from the business write it announces is the dual write the outbox exists to prevent. A use
|
||||
* case builds the event with {@code IntegrationEventEncoderPort} and appends it here.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface OutboxAppendPort {
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
package dev.caskeleton.application.outbox;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Immutable view of an outbox event row returned by {@link OutboxStorePort#claimBatch}.
|
||||
*
|
||||
* <p>This is a claim-result read model: it carries the full {@link NewOutboxEvent} fields plus the
|
||||
* current {@link OutboxEventStatus} and the number of delivery attempts already made. The relay
|
||||
* uses {@code attemptCount} to decide whether to DEAD-letter the event on the next failure ({@code
|
||||
* attemptCount >= maxAttempts}).
|
||||
*
|
||||
* @param eventId unique identifier for this event
|
||||
* @param eventType logical event type name
|
||||
* @param aggregateId the aggregate that emitted this event
|
||||
* @param payload serialised event payload (pre-serialised JSON string)
|
||||
* @param occurredAt wall-clock time at which the domain event occurred
|
||||
* @param correlationId trace / correlation identifier
|
||||
* @param idempotencyKey consumer-side deduplication key
|
||||
* @param status current lifecycle status (will be {@link OutboxEventStatus#IN_FLIGHT} immediately
|
||||
* after a successful claim)
|
||||
* @param attemptCount number of delivery attempts already made (1-based after the first claim)
|
||||
*/
|
||||
public record OutboxEvent(
|
||||
String eventId,
|
||||
String eventType,
|
||||
String aggregateId,
|
||||
String payload,
|
||||
Instant occurredAt,
|
||||
String correlationId,
|
||||
String idempotencyKey,
|
||||
OutboxEventStatus status,
|
||||
int attemptCount)
|
||||
implements ClaimedOutboxEvent {
|
||||
|
||||
public OutboxEvent {
|
||||
Objects.requireNonNull(eventId, "eventId");
|
||||
Objects.requireNonNull(eventType, "eventType");
|
||||
Objects.requireNonNull(aggregateId, "aggregateId");
|
||||
// Not merely non-null: the envelope serialiser inserts this verbatim and unescaped, so an
|
||||
// invalid or oversized payload becomes a permanently unparseable message that the relay
|
||||
// retries forever. See OutboxPayloadPolicy.
|
||||
OutboxPayloadPolicy.requireValidPayload(payload);
|
||||
Objects.requireNonNull(occurredAt, "occurredAt");
|
||||
Objects.requireNonNull(correlationId, "correlationId");
|
||||
Objects.requireNonNull(idempotencyKey, "idempotencyKey");
|
||||
Objects.requireNonNull(status, "status");
|
||||
if (attemptCount < 0) {
|
||||
throw new IllegalArgumentException("attemptCount must be >= 0, was " + attemptCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
-271
@@ -1,271 +0,0 @@
|
||||
package dev.caskeleton.application.outbox;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* What an outbox payload has to be before a row is written.
|
||||
*
|
||||
* <p>{@code OutboxEvent} checked that the payload was non-null and nothing else, and the envelope
|
||||
* serialiser then inserted it into the JSON document verbatim, unescaped, because it is documented
|
||||
* as "already valid JSON". Nothing enforced that. A payload that was not valid JSON produced a
|
||||
* malformed envelope that the broker accepted and every consumer failed to parse — permanently,
|
||||
* because the row is durable and the relay retries it forever. A payload containing {@code
|
||||
* "},"eventType":"} rewrote the envelope's own fields.
|
||||
*
|
||||
* <p>Size was equally unbounded. The row goes into a database column, through a broker with a
|
||||
* message limit, and into a JSON log line; a payload larger than any of those is a failure
|
||||
* discovered after the transaction committed, which is the one point at which it can no longer be
|
||||
* rejected.
|
||||
*
|
||||
* <p>This is a validator, not a parser: it walks the text and returns nothing. Building a tree
|
||||
* would mean a JSON library on {@code application-core}'s classpath, which the module's contract
|
||||
* forbids, and would allocate a second copy of every payload for a check that needs neither.
|
||||
*/
|
||||
public final class OutboxPayloadPolicy {
|
||||
|
||||
/**
|
||||
* The payload ceiling in UTF-8 bytes.
|
||||
*
|
||||
* <p>256 KiB: comfortably under the one mebibyte default of every broker in the platform, with
|
||||
* room for the envelope's own fields and for a log line that quotes it.
|
||||
*/
|
||||
public static final int MAX_PAYLOAD_BYTES = 262_144;
|
||||
|
||||
private OutboxPayloadPolicy() {}
|
||||
|
||||
/**
|
||||
* Refuses a payload that is not a single valid JSON value, or is too large.
|
||||
*
|
||||
* @param payload the serialised payload
|
||||
* @throws IllegalArgumentException naming what is wrong and where
|
||||
*/
|
||||
public static void requireValidPayload(String payload) {
|
||||
if (payload == null) {
|
||||
throw new IllegalArgumentException("outbox payload must not be null");
|
||||
}
|
||||
int bytes = payload.getBytes(StandardCharsets.UTF_8).length;
|
||||
if (bytes > MAX_PAYLOAD_BYTES) {
|
||||
throw new IllegalArgumentException(
|
||||
"outbox payload is "
|
||||
+ bytes
|
||||
+ " UTF-8 bytes; the limit is "
|
||||
+ MAX_PAYLOAD_BYTES
|
||||
+ ". Rejecting it here is the last point at which it can be rejected at all — after"
|
||||
+ " the row commits, the relay retries it forever.");
|
||||
}
|
||||
Scanner scanner = new Scanner(payload);
|
||||
scanner.skipWhitespace();
|
||||
scanner.readValue(0);
|
||||
scanner.skipWhitespace();
|
||||
if (!scanner.exhausted()) {
|
||||
throw new IllegalArgumentException(
|
||||
"outbox payload has trailing content at offset "
|
||||
+ scanner.position
|
||||
+ "; it must be exactly one JSON value");
|
||||
}
|
||||
}
|
||||
|
||||
/** A single-pass structural JSON validator over the payload text. */
|
||||
private static final class Scanner {
|
||||
|
||||
/**
|
||||
* The nesting ceiling.
|
||||
*
|
||||
* <p>Present because this validator recurses: without it a payload of ten thousand open
|
||||
* brackets overflows the stack of whatever thread appends the row.
|
||||
*/
|
||||
private static final int MAX_DEPTH = 64;
|
||||
|
||||
private final String text;
|
||||
private int position;
|
||||
|
||||
private Scanner(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
private boolean exhausted() {
|
||||
return position >= text.length();
|
||||
}
|
||||
|
||||
private void skipWhitespace() {
|
||||
while (position < text.length()) {
|
||||
char current = text.charAt(position);
|
||||
if (current == ' ' || current == '\t' || current == '\n' || current == '\r') {
|
||||
position++;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void readValue(int depth) {
|
||||
if (depth > MAX_DEPTH) {
|
||||
throw fail("nesting deeper than " + MAX_DEPTH + " levels");
|
||||
}
|
||||
if (exhausted()) {
|
||||
throw fail("a JSON value was expected");
|
||||
}
|
||||
char current = text.charAt(position);
|
||||
switch (current) {
|
||||
case '{' -> readObject(depth);
|
||||
case '[' -> readArray(depth);
|
||||
case '"' -> readString();
|
||||
case 't' -> readLiteral("true");
|
||||
case 'f' -> readLiteral("false");
|
||||
case 'n' -> readLiteral("null");
|
||||
default -> readNumber();
|
||||
}
|
||||
}
|
||||
|
||||
private void readObject(int depth) {
|
||||
expect('{');
|
||||
skipWhitespace();
|
||||
if (peekIs('}')) {
|
||||
position++;
|
||||
return;
|
||||
}
|
||||
while (true) {
|
||||
skipWhitespace();
|
||||
readString();
|
||||
skipWhitespace();
|
||||
expect(':');
|
||||
skipWhitespace();
|
||||
readValue(depth + 1);
|
||||
skipWhitespace();
|
||||
if (peekIs(',')) {
|
||||
position++;
|
||||
continue;
|
||||
}
|
||||
expect('}');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void readArray(int depth) {
|
||||
expect('[');
|
||||
skipWhitespace();
|
||||
if (peekIs(']')) {
|
||||
position++;
|
||||
return;
|
||||
}
|
||||
while (true) {
|
||||
skipWhitespace();
|
||||
readValue(depth + 1);
|
||||
skipWhitespace();
|
||||
if (peekIs(',')) {
|
||||
position++;
|
||||
continue;
|
||||
}
|
||||
expect(']');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void readString() {
|
||||
expect('"');
|
||||
while (true) {
|
||||
if (exhausted()) {
|
||||
throw fail("an unterminated string");
|
||||
}
|
||||
char current = text.charAt(position++);
|
||||
if (current == '"') {
|
||||
return;
|
||||
}
|
||||
if (current == '\\') {
|
||||
readEscape();
|
||||
} else if (current < 0x20) {
|
||||
// A raw control character inside a string is invalid JSON, and it is also exactly what
|
||||
// turns one log line into two.
|
||||
throw fail("a raw control character inside a string");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void readEscape() {
|
||||
if (exhausted()) {
|
||||
throw fail("an escape at the end of the payload");
|
||||
}
|
||||
char escaped = text.charAt(position++);
|
||||
switch (escaped) {
|
||||
case '"', '\\', '/', 'b', 'f', 'n', 'r', 't' -> {
|
||||
// A complete escape.
|
||||
}
|
||||
case 'u' -> {
|
||||
if (position + 4 > text.length()) {
|
||||
throw fail("a truncated unicode escape");
|
||||
}
|
||||
for (int index = 0; index < 4; index++) {
|
||||
char digit = text.charAt(position++);
|
||||
boolean hexadecimal =
|
||||
(digit >= '0' && digit <= '9')
|
||||
|| (digit >= 'a' && digit <= 'f')
|
||||
|| (digit >= 'A' && digit <= 'F');
|
||||
if (!hexadecimal) {
|
||||
throw fail("a unicode escape that is not hexadecimal");
|
||||
}
|
||||
}
|
||||
}
|
||||
default -> throw fail("an unknown escape \\" + escaped);
|
||||
}
|
||||
}
|
||||
|
||||
private void readNumber() {
|
||||
int start = position;
|
||||
if (peekIs('-')) {
|
||||
position++;
|
||||
}
|
||||
readDigits();
|
||||
if (peekIs('.')) {
|
||||
position++;
|
||||
readDigits();
|
||||
}
|
||||
if (peekIs('e') || peekIs('E')) {
|
||||
position++;
|
||||
if (peekIs('+') || peekIs('-')) {
|
||||
position++;
|
||||
}
|
||||
readDigits();
|
||||
}
|
||||
if (position == start) {
|
||||
throw fail("a JSON value was expected");
|
||||
}
|
||||
}
|
||||
|
||||
private void readDigits() {
|
||||
int start = position;
|
||||
while (position < text.length()
|
||||
&& text.charAt(position) >= '0'
|
||||
&& text.charAt(position) <= '9') {
|
||||
position++;
|
||||
}
|
||||
if (position == start) {
|
||||
throw fail("a number with no digits");
|
||||
}
|
||||
}
|
||||
|
||||
private void readLiteral(String literal) {
|
||||
if (!text.startsWith(literal, position)) {
|
||||
throw fail("an unrecognised literal");
|
||||
}
|
||||
position += literal.length();
|
||||
}
|
||||
|
||||
private boolean peekIs(char expected) {
|
||||
return position < text.length() && text.charAt(position) == expected;
|
||||
}
|
||||
|
||||
private void expect(char expected) {
|
||||
if (!peekIs(expected)) {
|
||||
throw fail("'" + expected + "' was expected");
|
||||
}
|
||||
position++;
|
||||
}
|
||||
|
||||
private IllegalArgumentException fail(String what) {
|
||||
// Deliberately reports the offset and not the text: the payload is business content and this
|
||||
// message reaches logs.
|
||||
return new IllegalArgumentException(
|
||||
"outbox payload is not valid JSON: " + what + " at offset " + position);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -7,8 +7,8 @@ import java.util.Objects;
|
||||
/**
|
||||
* Safe immutable allowlist for reporting a confirmed FAILED or DEAD outbox relay transition.
|
||||
*
|
||||
* <p>The report deliberately cannot carry an event payload, idempotency key, rendered message,
|
||||
* severity, arbitrary fields, or the whole {@link OutboxEvent}.
|
||||
* <p>The report deliberately cannot carry an event payload, envelope bytes, rendered message,
|
||||
* severity, arbitrary fields, or the whole {@link ClaimedOutboxEvent}.
|
||||
*
|
||||
* <p>It also cannot carry the exception. It used to, and the renderer passed that {@code Throwable}
|
||||
* to the logger as the event's cause — so the operational JSON gained a message and a stack trace
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "urn:dev-caskeleton:contracts:messaging:durable-operation.submitted:v1",
|
||||
"title": "DurableOperationSubmitted payload v1",
|
||||
"description": "Wakes a worker for one accepted durable operation. The worker reads what to run from the submission it claims, so the event carries only which operation and what kind of work it is.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"operationId",
|
||||
"operationName"
|
||||
],
|
||||
"properties": {
|
||||
"operationId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 128,
|
||||
"pattern": "^[A-Za-z0-9._~-]+$"
|
||||
},
|
||||
"operationName": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"unevaluatedProperties": false
|
||||
}
|
||||
+48
-29
@@ -4,9 +4,10 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.application.idempotency.RequestFingerprint;
|
||||
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
|
||||
import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder;
|
||||
import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStore;
|
||||
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
|
||||
import dev.caskeleton.application.outbox.NewOutboxEvent;
|
||||
import dev.caskeleton.application.outbox.OutboxAppendPort;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.application.usecase.CommandUseCase;
|
||||
import java.time.Clock;
|
||||
@@ -38,9 +39,10 @@ class SubmitDurableOperationUseCaseTest {
|
||||
private final RecordingOutbox outbox = new RecordingOutbox(insideTransaction);
|
||||
private final RollbackAwareTransactions transactions =
|
||||
new RollbackAwareTransactions(operations, outbox, insideTransaction);
|
||||
private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder();
|
||||
private final CommandUseCase<OperationCommand, OperationAcceptance> useCase =
|
||||
new SubmitDurableOperationUseCase(
|
||||
operations, outbox, transactions, Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
operations, outbox, encoder, transactions, Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
|
||||
private static OperationCommand command(DurableOperationId id, String hash) {
|
||||
return new OperationCommand(
|
||||
@@ -50,7 +52,6 @@ class SubmitDurableOperationUseCaseTest {
|
||||
null,
|
||||
new RequestFingerprint(hash),
|
||||
"{\"range\":\"2026-08\"}",
|
||||
"ReportRequested",
|
||||
Duration.ofHours(6));
|
||||
}
|
||||
|
||||
@@ -131,40 +132,58 @@ class SubmitDurableOperationUseCaseTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the outbox event carries the operation id as its routing key and dedup key")
|
||||
void outboxEventIsAnchoredToTheOperation() {
|
||||
void theOutboxEventIsTheSubmittedContractAnchoredToTheOperation() {
|
||||
// given
|
||||
useCase.handle(command(ID, "a".repeat(64)));
|
||||
|
||||
NewOutboxEvent event = outbox.appended.get(0);
|
||||
// when
|
||||
ValidatedIntegrationEvent event = outbox.appended.get(0);
|
||||
|
||||
// then
|
||||
// A worker that receives the message twice — which the relay's at-least-once delivery makes
|
||||
// ordinary — must be able to tell it is the same work. The operation id is what says so.
|
||||
assertThat(event.aggregateId()).isEqualTo("op-1");
|
||||
assertThat(event.idempotencyKey()).isEqualTo("op-1");
|
||||
assertThat(event.eventType()).isEqualTo("ReportRequested");
|
||||
assertThat(event)
|
||||
.extracting(
|
||||
e -> e.eventId().value(),
|
||||
e -> e.aggregate().aggregateId(),
|
||||
e -> e.contractId(),
|
||||
e -> e.logicalDestinationId())
|
||||
.containsExactly(
|
||||
"op-1",
|
||||
"op-1",
|
||||
DurableOperationSubmittedContract.CONTRACT_ID,
|
||||
DurableOperationSubmittedContract.DESTINATION);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a command with no event type is refused rather than accepted into silence")
|
||||
void missingEventTypeIsRefused() {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new OperationCommand(
|
||||
ID,
|
||||
"reports.generate",
|
||||
"alice",
|
||||
null,
|
||||
new RequestFingerprint("a".repeat(64)),
|
||||
"{}",
|
||||
" ",
|
||||
Duration.ofHours(1)))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("reaches no worker");
|
||||
void theSubmittedEventNamesTheOperationAndNotTheRequest() {
|
||||
// when
|
||||
useCase.handle(command(ID, "a".repeat(64)));
|
||||
|
||||
// then
|
||||
// The worker reads what to run from the submission it claims; the request never travels.
|
||||
assertThat(encoder.drafts())
|
||||
.<Object>extracting(draft -> draft.featurePayload())
|
||||
.containsExactly(new DurableOperationSubmitted("op-1", "reports.generate"));
|
||||
}
|
||||
|
||||
private static final class RecordingOutbox implements LegacyOutboxAppendPort {
|
||||
@Test
|
||||
void anOperationIdOutsideTheEventIdGrammarBecomesAStableDigestIdentity() {
|
||||
// given
|
||||
DurableOperationId tilde = new DurableOperationId("~report");
|
||||
|
||||
private final List<NewOutboxEvent> appended = new ArrayList<>();
|
||||
// when
|
||||
String identity = SubmitDurableOperationUseCase.canonicalIdentity(tilde);
|
||||
|
||||
// then
|
||||
assertThat(List.of(identity, SubmitDurableOperationUseCase.canonicalIdentity(tilde)))
|
||||
.allMatch(value -> value.matches("operation-[0-9a-f]{64}"))
|
||||
.containsOnly(identity);
|
||||
}
|
||||
|
||||
private static final class RecordingOutbox implements OutboxAppendPort {
|
||||
|
||||
private final List<ValidatedIntegrationEvent> appended = new ArrayList<>();
|
||||
private final List<String> appendedOutsideTransaction = new ArrayList<>();
|
||||
private final AtomicBoolean insideTransaction;
|
||||
private boolean failNext;
|
||||
@@ -174,11 +193,11 @@ class SubmitDurableOperationUseCaseTest {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void append(NewOutboxEvent event) {
|
||||
public void append(ValidatedIntegrationEvent event) {
|
||||
if (!insideTransaction.get()) {
|
||||
// The port's own contract: appending outside the caller's write transaction is silent
|
||||
// event loss, and it is invisible to any assertion about what ended up in the list.
|
||||
appendedOutsideTransaction.add(event.eventId());
|
||||
appendedOutsideTransaction.add(event.eventId().value());
|
||||
}
|
||||
if (failNext) {
|
||||
failNext = false;
|
||||
|
||||
+35
-59
@@ -1,79 +1,55 @@
|
||||
package dev.caskeleton.application.outbox;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.caskeleton.application.messaging.contract.ContractId;
|
||||
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
|
||||
import dev.caskeleton.application.messaging.contract.Sha256;
|
||||
import dev.caskeleton.application.messaging.event.AggregateIdentity;
|
||||
import dev.caskeleton.application.messaging.event.AggregateOrder;
|
||||
import dev.caskeleton.application.messaging.event.EventId;
|
||||
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import dev.caskeleton.application.outbox.testkit.OutboxEvents;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ClaimedOutboxEventContractTest {
|
||||
|
||||
private static final Instant OCCURRED_AT = Instant.parse("2026-09-18T03:00:00Z");
|
||||
|
||||
@Test
|
||||
void canonicalClaimExposesRelayIdentityWithoutLosingValidatedEvent() {
|
||||
ValidatedIntegrationEvent event = canonicalEvent();
|
||||
void aClaimExposesTheRelayIdentitiesOfTheValidatedEventItCarries() {
|
||||
// given
|
||||
ValidatedIntegrationEvent event = OutboxEvents.event("evt-1", "worklog-42", 17, OCCURRED_AT);
|
||||
|
||||
ClaimedOutboxEvent claimed =
|
||||
new CanonicalClaimedOutboxEvent(event, OutboxEventStatus.IN_FLIGHT, 2);
|
||||
// when
|
||||
ClaimedOutboxEvent claimed = new ClaimedOutboxEvent(event, OutboxEventStatus.IN_FLIGHT, 2);
|
||||
|
||||
assertThat(claimed.eventId()).isEqualTo(event.eventId().value());
|
||||
assertThat(claimed.eventType()).isEqualTo(event.contractId().value());
|
||||
assertThat(claimed.aggregateId()).isEqualTo(event.aggregate().aggregateId());
|
||||
assertThat(claimed.correlationId()).isEqualTo(event.correlationId());
|
||||
assertThat(claimed.occurredAt()).isEqualTo(event.occurredAt());
|
||||
assertThat(claimed.status()).isEqualTo(OutboxEventStatus.IN_FLIGHT);
|
||||
assertThat(claimed.attemptCount()).isEqualTo(2);
|
||||
assertThat(((CanonicalClaimedOutboxEvent) claimed).event()).isEqualTo(event);
|
||||
// then
|
||||
assertThat(claimed)
|
||||
.extracting(
|
||||
ClaimedOutboxEvent::eventId,
|
||||
ClaimedOutboxEvent::eventType,
|
||||
ClaimedOutboxEvent::aggregateId,
|
||||
ClaimedOutboxEvent::correlationId,
|
||||
ClaimedOutboxEvent::occurredAt,
|
||||
ClaimedOutboxEvent::event)
|
||||
.containsExactly(
|
||||
"evt-1",
|
||||
OutboxEvents.CONTRACT_ID,
|
||||
"worklog-42",
|
||||
"correlation-evt-1",
|
||||
OCCURRED_AT,
|
||||
event);
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyOutboxEventRemainsAClaimedSubtype() {
|
||||
ClaimedOutboxEvent claimed =
|
||||
new OutboxEvent(
|
||||
"legacy-1",
|
||||
"LegacyEvent",
|
||||
"aggregate-1",
|
||||
"{}",
|
||||
Instant.parse("2026-09-18T03:00:00Z"),
|
||||
"corr-1",
|
||||
"legacy-1",
|
||||
OutboxEventStatus.IN_FLIGHT,
|
||||
1);
|
||||
void aNegativeAttemptCountIsRefused() {
|
||||
// given
|
||||
ValidatedIntegrationEvent event = OutboxEvents.event("evt-2", OCCURRED_AT);
|
||||
|
||||
assertThat(claimed).isInstanceOf(OutboxEvent.class);
|
||||
}
|
||||
// when
|
||||
Throwable thrown =
|
||||
catchThrowable(() -> new ClaimedOutboxEvent(event, OutboxEventStatus.PENDING, -1));
|
||||
|
||||
private static ValidatedIntegrationEvent canonicalEvent() {
|
||||
String partition = "a".repeat(64);
|
||||
byte[] envelope = "{\"wire\":\"exact\"}".getBytes(StandardCharsets.UTF_8);
|
||||
Sha256 zero = new Sha256(new byte[32]);
|
||||
return new ValidatedIntegrationEvent(
|
||||
new EventId("01994e11-4d88-7000-8000-000000000001"),
|
||||
new ContractId("portfolio.worklog.reserved"),
|
||||
1,
|
||||
3,
|
||||
new LogicalDestinationId("portfolio-domain-events"),
|
||||
new AggregateIdentity("tenant-a", "worklog", "worklog-42"),
|
||||
new AggregateOrder(17, 2),
|
||||
Instant.parse("2026-09-18T03:00:00Z"),
|
||||
"corr-1",
|
||||
Optional.empty(),
|
||||
partition,
|
||||
partition.getBytes(StandardCharsets.US_ASCII),
|
||||
envelope,
|
||||
"application/json",
|
||||
zero,
|
||||
Sha256.of(envelope),
|
||||
zero,
|
||||
zero,
|
||||
"catalog-r1",
|
||||
"binding-r1");
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage("attemptCount must be >= 0, was -1");
|
||||
}
|
||||
}
|
||||
|
||||
-108
@@ -1,108 +0,0 @@
|
||||
package dev.caskeleton.application.outbox;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.time.Instant;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.NullAndEmptySource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
/** Validates {@link NewOutboxEvent} required-field invariants (D12). */
|
||||
class NewOutboxEventTest {
|
||||
|
||||
private static final Instant OCCURRED_AT = Instant.parse("2026-06-11T10:00:00Z");
|
||||
|
||||
@Test
|
||||
void validEventConstructsSuccessfully() {
|
||||
NewOutboxEvent event =
|
||||
new NewOutboxEvent("evt-1", "UserCreated", "agg-1", "{}", OCCURRED_AT, "corr-1", "ikey-1");
|
||||
assertThat(event.eventId()).isEqualTo("evt-1");
|
||||
assertThat(event.eventType()).isEqualTo("UserCreated");
|
||||
assertThat(event.aggregateId()).isEqualTo("agg-1");
|
||||
assertThat(event.payload()).isEqualTo("{}");
|
||||
assertThat(event.occurredAt()).isEqualTo(OCCURRED_AT);
|
||||
assertThat(event.correlationId()).isEqualTo("corr-1");
|
||||
assertThat(event.idempotencyKey()).isEqualTo("ikey-1");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" ", "\t", "\n"})
|
||||
void nullOrBlankEventIdIsRejected(String bad) {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new NewOutboxEvent(
|
||||
bad, "UserCreated", "agg-1", "{}", OCCURRED_AT, "corr-1", "ikey-1"))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("eventId");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" ", "\t"})
|
||||
void nullOrBlankEventTypeIsRejected(String bad) {
|
||||
assertThatThrownBy(
|
||||
() -> new NewOutboxEvent("evt-1", bad, "agg-1", "{}", OCCURRED_AT, "corr-1", "ikey-1"))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("eventType");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" "})
|
||||
void nullOrBlankAggregateIdIsRejected(String bad) {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new NewOutboxEvent(
|
||||
"evt-1", "UserCreated", bad, "{}", OCCURRED_AT, "corr-1", "ikey-1"))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("aggregateId");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" "})
|
||||
void nullOrBlankPayloadIsRejected(String bad) {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new NewOutboxEvent(
|
||||
"evt-1", "UserCreated", "agg-1", bad, OCCURRED_AT, "corr-1", "ikey-1"))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("payload");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullOccurredAtIsRejected() {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new NewOutboxEvent("evt-1", "UserCreated", "agg-1", "{}", null, "corr-1", "ikey-1"))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("occurredAt");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" "})
|
||||
void nullOrBlankCorrelationIdIsRejected(String bad) {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new NewOutboxEvent(
|
||||
"evt-1", "UserCreated", "agg-1", "{}", OCCURRED_AT, bad, "ikey-1"))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("correlationId");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" "})
|
||||
void nullOrBlankIdempotencyKeyIsRejected(String bad) {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new NewOutboxEvent(
|
||||
"evt-1", "UserCreated", "agg-1", "{}", OCCURRED_AT, "corr-1", bad))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("idempotencyKey");
|
||||
}
|
||||
}
|
||||
+7
-14
@@ -10,19 +10,12 @@ import org.junit.jupiter.api.Test;
|
||||
class OutboxAppendPortBoundaryTest {
|
||||
|
||||
@Test
|
||||
void canonicalAndLegacyAppendPortsHaveDisjointTypedInputs() {
|
||||
assertThat(singleAppendParameter(OutboxAppendPort.class))
|
||||
.isEqualTo(ValidatedIntegrationEvent.class);
|
||||
assertThat(singleAppendParameter(LegacyOutboxAppendPort.class)).isEqualTo(NewOutboxEvent.class);
|
||||
}
|
||||
|
||||
private static Class<?> singleAppendParameter(Class<?> portType) {
|
||||
Method append =
|
||||
Arrays.stream(portType.getDeclaredMethods())
|
||||
.filter(method -> method.getName().equals("append"))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
assertThat(append.getParameterCount()).isEqualTo(1);
|
||||
return append.getParameterTypes()[0];
|
||||
void theOnlyOutboxAppendTakesAValidatedIntegrationEvent() {
|
||||
assertThat(
|
||||
Arrays.stream(OutboxAppendPort.class.getDeclaredMethods())
|
||||
.map(Method::getParameterTypes)
|
||||
.map(Arrays::asList)
|
||||
.toList())
|
||||
.containsExactly(java.util.List.of(ValidatedIntegrationEvent.class));
|
||||
}
|
||||
}
|
||||
|
||||
-139
@@ -1,139 +0,0 @@
|
||||
package dev.caskeleton.application.outbox;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* What the outbox accepts as a payload.
|
||||
*
|
||||
* <p>It accepted anything. The envelope serialiser inserts the payload into the JSON document
|
||||
* verbatim and unescaped — that is documented, and nothing enforced the precondition it documents.
|
||||
* A payload that is not valid JSON produces an envelope no consumer can parse, permanently, because
|
||||
* the row is durable and the relay retries it until the attempt budget is gone. A payload
|
||||
* containing the envelope's own field syntax rewrites the envelope.
|
||||
*/
|
||||
class OutboxPayloadPolicyTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("ordinary JSON values are accepted")
|
||||
void ordinaryJsonValuesAreAccepted() {
|
||||
assertThatCode(
|
||||
() -> {
|
||||
OutboxPayloadPolicy.requireValidPayload("{}");
|
||||
OutboxPayloadPolicy.requireValidPayload("{\"orderId\":\"o-1\",\"amount\":12.5e3}");
|
||||
OutboxPayloadPolicy.requireValidPayload("[1,2,{\"a\":[true,false,null]}]");
|
||||
OutboxPayloadPolicy.requireValidPayload("\"a string\"");
|
||||
OutboxPayloadPolicy.requireValidPayload("-0.5");
|
||||
OutboxPayloadPolicy.requireValidPayload(" {\"padded\": true} ");
|
||||
})
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a payload that is not JSON is refused before the row is written")
|
||||
void aPayloadThatIsNotJsonIsRefused() {
|
||||
assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload("not json"))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("not valid JSON");
|
||||
assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload("{\"a\":}"))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload("{\"a\":1,}"))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload("[1,2"))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload(""))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a payload that would rewrite the envelope's own fields is refused")
|
||||
void aPayloadThatWouldRewriteTheEnvelopeIsRefused() {
|
||||
// Inserted verbatim, this closes the payload value and appends a field of its own.
|
||||
assertThatThrownBy(
|
||||
() -> OutboxPayloadPolicy.requireValidPayload("{\"a\":1},\"eventType\":\"forged\""))
|
||||
.as("the payload is concatenated into the envelope, so trailing content is an injection")
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("trailing content");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("two JSON values are not one payload")
|
||||
void twoJsonValuesAreNotOnePayload() {
|
||||
assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload("{} {}"))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("exactly one JSON value");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a raw control character inside a string is refused")
|
||||
void aRawControlCharacterInsideAStringIsRefused() {
|
||||
assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload("{\"a\":\"line\nbreak\"}"))
|
||||
.as("a raw newline is invalid JSON and is also what turns one log line into two")
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("control character");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the size limit is applied in UTF-8 bytes, at the boundary")
|
||||
void theSizeLimitIsAppliedInUtf8Bytes() {
|
||||
// A multi-byte character: a limit counted in char units would accept three times too much.
|
||||
String fill = "가";
|
||||
int perCharacter = fill.getBytes(StandardCharsets.UTF_8).length;
|
||||
int charactersThatFit = (OutboxPayloadPolicy.MAX_PAYLOAD_BYTES - 2) / perCharacter;
|
||||
|
||||
assertThatCode(
|
||||
() ->
|
||||
OutboxPayloadPolicy.requireValidPayload(
|
||||
"\"" + fill.repeat(charactersThatFit) + "\""))
|
||||
.doesNotThrowAnyException();
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
OutboxPayloadPolicy.requireValidPayload(
|
||||
"\"" + fill.repeat(charactersThatFit + 1) + "\""))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("UTF-8 bytes");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a surrogate pair survives the validator")
|
||||
void aSurrogatePairSurvivesTheValidator() {
|
||||
assertThatCode(() -> OutboxPayloadPolicy.requireValidPayload("{\"emoji\":\"🚀\"}"))
|
||||
.doesNotThrowAnyException();
|
||||
assertThatCode(
|
||||
() -> OutboxPayloadPolicy.requireValidPayload("{\"escaped\":\"\\ud83d\\ude80\"}"))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("deep nesting is refused rather than overflowing the appending thread's stack")
|
||||
void deepNestingIsRefused() {
|
||||
String deep = "[".repeat(5_000) + "]".repeat(5_000);
|
||||
|
||||
assertThatThrownBy(() -> OutboxPayloadPolicy.requireValidPayload(deep))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("nesting");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the outbox event applies the policy at construction")
|
||||
void theOutboxEventAppliesThePolicy() {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new OutboxEvent(
|
||||
"evt-1",
|
||||
"WorkLogReserved",
|
||||
"agg-1",
|
||||
"{\"unterminated\": ",
|
||||
java.time.Instant.parse("2026-08-10T09:00:00Z"),
|
||||
"corr-1",
|
||||
"idem-1",
|
||||
OutboxEventStatus.PENDING,
|
||||
0))
|
||||
.as("after the row commits, the relay retries an unparseable message until it is DEAD")
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
+3
-11
@@ -3,6 +3,7 @@ package dev.caskeleton.application.outbox;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore;
|
||||
import dev.caskeleton.application.outbox.testkit.OutboxEvents;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
@@ -148,17 +149,8 @@ class OutcomeAwareRelayTest {
|
||||
assertThat(store.failed()).containsKey("evt-5");
|
||||
}
|
||||
|
||||
private static OutboxEvent event(String eventId, int attemptCount) {
|
||||
return new OutboxEvent(
|
||||
eventId,
|
||||
"UserCreated",
|
||||
"agg-1",
|
||||
"{\"data\": \"test\"}",
|
||||
NOW.minusSeconds(60),
|
||||
"corr-" + eventId,
|
||||
"ikey-" + eventId,
|
||||
OutboxEventStatus.IN_FLIGHT,
|
||||
attemptCount);
|
||||
private static ClaimedOutboxEvent event(String eventId, int attemptCount) {
|
||||
return OutboxEvents.claimed(eventId, NOW.minusSeconds(60), attemptCount);
|
||||
}
|
||||
|
||||
/** A port that answers with an outcome, or throws when the test asks it to. */
|
||||
|
||||
+25
-56
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore;
|
||||
import dev.caskeleton.application.outbox.testkit.OutboxEvents;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
@@ -72,7 +73,7 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
|
||||
@Test
|
||||
void legacyVoidPublisherNormalReturnTransitionsEventToPublishedCharacterization() {
|
||||
OutboxEvent event = makeEvent("evt-1", "UserCreated", "agg-1", NOW.minusSeconds(60), 1);
|
||||
ClaimedOutboxEvent event = makeEvent("evt-1", "agg-1", NOW.minusSeconds(60), 1);
|
||||
store.addClaimable(event);
|
||||
|
||||
OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE);
|
||||
@@ -89,8 +90,8 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
@Test
|
||||
void multipleEventsPublishedInOccurredAtAscendingOrder() {
|
||||
// Add events out of order to ensure relay sorts defensively
|
||||
OutboxEvent late = makeEvent("evt-late", "UserUpdated", "agg-1", NOW.minusSeconds(10), 1);
|
||||
OutboxEvent early = makeEvent("evt-early", "UserCreated", "agg-1", NOW.minusSeconds(60), 1);
|
||||
ClaimedOutboxEvent late = makeEvent("evt-late", "agg-1", NOW.minusSeconds(10), 1);
|
||||
ClaimedOutboxEvent early = makeEvent("evt-early", "agg-1", NOW.minusSeconds(60), 1);
|
||||
store.addClaimable(late);
|
||||
store.addClaimable(early);
|
||||
|
||||
@@ -104,7 +105,7 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
|
||||
@Test
|
||||
void senderExceptionTransitionsEventToFailedWithBackoffCharacterization() {
|
||||
OutboxEvent event = makeEvent("evt-fail", "UserCreated", "agg-1", NOW.minusSeconds(60), 1);
|
||||
ClaimedOutboxEvent event = makeEvent("evt-fail", "agg-1", NOW.minusSeconds(60), 1);
|
||||
store.addClaimable(event);
|
||||
publishPort.failOn("evt-fail", new RuntimeException("broker down"));
|
||||
|
||||
@@ -123,9 +124,9 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
.containsExactly(
|
||||
OutboxRelayFailureReport.retryableFailure(
|
||||
"evt-fail",
|
||||
"UserCreated",
|
||||
OutboxEvents.CONTRACT_ID,
|
||||
"agg-1",
|
||||
"corr-evt-fail",
|
||||
"correlation-evt-fail",
|
||||
1,
|
||||
nextAttemptAt,
|
||||
publishPort.failureOn("evt-fail")));
|
||||
@@ -134,7 +135,7 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
@Test
|
||||
void senderExceptionAtRetryLimitTransitionsEventToDeadCharacterization() {
|
||||
// attemptCount=3 means this is the 3rd attempt — next failure should DEAD
|
||||
OutboxEvent event = makeEvent("evt-dead", "UserCreated", "agg-1", NOW.minusSeconds(60), 3);
|
||||
ClaimedOutboxEvent event = makeEvent("evt-dead", "agg-1", NOW.minusSeconds(60), 3);
|
||||
store.addClaimable(event);
|
||||
publishPort.failOn("evt-dead", new RuntimeException("persistent broker down"));
|
||||
|
||||
@@ -147,9 +148,9 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
.containsExactly(
|
||||
OutboxRelayFailureReport.deadLetter(
|
||||
"evt-dead",
|
||||
"UserCreated",
|
||||
OutboxEvents.CONTRACT_ID,
|
||||
"agg-1",
|
||||
"corr-evt-dead",
|
||||
"correlation-evt-dead",
|
||||
3,
|
||||
publishPort.failureOn("evt-dead")));
|
||||
}
|
||||
@@ -159,8 +160,8 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
@Test
|
||||
void failureIsNotSwallowedRelayContinuesWithNextEvent() {
|
||||
// Two events: first fails, second succeeds — both must produce status transitions
|
||||
OutboxEvent fail = makeEvent("evt-fail", "UserCreated", "agg-1", NOW.minusSeconds(120), 1);
|
||||
OutboxEvent ok = makeEvent("evt-ok", "UserUpdated", "agg-1", NOW.minusSeconds(60), 1);
|
||||
ClaimedOutboxEvent fail = makeEvent("evt-fail", "agg-1", NOW.minusSeconds(120), 1);
|
||||
ClaimedOutboxEvent ok = makeEvent("evt-ok", "agg-1", NOW.minusSeconds(60), 1);
|
||||
store.addClaimable(fail);
|
||||
store.addClaimable(ok);
|
||||
publishPort.failOn("evt-fail", new RuntimeException("transient"));
|
||||
@@ -190,7 +191,7 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
|
||||
@Test
|
||||
void failureOnSecondAttemptTransitionsToFailedNotDead() {
|
||||
OutboxEvent event = makeEvent("evt-2nd", "UserCreated", "agg-1", NOW.minusSeconds(60), 2);
|
||||
ClaimedOutboxEvent event = makeEvent("evt-2nd", "agg-1", NOW.minusSeconds(60), 2);
|
||||
store.addClaimable(event);
|
||||
publishPort.failOn("evt-2nd", new RuntimeException("2nd attempt failure"));
|
||||
|
||||
@@ -231,8 +232,7 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
*/
|
||||
@Test
|
||||
void legacyMarkPublishedFailureLeavesInFlightAndDuplicatePossibleCharacterization() {
|
||||
OutboxEvent event =
|
||||
makeEvent("evt-store-fail", "UserCreated", "agg-1", NOW.minusSeconds(60), 1);
|
||||
ClaimedOutboxEvent event = makeEvent("evt-store-fail", "agg-1", NOW.minusSeconds(60), 1);
|
||||
|
||||
MutableClock mutableClock = new MutableClock(NOW, ZoneOffset.UTC);
|
||||
TimeoutAwareThrowingOnMarkPublishedStorePort throwingStore =
|
||||
@@ -300,8 +300,8 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
*/
|
||||
@Test
|
||||
void markPublishedFailureAbortsRemainingBatchForCurrentTick() {
|
||||
OutboxEvent first = makeEvent("evt-first", "UserCreated", "agg-1", NOW.minusSeconds(120), 1);
|
||||
OutboxEvent second = makeEvent("evt-second", "UserUpdated", "agg-1", NOW.minusSeconds(60), 1);
|
||||
ClaimedOutboxEvent first = makeEvent("evt-first", "agg-1", NOW.minusSeconds(120), 1);
|
||||
ClaimedOutboxEvent second = makeEvent("evt-second", "agg-1", NOW.minusSeconds(60), 1);
|
||||
|
||||
ThrowingOnMarkPublishedStorePort throwingStore =
|
||||
new ThrowingOnMarkPublishedStorePort(new RuntimeException("DB down on markPublished"));
|
||||
@@ -341,7 +341,7 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
|
||||
@Test
|
||||
void markFailedFailurePropagatesAndEmitsNoReport() {
|
||||
OutboxEvent event = makeEvent("evt-fail", "UserCreated", "agg-1", NOW.minusSeconds(60), 1);
|
||||
ClaimedOutboxEvent event = makeEvent("evt-fail", "agg-1", NOW.minusSeconds(60), 1);
|
||||
ThrowingTransitionStorePort throwingStore =
|
||||
new ThrowingTransitionStorePort(new RuntimeException("markFailed failed"), null);
|
||||
throwingStore.addClaimable(event);
|
||||
@@ -365,7 +365,7 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
|
||||
@Test
|
||||
void markDeadFailurePropagatesAndEmitsNoReport() {
|
||||
OutboxEvent event = makeEvent("evt-dead", "UserCreated", "agg-1", NOW.minusSeconds(60), 3);
|
||||
ClaimedOutboxEvent event = makeEvent("evt-dead", "agg-1", NOW.minusSeconds(60), 3);
|
||||
ThrowingTransitionStorePort throwingStore =
|
||||
new ThrowingTransitionStorePort(null, new RuntimeException("markDead failed"));
|
||||
throwingStore.addClaimable(event);
|
||||
@@ -389,8 +389,8 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
|
||||
@Test
|
||||
void throwingReporterPreservesFailedOutcomeAndRelayContinues() {
|
||||
OutboxEvent failed = makeEvent("evt-fail", "UserCreated", "agg-1", NOW.minusSeconds(120), 1);
|
||||
OutboxEvent succeeded = makeEvent("evt-ok", "UserUpdated", "agg-1", NOW.minusSeconds(60), 1);
|
||||
ClaimedOutboxEvent failed = makeEvent("evt-fail", "agg-1", NOW.minusSeconds(120), 1);
|
||||
ClaimedOutboxEvent succeeded = makeEvent("evt-ok", "agg-1", NOW.minusSeconds(60), 1);
|
||||
store.addClaimable(failed);
|
||||
store.addClaimable(succeeded);
|
||||
publishPort.failOn("evt-fail", new RuntimeException("broker down"));
|
||||
@@ -420,43 +420,12 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
assertThat(store.published()).containsExactly("evt-ok");
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedReportDataPreservesFailedAndDeadOutcomesAndRelayContinues() {
|
||||
OutboxEvent failed = makeEvent("evt-fail", "UserCreated", " ", NOW.minusSeconds(180), 1);
|
||||
OutboxEvent dead = makeEvent("evt-dead", "UserDeleted", " ", NOW.minusSeconds(120), 3);
|
||||
OutboxEvent succeeded = makeEvent("evt-ok", "UserUpdated", "agg-1", NOW.minusSeconds(60), 1);
|
||||
store.addClaimable(failed);
|
||||
store.addClaimable(dead);
|
||||
store.addClaimable(succeeded);
|
||||
publishPort.failOn("evt-fail", new RuntimeException("transient broker failure"));
|
||||
publishPort.failOn("evt-dead", new RuntimeException("persistent broker failure"));
|
||||
|
||||
OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE);
|
||||
|
||||
assertThat(result.outcomes())
|
||||
.extracting(OutboxRelayResult.EventOutcome::outcome)
|
||||
.containsExactly(
|
||||
OutboxRelayResult.Outcome.FAILED,
|
||||
OutboxRelayResult.Outcome.DEAD,
|
||||
OutboxRelayResult.Outcome.PUBLISHED);
|
||||
assertThat(store.failed()).containsKey("evt-fail");
|
||||
assertThat(store.dead()).containsExactly("evt-dead");
|
||||
assertThat(store.published()).containsExactly("evt-ok");
|
||||
assertThat(reporter.reports).isEmpty();
|
||||
}
|
||||
|
||||
// ---- helper ----
|
||||
|
||||
private static OutboxEvent makeEvent(
|
||||
String eventId, String eventType, String aggregateId, Instant occurredAt, int attemptCount) {
|
||||
return new OutboxEvent(
|
||||
eventId,
|
||||
eventType,
|
||||
aggregateId,
|
||||
"{\"data\": \"test\"}",
|
||||
occurredAt,
|
||||
"corr-" + eventId,
|
||||
"ikey-" + eventId,
|
||||
private static ClaimedOutboxEvent makeEvent(
|
||||
String eventId, String aggregateId, Instant occurredAt, int attemptCount) {
|
||||
return new ClaimedOutboxEvent(
|
||||
OutboxEvents.event(eventId, aggregateId, 1, occurredAt),
|
||||
OutboxEventStatus.IN_FLIGHT,
|
||||
attemptCount);
|
||||
}
|
||||
@@ -491,7 +460,7 @@ class PublishPendingOutboxEventsUseCaseTest {
|
||||
private int markDeadCalls;
|
||||
|
||||
TimeoutAwareThrowingOnMarkPublishedStorePort(
|
||||
OutboxEvent event, RuntimeException markPublishedException) {
|
||||
ClaimedOutboxEvent event, RuntimeException markPublishedException) {
|
||||
this.eventId = event.eventId();
|
||||
this.markPublishedException = markPublishedException;
|
||||
addClaimable(event);
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
package dev.caskeleton.application.outbox.testkit;
|
||||
|
||||
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
|
||||
import dev.caskeleton.application.outbox.OutboxAppendPort;
|
||||
import dev.caskeleton.application.outbox.OutboxEventStatus;
|
||||
import dev.caskeleton.application.outbox.OutboxStorePort;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
@@ -16,7 +16,7 @@ class InMemoryOutboxStoreLeaseFencingContractTest extends OutboxLeaseFencingCont
|
||||
}
|
||||
|
||||
@Override
|
||||
protected LegacyOutboxAppendPort append() {
|
||||
protected OutboxAppendPort append() {
|
||||
return store;
|
||||
}
|
||||
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package dev.caskeleton.application.messaging.event.testkit;
|
||||
|
||||
import dev.caskeleton.application.messaging.contract.Sha256;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventDraft;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
|
||||
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The encoder fake: keeps every draft it was given and returns a validated event that carries the
|
||||
* draft's identities unchanged.
|
||||
*
|
||||
* <p>The envelope bytes are the draft's {@code toString()}, which is enough for a use-case test to
|
||||
* tell two events apart and nothing more; the canonical JSON rendering is the real encoder's
|
||||
* contract and is tested there.
|
||||
*/
|
||||
public final class FakeIntegrationEventEncoder implements IntegrationEventEncoderPort {
|
||||
|
||||
private static final Sha256 SCHEMA_HASH =
|
||||
Sha256.of("fake-integration-event-schema".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
private final List<IntegrationEventDraft<?>> drafts = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public ValidatedIntegrationEvent encode(IntegrationEventDraft<?> draft) {
|
||||
drafts.add(draft);
|
||||
byte[] envelope = draft.toString().getBytes(StandardCharsets.UTF_8);
|
||||
String partitionKey =
|
||||
HexFormat.of()
|
||||
.formatHex(
|
||||
Sha256.of(draft.aggregate().aggregateId().getBytes(StandardCharsets.UTF_8))
|
||||
.bytes());
|
||||
return new ValidatedIntegrationEvent(
|
||||
draft.eventId(),
|
||||
draft.contractId(),
|
||||
1,
|
||||
draft.payloadVersion(),
|
||||
draft.destinationId(),
|
||||
draft.aggregate(),
|
||||
draft.order(),
|
||||
draft.occurredAt(),
|
||||
draft.correlationId(),
|
||||
draft.causationId(),
|
||||
partitionKey,
|
||||
partitionKey.getBytes(StandardCharsets.US_ASCII),
|
||||
envelope,
|
||||
"application/json",
|
||||
SCHEMA_HASH,
|
||||
Sha256.of(envelope),
|
||||
SCHEMA_HASH,
|
||||
SCHEMA_HASH,
|
||||
"fake-catalog",
|
||||
"fake-binding");
|
||||
}
|
||||
|
||||
/** Every draft encoded so far, in order. */
|
||||
public List<IntegrationEventDraft<?>> drafts() {
|
||||
return List.copyOf(drafts);
|
||||
}
|
||||
}
|
||||
+25
-39
@@ -1,9 +1,9 @@
|
||||
package dev.caskeleton.application.outbox.testkit;
|
||||
|
||||
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
|
||||
import dev.caskeleton.application.outbox.NewOutboxEvent;
|
||||
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
|
||||
import dev.caskeleton.application.outbox.ClaimedOutboxEvent;
|
||||
import dev.caskeleton.application.outbox.OutboxAppendPort;
|
||||
import dev.caskeleton.application.outbox.OutboxCompletion;
|
||||
import dev.caskeleton.application.outbox.OutboxEvent;
|
||||
import dev.caskeleton.application.outbox.OutboxEventStatus;
|
||||
import dev.caskeleton.application.outbox.OutboxLease;
|
||||
import dev.caskeleton.application.outbox.OutboxStorePort;
|
||||
@@ -26,7 +26,7 @@ import java.util.Set;
|
||||
*
|
||||
* <p>Not final so a test can override one operation to inject a storage failure.
|
||||
*/
|
||||
public class InMemoryOutboxStore implements OutboxStorePort, LegacyOutboxAppendPort {
|
||||
public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort {
|
||||
|
||||
private static final Set<OutboxEventStatus> CLAIMABLE =
|
||||
Set.of(OutboxEventStatus.PENDING, OutboxEventStatus.FAILED, OutboxEventStatus.IN_FLIGHT);
|
||||
@@ -37,19 +37,8 @@ public class InMemoryOutboxStore implements OutboxStorePort, LegacyOutboxAppendP
|
||||
private final List<String> dead = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void append(NewOutboxEvent event) {
|
||||
add(
|
||||
new OutboxEvent(
|
||||
event.eventId(),
|
||||
event.eventType(),
|
||||
event.aggregateId(),
|
||||
event.payload(),
|
||||
event.occurredAt(),
|
||||
event.correlationId(),
|
||||
event.idempotencyKey(),
|
||||
OutboxEventStatus.PENDING,
|
||||
0),
|
||||
0);
|
||||
public void append(ValidatedIntegrationEvent event) {
|
||||
add(event, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,16 +48,22 @@ public class InMemoryOutboxStore implements OutboxStorePort, LegacyOutboxAppendP
|
||||
* @param claimedAs the event as the next claim returns it; its attempt count is the count after
|
||||
* that claim and must be at least 1
|
||||
*/
|
||||
public void addClaimable(OutboxEvent claimedAs) {
|
||||
public void addClaimable(ClaimedOutboxEvent claimedAs) {
|
||||
if (claimedAs.attemptCount() < 1) {
|
||||
throw new IllegalArgumentException("a claimed event has made at least one attempt");
|
||||
}
|
||||
add(claimedAs, claimedAs.attemptCount() - 1);
|
||||
add(claimedAs.event(), claimedAs.attemptCount() - 1);
|
||||
}
|
||||
|
||||
private void add(OutboxEvent event, int attemptsSoFar) {
|
||||
if (rows.putIfAbsent(event.eventId(), new Row(event, attemptsSoFar)) != null) {
|
||||
throw new IllegalStateException("duplicate outbox eventId " + event.eventId());
|
||||
/** Every event appended and still held, in append order. */
|
||||
public List<ValidatedIntegrationEvent> appended() {
|
||||
return rows.values().stream().map(row -> row.event).toList();
|
||||
}
|
||||
|
||||
private void add(ValidatedIntegrationEvent event, int attemptsSoFar) {
|
||||
String eventId = event.eventId().value();
|
||||
if (rows.putIfAbsent(eventId, new Row(event, attemptsSoFar)) != null) {
|
||||
throw new IllegalStateException("duplicate outbox eventId " + eventId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,7 +83,11 @@ public class InMemoryOutboxStore implements OutboxStorePort, LegacyOutboxAppendP
|
||||
row.nextAttemptAt = now.plus(inFlightTimeout);
|
||||
row.leaseOwner = owner;
|
||||
row.leaseToken++;
|
||||
leases.add(new OutboxLease(row.claimed(), owner, row.leaseToken));
|
||||
leases.add(
|
||||
new OutboxLease(
|
||||
new ClaimedOutboxEvent(row.event, row.status, row.attemptCount),
|
||||
owner,
|
||||
row.leaseToken));
|
||||
}
|
||||
return leases;
|
||||
}
|
||||
@@ -153,7 +152,7 @@ public class InMemoryOutboxStore implements OutboxStorePort, LegacyOutboxAppendP
|
||||
for (Row row : rows.values()) {
|
||||
if (row.status != OutboxEventStatus.PUBLISHED) {
|
||||
long age = Duration.between(row.event.occurredAt(), now).toSeconds();
|
||||
ages.merge(row.event.eventType(), age, Math::max);
|
||||
ages.merge(row.event.contractId().value(), age, Math::max);
|
||||
}
|
||||
}
|
||||
return ages;
|
||||
@@ -195,30 +194,17 @@ public class InMemoryOutboxStore implements OutboxStorePort, LegacyOutboxAppendP
|
||||
}
|
||||
|
||||
private static final class Row {
|
||||
private final OutboxEvent event;
|
||||
private final ValidatedIntegrationEvent event;
|
||||
private OutboxEventStatus status = OutboxEventStatus.PENDING;
|
||||
private int attemptCount;
|
||||
private Instant nextAttemptAt;
|
||||
private String leaseOwner;
|
||||
private long leaseToken;
|
||||
|
||||
private Row(OutboxEvent event, int attemptCount) {
|
||||
private Row(ValidatedIntegrationEvent event, int attemptCount) {
|
||||
this.event = event;
|
||||
this.attemptCount = attemptCount;
|
||||
this.nextAttemptAt = event.occurredAt();
|
||||
}
|
||||
|
||||
private OutboxEvent claimed() {
|
||||
return new OutboxEvent(
|
||||
event.eventId(),
|
||||
event.eventType(),
|
||||
event.aggregateId(),
|
||||
event.payload(),
|
||||
event.occurredAt(),
|
||||
event.correlationId(),
|
||||
event.idempotencyKey(),
|
||||
status,
|
||||
attemptCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-29
@@ -1,7 +1,6 @@
|
||||
package dev.caskeleton.application.outbox.testkit;
|
||||
|
||||
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
|
||||
import dev.caskeleton.application.outbox.NewOutboxEvent;
|
||||
import dev.caskeleton.application.outbox.OutboxAppendPort;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import java.time.Clock;
|
||||
import java.util.Objects;
|
||||
@@ -9,15 +8,16 @@ import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* Provider-neutral contract kit for the compatibility outbox append boundary.
|
||||
* Provider-neutral contract kit for the outbox append boundary: an append belongs to the caller's
|
||||
* write transaction, so it commits and rolls back with it.
|
||||
*
|
||||
* <p>The contract is intentionally expressed only in application-owned types. A persistence adapter
|
||||
* supplies its transaction port, append port, and a probe that can observe whether the event became
|
||||
* durable. No Spring, JPA, SQL, or provider type is part of this fixture.
|
||||
* <p>The contract is expressed only in application-owned types. A persistence adapter supplies its
|
||||
* transaction port, append port, and a probe that can observe whether the event became durable. No
|
||||
* Spring, JPA, SQL, or provider type is part of this fixture.
|
||||
*/
|
||||
public final class LegacyOutboxAppendContract {
|
||||
public final class OutboxAppendContract {
|
||||
|
||||
private LegacyOutboxAppendContract() {}
|
||||
private OutboxAppendContract() {}
|
||||
|
||||
/**
|
||||
* Verifies that an append performed inside a caller-owned write transaction disappears when that
|
||||
@@ -25,16 +25,16 @@ public final class LegacyOutboxAppendContract {
|
||||
*/
|
||||
public static void verifyRollbackRemovesEvent(
|
||||
TransactionPort transactions,
|
||||
LegacyOutboxAppendPort append,
|
||||
OutboxAppendPort append,
|
||||
Predicate<String> eventExists,
|
||||
Clock clock) {
|
||||
requireInputs(transactions, append, eventExists, clock);
|
||||
String eventId = "legacy-outbox-contract-rollback-" + UUID.randomUUID();
|
||||
String eventId = "outbox-contract-rollback-" + UUID.randomUUID();
|
||||
|
||||
try {
|
||||
transactions.inWrite(
|
||||
() -> {
|
||||
append.append(event(eventId, "rollback", clock));
|
||||
append.append(OutboxEvents.event(eventId, clock.instant()));
|
||||
throw new ExpectedRollback();
|
||||
});
|
||||
throw new AssertionError("write transaction swallowed the contract rollback signal");
|
||||
@@ -44,46 +44,34 @@ public final class LegacyOutboxAppendContract {
|
||||
|
||||
if (eventExists.test(eventId)) {
|
||||
throw new AssertionError(
|
||||
"legacy outbox append survived caller transaction rollback for event " + eventId);
|
||||
"outbox append survived caller transaction rollback for event " + eventId);
|
||||
}
|
||||
}
|
||||
|
||||
/** Verifies that an append becomes durable when the caller-owned write transaction commits. */
|
||||
public static void verifyCommitPersistsEvent(
|
||||
TransactionPort transactions,
|
||||
LegacyOutboxAppendPort append,
|
||||
OutboxAppendPort append,
|
||||
Predicate<String> eventExists,
|
||||
Clock clock) {
|
||||
requireInputs(transactions, append, eventExists, clock);
|
||||
String eventId = "legacy-outbox-contract-commit-" + UUID.randomUUID();
|
||||
String eventId = "outbox-contract-commit-" + UUID.randomUUID();
|
||||
|
||||
transactions.inWrite(
|
||||
() -> {
|
||||
append.append(event(eventId, "commit", clock));
|
||||
append.append(OutboxEvents.event(eventId, clock.instant()));
|
||||
return null;
|
||||
});
|
||||
|
||||
if (!eventExists.test(eventId)) {
|
||||
throw new AssertionError(
|
||||
"legacy outbox append was not durable after caller transaction commit for event "
|
||||
+ eventId);
|
||||
"outbox append was not durable after caller transaction commit for event " + eventId);
|
||||
}
|
||||
}
|
||||
|
||||
private static NewOutboxEvent event(String eventId, String scenario, Clock clock) {
|
||||
return new NewOutboxEvent(
|
||||
eventId,
|
||||
"LegacyOutboxContractEvent",
|
||||
"aggregate-" + eventId,
|
||||
"{\"scenario\":\"" + scenario + "\"}",
|
||||
clock.instant(),
|
||||
"correlation-" + eventId,
|
||||
eventId);
|
||||
}
|
||||
|
||||
private static void requireInputs(
|
||||
TransactionPort transactions,
|
||||
LegacyOutboxAppendPort append,
|
||||
OutboxAppendPort append,
|
||||
Predicate<String> eventExists,
|
||||
Clock clock) {
|
||||
Objects.requireNonNull(transactions, "transactions");
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package dev.caskeleton.application.outbox.testkit;
|
||||
|
||||
import dev.caskeleton.application.messaging.contract.ContractId;
|
||||
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
|
||||
import dev.caskeleton.application.messaging.contract.Sha256;
|
||||
import dev.caskeleton.application.messaging.event.AggregateIdentity;
|
||||
import dev.caskeleton.application.messaging.event.AggregateOrder;
|
||||
import dev.caskeleton.application.messaging.event.EventId;
|
||||
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
|
||||
import dev.caskeleton.application.outbox.ClaimedOutboxEvent;
|
||||
import dev.caskeleton.application.outbox.OutboxEventStatus;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Validated integration events for outbox tests.
|
||||
*
|
||||
* <p>Built directly rather than through an encoder: an outbox test is about where a row goes, not
|
||||
* how its bytes were rendered, and the value type still checks every invariant a real event has —
|
||||
* the envelope hash in particular is the SHA-256 of the envelope bytes.
|
||||
*/
|
||||
public final class OutboxEvents {
|
||||
|
||||
/** The contract every fixture event carries. */
|
||||
public static final String CONTRACT_ID = "testkit.outbox-event";
|
||||
|
||||
private static final Sha256 SCHEMA_HASH =
|
||||
Sha256.of("testkit-outbox-event-schema".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
private OutboxEvents() {}
|
||||
|
||||
/** An event of aggregate {@code aggregate-<eventId>} at sequence 1. */
|
||||
public static ValidatedIntegrationEvent event(String eventId, Instant occurredAt) {
|
||||
return event(eventId, "aggregate-" + eventId, 1, occurredAt);
|
||||
}
|
||||
|
||||
/** An event of the given aggregate at the given sequence. */
|
||||
public static ValidatedIntegrationEvent event(
|
||||
String eventId, String aggregateId, long sequence, Instant occurredAt) {
|
||||
byte[] envelope =
|
||||
("{\"eventId\":\"" + eventId + "\",\"aggregateId\":\"" + aggregateId + "\"}")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
String partitionKey =
|
||||
HexFormat.of().formatHex(Sha256.of(aggregateId.getBytes(StandardCharsets.UTF_8)).bytes());
|
||||
return new ValidatedIntegrationEvent(
|
||||
new EventId(eventId),
|
||||
new ContractId(CONTRACT_ID),
|
||||
1,
|
||||
1,
|
||||
new LogicalDestinationId("testkit-events"),
|
||||
new AggregateIdentity("default", "testkit", aggregateId),
|
||||
new AggregateOrder(sequence, 0),
|
||||
occurredAt,
|
||||
"correlation-" + eventId,
|
||||
Optional.empty(),
|
||||
partitionKey,
|
||||
partitionKey.getBytes(StandardCharsets.US_ASCII),
|
||||
envelope,
|
||||
"application/json",
|
||||
SCHEMA_HASH,
|
||||
Sha256.of(envelope),
|
||||
SCHEMA_HASH,
|
||||
SCHEMA_HASH,
|
||||
"testkit-catalog",
|
||||
"testkit-binding");
|
||||
}
|
||||
|
||||
/** The event as a claim returns it after {@code attemptCount} attempts. */
|
||||
public static ClaimedOutboxEvent claimed(String eventId, Instant occurredAt, int attemptCount) {
|
||||
return new ClaimedOutboxEvent(
|
||||
event(eventId, occurredAt), OutboxEventStatus.IN_FLIGHT, attemptCount);
|
||||
}
|
||||
}
|
||||
+3
-13
@@ -2,8 +2,7 @@ package dev.caskeleton.application.outbox.testkit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
|
||||
import dev.caskeleton.application.outbox.NewOutboxEvent;
|
||||
import dev.caskeleton.application.outbox.OutboxAppendPort;
|
||||
import dev.caskeleton.application.outbox.OutboxBackoffPolicy;
|
||||
import dev.caskeleton.application.outbox.OutboxCompletion;
|
||||
import dev.caskeleton.application.outbox.OutboxEventStatus;
|
||||
@@ -47,7 +46,7 @@ public abstract class OutboxLeaseFencingContract {
|
||||
|
||||
protected abstract OutboxStorePort store();
|
||||
|
||||
protected abstract LegacyOutboxAppendPort append();
|
||||
protected abstract OutboxAppendPort append();
|
||||
|
||||
protected abstract TransactionPort transactions();
|
||||
|
||||
@@ -161,16 +160,7 @@ public abstract class OutboxLeaseFencingContract {
|
||||
transactions()
|
||||
.inWrite(
|
||||
() -> {
|
||||
append()
|
||||
.append(
|
||||
new NewOutboxEvent(
|
||||
eventId,
|
||||
"LeaseFencingContractEvent",
|
||||
"aggregate-" + eventId,
|
||||
"{\"scenario\":\"" + scenario + "\"}",
|
||||
CLAIMED_AT.minusSeconds(1),
|
||||
"correlation-" + eventId,
|
||||
eventId));
|
||||
append().append(OutboxEvents.event(eventId, CLAIMED_AT.minusSeconds(1)));
|
||||
return null;
|
||||
});
|
||||
return eventId;
|
||||
|
||||
Reference in New Issue
Block a user