feat!: 남은 리뷰 발견을 고치고 개발 매뉴얼과 기능 생성 명령을 더한다
문제: High·P1을 고친 뒤에도 P2·P3 약 90건이 남았다. 연결·구독·메시지 크기 상한이 없는 전송(WebSocket·gRPC·GraphQL deadline), 낙관적 충돌의 500, upsert 경쟁, Mongo 무제한 timeout, 샘플 목록 N+1, 갈라진 복사본 (TenantId 3벌, 이벤트 ID 문법 5곳, SQLState 표 2벌), 문서를 읽는 PR 테스트와 캐시를 막는 lane 설정 등이다. 새 기능을 어디에 어떤 순서로 만드는지 알려 주는 문서와 도구가 없었다. MinIO 공식 이미지가 사라져 객체 저장소 lane이 돌지 않았다. 방법: 영역별 묶음으로 실패 테스트를 먼저 쓰고 고쳤다. 고치는 중에 찾은 결함도 함께 고쳤다(durable operation id가 UUIDv4라 이벤트가 전부 DEAD, S3 어댑터 생성·작은 chunk 읽기 실패, Redis 조건부 기록의 EVALSHA 권한). MinIO는 pgsty/minio를 digest로 고정했다(Chainguard는 태그·실행 사용자· mc 이미지 문제로 버림). docs/manual/에 작업 순서와 판단 지점을 쓰고, scripts/new-feature.sh가 5개 leaf에 뼈대를 만든다. 생성→빌드→통과 왕복을 verifyFeatureScaffold가 mainCheck에서 본다. 묶음별 결과와 결정은 리뷰 README 14절에 있다. 위험·한계: 파생 서비스 동작이 바뀐다. JDBC batch 50 기본, 운영 jar에서 H2 제거, 트랜잭션 30초 제한, 격리 수준을 Hikari에서 고정, gRPC· WebSocket·GraphQL 새 한도, correlation ID 규칙 밖이면 서버가 교체, 샘플 키 오류 코드 IDEMPOTENCY_KEY_INVALID. 새 leaf 두 개 (composition:durable-operation, adapter:inbound:messaging)와 새 마이그레이션(postgresql V20·V21, notification V11·V12, sample V8_1, grpc-ledger V002)이 생긴다. V21 유일 인덱스는 기존 중복이 있으면 실패한다(runbook에 확인 쿼리). 검증: ci, mainCheck(생성 명령 왕복 포함), integrationCheck(MinIO 포함 전 컨테이너 lane), -p optional-platforms ci integrationCheck 통과. Refs: docs/reviews/2026-11-01-maturity-review/README.md 14절 BREAKING CHANGE: JDBC batch 기본 켜짐, H2 운영 의존 제거, 트랜잭션 기본 제한 30초, gRPC·WebSocket·GraphQL 서버 한도 기본값 추가, 샘플 Idempotency-Key 오류 코드 변경.
This commit is contained in:
@@ -83,18 +83,37 @@ under `dev.caskeleton.application.notification` were removed on 2026-09-25; only
|
||||
|
||||
## Naming convention
|
||||
|
||||
- Inbound port implementations end with `UseCase` (e.g. `RegisterUserUseCase`). Enforced by ArchUnit.
|
||||
- Outbound port interfaces end with `Port` (e.g. `NotificationPort`).
|
||||
- Command records end with `Command`; query records end with `Query`.
|
||||
This section is the repository's naming rule book. `NamingConventionTest` (app-bootstrap
|
||||
architectureTest) enforces the machine-checkable rows; the rest are review rules, and a review checks
|
||||
them against this table. A new feature follows the "new code" column; the "existing exceptions" are
|
||||
named so nobody copies them by accident.
|
||||
|
||||
| Role | Name | Where | Existing exceptions (do not copy) |
|
||||
|---|---|---|---|
|
||||
| Use case (inbound port implementation) | `<Verb><Noun>UseCase`, enforced by ArchUnit | `application` package of the feature | `*ApplicationUseCase` (application-fileserver, application-notification), `*Service` (notification, fileserver) |
|
||||
| Command / query record | `*Command` / `*Query` | next to its use case | — |
|
||||
| Aggregate persistence (stores and returns whole aggregates) | `<Aggregate>Repository` | **domain** package of the aggregate, owned by the domain | — |
|
||||
| Technical store the application owns (outbox, idempotency, operation rows) | `<Thing>StorePort` | application package | `*WritePort` (old onboarding fixture, removed) |
|
||||
| Read model that returns projections, not aggregates | `<Thing>QueryPort` | application package; returns projections only (ArchUnit) | — |
|
||||
| Any other outbound port | `<Capability>Port` | application package | — |
|
||||
| Server-assigned id generation | `<Aggregate>IdFactory extends IdFactory<<Aggregate>Id>` | domain package; the id record `implements ResourceId<Self>` | `OutboxEventIdFactory` (sample; event ids are not resource ids) |
|
||||
| Configuration binding | `*Settings` (operational) or `*Policy` (authorization / domain policy), enforced by ArchUnit | the leaf that binds it | — |
|
||||
| Throwable | `*Exception`, enforced by ArchUnit | — | — |
|
||||
| Contract test kit for a port | abstract `<Port>Contract` in the port owner's testFixtures; the fake's and each adapter's test extend it | testFixtures | value-type tests were once named `*ContractTest`; they are `*ValueTypesTest` now |
|
||||
|
||||
The one-line rule for stores: **if the domain would recognise the thing it stores, it is a
|
||||
`Repository` in the domain; if it is plumbing the application needs, it is a `StorePort` in the
|
||||
application.**
|
||||
|
||||
## Canonical use case shape
|
||||
|
||||
```java
|
||||
@RequiresPermission("user:register")
|
||||
@UseCaseCapability(
|
||||
transactionMode = TransactionMode.WRITE,
|
||||
idempotency = Idempotency.KEYED,
|
||||
repositoryAccess = RepositoryAccess.WRITE_REPOSITORY)
|
||||
public final class RegisterUserUseCase implements CommandUseCase<RegisterUserCommand, User> {
|
||||
public class RegisterUserUseCase implements CommandUseCase<RegisterUserCommand, User> {
|
||||
|
||||
private final UserRepository users;
|
||||
private final TransactionPort tx;
|
||||
@@ -114,7 +133,13 @@ public final class RegisterUserUseCase implements CommandUseCase<RegisterUserCom
|
||||
```
|
||||
|
||||
The class is plain Java. A composition root constructs it with its ports and configuration values;
|
||||
application-core never self-registers with a DI framework.
|
||||
application-core never self-registers with a DI framework. It is **not final**: a mutating use case
|
||||
declares `@RequiresPermission`, the web adapter enforces it through a CGLIB proxy, and CGLIB cannot
|
||||
subclass a final class (`RequiresPermissionProxyabilityTest`). It is registered as a bean for the
|
||||
same reason — a use case built with `new` is never checked. A use case only the system calls (a
|
||||
scheduler, a relay) carries `@SystemInvoked(reason = ...)` instead of a permission and is not a bean.
|
||||
A composition with `@RequiresPermission` beans but no enforcing advisor fails startup
|
||||
(`composition:service-runtime` `PermissionEnforcementGuard`).
|
||||
|
||||
## Allowed transactional shapes
|
||||
|
||||
|
||||
@@ -315,7 +315,7 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장.
|
||||
### OutboxStorePort
|
||||
|
||||
- relay 측에서 outbox store 에 접근하는 포트. 모든 mutating 연산
|
||||
(`claimBatch`/`markPublished`/`markFailed`/`markDead`)은 relay 유스케이스가 소유한
|
||||
(`claimBatch`/`markPublished`/`markFailed`/`markDeferred`/`releaseLease`/`markDead`)은 relay 유스케이스가 소유한
|
||||
`TransactionPort.inWrite` 경계 안에서 호출하며, 구현은 자체 트랜잭션을 열지 않는다.
|
||||
- **claim 의미(I4 / I6)** — `claimBatch` 가 적격 행을 atomic 하게 `IN_FLIGHT` 로 전이시킨다:
|
||||
- 적격 행: `PENDING`, `next_attempt_at <= now` 인 `FAILED`, `next_attempt_at <= now` 인
|
||||
@@ -367,13 +367,19 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장.
|
||||
- 발행 성공(`CONFIRMED`) → `inWrite { markPublished }` → `PUBLISHED`.
|
||||
- 확정 거부(`REJECTED_BEFORE_SEND`·`REJECTED_AFTER_BROKER`) → 시도 예산과 무관하게 바로 `markDead`.
|
||||
- 일시적 실패(`AMBIGUOUS`·`REJECTED_RETRYABLE`, 즉 `OutboxPublishOutcome.retryable()`) →
|
||||
시도 예산을 쓰지 않고 항상 `markFailed(nextAttemptAt)`. broker 정지·종료 중·permit 부족·
|
||||
시도 예산을 쓰지 않고 항상 `markDeferred(nextAttemptAt)`(FAILED 전이 + 미룬 시도로 기록). broker 정지·종료 중·permit 부족·
|
||||
credential 교체는 모든 행을 같은 방식으로 실패시키고 저절로 끝나므로, 예산을 쓰게 하면 몇 분
|
||||
장애가 aggregate 머리마다 DEAD 행을 남긴다(2026-11-01 리뷰 06-01·06-03).
|
||||
- 발행 예외(`RuntimeException`, adapter가 분류하지 못한 실패): `attemptCount >= maxAttempts` 면
|
||||
`markDead`, 아니면 `markFailed(nextAttemptAt)`. 예산은 이 경우에만 쓴다 — payload 자체 결함일
|
||||
수 있는 실패가 aggregate를 영원히 막지 않게 하는 장치다. `attemptCount`는 일시적 실패의 claim도
|
||||
센다. 그래서 장애를 오래 기다린 행은 그 뒤 첫 발행 예외에서 바로 DEAD가 된다(알려진 한계).
|
||||
- 발행 예외(`RuntimeException`, adapter가 분류하지 못한 실패): `budgetedAttemptCount() >=
|
||||
maxAttempts` 면 `markDead`, 아니면 `markFailed(nextAttemptAt)`. 예산은 이 경우에만 쓴다 —
|
||||
payload 자체 결함일 수 있는 실패가 aggregate를 영원히 막지 않게 하는 장치다.
|
||||
`budgetedAttemptCount() = attemptCount - deferredAttemptCount`: 미룬(일시적 실패) claim은 빼고,
|
||||
결과를 남기지 못하고 죽은 claim(lease 만료)은 센다. 그래서 장애를 오래 기다린 행도 그 뒤 예산을
|
||||
온전히 받는다(예전 한계: `attemptCount`가 일시 실패 claim까지 세어 첫 발행 예외에서 바로 DEAD).
|
||||
재시도 지연은 계속 전체 `attemptCount`로 늘어나 긴 장애에서도 최대 5분 간격을 유지한다.
|
||||
- 멈춤 요청(`PublishPendingOutboxEventsCommand.stopRequested`, 종료 중인 scheduler가 건다): 지금
|
||||
발행을 끝낸 뒤 남은 claim은 발행하지 않고 `releaseLease(now)`로 놓는다 → `PENDING`, 시도 수에서
|
||||
그 claim을 빼고 바로 claim 가능. 결과는 `RELEASED`.
|
||||
- 전이를 먼저 성공시킨 뒤 해당 typed failure report를 보낸다.
|
||||
- `nextAttemptAt` 의 기준 시각은 **그 행이 실패한 시각**(`clock.instant()`)이다. 회차 시작
|
||||
시각을 쓰면 broker가 멈춘 동안 publish 하나가 deadline(약 5초)을 다 쓰므로 배치 뒤쪽 행은
|
||||
@@ -395,16 +401,16 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장.
|
||||
흡수(at-least-once). 배치 중간의 상태 갱신 실패가 그 tick 의 남은 배치를 중단시키는 것은
|
||||
허용된다 — DB 가 실패 중이면 뒤따르는 갱신도 실패할 테고, 다음 tick 이 모든 `IN_FLIGHT` 고아를
|
||||
재시도하기 때문.
|
||||
- **수동 와이어링(@Service 아님, context 빈 아님)**: `app-bootstrap` 이 수동으로 생성한다
|
||||
- **수동 와이어링(@Service 아님, context 빈 아님)**: outbox-relay composition이 직접 생성한다
|
||||
(`batchSize`·`inFlightTimeout` 같은 설정값이 필요해서 자동 등록이 안 된다). `UseCaseCapability`
|
||||
는 빈 등록 방식과 무관하게 필수다(ArchUnit 강제). 그리고 **Spring 빈으로 등록하면 안 된다**:
|
||||
클래스 레벨 `@RequiresPermission` pointcut(web `MethodSecurityConfig`)이 이 타입 빈을 CGLIB
|
||||
프록시하려 드는데, `final` 클래스라 불가능하고, 스케줄러 스레드엔 `Authentication` 이 없어 매
|
||||
relay tick 이 fail-closed 거부될 것이다.
|
||||
- **권한**: `"outbox:relay"` 는 시스템 내부 권한이다. relay 는 엔드유저가 아니라 스케줄러 빈이
|
||||
호출한다. `@RequiresPermission` 선언은 ArchUnit `mutating_use_cases_declare_required_permission`
|
||||
(D4) 을 충족시키기 위함이고, 스케줄러 컨텍스트에서의 실제 강제는 관례에 맡긴다(스케줄러는
|
||||
app-bootstrap 내부).
|
||||
relay를 부르는 것은 스케줄러뿐이고, 스케줄러 스레드에는 `Authentication`이 없다. 빈으로
|
||||
노출하면 전송 계층이 권한 검사 없이 닿을 수 있다.
|
||||
- **권한 선언 없음 — `@SystemInvoked`**: relay는 엔드유저가 아니라 시스템이 부르는 유스케이스라
|
||||
`@RequiresPermission`을 달지 않고 `@SystemInvoked(reason = ...)`로 그 사실을 적는다. 예전의
|
||||
`@RequiresPermission("outbox:relay")`는 D4 규칙을 통과시키려고 붙인 장식이었다(빈이 아니라 한
|
||||
번도 검사되지 않았고, 빈이었다면 매 tick 거부됐다). ArchUnit D4는 `@SystemInvoked`를 권한 선언
|
||||
대신 받고, `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`이 둘을 함께 다는 것을 막는다.
|
||||
|
||||
### OutboxBackoffPolicy
|
||||
|
||||
@@ -420,7 +426,7 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장.
|
||||
- 버린 대안: `MAX_ATTEMPTS` 만 늘리기(장애 길이에 비례해 계속 키워야 하고 진짜 poison 행이 늦게
|
||||
격리된다), 예산을 설정 키로 외부화(I10 — registry·runbook과 어긋난다; 일시적 실패가 예산을 쓰지
|
||||
않으므로 장애 길이에 맞춰 예산을 조정할 이유도 사라졌다), 일시적 실패 시 `attempt_count` 되돌리기
|
||||
(store 포트·SQL·계약 테스트를 넓히고, 지수 간격을 키울 근거가 사라진다).
|
||||
(지수 간격을 키울 근거가 사라진다 — 그래서 별도 열 `deferred_attempt_count`(V20)로 센다).
|
||||
- 더하는 spread 는 한 base 짜리 full jitter(`Backoff#fullJitter`, `[0, base]` 균등)이며 주입된
|
||||
`RandomGenerator` 로 뽑는다. 0 을 반환하는 generator 를 주면 테스트가 결정적이 된다(I10).
|
||||
- **상수는 고정이다(I10)**: `BASE_DELAY`·`MAX_ATTEMPTS`·jitter 범위는 설정 프로퍼티가 아니다.
|
||||
@@ -579,3 +585,18 @@ R1 오케스트레이션 타입(`dev.caskeleton.application.notification` 직속
|
||||
- **계층**: 순수 Java 인터페이스다. 구현은 application-core/domain-core 에서 참조하면 안 된다.
|
||||
consumer(`adapter-web` 의 `RequestLoggingFilter`)가 이 포트를 주입받아
|
||||
`AuthenticatedPrincipal.idpUserId()` 를 가명화한 뒤 `MDC.put("user_principal", ...)` 한다.
|
||||
|
||||
### OutboxAggregateSequencePort (2026-11-01 리뷰 06-07)
|
||||
|
||||
- aggregate의 다음 순서 번호(`AggregateOrder.sequence`)를 append와 같은 caller 쓰기 트랜잭션에서 준다.
|
||||
claim gate와 소비자가 이 번호로 "어느 변경이 나중인가"를 판단하므로 번호는 커밋 순서를 따라야 한다.
|
||||
벽시계(예전 샘플의 epoch 마이크로초)는 인스턴스 사이 시계 차이·NTP 되돌림·같은 마이크로초 두 건에서
|
||||
커밋 순서와 달라진다.
|
||||
- 계약(`OutboxAggregateSequenceContract`, fake `InMemoryOutboxAggregateSequences`와 JPA 구현이 공유):
|
||||
aggregate마다 1부터 하나씩 커지고 aggregate끼리 독립이다. JPA 구현(`JpaOutboxStore`, V21
|
||||
`outbox_aggregate_sequence`)은 counter row lock으로 같은 aggregate 쓰기를 직렬화하고, 기존 outbox
|
||||
row의 최대 번호 다음에서 시작하며, reaper가 row를 지워도 번호를 다시 쓰지 않는다. 같은
|
||||
`(tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index)` 두 번째 append는 V21
|
||||
유일 인덱스가 append 시점에 거부한다.
|
||||
- aggregate가 자체 version 열(낙관적 락)을 가지면 그 값을 써도 된다. 이 포트는 counter가 없는
|
||||
aggregate를 위한 것이다.
|
||||
|
||||
@@ -16,6 +16,10 @@ dependencies {
|
||||
testFixturesImplementation project(':shared-contract')
|
||||
testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api'
|
||||
testFixturesImplementation 'org.assertj:assertj-core'
|
||||
|
||||
// Use case tests run over the domain ports' fakes (a feature's in-memory repository and id
|
||||
// factory), which live with their owner in domain-core's test fixtures.
|
||||
testImplementation testFixtures(project(':domain-core'))
|
||||
}
|
||||
|
||||
// Half of the root `verifyMessagingContracts`: the integration-event contract, run by name, no skips.
|
||||
@@ -26,6 +30,5 @@ strictTestLanes {
|
||||
'dev.caskeleton.application.messaging.event.IntegrationEventDraftTest',
|
||||
'dev.caskeleton.application.messaging.event.ValidatedIntegrationEventTest'
|
||||
rejectSkipped = true
|
||||
jvmArgs '-Duser.timezone=UTC'
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+17
-1
@@ -2,7 +2,15 @@ package dev.caskeleton.application.cache;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/** Source revision plus an optional opaque condition captured by the preceding cache lookup. */
|
||||
/**
|
||||
* Source revision plus an optional opaque condition captured by the preceding cache lookup.
|
||||
*
|
||||
* <p>A usable {@code writeCondition} is checked before the intent: the write applies only while the
|
||||
* entry is still in the state the lookup that issued the condition saw. That is what rejects a slow
|
||||
* source load which began before an {@link CacheRegionPort#invalidate invalidation} and finished
|
||||
* after it. {@link CacheRecordIntent#ONLY_IF_SOURCE_REVISION_NEWER} orders revisions by {@link
|
||||
* CacheSourceRevisionOrder}.
|
||||
*/
|
||||
public record CacheRecordMetadata(
|
||||
String sourceRevision,
|
||||
CacheRecordIntent intent,
|
||||
@@ -33,6 +41,14 @@ public record CacheRecordMetadata(
|
||||
throw new IllegalArgumentException(
|
||||
"ONLY_IF_OBSERVED requires a usable cache observation token");
|
||||
}
|
||||
if (intent == CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER
|
||||
&& !CacheSourceRevisionOrder.isOrdered(sourceRevision)) {
|
||||
// Refused here, for every provider alike: "newer" needs the order the contract defines, and
|
||||
// a provider that quietly fell back to text order would rank revision 10 below revision 9.
|
||||
throw new IllegalArgumentException(
|
||||
"ONLY_IF_SOURCE_REVISION_NEWER needs a source revision that is a non-negative decimal"
|
||||
+ " integer without leading zeros");
|
||||
}
|
||||
if (intent != CacheRecordIntent.ONLY_IF_OBSERVED && observedToken.usable()) {
|
||||
throw new IllegalArgumentException(
|
||||
"a cache observation token is valid only for ONLY_IF_OBSERVED");
|
||||
|
||||
+15
@@ -12,6 +12,21 @@ public interface CacheRegionPort<K, V> {
|
||||
|
||||
CacheRecordOutcome recordAbsent(K key, AuthoritativeAbsence reason, CacheRecordMetadata metadata);
|
||||
|
||||
/**
|
||||
* Makes the key's entry invisible and refuses, for a bounded time, records based on lookups made
|
||||
* before this call.
|
||||
*
|
||||
* <p>A source load that began before the invalidation and finishes after it must not put the old
|
||||
* value back. A record whose {@link CacheWriteCondition} came from an earlier lookup is therefore
|
||||
* rejected with {@link CacheRecordOutcome#NOT_RECORDED_CONDITION}, and so is an unconditioned
|
||||
* {@link CacheRecordIntent#ONLY_IF_ABSENT} or {@link
|
||||
* CacheRecordIntent#ONLY_IF_SOURCE_REVISION_NEWER} while the invalidation marker lives. A lookup
|
||||
* made after the invalidation returns a condition that records normally. {@link
|
||||
* CacheRecordIntent#UPSERT} without a condition is unconditional and overwrites the marker.
|
||||
*
|
||||
* <p>There is no stampede protection: concurrent misses on one key each load from the source.
|
||||
* Single-flight, where it matters, is the caller's.
|
||||
*/
|
||||
CacheInvalidationOutcome invalidate(K key);
|
||||
|
||||
/**
|
||||
|
||||
Vendored
+69
@@ -0,0 +1,69 @@
|
||||
package dev.caskeleton.application.cache;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The order {@link CacheRecordIntent#ONLY_IF_SOURCE_REVISION_NEWER} compares source revisions by.
|
||||
*
|
||||
* <p>Part of the cache contract, not of any provider: "newer" means the same thing to every adapter
|
||||
* and fake, and to the application that produces the revisions. A source revision that takes part
|
||||
* in this order is a canonical non-negative decimal integer — digits only, no sign, no leading zero
|
||||
* except {@code "0"} itself — and revisions compare numerically at any length. Text order would
|
||||
* rank {@code "10"} below {@code "9"}; a floating-point parse would stop distinguishing revisions
|
||||
* above 2^53.
|
||||
*
|
||||
* <p>A provider that cannot run Java at the comparison point (Redis compares inside a Lua program,
|
||||
* so the check and the replacement are one atomic step) reimplements this rule there. The shared
|
||||
* {@code CacheRegionContract} in this module's test fixtures is what keeps those copies equal to
|
||||
* this one.
|
||||
*/
|
||||
public final class CacheSourceRevisionOrder {
|
||||
|
||||
private CacheSourceRevisionOrder() {}
|
||||
|
||||
/**
|
||||
* Whether a revision takes part in the order.
|
||||
*
|
||||
* @param revision the source revision
|
||||
* @return true for a canonical non-negative decimal integer
|
||||
*/
|
||||
public static boolean isOrdered(String revision) {
|
||||
Objects.requireNonNull(revision, "revision must be non-null");
|
||||
if (revision.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (int index = 0; index < revision.length(); index++) {
|
||||
char digit = revision.charAt(index);
|
||||
if (digit < '0' || digit > '9') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return revision.length() == 1 || revision.charAt(0) != '0';
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a candidate revision is strictly newer than a stored one.
|
||||
*
|
||||
* <p>Compared by length first and then digit by digit, which for canonical decimals is numeric
|
||||
* order. A stored revision outside the order is never proven older, so the answer is false.
|
||||
*
|
||||
* @param candidate the revision the caller wants to record; must be ordered
|
||||
* @param stored the revision already recorded
|
||||
* @return true only when both are ordered and the candidate is numerically greater
|
||||
* @throws IllegalArgumentException when the candidate is not ordered
|
||||
*/
|
||||
public static boolean isStrictlyNewer(String candidate, String stored) {
|
||||
if (!isOrdered(candidate)) {
|
||||
throw new IllegalArgumentException(
|
||||
"a source revision compared for ONLY_IF_SOURCE_REVISION_NEWER must be a non-negative"
|
||||
+ " decimal integer without leading zeros");
|
||||
}
|
||||
if (!isOrdered(stored)) {
|
||||
return false;
|
||||
}
|
||||
if (candidate.length() != stored.length()) {
|
||||
return candidate.length() > stored.length();
|
||||
}
|
||||
return candidate.compareTo(stored) > 0;
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -15,9 +15,8 @@ public record AggregateIdentity(String tenantScope, String aggregateType, String
|
||||
|| !aggregateType.matches("[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*")) {
|
||||
throw new IllegalArgumentException("aggregateType must be a canonical lower-case identifier");
|
||||
}
|
||||
if (aggregateId == null
|
||||
|| aggregateId.length() > 160
|
||||
|| !aggregateId.matches("[A-Za-z0-9][A-Za-z0-9._:-]*")) {
|
||||
if (!IntegrationIdentity.isCanonical(
|
||||
aggregateId, IntegrationIdentity.AGGREGATE_ID_MAX_LENGTH)) {
|
||||
throw new IllegalArgumentException("aggregateId must be a canonical bounded identifier");
|
||||
}
|
||||
}
|
||||
|
||||
+21
-1
@@ -1,8 +1,23 @@
|
||||
package dev.caskeleton.application.messaging.event;
|
||||
|
||||
/** Total order within one aggregate identity. */
|
||||
/**
|
||||
* Total order within one aggregate identity.
|
||||
*
|
||||
* <p>The sequence must follow the commit order of the aggregate's writes: the outbox claim gate
|
||||
* releases an aggregate's events in this order and consumers read it as "which change came last".
|
||||
* Three ways to choose it, named so a feature picks one instead of inventing a fourth: {@link
|
||||
* #first()} for an aggregate that only ever emits one event; the aggregate's own version column,
|
||||
* passed to the constructor; or, for an aggregate that keeps no counter, {@code
|
||||
* OutboxAggregateSequencePort#nextSequence} in the appending transaction.
|
||||
*
|
||||
* <p>Not the occurrence time. A wall clock is not the commit order when two instances' clocks
|
||||
* differ or NTP steps back, and two events in one microsecond share it (review 2026-11-01 06-07);
|
||||
* the {@code ofOccurrence} factory that encoded that rule was removed for the sequence port.
|
||||
*/
|
||||
public record AggregateOrder(long sequence, int eventIndex) {
|
||||
|
||||
private static final AggregateOrder FIRST = new AggregateOrder(1, 0);
|
||||
|
||||
public AggregateOrder {
|
||||
if (sequence <= 0) {
|
||||
throw new IllegalArgumentException("aggregate sequence must be positive");
|
||||
@@ -11,4 +26,9 @@ public record AggregateOrder(long sequence, int eventIndex) {
|
||||
throw new IllegalArgumentException("eventIndex must be non-negative");
|
||||
}
|
||||
}
|
||||
|
||||
/** The order of the only event an aggregate emits: sequence 1, index 0. */
|
||||
public static AggregateOrder first() {
|
||||
return FIRST;
|
||||
}
|
||||
}
|
||||
|
||||
+8
-5
@@ -1,14 +1,17 @@
|
||||
package dev.caskeleton.application.messaging.event;
|
||||
|
||||
/** Canonical integration-event identity. */
|
||||
/**
|
||||
* Canonical integration-event identity: {@link IntegrationIdentity#GRAMMAR}, at most 96 characters.
|
||||
*/
|
||||
public record EventId(String value) {
|
||||
|
||||
private static final String GRAMMAR = "[A-Za-z0-9][A-Za-z0-9._:-]*";
|
||||
|
||||
public EventId {
|
||||
if (value == null || value.length() > 96 || !value.matches(GRAMMAR)) {
|
||||
if (!IntegrationIdentity.isCanonical(value, IntegrationIdentity.EVENT_ID_MAX_LENGTH)) {
|
||||
throw new IllegalArgumentException(
|
||||
"eventId must be 1-96 US-ASCII characters matching " + "[A-Za-z0-9][A-Za-z0-9._:-]*");
|
||||
"eventId must be 1-"
|
||||
+ IntegrationIdentity.EVENT_ID_MAX_LENGTH
|
||||
+ " US-ASCII characters matching "
|
||||
+ IntegrationIdentity.GRAMMAR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-10
@@ -19,8 +19,6 @@ public record IntegrationEventDraft<P extends IntegrationPayload>(
|
||||
Optional<String> causationId,
|
||||
P featurePayload) {
|
||||
|
||||
private static final String CORRELATION_GRAMMAR = "[A-Za-z0-9][A-Za-z0-9._:-]*";
|
||||
|
||||
public IntegrationEventDraft {
|
||||
if (eventId == null
|
||||
|| contractId == null
|
||||
@@ -35,19 +33,13 @@ public record IntegrationEventDraft<P extends IntegrationPayload>(
|
||||
if (occurredAt == null) {
|
||||
throw new IllegalArgumentException("occurredAt must not be null");
|
||||
}
|
||||
requireCanonicalCorrelationIdentity("correlationId", correlationId);
|
||||
IntegrationIdentity.requireCorrelation("correlationId", correlationId);
|
||||
if (causationId == null) {
|
||||
throw new IllegalArgumentException("causationId Optional must not be null");
|
||||
}
|
||||
causationId.ifPresent(value -> requireCanonicalCorrelationIdentity("causationId", value));
|
||||
causationId.ifPresent(value -> IntegrationIdentity.requireCorrelation("causationId", value));
|
||||
if (featurePayload == null) {
|
||||
throw new IllegalArgumentException("featurePayload must not be null");
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireCanonicalCorrelationIdentity(String field, String value) {
|
||||
if (value == null || value.length() > 96 || !value.matches(CORRELATION_GRAMMAR)) {
|
||||
throw new IllegalArgumentException(field + " must be a canonical bounded US-ASCII identity");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package dev.caskeleton.application.messaging.event;
|
||||
|
||||
import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution;
|
||||
import dev.caskeleton.application.messaging.contract.IntegrationPayload;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Builds an {@link IntegrationEventDraft} from a contract with the rules every feature shares, so a
|
||||
* feature decides only what is really its own: the aggregate, the order and the payload.
|
||||
*
|
||||
* <p>Fixed here, once:
|
||||
*
|
||||
* <ul>
|
||||
* <li>Contract id, payload version and destination come from the contract, never typed again.
|
||||
* <li>The correlation id is the request's when it fits {@link IntegrationIdentity}, and otherwise
|
||||
* the event id. An unusable correlation header must not fail the business write, and an event
|
||||
* with no request behind it (a scheduler, a relay) correlates to itself.
|
||||
* <li>A single-tenant feature uses {@link #SINGLE_TENANT_SCOPE}. Before this, the sample said
|
||||
* {@code portfolio} and durable operations said {@code global} for the same meaning.
|
||||
* </ul>
|
||||
*
|
||||
* <p>The order rule is the feature's choice between the two {@link AggregateOrder} factories.
|
||||
*/
|
||||
public final class IntegrationEventDrafts {
|
||||
|
||||
/**
|
||||
* The tenant scope of an event that belongs to no tenant. Carrying a {@code TenantId} instead
|
||||
* needs a mapping into the lower-case scope grammar, which the messaging platform owns.
|
||||
*/
|
||||
public static final String SINGLE_TENANT_SCOPE = "global";
|
||||
|
||||
private IntegrationEventDrafts() {}
|
||||
|
||||
/**
|
||||
* A draft of {@code contract} with no causation.
|
||||
*
|
||||
* @param contract the contract the event follows
|
||||
* @param eventId the event id consumers deduplicate on
|
||||
* @param aggregate tenant scope, aggregate type and id
|
||||
* @param order the order within the aggregate
|
||||
* @param occurredAt when it happened
|
||||
* @param requestCorrelationId the caller's correlation id, if there is one
|
||||
* @param payload the payload record
|
||||
* @param <P> the payload type
|
||||
* @return the draft, ready for {@link IntegrationEventEncoderPort#encode}
|
||||
*/
|
||||
public static <P extends IntegrationPayload> IntegrationEventDraft<P> draft(
|
||||
IntegrationEventContractContribution<P> contract,
|
||||
EventId eventId,
|
||||
AggregateIdentity aggregate,
|
||||
AggregateOrder order,
|
||||
Instant occurredAt,
|
||||
Optional<String> requestCorrelationId,
|
||||
P payload) {
|
||||
if (contract == null || eventId == null || requestCorrelationId == null) {
|
||||
throw new IllegalArgumentException("contract, eventId and requestCorrelationId are required");
|
||||
}
|
||||
return new IntegrationEventDraft<>(
|
||||
eventId,
|
||||
contract.contractId(),
|
||||
contract.payloadVersion(),
|
||||
contract.descriptor().logicalDestination(),
|
||||
aggregate,
|
||||
order,
|
||||
occurredAt,
|
||||
correlationId(requestCorrelationId, eventId),
|
||||
Optional.empty(),
|
||||
payload);
|
||||
}
|
||||
|
||||
/** The request's correlation id when it is canonical, otherwise the event id. */
|
||||
static String correlationId(Optional<String> requestCorrelationId, EventId eventId) {
|
||||
return requestCorrelationId
|
||||
.filter(
|
||||
value ->
|
||||
IntegrationIdentity.isCanonical(value, IntegrationIdentity.CORRELATION_MAX_LENGTH))
|
||||
.orElse(eventId.value());
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package dev.caskeleton.application.messaging.event;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The one identity grammar integration events use: event ids, correlation and causation ids and
|
||||
* aggregate ids.
|
||||
*
|
||||
* <p>Five places used to spell {@code [A-Za-z0-9][A-Za-z0-9._:-]} out themselves with two different
|
||||
* length bounds, so a correlation id could pass one path and be refused by another. The grammar and
|
||||
* the bounds live here; a caller that needs to test a value before building an event (a request
|
||||
* correlation id that may not fit, an operation id that may be too long) asks {@link
|
||||
* #isCanonical(String, int)} instead of copying the pattern.
|
||||
*/
|
||||
public final class IntegrationIdentity {
|
||||
|
||||
/** US-ASCII letters and digits, then any of {@code . _ : -}; never starts with a separator. */
|
||||
public static final String GRAMMAR = "[A-Za-z0-9][A-Za-z0-9._:-]*";
|
||||
|
||||
/** Upper bound of an event id. */
|
||||
public static final int EVENT_ID_MAX_LENGTH = 96;
|
||||
|
||||
/**
|
||||
* Upper bound of a correlation or causation id: the width of the outbox {@code correlation_id}
|
||||
* and {@code causation_id} columns. A draft and a stored event share it, so an event read back
|
||||
* from the outbox is never refused on the way in.
|
||||
*/
|
||||
public static final int CORRELATION_MAX_LENGTH = 128;
|
||||
|
||||
/** Upper bound of an aggregate id. */
|
||||
public static final int AGGREGATE_ID_MAX_LENGTH = 160;
|
||||
|
||||
private static final Pattern PATTERN = Pattern.compile(GRAMMAR);
|
||||
|
||||
private IntegrationIdentity() {}
|
||||
|
||||
/**
|
||||
* Whether {@code value} is a canonical identity of at most {@code maxLength} characters.
|
||||
*
|
||||
* @param value the candidate; {@code null} is not canonical
|
||||
* @param maxLength the bound for this kind of identity
|
||||
* @return {@code true} when it matches {@link #GRAMMAR} within the bound
|
||||
*/
|
||||
public static boolean isCanonical(String value, int maxLength) {
|
||||
return value != null
|
||||
&& !value.isEmpty()
|
||||
&& value.length() <= maxLength
|
||||
&& PATTERN.matcher(value).matches();
|
||||
}
|
||||
|
||||
/** Refuses a correlation or causation id outside the grammar or the bound. */
|
||||
static void requireCorrelation(String field, String value) {
|
||||
if (!isCanonical(value, CORRELATION_MAX_LENGTH)) {
|
||||
throw new IllegalArgumentException(field + " must be a canonical bounded US-ASCII identity");
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -33,8 +33,6 @@ public record ValidatedIntegrationEvent(
|
||||
String contractCatalogRevision,
|
||||
String destinationBindingRevision) {
|
||||
|
||||
// 128 characters: the width of the outbox correlation_id and causation_id columns.
|
||||
private static final String CORRELATION_GRAMMAR = "[A-Za-z0-9][A-Za-z0-9._:-]{0,127}";
|
||||
private static final String REVISION_GRAMMAR = "[a-z0-9][a-z0-9._:-]{0,95}";
|
||||
private static final String CONTENT_TYPE_GRAMMAR = "[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+";
|
||||
|
||||
@@ -52,12 +50,11 @@ public record ValidatedIntegrationEvent(
|
||||
if (occurredAt == null) {
|
||||
throw new IllegalArgumentException("occurredAt must not be null");
|
||||
}
|
||||
requireCanonicalIdentity("correlationId", correlationId, CORRELATION_GRAMMAR);
|
||||
IntegrationIdentity.requireCorrelation("correlationId", correlationId);
|
||||
if (causationId == null) {
|
||||
throw new IllegalArgumentException("causationId Optional must not be null");
|
||||
}
|
||||
causationId.ifPresent(
|
||||
value -> requireCanonicalIdentity("causationId", value, CORRELATION_GRAMMAR));
|
||||
causationId.ifPresent(value -> IntegrationIdentity.requireCorrelation("causationId", value));
|
||||
if (partitionKeyText == null || !partitionKeyText.matches("[0-9a-f]{64}")) {
|
||||
throw new IllegalArgumentException(
|
||||
"partitionKeyText must contain exactly 64 lower-case hexadecimal characters");
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package dev.caskeleton.application.operation;
|
||||
|
||||
/**
|
||||
* Mints the id of a newly submitted durable operation. Identifier generation stays out of the
|
||||
* transport and the application layer; an infrastructure adapter implements this.
|
||||
*
|
||||
* <p>The id is a canonical lower-case UUIDv7. It becomes the submission event's id ({@link
|
||||
* SubmitDurableOperationUseCase}), and the messaging platform carries an event id only as a UUIDv7
|
||||
* message id: any other id is refused at publish time and the event is dead-lettered after the
|
||||
* business transaction already committed (review 2026-11-01 06-06).
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface DurableOperationIdFactory {
|
||||
|
||||
/**
|
||||
* Returns a new operation id.
|
||||
*
|
||||
* @return a canonical lower-case UUIDv7 id
|
||||
*/
|
||||
DurableOperationId newOperationId();
|
||||
}
|
||||
+14
-13
@@ -7,7 +7,9 @@ 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.IntegrationEventDrafts;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationIdentity;
|
||||
import dev.caskeleton.application.outbox.OutboxAppendPort;
|
||||
import dev.caskeleton.application.security.RequiresPermission;
|
||||
import dev.caskeleton.application.transaction.TransactionMode;
|
||||
@@ -17,7 +19,6 @@ import dev.caskeleton.shared.digest.Sha256;
|
||||
import java.time.Clock;
|
||||
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.
|
||||
@@ -61,11 +62,9 @@ import java.util.regex.Pattern;
|
||||
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 static final DurableOperationSubmittedContract CONTRACT =
|
||||
new DurableOperationSubmittedContract();
|
||||
|
||||
private final DurableOperationStorePort operations;
|
||||
private final OutboxAppendPort outbox;
|
||||
@@ -143,15 +142,17 @@ public class SubmitDurableOperationUseCase
|
||||
private static IntegrationEventDraft<DurableOperationSubmitted> submittedEvent(
|
||||
DurableOperation operation) {
|
||||
String identity = canonicalIdentity(operation.operationId());
|
||||
return new IntegrationEventDraft<>(
|
||||
// Single-tenant scope even when the command names a tenant: the event only wakes a worker, the
|
||||
// tenant travels in the stored operation, and mapping a TenantId into the lower-case scope
|
||||
// grammar is the messaging platform's decision, not this use case's.
|
||||
// No request correlation: the event correlates to the operation itself, so a retry under the
|
||||
// same operation id produces the same event.
|
||||
return IntegrationEventDrafts.draft(
|
||||
CONTRACT,
|
||||
new EventId(identity),
|
||||
DurableOperationSubmittedContract.CONTRACT_ID,
|
||||
1,
|
||||
DurableOperationSubmittedContract.DESTINATION,
|
||||
new AggregateIdentity(TENANT_SCOPE, AGGREGATE_TYPE, identity),
|
||||
FIRST_EVENT,
|
||||
new AggregateIdentity(IntegrationEventDrafts.SINGLE_TENANT_SCOPE, AGGREGATE_TYPE, identity),
|
||||
AggregateOrder.first(),
|
||||
operation.submittedAt(),
|
||||
identity,
|
||||
Optional.empty(),
|
||||
new DurableOperationSubmitted(operation.operationId().value(), operation.operationName()));
|
||||
}
|
||||
@@ -166,7 +167,7 @@ public class SubmitDurableOperationUseCase
|
||||
*/
|
||||
static String canonicalIdentity(DurableOperationId operationId) {
|
||||
String value = operationId.value();
|
||||
if (value.length() <= MAXIMUM_EVENT_ID_LENGTH && EVENT_ID_GRAMMAR.matcher(value).matches()) {
|
||||
if (IntegrationIdentity.isCanonical(value, IntegrationIdentity.EVENT_ID_MAX_LENGTH)) {
|
||||
return value;
|
||||
}
|
||||
return "operation-" + Sha256.ofUtf8(value).hex();
|
||||
|
||||
+31
-2
@@ -14,10 +14,17 @@ import java.util.Objects;
|
||||
*
|
||||
* @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
|
||||
* @param attemptCount claims made, counting the claim that returned this row; the retry delay grows
|
||||
* with it
|
||||
* @param deferredAttemptCount earlier claims that ended in a transient outcome ({@link
|
||||
* OutboxPublishOutcome#retryable()}) and were marked with {@link OutboxStorePort#markDeferred};
|
||||
* they are about the moment, not the message, so they do not count against the attempt budget
|
||||
*/
|
||||
public record ClaimedOutboxEvent(
|
||||
ValidatedIntegrationEvent event, OutboxEventStatus status, int attemptCount) {
|
||||
ValidatedIntegrationEvent event,
|
||||
OutboxEventStatus status,
|
||||
int attemptCount,
|
||||
int deferredAttemptCount) {
|
||||
|
||||
public ClaimedOutboxEvent {
|
||||
Objects.requireNonNull(event, "event must not be null");
|
||||
@@ -25,6 +32,28 @@ public record ClaimedOutboxEvent(
|
||||
if (attemptCount < 0) {
|
||||
throw new IllegalArgumentException("attemptCount must be >= 0, was " + attemptCount);
|
||||
}
|
||||
if (deferredAttemptCount < 0 || deferredAttemptCount > attemptCount) {
|
||||
throw new IllegalArgumentException(
|
||||
"deferredAttemptCount must be between 0 and attemptCount ("
|
||||
+ attemptCount
|
||||
+ "), was "
|
||||
+ deferredAttemptCount);
|
||||
}
|
||||
}
|
||||
|
||||
/** A row none of whose earlier claims was deferred. */
|
||||
public ClaimedOutboxEvent(
|
||||
ValidatedIntegrationEvent event, OutboxEventStatus status, int attemptCount) {
|
||||
this(event, status, attemptCount, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* The attempts that count against {@link OutboxBackoffPolicy#MAX_ATTEMPTS}: every claim except
|
||||
* the deferred ones. A claim whose relay died before writing a result counts, because a message
|
||||
* that kills the relay is exactly what the budget exists to isolate.
|
||||
*/
|
||||
public int budgetedAttemptCount() {
|
||||
return attemptCount - deferredAttemptCount;
|
||||
}
|
||||
|
||||
public String eventId() {
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package dev.caskeleton.application.outbox;
|
||||
|
||||
import dev.caskeleton.application.messaging.event.AggregateIdentity;
|
||||
|
||||
/**
|
||||
* Hands out an aggregate's next order number ({@code AggregateOrder.sequence}) for an event about
|
||||
* to be appended to the outbox.
|
||||
*
|
||||
* <p>The claim gate releases an aggregate's events in this order, and consumers read it as "which
|
||||
* change came last". So the number must grow with the commit order of the aggregate's writes. A
|
||||
* wall clock does not: two instances whose clocks differ, an NTP step back, or two events in one
|
||||
* microsecond each produce an order that is not the commit order, and the gate then releases a
|
||||
* later change first or two events in no defined order (review 06-07). An aggregate whose own
|
||||
* version column already counts its writes may use that instead; this port is for the aggregates
|
||||
* that keep no counter.
|
||||
*
|
||||
* <p>Contract, which {@code OutboxAggregateSequenceContract} holds every implementation to:
|
||||
*
|
||||
* <ul>
|
||||
* <li>Called inside the caller's write transaction ({@code TransactionPort.inWrite}), the same
|
||||
* one that appends the event. The number is taken under a lock on the aggregate's counter, so
|
||||
* a second writer of the same aggregate waits for the first to commit or roll back; a rolled
|
||||
* back number is handed out again.
|
||||
* <li>Strictly greater than every number this port returned for the aggregate before, including
|
||||
* for events the retention reaper has since deleted, and greater than any number an earlier
|
||||
* outbox row of the aggregate carries.
|
||||
* <li>Independent per aggregate identity: one aggregate's numbers say nothing about another's.
|
||||
* </ul>
|
||||
*/
|
||||
public interface OutboxAggregateSequencePort {
|
||||
|
||||
/**
|
||||
* Returns the aggregate's next order number, at least 1.
|
||||
*
|
||||
* @param aggregate the aggregate the event is about
|
||||
* @return the number to put in the event's {@code AggregateOrder}
|
||||
*/
|
||||
long nextSequence(AggregateIdentity aggregate);
|
||||
}
|
||||
+16
-1
@@ -20,6 +20,14 @@ public record OutboxRelayResult(int claimedCount, List<EventOutcome> outcomes) {
|
||||
outcomes = List.copyOf(Objects.requireNonNull(outcomes, "outcomes must not be null"));
|
||||
}
|
||||
|
||||
/**
|
||||
* True when at least one row was published. Publishing the head of an aggregate is what makes its
|
||||
* next row claimable, so a cycle that published something may have more work right behind it.
|
||||
*/
|
||||
public boolean publishedAny() {
|
||||
return outcomes.stream().anyMatch(outcome -> outcome.outcome() == Outcome.PUBLISHED);
|
||||
}
|
||||
|
||||
/**
|
||||
* Outcome of a single event during one relay cycle.
|
||||
*
|
||||
@@ -60,6 +68,13 @@ public record OutboxRelayResult(int claimedCount, List<EventOutcome> outcomes) {
|
||||
* written, so nothing was written. The other relay owns the row's outcome; the broker may have
|
||||
* seen this relay's attempt as well.
|
||||
*/
|
||||
STALE
|
||||
STALE,
|
||||
|
||||
/**
|
||||
* The relay was asked to stop before it reached this row, so it gave the claim back without
|
||||
* publishing ({@link OutboxStorePort#releaseLease}). Nothing was sent and no attempt was spent;
|
||||
* the row is claimable again at once, by this relay after a restart or by another instance.
|
||||
*/
|
||||
RELEASED
|
||||
}
|
||||
}
|
||||
|
||||
+30
-2
@@ -41,8 +41,9 @@ public interface OutboxStorePort {
|
||||
|
||||
/**
|
||||
* Marks the leased event as failed and schedules the next retry attempt. Must be called inside
|
||||
* {@code TransactionPort.inWrite(...)} when a publish fails transiently and {@code attemptCount <
|
||||
* maxAttempts}.
|
||||
* {@code TransactionPort.inWrite(...)} when a publish failed in a way the adapter could not
|
||||
* classify and the budget is not spent ({@code budgetedAttemptCount < maxAttempts}). This claim
|
||||
* counts against the budget; a transient outcome uses {@link #markDeferred} instead.
|
||||
*
|
||||
* @param lease the claim this relay holds
|
||||
* @param nextAttemptAt the earliest instant at which the event may be re-claimed
|
||||
@@ -50,6 +51,33 @@ public interface OutboxStorePort {
|
||||
*/
|
||||
OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt);
|
||||
|
||||
/**
|
||||
* Marks the leased event as failed for a reason that belongs to the moment — the broker did not
|
||||
* answer, or refused for now ({@link OutboxPublishOutcome#retryable()}) — and schedules the next
|
||||
* attempt. Same transition as {@link #markFailed}, but the row records that this claim was
|
||||
* deferred, so it does not count against the attempt budget ({@link
|
||||
* ClaimedOutboxEvent#budgetedAttemptCount()}). Must be called inside {@code
|
||||
* TransactionPort.inWrite(...)}.
|
||||
*
|
||||
* @param lease the claim this relay holds
|
||||
* @param nextAttemptAt the earliest instant at which the event may be re-claimed
|
||||
* @return {@link OutboxCompletion#STALE}, writing nothing, when the lease no longer holds the row
|
||||
*/
|
||||
OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt);
|
||||
|
||||
/**
|
||||
* Gives a claimed row back without having tried to publish it: the row is claimable again from
|
||||
* {@code claimableAt}, by any relay, and the claim that is released does not count as an attempt.
|
||||
* The relay calls it for the rows it claimed but will not get to — it was asked to stop — so they
|
||||
* do not wait out the in-flight timeout. Must be called inside {@code
|
||||
* TransactionPort.inWrite(...)}.
|
||||
*
|
||||
* @param lease the claim this relay holds and has not used
|
||||
* @param claimableAt when the row may be claimed again; normally now
|
||||
* @return {@link OutboxCompletion#STALE}, writing nothing, when the lease no longer holds the row
|
||||
*/
|
||||
OutboxCompletion releaseLease(OutboxLease lease, Instant claimableAt);
|
||||
|
||||
/**
|
||||
* Marks the leased event as dead-lettered after all retry attempts are exhausted. Must be called
|
||||
* inside {@code TransactionPort.inWrite(...)}. A DEAD row blocks its aggregate's FIFO queue until
|
||||
|
||||
+18
-6
@@ -1,15 +1,27 @@
|
||||
package dev.caskeleton.application.outbox;
|
||||
|
||||
import dev.caskeleton.application.command.Command;
|
||||
import java.util.Objects;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
/**
|
||||
* Command marker for the outbox relay use case. The relay is scheduler-driven and carries no caller
|
||||
* parameters (operational params are injected at construction); the {@link #INSTANCE} singleton
|
||||
* conveys the intent. See README.
|
||||
* Command for the outbox relay use case. The relay is scheduler-driven and carries no caller
|
||||
* parameters (operational params are injected at construction). See README.
|
||||
*
|
||||
* <p>It carries one thing the scheduler knows and the use case does not: whether the relay has been
|
||||
* asked to stop. A cycle that is asked to stop finishes the publish it is in, then releases the
|
||||
* rows it claimed and did not reach ({@link OutboxStorePort#releaseLease}) instead of publishing
|
||||
* them into a platform that is about to close its admission.
|
||||
*
|
||||
* @param stopRequested read before each row; true once the relay is stopping
|
||||
*/
|
||||
public record PublishPendingOutboxEventsCommand() implements Command {
|
||||
public record PublishPendingOutboxEventsCommand(BooleanSupplier stopRequested) implements Command {
|
||||
|
||||
/** Canonical no-parameter instance — the relay command carries no parameters. */
|
||||
/** A cycle that is never asked to stop: it handles every row it claims. */
|
||||
public static final PublishPendingOutboxEventsCommand INSTANCE =
|
||||
new PublishPendingOutboxEventsCommand();
|
||||
new PublishPendingOutboxEventsCommand(() -> false);
|
||||
|
||||
public PublishPendingOutboxEventsCommand {
|
||||
Objects.requireNonNull(stopRequested, "stopRequested must not be null");
|
||||
}
|
||||
}
|
||||
|
||||
+59
-18
@@ -3,7 +3,7 @@ package dev.caskeleton.application.outbox;
|
||||
import dev.caskeleton.application.capability.Idempotency;
|
||||
import dev.caskeleton.application.capability.RepositoryAccess;
|
||||
import dev.caskeleton.application.capability.UseCaseCapability;
|
||||
import dev.caskeleton.application.security.RequiresPermission;
|
||||
import dev.caskeleton.application.security.SystemInvoked;
|
||||
import dev.caskeleton.application.transaction.TransactionMode;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.application.usecase.CommandUseCase;
|
||||
@@ -24,11 +24,17 @@ import java.util.function.Supplier;
|
||||
* failures are never rethrown; a status-update failure after a successful publish propagates and
|
||||
* the row is recovered via the in-flight timeout. A completion runs only under the claim's {@link
|
||||
* OutboxLease}; when that claim has been superseded the result is recorded as {@code STALE} and
|
||||
* reported, never written. Wired manually by {@code app-bootstrap} (not a Spring bean). See README
|
||||
* for the full algorithm, failure semantics, manual-wiring rationale, and the {@code
|
||||
* "outbox:relay"} permission.
|
||||
* reported, never written. See README for the full algorithm and failure semantics.
|
||||
*
|
||||
* <p><b>Do not make this a Spring bean.</b> Only the relay scheduler calls it, on a thread with no
|
||||
* {@code Authentication}; it is {@link SystemInvoked} and carries no permission gate, and the
|
||||
* outbox-relay composition constructs it directly. Exposed as a bean, a transport could reach it
|
||||
* with no authorization at all.
|
||||
*/
|
||||
@RequiresPermission("outbox:relay")
|
||||
@SystemInvoked(
|
||||
reason =
|
||||
"the outbox relay scheduler calls it on a thread with no Authentication; a bean with a"
|
||||
+ " permission gate would be refused on every tick")
|
||||
@UseCaseCapability(
|
||||
transactionMode = TransactionMode.WRITE,
|
||||
idempotency = Idempotency.IDEMPOTENT,
|
||||
@@ -51,7 +57,7 @@ public class PublishPendingOutboxEventsUseCase
|
||||
|
||||
/**
|
||||
* Constructs the relay use case with all required collaborators (wired manually by {@code
|
||||
* app-bootstrap}; see README).
|
||||
* composition:outbox-relay}; see README).
|
||||
*
|
||||
* @param store outbox store port (claim + status update)
|
||||
* @param publishPort fail-closed broker publish port
|
||||
@@ -111,9 +117,15 @@ public class PublishPendingOutboxEventsUseCase
|
||||
List<OutboxLease> sorted = new ArrayList<>(claimed);
|
||||
sorted.sort(Comparator.comparing(lease -> lease.event().occurredAt()));
|
||||
|
||||
// Step 3: Publish each event outside any transaction; drive status machine per result.
|
||||
// Step 3: Publish each event outside any transaction; drive status machine per result. A relay
|
||||
// asked to stop finishes the publish it is in and gives the rest of its claims back.
|
||||
List<OutboxRelayResult.EventOutcome> outcomes = new ArrayList<>(sorted.size());
|
||||
for (OutboxLease lease : sorted) {
|
||||
for (int i = 0; i < sorted.size(); i++) {
|
||||
if (command.stopRequested().getAsBoolean()) {
|
||||
outcomes.addAll(release(sorted.subList(i, sorted.size())));
|
||||
break;
|
||||
}
|
||||
OutboxLease lease = sorted.get(i);
|
||||
OutboxRelayResult.Outcome outcome = publishOne(lease);
|
||||
outcomes.add(
|
||||
new OutboxRelayResult.EventOutcome(lease.eventId(), lease.event().eventType(), outcome));
|
||||
@@ -122,6 +134,26 @@ public class PublishPendingOutboxEventsUseCase
|
||||
return new OutboxRelayResult(claimed.size(), outcomes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives back claims this cycle will not use. Without it a stopping relay either publishes them
|
||||
* into a platform that is closing its admission — each refusal schedules a retry at least a base
|
||||
* delay away and is reported as a failure — or leaves them IN_FLIGHT until the in-flight timeout,
|
||||
* five minutes by default, before any other instance may take them.
|
||||
*/
|
||||
private List<OutboxRelayResult.EventOutcome> release(List<OutboxLease> unused) {
|
||||
Instant claimableAt = clock.instant();
|
||||
List<OutboxRelayResult.EventOutcome> released = new ArrayList<>(unused.size());
|
||||
for (OutboxLease lease : unused) {
|
||||
OutboxRelayResult.Outcome outcome =
|
||||
tx.inWrite(() -> store.releaseLease(lease, claimableAt)) == OutboxCompletion.STALE
|
||||
? OutboxRelayResult.Outcome.STALE
|
||||
: OutboxRelayResult.Outcome.RELEASED;
|
||||
released.add(
|
||||
new OutboxRelayResult.EventOutcome(lease.eventId(), lease.event().eventType(), outcome));
|
||||
}
|
||||
return released;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to publish one event and drives the FAILED/DEAD state machine on publish failure. A
|
||||
* publish failure is caught here and never rethrown; a {@code markPublished} failure after a
|
||||
@@ -152,13 +184,13 @@ public class PublishPendingOutboxEventsUseCase
|
||||
// idempotency key, and the alternative — parking it — loses a message that was delivered.
|
||||
// It does not spend the attempt budget: a broker that stopped answering fails every row this
|
||||
// way, and parking them after three tries is what turned a short outage into DEAD rows.
|
||||
return retryLater(lease, clock.instant(), new OutboxPublishAmbiguousException());
|
||||
return retryLater(lease, clock.instant(), new OutboxPublishAmbiguousException(), false);
|
||||
}
|
||||
if (achieved == OutboxPublishOutcome.REJECTED_RETRYABLE) {
|
||||
// Refused for a reason that is about the moment — shutdown, saturation, a closed transport,
|
||||
// a credential being rotated — not about the message. Retried like an ambiguous outcome and
|
||||
// for the same reason; the cause says it was a refusal, so no duplicate is suspected.
|
||||
return retryLater(lease, clock.instant(), new OutboxPublishRefusedException(achieved));
|
||||
return retryLater(lease, clock.instant(), new OutboxPublishRefusedException(achieved), false);
|
||||
}
|
||||
if (achieved != OutboxPublishOutcome.CONFIRMED) {
|
||||
// Definite refusal. Retrying the same payload fails the same way, so the attempt budget is
|
||||
@@ -181,28 +213,37 @@ public class PublishPendingOutboxEventsUseCase
|
||||
*
|
||||
* <p>The attempt budget is spent here and only here: a thrown failure is one the adapter could
|
||||
* not classify, so it may be the message's own fault, and the budget is what keeps such a row
|
||||
* from blocking its aggregate forever. {@code attemptCount} counts every claim, transient ones
|
||||
* included, so a row that has already waited out an outage is dead-lettered by the first thrown
|
||||
* failure after it.
|
||||
* from blocking its aggregate forever. The budget counts {@link
|
||||
* ClaimedOutboxEvent#budgetedAttemptCount()}, not every claim: the claims an outage deferred are
|
||||
* left out, so a row that waited out a long outage still gets its whole budget afterwards instead
|
||||
* of being dead-lettered by the first unclassified failure.
|
||||
*/
|
||||
private OutboxRelayResult.Outcome handlePublishFailure(
|
||||
OutboxLease lease, Instant failedAt, RuntimeException cause) {
|
||||
if (lease.event().attemptCount() >= backoffPolicy.maxAttempts()) {
|
||||
if (lease.event().budgetedAttemptCount() >= backoffPolicy.maxAttempts()) {
|
||||
// All attempts exhausted — DEAD-letter the event.
|
||||
return deadLetter(lease, cause);
|
||||
}
|
||||
return retryLater(lease, failedAt, cause);
|
||||
return retryLater(lease, failedAt, cause, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the row FAILED with its next attempt time and reports it. Never dead-letters: the caller
|
||||
* has decided this failure is worth another attempt.
|
||||
* has decided this failure is worth another attempt. The delay grows with every claim, deferred
|
||||
* ones included, so a long outage is polled at most {@link OutboxBackoffPolicy#MAX_DELAY} apart;
|
||||
* only a {@code budgeted} failure is recorded as spending the budget.
|
||||
*/
|
||||
private OutboxRelayResult.Outcome retryLater(
|
||||
OutboxLease lease, Instant failedAt, RuntimeException cause) {
|
||||
OutboxLease lease, Instant failedAt, RuntimeException cause, boolean budgeted) {
|
||||
ClaimedOutboxEvent event = lease.event();
|
||||
Instant nextAttemptAt = backoffPolicy.nextAttemptAt(event.attemptCount(), failedAt);
|
||||
if (tx.inWrite(() -> store.markFailed(lease, nextAttemptAt)) == OutboxCompletion.STALE) {
|
||||
OutboxCompletion completion =
|
||||
tx.inWrite(
|
||||
() ->
|
||||
budgeted
|
||||
? store.markFailed(lease, nextAttemptAt)
|
||||
: store.markDeferred(lease, nextAttemptAt));
|
||||
if (completion == OutboxCompletion.STALE) {
|
||||
return stale(lease, OutboxRelayResult.Outcome.FAILED);
|
||||
}
|
||||
reportFailure(
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package dev.caskeleton.application.security;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Marks a mutating use case that only the system calls — a scheduler, a relay — and that therefore
|
||||
* carries no {@link RequiresPermission}.
|
||||
*
|
||||
* <p>A permission gate on such a use case is decoration: the method-security advisor checks the
|
||||
* caller's {@code Authentication}, a scheduler thread has none, so the gate either never runs (the
|
||||
* use case is not a bean) or refuses every call (it is). This marker states that instead, and the
|
||||
* architecture rule that otherwise requires a permission on every {@code WRITE_REPOSITORY} use case
|
||||
* accepts it in place of one.
|
||||
*
|
||||
* <p>A use case marked this way must not become a Spring bean that a transport can reach; the
|
||||
* composition that runs it constructs it directly.
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
public @interface SystemInvoked {
|
||||
|
||||
/** Who calls it and why no end-user permission applies. */
|
||||
String reason();
|
||||
}
|
||||
@@ -9,7 +9,13 @@ import java.util.regex.Pattern;
|
||||
* <p>Opaque, short and safe to place in a log field: {@code [A-Za-z0-9][A-Za-z0-9_.-]{0,63}}. The
|
||||
* web and GraphQL transports each held a {@code TenantContext} with its own rule — web this
|
||||
* grammar, GraphQL "non-blank, at most 128 characters" — so the same tenant passed one transport
|
||||
* and was refused by the other (review X2-P2-6a, S5-lead-3). Both now carry this type.
|
||||
* and was refused by the other (review X2-P2-6a, S5-lead-3). Both now carry this type, and so does
|
||||
* persistence-jpa's experimental tenant binding, which had a third, lower-case-only copy. A store
|
||||
* that needs a narrower rule checks it on top of this type; it does not declare another one.
|
||||
*
|
||||
* <p>application-notification still has its own lenient {@code TenantId} for rows stored before its
|
||||
* writes adopted this grammar; folding it in needs those rows checked first (see that type's
|
||||
* Javadoc).
|
||||
*
|
||||
* <p>A tenant is a security boundary, so where one comes from matters more than its shape: a
|
||||
* transport builds it from verified authentication data, never from a request parameter.
|
||||
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package dev.caskeleton.application.cache;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CacheSourceRevisionOrderTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("정규 10진 정수만 순서에 참여한다")
|
||||
void onlyCanonicalDecimalsAreOrdered() {
|
||||
// given
|
||||
String[] ordered = {"0", "9", "10", "123456789012345678901234567890"};
|
||||
String[] unordered = {"", "-1", "01", "1.0", "v1", "1e3", "1"};
|
||||
|
||||
// when
|
||||
boolean anyUnorderedAccepted = false;
|
||||
for (String revision : unordered) {
|
||||
anyUnorderedAccepted |= CacheSourceRevisionOrder.isOrdered(revision);
|
||||
}
|
||||
|
||||
// then
|
||||
assertThat(anyUnorderedAccepted).isFalse();
|
||||
for (String revision : ordered) {
|
||||
assertThat(CacheSourceRevisionOrder.isOrdered(revision)).as(revision).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("길이가 2^53을 넘어도 숫자 순서로 비교한다")
|
||||
void comparesNumericallyBeyondDoublePrecision() {
|
||||
// given
|
||||
String stored = "9007199254740993";
|
||||
|
||||
// when
|
||||
boolean newer = CacheSourceRevisionOrder.isStrictlyNewer("9007199254740994", stored);
|
||||
|
||||
// then
|
||||
assertThat(newer).isTrue();
|
||||
assertThat(CacheSourceRevisionOrder.isStrictlyNewer("10", "9")).isTrue();
|
||||
assertThat(CacheSourceRevisionOrder.isStrictlyNewer("9", "10")).isFalse();
|
||||
assertThat(CacheSourceRevisionOrder.isStrictlyNewer("10", "10")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("순서 밖의 저장 revision보다 새롭다고는 판단하지 않는다")
|
||||
void anUnorderedStoredRevisionIsNeverProvenOlder() {
|
||||
// given
|
||||
String stored = "rev-2";
|
||||
|
||||
// when
|
||||
boolean newer = CacheSourceRevisionOrder.isStrictlyNewer("99", stored);
|
||||
|
||||
// then
|
||||
assertThat(newer).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER metadata는 순서 밖의 revision을 만들 때 거부한다")
|
||||
void revisionNewerMetadataRejectsAnUnorderedRevision() {
|
||||
// given
|
||||
String revision = "rev-2";
|
||||
|
||||
// when
|
||||
Throwable refused =
|
||||
catchThrowable(
|
||||
() ->
|
||||
new CacheRecordMetadata(revision, CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER));
|
||||
|
||||
// then
|
||||
assertThat(refused)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("ONLY_IF_SOURCE_REVISION_NEWER");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import java.time.Instant;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CacheRegionContractTest {
|
||||
class CacheValueTypesTest {
|
||||
|
||||
private static final Instant SOFT_EXPIRES_AT = Instant.parse("2026-07-28T01:00:00Z");
|
||||
private static final Instant HARD_EXPIRES_AT = Instant.parse("2026-07-28T01:05:00Z");
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package dev.caskeleton.application.cache;
|
||||
|
||||
import dev.caskeleton.application.cache.testkit.CacheRegionContract;
|
||||
import dev.caskeleton.application.cache.testkit.InMemoryCacheRegion;
|
||||
|
||||
/** The in-memory fake keeps the cache contract its use-case tests rely on. */
|
||||
class InMemoryCacheRegionContractTest extends CacheRegionContract {
|
||||
|
||||
@Override
|
||||
protected CacheRegionPort<String, String> region() {
|
||||
return new InMemoryCacheRegion<>();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -8,7 +8,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class IdempotencyContractTest {
|
||||
class IdempotencyValueTypesTest {
|
||||
|
||||
private static final IdempotencyScopeDigest SCOPE =
|
||||
new IdempotencyScopeDigest("a".repeat(64), 3, "CREATE_WORK_LOG");
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package dev.caskeleton.application.idempotency;
|
||||
|
||||
import dev.caskeleton.application.idempotency.testkit.IdempotencyStoreContract;
|
||||
import dev.caskeleton.application.idempotency.testkit.InMemoryIdempotencyStore;
|
||||
|
||||
/** The in-memory fake keeps the idempotency store contract its use-case tests rely on. */
|
||||
class InMemoryIdempotencyStoreContractTest extends IdempotencyStoreContract {
|
||||
|
||||
@Override
|
||||
protected IdempotencyStorePort store() {
|
||||
return new InMemoryIdempotencyStore();
|
||||
}
|
||||
}
|
||||
+13
-52
@@ -3,19 +3,19 @@ package dev.caskeleton.application.lock;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.application.lock.testkit.InMemoryDistributedLock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Contract-shape test for {@link DistributedLockPort} and {@link DistributedLock}.
|
||||
*
|
||||
* <p>Uses an in-test fake backed by {@link ReentrantLock} to prove:
|
||||
* <p>Uses the port owner's fake, {@link InMemoryDistributedLock} (testFixtures), which also passes
|
||||
* {@link dev.caskeleton.application.lock.testkit.DistributedLockContract} with the JDBC adapter, to
|
||||
* prove:
|
||||
*
|
||||
* <ol>
|
||||
* <li>{@code tryAcquire} returns a non-null handle.
|
||||
@@ -31,46 +31,13 @@ class DistributedLockPortContractTest {
|
||||
private static final Duration SHORT_WAIT = Duration.ofMillis(50);
|
||||
private static final Duration LEASE_TTL = Duration.ofSeconds(30);
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Fake implementation — kept in-test to avoid polluting production sources
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* In-test fake backed by {@link ReentrantLock} (non-reentrant mode enforced via {@link
|
||||
* ReentrantLock#tryLock(long, TimeUnit)} with the supplied waitTime).
|
||||
*
|
||||
* <p>TTL is not enforced by the in-process fake (TTL enforcement is the JDBC registry adapter's
|
||||
* responsibility). The leaseTtl parameter is accepted but ignored here, mirroring the fact that
|
||||
* the port surface carries it as a contract hint to the adapter.
|
||||
*/
|
||||
private static final class FakeDistributedLockPort implements DistributedLockPort {
|
||||
|
||||
private final ConcurrentHashMap<String, ReentrantLock> locks = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public DistributedLock tryAcquire(String key, Duration waitTime, Duration leaseTtl) {
|
||||
ReentrantLock lock = locks.computeIfAbsent(key, k -> new ReentrantLock());
|
||||
boolean acquired;
|
||||
try {
|
||||
acquired = lock.tryLock(waitTime.toMillis(), TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new LockAcquisitionTimeoutException(key, waitTime);
|
||||
}
|
||||
if (!acquired) {
|
||||
throw new LockAcquisitionTimeoutException(key, waitTime);
|
||||
}
|
||||
return () -> lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Tests
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void acquireReturnsNonNullHandle() {
|
||||
DistributedLockPort port = new FakeDistributedLockPort();
|
||||
DistributedLockPort port = new InMemoryDistributedLock();
|
||||
DistributedLock lock = port.tryAcquire("test-key", SHORT_WAIT, LEASE_TTL);
|
||||
|
||||
assertThat(lock).isNotNull();
|
||||
@@ -79,7 +46,7 @@ class DistributedLockPortContractTest {
|
||||
|
||||
@Test
|
||||
void closeReleasesLockSoSubsequentAcquireSucceeds() {
|
||||
DistributedLockPort port = new FakeDistributedLockPort();
|
||||
DistributedLockPort port = new InMemoryDistributedLock();
|
||||
|
||||
DistributedLock first = port.tryAcquire("orders/1", SHORT_WAIT, LEASE_TTL);
|
||||
first.close(); // release
|
||||
@@ -107,7 +74,7 @@ class DistributedLockPortContractTest {
|
||||
*/
|
||||
@Test
|
||||
void tryFinallyReleaseAfterWorkDemonstratesD4Ordering() {
|
||||
DistributedLockPort port = new FakeDistributedLockPort();
|
||||
DistributedLockPort port = new InMemoryDistributedLock();
|
||||
List<String> events = new ArrayList<>();
|
||||
|
||||
DistributedLock lock = port.tryAcquire("payment/99", SHORT_WAIT, LEASE_TTL);
|
||||
@@ -123,23 +90,17 @@ class DistributedLockPortContractTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* While the main thread holds the lock, a second attempt on the same key (same thread —
|
||||
* ReentrantLock is non-reentrant when used via tryLock with a zero-ish wait) must time out and
|
||||
* throw {@link LockAcquisitionTimeoutException} carrying the correct key.
|
||||
* While the lock is held, a second attempt on the same key must time out and throw {@link
|
||||
* LockAcquisitionTimeoutException} carrying the correct key.
|
||||
*
|
||||
* <p>We hold the lock on the main thread and call tryAcquire again immediately with a very short
|
||||
* waitTime. Because the fake uses a {@link ReentrantLock} and the second attempt uses a
|
||||
* <em>different</em> {@link ReentrantLock#tryLock(long, TimeUnit)} call (not the re-entrant
|
||||
* path), this is deterministic without needing a second thread.
|
||||
*
|
||||
* <p>Note: {@link ReentrantLock} IS re-entrant by design, so for true non-reentrancy the fake
|
||||
* uses a second thread here to keep the test deterministic.
|
||||
* <p>The lock is held on a second thread, so the timeout does not depend on whether the fake is
|
||||
* thread-bound.
|
||||
*/
|
||||
@Test
|
||||
void timeoutWhileKeyIsHeldThrowsLockAcquisitionTimeoutExceptionWithCorrectKey()
|
||||
throws InterruptedException {
|
||||
|
||||
FakeDistributedLockPort port = new FakeDistributedLockPort();
|
||||
InMemoryDistributedLock port = new InMemoryDistributedLock();
|
||||
String key = "inventory/sku-99";
|
||||
|
||||
// Hold the lock in a background thread until the main thread's test completes.
|
||||
@@ -180,7 +141,7 @@ class DistributedLockPortContractTest {
|
||||
|
||||
@Test
|
||||
void tryWithResourcesCompilesAndReleases() {
|
||||
DistributedLockPort port = new FakeDistributedLockPort();
|
||||
DistributedLockPort port = new InMemoryDistributedLock();
|
||||
|
||||
// DistributedLock extends AutoCloseable — must compile with try-with-resources
|
||||
try (DistributedLock ignored = port.tryAcquire("key", SHORT_WAIT, LEASE_TTL)) {
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package dev.caskeleton.application.lock.testkit;
|
||||
|
||||
import dev.caskeleton.application.lock.DistributedLockPort;
|
||||
|
||||
class InMemoryDistributedLockContractTest extends DistributedLockContract {
|
||||
|
||||
private final InMemoryDistributedLock first = new InMemoryDistributedLock();
|
||||
private final InMemoryDistributedLock second = InMemoryDistributedLock.sharingStateWith(first);
|
||||
|
||||
@Override
|
||||
protected DistributedLockPort firstInstance() {
|
||||
return first;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DistributedLockPort secondInstance() {
|
||||
return second;
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -154,7 +154,7 @@ class IntegrationEventContractContributionTest {
|
||||
new ContractDescriptor(
|
||||
"sample-portfolio",
|
||||
new LogicalDestinationId("portfolio-domain-events"),
|
||||
"json-schema-envelope-v1",
|
||||
"json-envelope-v1",
|
||||
true,
|
||||
0,
|
||||
128 * 1024,
|
||||
@@ -167,7 +167,7 @@ class IntegrationEventContractContributionTest {
|
||||
return new ContractDescriptor(
|
||||
"sample-portfolio",
|
||||
new LogicalDestinationId("portfolio-domain-events"),
|
||||
"json-schema-envelope-v1",
|
||||
"json-envelope-v1",
|
||||
true,
|
||||
64 * 1024,
|
||||
128 * 1024,
|
||||
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package dev.caskeleton.application.messaging.event;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.caskeleton.application.messaging.event.testkit.EncoderContractKitContract;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
class IntegrationEventDraftsTest {
|
||||
|
||||
private static final EventId EVENT_ID = new EventId("event-1");
|
||||
private static final Instant OCCURRED_AT = Instant.parse("2026-11-01T00:00:00.000001Z");
|
||||
private static final AggregateIdentity AGGREGATE =
|
||||
new AggregateIdentity(IntegrationEventDrafts.SINGLE_TENANT_SCOPE, "kit", "kit-1");
|
||||
|
||||
@Test
|
||||
void aDraftTakesItsContractIdVersionAndDestinationFromTheContract() {
|
||||
// when
|
||||
IntegrationEventDraft<?> draft = draft(Optional.of("corr-1"));
|
||||
|
||||
// then
|
||||
assertThat(draft)
|
||||
.extracting(
|
||||
IntegrationEventDraft::contractId,
|
||||
IntegrationEventDraft::payloadVersion,
|
||||
IntegrationEventDraft::destinationId,
|
||||
IntegrationEventDraft::correlationId)
|
||||
.containsExactly(
|
||||
EncoderContractKitContract.CONTRACT_ID,
|
||||
1,
|
||||
EncoderContractKitContract.DESTINATION,
|
||||
"corr-1");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", " ", "not canonical", "-leading-dash"})
|
||||
@DisplayName("쓸 수 없는 요청 correlation id는 쓰기를 실패시키지 않고 이벤트 id로 대신한다")
|
||||
void anUnusableRequestCorrelationIdFallsBackToTheEventId(String requested) {
|
||||
// when
|
||||
IntegrationEventDraft<?> draft = draft(Optional.of(requested));
|
||||
|
||||
// then
|
||||
assertThat(draft.correlationId()).isEqualTo(EVENT_ID.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEventWithNoRequestBehindItCorrelatesToItself() {
|
||||
assertThat(draft(Optional.empty()).correlationId()).isEqualTo(EVENT_ID.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("128자 요청 correlation id는 저장 열 폭과 같아서 그대로 쓴다")
|
||||
void aRequestCorrelationIdAsLongAsTheStoredColumnIsKept() {
|
||||
// given
|
||||
String longest = "c".repeat(IntegrationIdentity.CORRELATION_MAX_LENGTH);
|
||||
|
||||
// when
|
||||
IntegrationEventDraft<?> draft = draft(Optional.of(longest));
|
||||
|
||||
// then
|
||||
assertThat(draft.correlationId()).isEqualTo(longest);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("한 번만 이벤트를 내는 aggregate의 순서는 1번 0번째다")
|
||||
void theOrderOfAnAggregatesOnlyEventIsSequenceOneIndexZero() {
|
||||
// when
|
||||
AggregateOrder order = AggregateOrder.first();
|
||||
|
||||
// then
|
||||
assertThat(order).isEqualTo(new AggregateOrder(1, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDraftWithoutAContractIsRefused() {
|
||||
// when
|
||||
Throwable thrown =
|
||||
catchThrowable(
|
||||
() ->
|
||||
IntegrationEventDrafts.draft(
|
||||
null,
|
||||
EVENT_ID,
|
||||
AGGREGATE,
|
||||
AggregateOrder.first(),
|
||||
OCCURRED_AT,
|
||||
Optional.empty(),
|
||||
new EncoderContractKitContract.Payload("a")));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage("contract, eventId and requestCorrelationId are required");
|
||||
}
|
||||
|
||||
private static IntegrationEventDraft<?> draft(Optional<String> requested) {
|
||||
return IntegrationEventDrafts.draft(
|
||||
new EncoderContractKitContract(),
|
||||
EVENT_ID,
|
||||
AGGREGATE,
|
||||
AggregateOrder.first(),
|
||||
OCCURRED_AT,
|
||||
requested,
|
||||
new EncoderContractKitContract.Payload("a"));
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package dev.caskeleton.application.messaging.event;
|
||||
|
||||
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.IntegrationPayload;
|
||||
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
class IntegrationIdentityTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"a", "A0:event.id-1", "0190bd6e-7c3e-7abc-8def-0123456789ff"})
|
||||
void aValueInTheGrammarIsCanonical(String value) {
|
||||
assertThat(IntegrationIdentity.isCanonical(value, 96)).isTrue();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", "-a", ".a", "a b", "a/b", "한글"})
|
||||
void aValueOutsideTheGrammarIsNotCanonical(String value) {
|
||||
assertThat(IntegrationIdentity.isCanonical(value, 96)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aValueLongerThanItsBoundIsNotCanonical() {
|
||||
assertThat(IntegrationIdentity.isCanonical("a".repeat(97), 96)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("draft의 correlation id 상한은 저장된 이벤트와 같은 128자다")
|
||||
void aDraftAcceptsTheSameCorrelationLengthAStoredEventDoes() {
|
||||
// when
|
||||
IntegrationEventDraft<TestPayload> draft = draftWithCorrelation("c".repeat(128));
|
||||
|
||||
// then
|
||||
assertThat(draft.correlationId()).hasSize(128);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("129자 correlation id는 draft에서 거부한다")
|
||||
void aDraftRefusesACorrelationIdLongerThanTheStoredColumn() {
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> draftWithCorrelation("c".repeat(129)));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage("correlationId must be a canonical bounded US-ASCII identity");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("97자 event id는 거부한다")
|
||||
void anEventIdLongerThanNinetySixCharactersIsRefused() {
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> new EventId("e".repeat(97)));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage(
|
||||
"eventId must be 1-96 US-ASCII characters matching " + IntegrationIdentity.GRAMMAR);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEventIdOfNinetySixCharactersIsAccepted() {
|
||||
assertThat(new EventId("e".repeat(96)).value()).hasSize(96);
|
||||
}
|
||||
|
||||
private static IntegrationEventDraft<TestPayload> draftWithCorrelation(String correlationId) {
|
||||
return new IntegrationEventDraft<>(
|
||||
new EventId("event-1"),
|
||||
new ContractId("portfolio.worklog.reserved"),
|
||||
1,
|
||||
new LogicalDestinationId("portfolio-domain-events"),
|
||||
new AggregateIdentity("tenant-a", "worklog", "worklog-42"),
|
||||
AggregateOrder.first(),
|
||||
Instant.parse("2026-07-28T05:10:30.123Z"),
|
||||
correlationId,
|
||||
Optional.empty(),
|
||||
new TestPayload("worklog-42"));
|
||||
}
|
||||
|
||||
private record TestPayload(String workLogId) implements IntegrationPayload {}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package dev.caskeleton.application.messaging.event.testkit;
|
||||
|
||||
import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
|
||||
import java.util.Collection;
|
||||
|
||||
class FakeIntegrationEventEncoderContractTest extends IntegrationEventEncoderContract {
|
||||
|
||||
@Override
|
||||
protected IntegrationEventEncoderPort encoderKnowing(
|
||||
Collection<? extends IntegrationEventContractContribution<?>> contracts) {
|
||||
return new FakeIntegrationEventEncoder(contracts);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -39,7 +39,8 @@ 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 FakeIntegrationEventEncoder encoder =
|
||||
new FakeIntegrationEventEncoder(new DurableOperationSubmittedContract());
|
||||
private final CommandUseCase<OperationCommand, OperationAcceptance> useCase =
|
||||
new SubmitDurableOperationUseCase(
|
||||
operations, outbox, encoder, transactions, Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package dev.caskeleton.application.outbox;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCaseTest.ZeroRandom;
|
||||
import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore;
|
||||
import dev.caskeleton.application.outbox.testkit.OutboxEvents;
|
||||
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* A relay asked to stop — the application is shutting down — finishes the publish it is in and
|
||||
* gives back the rest of its claims, unspent, instead of publishing them into a platform that is
|
||||
* closing its admission or leaving them IN_FLIGHT until the in-flight timeout.
|
||||
*/
|
||||
class StoppingRelayReleasesItsClaimsTest {
|
||||
|
||||
private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z");
|
||||
|
||||
@Test
|
||||
@DisplayName("멈추라는 요청을 받은 회차는 진행 중 발행을 끝내고 남은 claim을 시도 없이 놓는다")
|
||||
void aStoppingCycleFinishesItsPublishAndReleasesTheRowsItDidNotReach() {
|
||||
// given: three claimable rows; the stop request arrives while the first one is publishing
|
||||
InMemoryOutboxStore store = new InMemoryOutboxStore();
|
||||
String first = "0193a000-0000-7000-8000-000000000001";
|
||||
String second = "0193a000-0000-7000-8000-000000000002";
|
||||
String third = "0193a000-0000-7000-8000-000000000003";
|
||||
store.append(OutboxEvents.event(first, NOW.minusSeconds(3)));
|
||||
store.append(OutboxEvents.event(second, NOW.minusSeconds(2)));
|
||||
store.append(OutboxEvents.event(third, NOW.minusSeconds(1)));
|
||||
AtomicBoolean stopRequested = new AtomicBoolean();
|
||||
List<String> sent = new ArrayList<>();
|
||||
OutboxMessagePublishPort port =
|
||||
event -> {
|
||||
sent.add(event.eventId());
|
||||
stopRequested.set(true);
|
||||
};
|
||||
PublishPendingOutboxEventsUseCase relay = relay(store, port);
|
||||
|
||||
// when
|
||||
OutboxRelayResult result =
|
||||
relay.handle(new PublishPendingOutboxEventsCommand(stopRequested::get));
|
||||
|
||||
// then
|
||||
assertThat(sent).containsExactly(first);
|
||||
assertThat(result.outcomes())
|
||||
.extracting(OutboxRelayResult.EventOutcome::outcome)
|
||||
.containsExactly(
|
||||
OutboxRelayResult.Outcome.PUBLISHED,
|
||||
OutboxRelayResult.Outcome.RELEASED,
|
||||
OutboxRelayResult.Outcome.RELEASED);
|
||||
assertThat(List.of(store.status(second), store.status(third)))
|
||||
.containsOnly(OutboxEventStatus.PENDING);
|
||||
assertThat(List.of(store.attemptCount(second), store.attemptCount(third))).containsOnly(0);
|
||||
assertThat(List.of(store.nextAttemptAt(second), store.nextAttemptAt(third))).containsOnly(NOW);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("멈추라는 요청이 없으면 회차는 claim한 행을 모두 발행한다")
|
||||
void aCycleThatIsNotStoppedPublishesEveryRowItClaimed() {
|
||||
// given
|
||||
InMemoryOutboxStore store = new InMemoryOutboxStore();
|
||||
store.append(OutboxEvents.event("0193a000-0000-7000-8000-000000000011", NOW.minusSeconds(2)));
|
||||
store.append(OutboxEvents.event("0193a000-0000-7000-8000-000000000012", NOW.minusSeconds(1)));
|
||||
PublishPendingOutboxEventsUseCase relay = relay(store, event -> {});
|
||||
|
||||
// when
|
||||
OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE);
|
||||
|
||||
// then
|
||||
assertThat(result.outcomes())
|
||||
.extracting(OutboxRelayResult.EventOutcome::outcome)
|
||||
.containsOnly(OutboxRelayResult.Outcome.PUBLISHED);
|
||||
assertThat(store.released()).isEmpty();
|
||||
}
|
||||
|
||||
private static PublishPendingOutboxEventsUseCase relay(
|
||||
InMemoryOutboxStore store, OutboxMessagePublishPort port) {
|
||||
return new PublishPendingOutboxEventsUseCase(
|
||||
store,
|
||||
port,
|
||||
report -> {},
|
||||
new DirectTransactionPort(),
|
||||
new OutboxBackoffPolicy(new ZeroRandom()),
|
||||
Clock.fixed(NOW, ZoneOffset.UTC),
|
||||
20,
|
||||
Duration.ofMinutes(5),
|
||||
"relay-under-test");
|
||||
}
|
||||
}
|
||||
+53
@@ -161,6 +161,53 @@ class TransientPublishFailureRelayTest {
|
||||
.isEqualTo(START.plus(OutboxBackoffPolicy.MAX_DELAY));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("일시 실패를 오래 겪은 행도 처음 분류 못 한 실패에서는 DEAD가 아니라 FAILED가 된다")
|
||||
void aRowThatWaitedOutAnOutageIsNotDeadLetteredByItsFirstUnclassifiedFailure() {
|
||||
// given: a row that went through more transient refusals than the whole attempt budget
|
||||
store.addClaimable(OutboxEvents.claimed("evt-after-outage", START.minusSeconds(1), 1));
|
||||
port.answer = OutboxPublishOutcome.REJECTED_RETRYABLE;
|
||||
for (int i = 0; i <= OutboxBackoffPolicy.MAX_ATTEMPTS; i++) {
|
||||
relay.handle(PublishPendingOutboxEventsCommand.INSTANCE);
|
||||
clock.advance(OutboxBackoffPolicy.MAX_DELAY.plus(OutboxBackoffPolicy.BASE_DELAY));
|
||||
}
|
||||
port.thrown = new IllegalStateException("a failure the adapter could not classify");
|
||||
|
||||
// when
|
||||
OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE);
|
||||
|
||||
// then: only budgeted attempts count, and this is the first one
|
||||
assertThat(result.outcomes())
|
||||
.extracting(OutboxRelayResult.EventOutcome::outcome)
|
||||
.containsExactly(OutboxRelayResult.Outcome.FAILED);
|
||||
assertThat(store.dead()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("분류 못 한 실패는 일시 실패와 섞여도 예산만큼만 재시도하고 DEAD가 된다")
|
||||
void unclassifiedFailuresStillExhaustTheBudgetBetweenTransientOnes() {
|
||||
// given: transient refusals interleaved with failures the adapter could not classify
|
||||
store.addClaimable(OutboxEvents.claimed("evt-poison", START.minusSeconds(1), 1));
|
||||
port.thrown = new IllegalStateException("payload the adapter cannot classify");
|
||||
for (int i = 1; i < OutboxBackoffPolicy.MAX_ATTEMPTS; i++) {
|
||||
relay.handle(PublishPendingOutboxEventsCommand.INSTANCE);
|
||||
clock.advance(OutboxBackoffPolicy.MAX_DELAY.plus(OutboxBackoffPolicy.BASE_DELAY));
|
||||
port.thrown = null;
|
||||
port.answer = OutboxPublishOutcome.REJECTED_RETRYABLE;
|
||||
relay.handle(PublishPendingOutboxEventsCommand.INSTANCE);
|
||||
clock.advance(OutboxBackoffPolicy.MAX_DELAY.plus(OutboxBackoffPolicy.BASE_DELAY));
|
||||
port.thrown = new IllegalStateException("payload the adapter cannot classify");
|
||||
}
|
||||
|
||||
// when
|
||||
OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE);
|
||||
|
||||
// then
|
||||
assertThat(result.outcomes())
|
||||
.extracting(OutboxRelayResult.EventOutcome::outcome)
|
||||
.containsExactly(OutboxRelayResult.Outcome.DEAD);
|
||||
}
|
||||
|
||||
private void runRelayEvery(Duration pollInterval, Instant until) {
|
||||
while (clock.instant().isBefore(until)) {
|
||||
relay.handle(PublishPendingOutboxEventsCommand.INSTANCE);
|
||||
@@ -179,6 +226,9 @@ class TransientPublishFailureRelayTest {
|
||||
|
||||
private Duration costPerPublish = Duration.ZERO;
|
||||
|
||||
/** When set, every publish throws it instead of answering. */
|
||||
private RuntimeException thrown;
|
||||
|
||||
void script(String eventId, OutboxPublishOutcome outcome) {
|
||||
scripted.put(eventId, outcome);
|
||||
}
|
||||
@@ -197,6 +247,9 @@ class TransientPublishFailureRelayTest {
|
||||
public OutboxPublishOutcome publishForOutcome(ClaimedOutboxEvent event) {
|
||||
Instant calledAt = clock.instant();
|
||||
clock.advance(costPerPublish);
|
||||
if (thrown != null) {
|
||||
throw thrown;
|
||||
}
|
||||
OutboxPublishOutcome outcome = scripted.get(event.eventId());
|
||||
if (outcome != null) {
|
||||
return outcome;
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package dev.caskeleton.application.outbox.testkit;
|
||||
|
||||
import dev.caskeleton.application.outbox.OutboxAggregateSequencePort;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
|
||||
|
||||
class InMemoryOutboxAggregateSequenceContractTest extends OutboxAggregateSequenceContract {
|
||||
|
||||
private final InMemoryOutboxAggregateSequences sequences = new InMemoryOutboxAggregateSequences();
|
||||
|
||||
@Override
|
||||
protected OutboxAggregateSequencePort sequences() {
|
||||
return sequences;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected TransactionPort transactions() {
|
||||
return new DirectTransactionPort();
|
||||
}
|
||||
}
|
||||
+15
-2
@@ -18,8 +18,21 @@ class TenantIdTest {
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", " ", "-acme", ".acme", "ac me", "acme\n", "../public", "테넌트"})
|
||||
@DisplayName("문법 밖의 tenant(선행 구분자, 공백, 줄바꿈, 경로, 비ASCII)는 거부한다")
|
||||
@ValueSource(
|
||||
strings = {
|
||||
"",
|
||||
" ",
|
||||
"-acme",
|
||||
".acme",
|
||||
"ac me",
|
||||
"acme\n",
|
||||
"../public",
|
||||
"acme/eu",
|
||||
"acme\\eu",
|
||||
"acme:eu",
|
||||
"테넌트"
|
||||
})
|
||||
@DisplayName("문법 밖의 tenant(선행 구분자, 공백, 줄바꿈, 경로 구분자, 콜론, 비ASCII)는 거부한다")
|
||||
void aTenantOutsideTheGrammarIsRefused(String value) {
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> new TenantId(value));
|
||||
|
||||
+315
@@ -0,0 +1,315 @@
|
||||
package dev.caskeleton.application.cache.testkit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.application.cache.AuthoritativeAbsence;
|
||||
import dev.caskeleton.application.cache.CacheInvalidationOutcome;
|
||||
import dev.caskeleton.application.cache.CacheLookup;
|
||||
import dev.caskeleton.application.cache.CacheObservationToken;
|
||||
import dev.caskeleton.application.cache.CacheRecordIntent;
|
||||
import dev.caskeleton.application.cache.CacheRecordMetadata;
|
||||
import dev.caskeleton.application.cache.CacheRecordOutcome;
|
||||
import dev.caskeleton.application.cache.CacheRegionPort;
|
||||
import dev.caskeleton.application.cache.CacheWriteCondition;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The behaviour every {@link CacheRegionPort} owes its callers, run unchanged against the in-memory
|
||||
* fake and every adapter.
|
||||
*
|
||||
* <p>Each implementation extends this class and supplies a fresh, empty region. A rule that lives
|
||||
* only in one adapter's tests is a rule the fake does not keep, and a use case tested on the fake
|
||||
* would then be tested against a different cache than the one it runs on.
|
||||
*/
|
||||
public abstract class CacheRegionContract {
|
||||
|
||||
/**
|
||||
* Returns a fresh, empty region; called once per test.
|
||||
*
|
||||
* @return the region under test
|
||||
*/
|
||||
protected abstract CacheRegionPort<String, String> region();
|
||||
|
||||
private static CacheRecordMetadata upsert(String revision) {
|
||||
return new CacheRecordMetadata(revision, CacheRecordIntent.UPSERT);
|
||||
}
|
||||
|
||||
private static CacheRecordMetadata conditioned(
|
||||
String revision, CacheRecordIntent intent, CacheWriteCondition condition) {
|
||||
return new CacheRecordMetadata(
|
||||
revision, intent, CacheObservationToken.unavailable(), condition);
|
||||
}
|
||||
|
||||
private static CacheRecordMetadata newerThanStored(String revision) {
|
||||
return new CacheRecordMetadata(revision, CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER);
|
||||
}
|
||||
|
||||
private static CacheWriteCondition conditionOf(CacheLookup<String> lookup) {
|
||||
return switch (lookup) {
|
||||
case CacheLookup.Miss<String> miss -> miss.writeCondition();
|
||||
case CacheLookup.Hit<String> hit -> hit.writeCondition();
|
||||
default -> throw new AssertionError("expected a miss or a hit, got " + lookup);
|
||||
};
|
||||
}
|
||||
|
||||
private static String valueOf(CacheLookup<String> lookup) {
|
||||
assertThat(lookup).isInstanceOf(CacheLookup.Hit.class);
|
||||
return ((CacheLookup.Hit<String>) lookup).value();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("기록한 값은 다음 조회에서 같은 값과 revision의 hit으로 돌아온다")
|
||||
void aRecordedValueIsReturnedAsAHit() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
region.record("k", "v1", upsert("7"));
|
||||
|
||||
// when
|
||||
CacheLookup<String> lookup = region.lookup("k");
|
||||
|
||||
// then
|
||||
assertThat(valueOf(lookup)).isEqualTo("v1");
|
||||
assertThat(((CacheLookup.Hit<String>) lookup).sourceRevision()).isEqualTo("7");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("비어 있는 키의 miss는 기록에 쓸 수 있는 write condition을 돌려준다")
|
||||
void aMissCarriesAUsableWriteCondition() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
|
||||
// when
|
||||
CacheLookup<String> lookup = region.lookup("k");
|
||||
|
||||
// then
|
||||
assertThat(lookup).isInstanceOf(CacheLookup.Miss.class);
|
||||
assertThat(conditionOf(lookup).usable()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_ABSENT는 이미 있는 항목을 덮어쓰지 않는다")
|
||||
void onlyIfAbsentKeepsAnExistingEntry() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
region.record("k", "first", upsert("1"));
|
||||
|
||||
// when
|
||||
CacheRecordOutcome outcome =
|
||||
region.record(
|
||||
"k", "second", new CacheRecordMetadata("2", CacheRecordIntent.ONLY_IF_ABSENT));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
|
||||
assertThat(valueOf(region.lookup("k"))).isEqualTo("first");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_OBSERVED는 읽은 뒤 바뀐 항목을 덮어쓰지 않는다")
|
||||
void onlyIfObservedRefusesAChangedEntry() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
region.record("k", "first", upsert("1"));
|
||||
CacheLookup.Hit<String> observed = (CacheLookup.Hit<String>) region.lookup("k");
|
||||
region.record("k", "second", upsert("2"));
|
||||
|
||||
// when
|
||||
CacheRecordOutcome outcome =
|
||||
region.record(
|
||||
"k",
|
||||
"third",
|
||||
new CacheRecordMetadata(
|
||||
"3", CacheRecordIntent.ONLY_IF_OBSERVED, observed.observationToken()));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
|
||||
assertThat(valueOf(region.lookup("k"))).isEqualTo("second");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_OBSERVED는 읽은 뒤 바뀌지 않은 항목을 교체한다")
|
||||
void onlyIfObservedReplacesAnUnchangedEntry() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
region.record("k", "first", upsert("1"));
|
||||
CacheLookup.Hit<String> observed = (CacheLookup.Hit<String>) region.lookup("k");
|
||||
|
||||
// when
|
||||
CacheRecordOutcome outcome =
|
||||
region.record(
|
||||
"k",
|
||||
"second",
|
||||
new CacheRecordMetadata(
|
||||
"2", CacheRecordIntent.ONLY_IF_OBSERVED, observed.observationToken()));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
|
||||
assertThat(valueOf(region.lookup("k"))).isEqualTo("second");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 저장된 것보다 작거나 같은 revision을 기록하지 않는다")
|
||||
void onlyIfSourceRevisionNewerRefusesAnOlderOrEqualRevision() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
region.record("k", "at-10", upsert("10"));
|
||||
|
||||
// when
|
||||
CacheRecordOutcome older = region.record("k", "at-9", newerThanStored("9"));
|
||||
|
||||
// then
|
||||
assertThat(older).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
|
||||
assertThat(region.record("k", "again-10", newerThanStored("10")))
|
||||
.isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
|
||||
assertThat(valueOf(region.lookup("k"))).isEqualTo("at-10");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 revision을 글자 순서가 아니라 숫자 순서로 비교한다")
|
||||
void onlyIfSourceRevisionNewerComparesNumerically() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
region.record("k", "at-9", upsert("9"));
|
||||
|
||||
// when
|
||||
CacheRecordOutcome outcome = region.record("k", "at-10", newerThanStored("10"));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
|
||||
assertThat(valueOf(region.lookup("k"))).isEqualTo("at-10");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 비어 있는 키에 기록한다")
|
||||
void onlyIfSourceRevisionNewerRecordsIntoAnEmptyKey() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
|
||||
// when
|
||||
CacheRecordOutcome outcome = region.record("k", "at-1", newerThanStored("1"));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("miss 뒤 원본을 읽는 사이 무효화되면 그 miss의 condition으로 한 기록은 거부된다")
|
||||
void aLoadThatBeganBeforeAnInvalidationCannotRecordAfterIt() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
CacheWriteCondition beforeInvalidation = conditionOf(region.lookup("k"));
|
||||
region.invalidate("k");
|
||||
|
||||
// when
|
||||
CacheRecordOutcome outcome =
|
||||
region.record("k", "old", conditioned("1", CacheRecordIntent.UPSERT, beforeInvalidation));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
|
||||
assertThat(region.lookup("k")).isInstanceOf(CacheLookup.Miss.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("hit 뒤 원본을 읽는 사이 무효화되면 그 hit의 condition으로 한 기록은 거부된다")
|
||||
void aRefreshThatBeganBeforeAnInvalidationCannotRecordAfterIt() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
region.record("k", "v1", upsert("1"));
|
||||
CacheWriteCondition beforeInvalidation = conditionOf(region.lookup("k"));
|
||||
region.invalidate("k");
|
||||
|
||||
// when
|
||||
CacheRecordOutcome outcome =
|
||||
region.record("k", "old", conditioned("2", CacheRecordIntent.UPSERT, beforeInvalidation));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
|
||||
assertThat(region.lookup("k")).isInstanceOf(CacheLookup.Miss.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("무효화 뒤 다시 조회한 miss의 condition으로는 정상 기록된다")
|
||||
void aLoadThatBeganAfterAnInvalidationRecords() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
region.record("k", "v1", upsert("1"));
|
||||
region.invalidate("k");
|
||||
CacheLookup<String> afterInvalidation = region.lookup("k");
|
||||
|
||||
// when
|
||||
CacheRecordOutcome outcome =
|
||||
region.record(
|
||||
"k",
|
||||
"v2",
|
||||
conditioned("2", CacheRecordIntent.ONLY_IF_ABSENT, conditionOf(afterInvalidation)));
|
||||
|
||||
// then
|
||||
assertThat(afterInvalidation).isInstanceOf(CacheLookup.Miss.class);
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
|
||||
assertThat(valueOf(region.lookup("k"))).isEqualTo("v2");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("무효화 표시가 남은 동안 condition 없는 ONLY_IF_ABSENT와 revision 조건 기록은 거부된다")
|
||||
void anInvalidationRefusesUnconditionedLoadsWhileItsMarkerLives() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
region.record("k", "v1", upsert("1"));
|
||||
region.invalidate("k");
|
||||
|
||||
// when
|
||||
CacheRecordOutcome absent =
|
||||
region.record("k", "old", new CacheRecordMetadata("1", CacheRecordIntent.ONLY_IF_ABSENT));
|
||||
|
||||
// then
|
||||
assertThat(absent).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
|
||||
assertThat(region.record("k", "old", newerThanStored("1")))
|
||||
.isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("있는 키를 무효화하면 INVALIDATED, 다시 무효화하면 ALREADY_ABSENT다")
|
||||
void invalidatingTwiceReportsAbsenceTheSecondTime() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
region.record("k", "v1", upsert("1"));
|
||||
region.invalidate("k");
|
||||
|
||||
// when
|
||||
CacheInvalidationOutcome second = region.invalidate("k");
|
||||
|
||||
// then
|
||||
assertThat(second).isEqualTo(CacheInvalidationOutcome.ALREADY_ABSENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("region 무효화 뒤 이전 항목은 miss다")
|
||||
void aRegionInvalidationHidesEarlierEntries() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
region.record("k", "v1", upsert("1"));
|
||||
|
||||
// when
|
||||
CacheInvalidationOutcome outcome = region.invalidateRegion();
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheInvalidationOutcome.INVALIDATED);
|
||||
assertThat(region.lookup("k")).isInstanceOf(CacheLookup.Miss.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("권위 있는 부재는 miss가 아니라 negative hit이다")
|
||||
void anAuthoritativeAbsenceIsANegativeHit() {
|
||||
// given
|
||||
CacheRegionPort<String, String> region = region();
|
||||
region.recordAbsent("k", AuthoritativeAbsence.NOT_FOUND, upsert("1"));
|
||||
|
||||
// when
|
||||
CacheLookup<String> lookup = region.lookup("k");
|
||||
|
||||
// then
|
||||
assertThat(lookup).isInstanceOf(CacheLookup.NegativeHit.class);
|
||||
assertThat(((CacheLookup.NegativeHit<String>) lookup).reason())
|
||||
.isEqualTo(AuthoritativeAbsence.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package dev.caskeleton.application.cache.testkit;
|
||||
|
||||
import dev.caskeleton.application.cache.AuthoritativeAbsence;
|
||||
import dev.caskeleton.application.cache.CacheInvalidationOutcome;
|
||||
import dev.caskeleton.application.cache.CacheLookup;
|
||||
import dev.caskeleton.application.cache.CacheObservationToken;
|
||||
import dev.caskeleton.application.cache.CacheRecordMetadata;
|
||||
import dev.caskeleton.application.cache.CacheRecordOutcome;
|
||||
import dev.caskeleton.application.cache.CacheRegionPort;
|
||||
import dev.caskeleton.application.cache.CacheSourceRevisionOrder;
|
||||
import dev.caskeleton.application.cache.CacheWriteCondition;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The one in-memory fake of {@link CacheRegionPort}, for use-case tests that need a cache.
|
||||
*
|
||||
* <p>It keeps the contract's consistency rules — write conditions, invalidation markers, the {@link
|
||||
* CacheSourceRevisionOrder} — and leaves out everything provider-specific: no codec, no schema
|
||||
* versions, no outage. {@code CacheRegionContract} runs against it exactly as against a real
|
||||
* adapter.
|
||||
*
|
||||
* @param <K> the semantic key type
|
||||
* @param <V> the cached value type
|
||||
*/
|
||||
public final class InMemoryCacheRegion<K, V> implements CacheRegionPort<K, V> {
|
||||
|
||||
private static final String ABSENT = "absent";
|
||||
|
||||
private final Map<K, Slot<V>> slots = new HashMap<>();
|
||||
private final Clock clock;
|
||||
private final Duration softTtl;
|
||||
private final Duration hardTtl;
|
||||
private final Duration negativeTtl;
|
||||
private final Duration invalidationTtl;
|
||||
private long generation;
|
||||
private long versions;
|
||||
|
||||
/**
|
||||
* Creates the fake.
|
||||
*
|
||||
* @param clock the clock expiries are measured against
|
||||
* @param softTtl how long an entry stays fresh
|
||||
* @param hardTtl how long an entry stays usable
|
||||
* @param negativeTtl how long an authoritative absence is cached
|
||||
* @param invalidationTtl how long an invalidation marker refuses older records
|
||||
*/
|
||||
public InMemoryCacheRegion(
|
||||
Clock clock,
|
||||
Duration softTtl,
|
||||
Duration hardTtl,
|
||||
Duration negativeTtl,
|
||||
Duration invalidationTtl) {
|
||||
this.clock = Objects.requireNonNull(clock, "clock must be non-null");
|
||||
this.softTtl = Objects.requireNonNull(softTtl, "soft TTL must be non-null");
|
||||
this.hardTtl = Objects.requireNonNull(hardTtl, "hard TTL must be non-null");
|
||||
this.negativeTtl = Objects.requireNonNull(negativeTtl, "negative TTL must be non-null");
|
||||
this.invalidationTtl =
|
||||
Objects.requireNonNull(invalidationTtl, "invalidation TTL must be non-null");
|
||||
}
|
||||
|
||||
/** Creates the fake on the system clock with the template's default lifetimes. */
|
||||
public InMemoryCacheRegion() {
|
||||
this(
|
||||
Clock.systemUTC(),
|
||||
Duration.ofSeconds(30),
|
||||
Duration.ofMinutes(5),
|
||||
Duration.ofSeconds(10),
|
||||
Duration.ofSeconds(30));
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized CacheLookup<V> lookup(K key) {
|
||||
Objects.requireNonNull(key, "key must be non-null");
|
||||
Instant now = clock.instant();
|
||||
Slot<V> slot = live(key, now);
|
||||
if (slot == null) {
|
||||
return new CacheLookup.Miss<>(CacheLookup.MissReason.ABSENT, new CacheWriteCondition(ABSENT));
|
||||
}
|
||||
CacheWriteCondition vacant = new CacheWriteCondition("vacant-" + slot.version());
|
||||
if (slot.tombstone() || slot.generation() != generation) {
|
||||
return new CacheLookup.Miss<>(CacheLookup.MissReason.INVALIDATED, vacant);
|
||||
}
|
||||
if (slot.absence() != null) {
|
||||
return new CacheLookup.NegativeHit<>(slot.absence(), slot.hardExpiresAt());
|
||||
}
|
||||
CacheObservationToken token = tokenOf(slot);
|
||||
return new CacheLookup.Hit<>(
|
||||
slot.value(),
|
||||
slot.softExpiresAt().isAfter(now)
|
||||
? CacheLookup.Freshness.FRESH
|
||||
: CacheLookup.Freshness.STALE,
|
||||
slot.revision(),
|
||||
slot.softExpiresAt(),
|
||||
slot.hardExpiresAt(),
|
||||
token,
|
||||
new CacheWriteCondition("present-" + slot.version()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CacheRecordOutcome record(K key, V value, CacheRecordMetadata metadata) {
|
||||
Objects.requireNonNull(value, "value must be non-null");
|
||||
return write(key, value, null, metadata, hardTtl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CacheRecordOutcome recordAbsent(
|
||||
K key, AuthoritativeAbsence reason, CacheRecordMetadata metadata) {
|
||||
Objects.requireNonNull(reason, "reason must be non-null");
|
||||
return write(key, null, reason, metadata, negativeTtl);
|
||||
}
|
||||
|
||||
private synchronized CacheRecordOutcome write(
|
||||
K key, V value, AuthoritativeAbsence absence, CacheRecordMetadata metadata, Duration ttl) {
|
||||
Objects.requireNonNull(key, "key must be non-null");
|
||||
Objects.requireNonNull(metadata, "metadata must be non-null");
|
||||
Instant now = clock.instant();
|
||||
Slot<V> current = live(key, now);
|
||||
CacheWriteCondition condition = metadata.writeCondition();
|
||||
boolean conditioned = condition.usable();
|
||||
if (conditioned && !condition.value().equals(conditionOf(current))) {
|
||||
return CacheRecordOutcome.NOT_RECORDED_CONDITION;
|
||||
}
|
||||
boolean vacant = current == null || current.tombstone() || current.generation() != generation;
|
||||
boolean applies =
|
||||
switch (metadata.intent()) {
|
||||
case UPSERT -> true;
|
||||
// An invalidation marker is vacant only to a writer who saw it: without a condition
|
||||
// nothing proves the load began after the invalidation.
|
||||
case ONLY_IF_ABSENT -> current == null || (vacant && conditioned);
|
||||
case ONLY_IF_OBSERVED ->
|
||||
current != null
|
||||
&& !vacant
|
||||
&& tokenOf(current).value().equals(metadata.observedToken().value());
|
||||
case ONLY_IF_SOURCE_REVISION_NEWER ->
|
||||
current == null
|
||||
|| (vacant && (conditioned || !current.tombstone()))
|
||||
|| (!vacant
|
||||
&& CacheSourceRevisionOrder.isStrictlyNewer(
|
||||
metadata.sourceRevision(), current.revision()));
|
||||
};
|
||||
if (!applies) {
|
||||
return CacheRecordOutcome.NOT_RECORDED_CONDITION;
|
||||
}
|
||||
Duration soft = softTtl.compareTo(ttl) > 0 ? ttl : softTtl;
|
||||
slots.put(
|
||||
key,
|
||||
new Slot<>(
|
||||
value,
|
||||
absence,
|
||||
false,
|
||||
metadata.sourceRevision(),
|
||||
generation,
|
||||
++versions,
|
||||
now.plus(soft),
|
||||
now.plus(ttl)));
|
||||
return CacheRecordOutcome.RECORDED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized CacheInvalidationOutcome invalidate(K key) {
|
||||
Objects.requireNonNull(key, "key must be non-null");
|
||||
Instant now = clock.instant();
|
||||
Slot<V> current = live(key, now);
|
||||
Instant until = now.plus(invalidationTtl);
|
||||
slots.put(key, new Slot<>(null, null, true, "0", generation, ++versions, until, until));
|
||||
return current == null || current.tombstone()
|
||||
? CacheInvalidationOutcome.ALREADY_ABSENT
|
||||
: CacheInvalidationOutcome.INVALIDATED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized CacheInvalidationOutcome invalidateRegion() {
|
||||
generation++;
|
||||
return CacheInvalidationOutcome.INVALIDATED;
|
||||
}
|
||||
|
||||
private Slot<V> live(K key, Instant now) {
|
||||
Slot<V> slot = slots.get(key);
|
||||
if (slot != null && !slot.hardExpiresAt().isAfter(now)) {
|
||||
slots.remove(key);
|
||||
return null;
|
||||
}
|
||||
return slot;
|
||||
}
|
||||
|
||||
private String conditionOf(Slot<V> slot) {
|
||||
if (slot == null) {
|
||||
return ABSENT;
|
||||
}
|
||||
boolean vacant = slot.tombstone() || slot.generation() != generation;
|
||||
return (vacant ? "vacant-" : "present-") + slot.version();
|
||||
}
|
||||
|
||||
private static CacheObservationToken tokenOf(Slot<?> slot) {
|
||||
return new CacheObservationToken(String.format("observation-%016d", slot.version()));
|
||||
}
|
||||
|
||||
private record Slot<V>(
|
||||
V value,
|
||||
AuthoritativeAbsence absence,
|
||||
boolean tombstone,
|
||||
String revision,
|
||||
long generation,
|
||||
long version,
|
||||
Instant softExpiresAt,
|
||||
Instant hardExpiresAt) {}
|
||||
}
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
package dev.caskeleton.application.idempotency.testkit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyClaimRequest;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyCompleteOutcome;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyFailOutcome;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyFailureDisposition;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyOwner;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyReleaseOutcome;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyRenewOutcome;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyScopeDigest;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyStartOutcome;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyStorePort;
|
||||
import dev.caskeleton.application.idempotency.RequestFingerprint;
|
||||
import dev.caskeleton.application.idempotency.StoredResponse;
|
||||
import dev.caskeleton.application.transaction.OperationId;
|
||||
import java.time.Duration;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The owner-safe state machine every {@link IdempotencyStorePort} owes its callers, run unchanged
|
||||
* against the in-memory fake and every store.
|
||||
*
|
||||
* <p>Time-free on purpose: lease expiry and take-over depend on whose clock the store trusts, and
|
||||
* those cases stay with each store's own tests. What is here is what a caller of the port relies on
|
||||
* whichever store is composed.
|
||||
*/
|
||||
public abstract class IdempotencyStoreContract {
|
||||
|
||||
private static final IdempotencyScopeDigest SCOPE =
|
||||
new IdempotencyScopeDigest("a".repeat(64), 1, "CHARGE_CARD");
|
||||
|
||||
private static final RequestFingerprint FINGERPRINT = new RequestFingerprint("b".repeat(64));
|
||||
|
||||
private static final RequestFingerprint OTHER_FINGERPRINT =
|
||||
new RequestFingerprint("c".repeat(64));
|
||||
|
||||
private static final OperationId OPERATION = new OperationId("operation-aaaaaaaaaa");
|
||||
|
||||
private static final OperationId OTHER_OPERATION = new OperationId("operation-bbbbbbbbbb");
|
||||
|
||||
/**
|
||||
* Returns a fresh, empty store; called once per test.
|
||||
*
|
||||
* @return the store under test
|
||||
*/
|
||||
protected abstract IdempotencyStorePort store();
|
||||
|
||||
private static IdempotencyClaimRequest claim(
|
||||
IdempotencyClaimAttempt attempt, RequestFingerprint fingerprint) {
|
||||
return new IdempotencyClaimRequest(
|
||||
SCOPE, fingerprint, attempt, Duration.ofSeconds(30), Duration.ofHours(24), "json-v2", 1);
|
||||
}
|
||||
|
||||
private static IdempotencyOwner acquire(IdempotencyStorePort store) {
|
||||
return ((IdempotencyClaimOutcome.Acquired)
|
||||
store.claim(claim(store.newClaimAttempt(OPERATION), FINGERPRINT)))
|
||||
.owner();
|
||||
}
|
||||
|
||||
private static IdempotencyOwner executing(IdempotencyStorePort store) {
|
||||
return store.markExecutionStarted(acquire(store), OPERATION).owner().orElseThrow();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("먼저 claim한 쪽이 얻고 다른 요청은 진행 중으로 막힌다")
|
||||
void aFirstClaimExcludesTheSecond() {
|
||||
// given
|
||||
IdempotencyStorePort store = store();
|
||||
acquire(store);
|
||||
|
||||
// when
|
||||
IdempotencyClaimOutcome second =
|
||||
store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT));
|
||||
|
||||
// then
|
||||
assertThat(second).isInstanceOf(IdempotencyClaimOutcome.InProgress.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 attempt로 다시 claim하면 새로 얻지 않고 재생한다")
|
||||
void theSameAttemptReplaysItsAcquire() {
|
||||
// given
|
||||
IdempotencyStorePort store = store();
|
||||
IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION);
|
||||
store.claim(claim(attempt, FINGERPRINT));
|
||||
|
||||
// when
|
||||
IdempotencyClaimOutcome again = store.claim(claim(attempt, FINGERPRINT));
|
||||
|
||||
// then
|
||||
assertThat(again).isInstanceOf(IdempotencyClaimOutcome.ReplayedAcquire.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 scope의 다른 요청 본문은 재생이 아니라 fingerprint 불일치다")
|
||||
void aDifferentRequestUnderTheSameScopeIsAMismatch() {
|
||||
// given
|
||||
IdempotencyStorePort store = store();
|
||||
acquire(store);
|
||||
|
||||
// when
|
||||
IdempotencyClaimOutcome other =
|
||||
store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), OTHER_FINGERPRINT));
|
||||
|
||||
// then
|
||||
assertThat(other).isInstanceOf(IdempotencyClaimOutcome.FingerprintMismatch.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("완료한 결과는 다음 claim에서 그대로 재생된다")
|
||||
void aCompletedResultReplays() {
|
||||
// given
|
||||
IdempotencyStorePort store = store();
|
||||
store.complete(
|
||||
executing(store), new StoredResponse("{\"ok\":true}"), Duration.ofHours(1), OPERATION);
|
||||
|
||||
// when
|
||||
IdempotencyClaimOutcome replay =
|
||||
store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT));
|
||||
|
||||
// then
|
||||
assertThat(replay).isInstanceOf(IdempotencyClaimOutcome.CompletedReplay.class);
|
||||
assertThat(((IdempotencyClaimOutcome.CompletedReplay) replay).response().payload())
|
||||
.isEqualTo("{\"ok\":true}");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("전이 전에 받은 오래된 owner 핸들로는 complete할 수 없다")
|
||||
void aStaleHandleCannotComplete() {
|
||||
// given
|
||||
IdempotencyStorePort store = store();
|
||||
IdempotencyOwner stale = acquire(store);
|
||||
store.markExecutionStarted(stale, OPERATION);
|
||||
|
||||
// when
|
||||
IdempotencyCompleteOutcome outcome =
|
||||
store.complete(stale, new StoredResponse("{}"), Duration.ofHours(1), OPERATION);
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(IdempotencyCompleteOutcome.NOT_OWNER);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("renew는 RENEWED와 더 새 revision의 핸들을 돌려주고 그 핸들로 complete할 수 있다")
|
||||
void renewReturnsANewerHandleThatCanComplete() {
|
||||
// given
|
||||
IdempotencyStorePort store = store();
|
||||
IdempotencyOwner executing = executing(store);
|
||||
|
||||
// when
|
||||
var renewed = store.renew(executing, Duration.ofSeconds(30), OPERATION);
|
||||
|
||||
// then
|
||||
assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.RENEWED);
|
||||
IdempotencyOwner current = renewed.owner().orElseThrow();
|
||||
assertThat(current.stateRevision()).isGreaterThan(executing.stateRevision());
|
||||
assertThat(store.complete(current, new StoredResponse("{}"), Duration.ofHours(1), OPERATION))
|
||||
.isEqualTo(IdempotencyCompleteOutcome.COMPLETED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("실행을 시작하기 전 claim은 renew할 수 없다")
|
||||
void aClaimNotYetExecutingCannotBeRenewed() {
|
||||
// given
|
||||
IdempotencyStorePort store = store();
|
||||
IdempotencyOwner claimed = acquire(store);
|
||||
|
||||
// when
|
||||
var renewed = store.renew(claimed, Duration.ofSeconds(30), OPERATION);
|
||||
|
||||
// then
|
||||
assertThat(renewed.outcome()).isNotEqualTo(IdempotencyRenewOutcome.RENEWED);
|
||||
assertThat(renewed.owner()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("재시도 가능한 실패는 다음 claim이 attempt 2로 넘겨받게 한다")
|
||||
void aRetryableFailureLetsTheNextClaimTakeOver() {
|
||||
// given
|
||||
IdempotencyStorePort store = store();
|
||||
store.markFailed(
|
||||
executing(store),
|
||||
IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE,
|
||||
Duration.ofHours(1),
|
||||
OPERATION);
|
||||
|
||||
// when
|
||||
IdempotencyClaimOutcome next =
|
||||
store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT));
|
||||
|
||||
// then
|
||||
assertThat(next).isInstanceOf(IdempotencyClaimOutcome.TakenOverClaimed.class);
|
||||
assertThat(((IdempotencyClaimOutcome.TakenOverClaimed) next).owner().attempt()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("효과가 불명인 채 포기한 작업은 다시 돌리지 않고 복구를 요구한다")
|
||||
void anAbandonedOperationRequiresRecovery() {
|
||||
// given
|
||||
IdempotencyStorePort store = store();
|
||||
IdempotencyFailOutcome marked =
|
||||
store.markFailed(
|
||||
executing(store),
|
||||
IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED,
|
||||
Duration.ofHours(1),
|
||||
OPERATION);
|
||||
|
||||
// when
|
||||
IdempotencyClaimOutcome next =
|
||||
store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT));
|
||||
|
||||
// then
|
||||
assertThat(marked).isEqualTo(IdempotencyFailOutcome.MARKED_ABANDONED);
|
||||
assertThat(next).isInstanceOf(IdempotencyClaimOutcome.RecoveryRequired.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("실행 전 release는 scope를 비우고 실행 뒤 release는 거부된다")
|
||||
void releaseFreesTheScopeOnlyBeforeExecution() {
|
||||
// given
|
||||
IdempotencyStorePort store = store();
|
||||
IdempotencyOwner claimed = acquire(store);
|
||||
|
||||
// when
|
||||
IdempotencyReleaseOutcome released = store.releaseBeforeExecution(claimed, OPERATION);
|
||||
|
||||
// then
|
||||
assertThat(released).isEqualTo(IdempotencyReleaseOutcome.RELEASED_BEFORE_EXECUTION);
|
||||
IdempotencyOwner executing = executing(store);
|
||||
assertThat(store.releaseBeforeExecution(executing, OPERATION))
|
||||
.isEqualTo(IdempotencyReleaseOutcome.EXECUTION_ALREADY_STARTED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 결과로 두 번 complete하면 멱등이고 다른 결과면 충돌이다")
|
||||
void completingTwiceIsIdempotentOnlyForTheSameResult() {
|
||||
// given
|
||||
IdempotencyStorePort store = store();
|
||||
IdempotencyOwner executing = executing(store);
|
||||
store.complete(executing, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION);
|
||||
|
||||
// when
|
||||
IdempotencyCompleteOutcome same =
|
||||
store.complete(executing, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION);
|
||||
|
||||
// then
|
||||
assertThat(same).isEqualTo(IdempotencyCompleteOutcome.ALREADY_COMPLETED_SAME_RESULT);
|
||||
assertThat(
|
||||
store.complete(
|
||||
executing, new StoredResponse("{\"v\":2}"), Duration.ofHours(1), OPERATION))
|
||||
.isEqualTo(IdempotencyCompleteOutcome.RESPONSE_CONFLICT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("STARTED 전이는 새 revision의 핸들을 돌려준다")
|
||||
void startingAdvancesTheRevision() {
|
||||
// given
|
||||
IdempotencyStorePort store = store();
|
||||
IdempotencyOwner claimed = acquire(store);
|
||||
|
||||
// when
|
||||
var started = store.markExecutionStarted(claimed, OPERATION);
|
||||
|
||||
// then
|
||||
assertThat(started.outcome()).isEqualTo(IdempotencyStartOutcome.STARTED);
|
||||
assertThat(started.owner().orElseThrow().stateRevision())
|
||||
.isGreaterThan(claimed.stateRevision());
|
||||
}
|
||||
}
|
||||
+20
-7
@@ -100,9 +100,17 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort {
|
||||
public synchronized IdempotencyMutationResult<IdempotencyRenewOutcome> renew(
|
||||
IdempotencyOwner owner, Duration processingLeaseTtl, OperationId operationId) {
|
||||
Row row = rows.get(owner.scope().digest());
|
||||
if (row == null || !row.owner.equals(owner) || !row.inProgress()) {
|
||||
IdempotencyRenewOutcome refused =
|
||||
row == null ? IdempotencyRenewOutcome.ABSENT : IdempotencyRenewOutcome.NOT_OWNER;
|
||||
// Only a running execution has a processing lease to extend; the stores answer a claim that
|
||||
// has not started with NOT_IN_PROGRESS, and IdempotencyStoreContract holds the fake to that.
|
||||
IdempotencyRenewOutcome refused =
|
||||
row == null
|
||||
? IdempotencyRenewOutcome.ABSENT
|
||||
: !row.owner.equals(owner)
|
||||
? IdempotencyRenewOutcome.NOT_OWNER
|
||||
: row.state != IdempotencyState.EXECUTING
|
||||
? IdempotencyRenewOutcome.NOT_IN_PROGRESS
|
||||
: null;
|
||||
if (refused != null) {
|
||||
return new IdempotencyMutationResult<>(refused, null, IdempotencyRenewOutcome::carriesOwner);
|
||||
}
|
||||
row.advance(row.state);
|
||||
@@ -120,6 +128,13 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort {
|
||||
if (row == null) {
|
||||
return IdempotencyCompleteOutcome.ABSENT;
|
||||
}
|
||||
if (row.state == IdempotencyState.COMPLETED && owner.equals(row.completedBy)) {
|
||||
// The completing handle retried, as after a lost reply: the same result is a no-op, another
|
||||
// result is a conflict, exactly as the stores answer.
|
||||
return row.response.equals(response)
|
||||
? IdempotencyCompleteOutcome.ALREADY_COMPLETED_SAME_RESULT
|
||||
: IdempotencyCompleteOutcome.RESPONSE_CONFLICT;
|
||||
}
|
||||
if (!row.owner.equals(owner)) {
|
||||
return IdempotencyCompleteOutcome.NOT_OWNER;
|
||||
}
|
||||
@@ -127,6 +142,7 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort {
|
||||
return IdempotencyCompleteOutcome.NOT_IN_PROGRESS;
|
||||
}
|
||||
row.response = response;
|
||||
row.completedBy = owner;
|
||||
row.advance(IdempotencyState.COMPLETED);
|
||||
return IdempotencyCompleteOutcome.COMPLETED;
|
||||
}
|
||||
@@ -232,6 +248,7 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort {
|
||||
private IdempotencyOwner owner;
|
||||
private IdempotencyState state = IdempotencyState.CLAIMED;
|
||||
private StoredResponse response;
|
||||
private IdempotencyOwner completedBy;
|
||||
|
||||
Row(RequestFingerprint fingerprint, IdempotencyClaimRequest request, long attempt, long rev) {
|
||||
this.fingerprint = fingerprint;
|
||||
@@ -244,10 +261,6 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort {
|
||||
request.claimAttempt().operationId());
|
||||
}
|
||||
|
||||
boolean inProgress() {
|
||||
return state == IdempotencyState.CLAIMED || state == IdempotencyState.EXECUTING;
|
||||
}
|
||||
|
||||
void advance(IdempotencyState next) {
|
||||
owner = owner.withStateRevision(owner.stateRevision() + 1);
|
||||
state = next;
|
||||
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package dev.caskeleton.application.lock.testkit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.caskeleton.application.lock.DistributedLock;
|
||||
import dev.caskeleton.application.lock.DistributedLockPort;
|
||||
import dev.caskeleton.application.lock.LockAcquisitionTimeoutException;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* What every {@link DistributedLockPort} promises, run by the fake's test and the JDBC adapter's
|
||||
* PostgreSQL test alike.
|
||||
*
|
||||
* <p>Contention is between two <em>instances</em> — two ports over one lock store — because that is
|
||||
* what the lock exists for. Two acquires through one instance from one thread prove nothing: a
|
||||
* thread-bound lock lets them both through.
|
||||
*/
|
||||
public abstract class DistributedLockContract {
|
||||
|
||||
/** How long a contested acquire waits before giving up. */
|
||||
protected static final Duration SHORT_WAIT = Duration.ofMillis(100);
|
||||
|
||||
/** A lease long enough not to expire during a test. */
|
||||
protected static final Duration LEASE = Duration.ofSeconds(30);
|
||||
|
||||
/** The first instance. */
|
||||
protected abstract DistributedLockPort firstInstance();
|
||||
|
||||
/** A second instance over the same lock store as {@link #firstInstance()}. */
|
||||
protected abstract DistributedLockPort secondInstance();
|
||||
|
||||
@Test
|
||||
void aKeyHeldByOneInstanceTimesOutForAnotherWithTheKeyNamed() {
|
||||
// given
|
||||
String key = uniqueKey();
|
||||
DistributedLock held = firstInstance().tryAcquire(key, SHORT_WAIT, LEASE);
|
||||
|
||||
// when
|
||||
Throwable refused = catchThrowable(() -> secondInstance().tryAcquire(key, SHORT_WAIT, LEASE));
|
||||
|
||||
// then
|
||||
held.close();
|
||||
assertThat(refused)
|
||||
.isInstanceOfSatisfying(
|
||||
LockAcquisitionTimeoutException.class, e -> assertThat(e.key()).isEqualTo(key));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReleasedKeyCanBeAcquiredByAnotherInstance() {
|
||||
// given
|
||||
String key = uniqueKey();
|
||||
firstInstance().tryAcquire(key, SHORT_WAIT, LEASE).close();
|
||||
|
||||
// when
|
||||
Throwable thrown =
|
||||
catchThrowable(() -> secondInstance().tryAcquire(key, SHORT_WAIT, LEASE).close());
|
||||
|
||||
// then
|
||||
assertThat(thrown).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void differentKeysDoNotContend() {
|
||||
// given
|
||||
DistributedLock held = firstInstance().tryAcquire(uniqueKey(), SHORT_WAIT, LEASE);
|
||||
|
||||
// when
|
||||
Throwable thrown =
|
||||
catchThrowable(() -> secondInstance().tryAcquire(uniqueKey(), SHORT_WAIT, LEASE).close());
|
||||
|
||||
// then
|
||||
held.close();
|
||||
assertThat(thrown).isNull();
|
||||
}
|
||||
|
||||
private static String uniqueKey() {
|
||||
return "contract-" + UUID.randomUUID();
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package dev.caskeleton.application.lock.testkit;
|
||||
|
||||
import dev.caskeleton.application.lock.DistributedLock;
|
||||
import dev.caskeleton.application.lock.DistributedLockPort;
|
||||
import dev.caskeleton.application.lock.LockAcquisitionTimeoutException;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* The {@link DistributedLockPort} fake: one permit per key, held by the handle rather than by a
|
||||
* thread.
|
||||
*
|
||||
* <p>The earlier fake, private to a test, used a {@code ReentrantLock}, so a second acquire from
|
||||
* the same thread succeeded and a release from another thread threw — neither is how a lock shared
|
||||
* by several instances behaves. Ports made with {@link #sharingStateWith(InMemoryDistributedLock)}
|
||||
* stand for several instances of one service sharing a lock store, which is what {@link
|
||||
* DistributedLockContract} contends with.
|
||||
*
|
||||
* <p>The lease TTL is accepted and not enforced: expiry needs a clock the store owns, and the JDBC
|
||||
* adapter's tests cover it.
|
||||
*/
|
||||
public final class InMemoryDistributedLock implements DistributedLockPort {
|
||||
|
||||
private final Map<String, Semaphore> permits;
|
||||
|
||||
public InMemoryDistributedLock() {
|
||||
this(new ConcurrentHashMap<>());
|
||||
}
|
||||
|
||||
private InMemoryDistributedLock(Map<String, Semaphore> permits) {
|
||||
this.permits = permits;
|
||||
}
|
||||
|
||||
/** Another instance over the same lock store. */
|
||||
public static InMemoryDistributedLock sharingStateWith(InMemoryDistributedLock other) {
|
||||
return new InMemoryDistributedLock(other.permits);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DistributedLock tryAcquire(String key, Duration waitTime, Duration leaseTtl) {
|
||||
Objects.requireNonNull(key, "key");
|
||||
Semaphore permit = permits.computeIfAbsent(key, k -> new Semaphore(1));
|
||||
boolean acquired;
|
||||
try {
|
||||
acquired = permit.tryAcquire(waitTime.toMillis(), TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new LockAcquisitionTimeoutException(key, waitTime);
|
||||
}
|
||||
if (!acquired) {
|
||||
throw new LockAcquisitionTimeoutException(key, waitTime);
|
||||
}
|
||||
AtomicBoolean released = new AtomicBoolean();
|
||||
return () -> {
|
||||
if (released.compareAndSet(false, true)) {
|
||||
permit.release();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package dev.caskeleton.application.messaging.event.testkit;
|
||||
|
||||
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.IntegrationPayload;
|
||||
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
|
||||
import dev.caskeleton.application.messaging.contract.SchemaResourceId;
|
||||
import dev.caskeleton.shared.digest.Sha256;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The one contract {@link IntegrationEventEncoderContract} encodes against: {@code
|
||||
* testkit.encoder-contract} v1 to {@link #DESTINATION}, payload {@link Payload}.
|
||||
*
|
||||
* <p>Its schema is a testFixtures resource and its hash is read from that resource, so any encoder
|
||||
* that checks a declared hash against the classpath accepts it.
|
||||
*/
|
||||
public final class EncoderContractKitContract
|
||||
implements IntegrationEventContractContribution<EncoderContractKitContract.Payload> {
|
||||
|
||||
/** The contract id. */
|
||||
public static final ContractId CONTRACT_ID = new ContractId("testkit.encoder-contract");
|
||||
|
||||
/** The destination the contract declares. */
|
||||
public static final LogicalDestinationId DESTINATION =
|
||||
new LogicalDestinationId("testkit-encoder-contract");
|
||||
|
||||
/** The serializer id the template's encoders know. */
|
||||
public static final String SERIALIZER_ID = "json-envelope-v1";
|
||||
|
||||
private static final SchemaResourceId SCHEMA =
|
||||
new SchemaResourceId("contracts/messaging/testkit.encoder-contract/v1.schema.json");
|
||||
|
||||
/** The payload record the contract declares. */
|
||||
public record Payload(String name) implements IntegrationPayload {}
|
||||
|
||||
/** A payload record the contract does not declare. */
|
||||
public record OtherPayload(String name) implements IntegrationPayload {}
|
||||
|
||||
@Override
|
||||
public ContractId contractId() {
|
||||
return CONTRACT_ID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int payloadVersion() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<Payload> exactPayloadRecordType() {
|
||||
return Payload.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> canonicalRecordComponentOrder() {
|
||||
return List.of("name");
|
||||
}
|
||||
|
||||
@Override
|
||||
public SchemaResourceId payloadSchemaResource() {
|
||||
return SCHEMA;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Sha256 payloadSchemaHash() {
|
||||
try (InputStream in =
|
||||
EncoderContractKitContract.class.getClassLoader().getResourceAsStream(SCHEMA.value())) {
|
||||
if (in == null) {
|
||||
throw new IllegalStateException("missing " + SCHEMA.value());
|
||||
}
|
||||
return Sha256.of(in.readAllBytes());
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ContractDescriptor descriptor() {
|
||||
return new ContractDescriptor(
|
||||
"application-core",
|
||||
DESTINATION,
|
||||
SERIALIZER_ID,
|
||||
false,
|
||||
4 * 1024,
|
||||
16 * 1024,
|
||||
ContractDescriptor.SensitivityClassification.INTERNAL,
|
||||
Duration.ofDays(1));
|
||||
}
|
||||
}
|
||||
+50
-2
@@ -1,17 +1,26 @@
|
||||
package dev.caskeleton.application.messaging.event.testkit;
|
||||
|
||||
import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventDraft;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
|
||||
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
|
||||
import dev.caskeleton.shared.digest.Sha256;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The encoder fake: keeps every draft it was given and returns a validated event that carries the
|
||||
* draft's identities unchanged.
|
||||
* The encoder fake: knows a closed set of contracts like the real encoder, keeps every draft it was
|
||||
* given and returns a validated event that carries the draft's identities unchanged.
|
||||
*
|
||||
* <p>It refuses what the real encoder refuses because the server assembled it wrong — an
|
||||
* unregistered contract, another destination, another payload record — with the same {@link
|
||||
* IllegalStateException}; {@link IntegrationEventEncoderContract} holds both to that. It does not
|
||||
* render JSON, so the payload and envelope size bounds are the real encoder's alone.
|
||||
*
|
||||
* <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
|
||||
@@ -22,10 +31,45 @@ public final class FakeIntegrationEventEncoder implements IntegrationEventEncode
|
||||
private static final Sha256 SCHEMA_HASH =
|
||||
Sha256.of("fake-integration-event-schema".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
private final Map<String, IntegrationEventContractContribution<?>> contracts = new HashMap<>();
|
||||
private final List<IntegrationEventDraft<?>> drafts = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* A fake that knows exactly {@code contracts}, as the deployment's encoder would.
|
||||
*
|
||||
* @param contracts the contracts the use case under test is registered with
|
||||
*/
|
||||
public FakeIntegrationEventEncoder(
|
||||
Collection<? extends IntegrationEventContractContribution<?>> contracts) {
|
||||
for (IntegrationEventContractContribution<?> contract : contracts) {
|
||||
this.contracts.put(key(contract.contractId().value(), contract.payloadVersion()), contract);
|
||||
}
|
||||
}
|
||||
|
||||
/** A fake that knows {@code contracts}. */
|
||||
public FakeIntegrationEventEncoder(IntegrationEventContractContribution<?>... contracts) {
|
||||
this(List.of(contracts));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ValidatedIntegrationEvent encode(IntegrationEventDraft<?> draft) {
|
||||
String key = key(draft.contractId().value(), draft.payloadVersion());
|
||||
IntegrationEventContractContribution<?> contract = contracts.get(key);
|
||||
if (contract == null) {
|
||||
throw new IllegalStateException("no integration event contract is registered for " + key);
|
||||
}
|
||||
if (!draft.destinationId().equals(contract.descriptor().logicalDestination())) {
|
||||
throw new IllegalStateException(
|
||||
"draft destination "
|
||||
+ draft.destinationId().value()
|
||||
+ " is not the destination contract "
|
||||
+ key
|
||||
+ " declares");
|
||||
}
|
||||
if (draft.featurePayload().getClass() != contract.exactPayloadRecordType()) {
|
||||
throw new IllegalStateException(
|
||||
"draft payload must be exactly " + contract.exactPayloadRecordType());
|
||||
}
|
||||
drafts.add(draft);
|
||||
byte[] envelope = draft.toString().getBytes(StandardCharsets.UTF_8);
|
||||
String partitionKey =
|
||||
@@ -60,4 +104,8 @@ public final class FakeIntegrationEventEncoder implements IntegrationEventEncode
|
||||
public List<IntegrationEventDraft<?>> drafts() {
|
||||
return List.copyOf(drafts);
|
||||
}
|
||||
|
||||
private static String key(String contractId, int payloadVersion) {
|
||||
return contractId + ":v" + payloadVersion;
|
||||
}
|
||||
}
|
||||
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
package dev.caskeleton.application.messaging.event.testkit;
|
||||
|
||||
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.IntegrationEventContractContribution;
|
||||
import dev.caskeleton.application.messaging.contract.IntegrationPayload;
|
||||
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
|
||||
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.messaging.event.ValidatedIntegrationEvent;
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* What every {@link IntegrationEventEncoderPort} promises, run by the real encoder's test and the
|
||||
* fake's test alike.
|
||||
*
|
||||
* <p>The fake used to accept any draft. A feature whose contract was never registered — or whose
|
||||
* payload record changed without its contract — passed every use-case test and failed every request
|
||||
* in a deployment. These are the refusals a use-case test now sees too, and they are {@link
|
||||
* IllegalStateException}: a server assembly fault, which the transports report as 500 with a log
|
||||
* line, not a 400 that tells the client to fix a request it got right.
|
||||
*/
|
||||
public abstract class IntegrationEventEncoderContract {
|
||||
|
||||
private static final Instant OCCURRED_AT = Instant.parse("2026-11-01T00:00:00Z");
|
||||
|
||||
private static final EncoderContractKitContract KNOWN = new EncoderContractKitContract();
|
||||
|
||||
/** An encoder that knows exactly {@code contracts}. */
|
||||
protected abstract IntegrationEventEncoderPort encoderKnowing(
|
||||
Collection<? extends IntegrationEventContractContribution<?>> contracts);
|
||||
|
||||
@Test
|
||||
void aDraftOfARegisteredContractKeepsItsIdentities() {
|
||||
// given
|
||||
IntegrationEventDraft<?> draft =
|
||||
draft(EncoderContractKitContract.DESTINATION, new EncoderContractKitContract.Payload("a"));
|
||||
|
||||
// when
|
||||
ValidatedIntegrationEvent event = encoderKnowing(List.of(KNOWN)).encode(draft);
|
||||
|
||||
// then
|
||||
assertThat(event)
|
||||
.extracting(
|
||||
ValidatedIntegrationEvent::eventId,
|
||||
ValidatedIntegrationEvent::contractId,
|
||||
ValidatedIntegrationEvent::payloadVersion,
|
||||
ValidatedIntegrationEvent::logicalDestinationId,
|
||||
ValidatedIntegrationEvent::aggregate,
|
||||
ValidatedIntegrationEvent::order,
|
||||
ValidatedIntegrationEvent::correlationId)
|
||||
.containsExactly(
|
||||
draft.eventId(),
|
||||
draft.contractId(),
|
||||
draft.payloadVersion(),
|
||||
draft.destinationId(),
|
||||
draft.aggregate(),
|
||||
draft.order(),
|
||||
draft.correlationId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDraftOfAnUnregisteredContractIsRefusedAsAServerFault() {
|
||||
// given
|
||||
IntegrationEventEncoderPort encoder = encoderKnowing(List.of());
|
||||
|
||||
// when
|
||||
Throwable refused =
|
||||
catchThrowable(
|
||||
() ->
|
||||
encoder.encode(
|
||||
draft(
|
||||
EncoderContractKitContract.DESTINATION,
|
||||
new EncoderContractKitContract.Payload("a"))));
|
||||
|
||||
// then
|
||||
assertThat(refused)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessage("no integration event contract is registered for testkit.encoder-contract:v1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDraftAddressedToAnotherDestinationIsRefusedAsAServerFault() {
|
||||
// given
|
||||
IntegrationEventEncoderPort encoder = encoderKnowing(List.of(KNOWN));
|
||||
|
||||
// when
|
||||
Throwable refused =
|
||||
catchThrowable(
|
||||
() ->
|
||||
encoder.encode(
|
||||
draft(
|
||||
new LogicalDestinationId("somewhere-else"),
|
||||
new EncoderContractKitContract.Payload("a"))));
|
||||
|
||||
// then
|
||||
assertThat(refused)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("draft destination somewhere-else is not the destination");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDraftWhosePayloadIsNotTheContractRecordIsRefusedAsAServerFault() {
|
||||
// given
|
||||
IntegrationEventEncoderPort encoder = encoderKnowing(List.of(KNOWN));
|
||||
|
||||
// when
|
||||
Throwable refused =
|
||||
catchThrowable(
|
||||
() ->
|
||||
encoder.encode(
|
||||
draft(
|
||||
EncoderContractKitContract.DESTINATION,
|
||||
new EncoderContractKitContract.OtherPayload("a"))));
|
||||
|
||||
// then
|
||||
assertThat(refused)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessage("draft payload must be exactly " + EncoderContractKitContract.Payload.class);
|
||||
}
|
||||
|
||||
private static IntegrationEventDraft<IntegrationPayload> draft(
|
||||
LogicalDestinationId destination, IntegrationPayload payload) {
|
||||
ContractId contractId = EncoderContractKitContract.CONTRACT_ID;
|
||||
return new IntegrationEventDraft<>(
|
||||
new EventId("event-1"),
|
||||
contractId,
|
||||
1,
|
||||
destination,
|
||||
new AggregateIdentity("global", "kit", "kit-1"),
|
||||
AggregateOrder.first(),
|
||||
OCCURRED_AT,
|
||||
"correlation-1",
|
||||
Optional.empty(),
|
||||
payload);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package dev.caskeleton.application.outbox.testkit;
|
||||
|
||||
import dev.caskeleton.application.messaging.event.AggregateIdentity;
|
||||
import dev.caskeleton.application.outbox.OutboxAggregateSequencePort;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** In-memory {@link OutboxAggregateSequencePort}: one counter per aggregate identity. */
|
||||
public final class InMemoryOutboxAggregateSequences implements OutboxAggregateSequencePort {
|
||||
|
||||
private final Map<AggregateIdentity, Long> last = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public synchronized long nextSequence(AggregateIdentity aggregate) {
|
||||
return last.merge(aggregate, 1L, Long::sum);
|
||||
}
|
||||
}
|
||||
+38
-3
@@ -21,8 +21,9 @@ import java.util.Set;
|
||||
/**
|
||||
* In-memory outbox store with the relay semantics of the SQL one: claim eligibility by status and
|
||||
* {@code nextAttemptAt}, in-flight reclaim after the timeout, and completions fenced by lease owner
|
||||
* and token. It does not model the per-aggregate FIFO gate; that lives in the claim SQL and is
|
||||
* covered against PostgreSQL.
|
||||
* and token, deferred claims kept out of the attempt budget, and released claims returned unspent.
|
||||
* It does not model the per-aggregate FIFO gate; that lives in the claim SQL and is covered against
|
||||
* PostgreSQL.
|
||||
*
|
||||
* <p>Not final so a test can override one operation to inject a storage failure.
|
||||
*/
|
||||
@@ -35,6 +36,7 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort {
|
||||
private final List<String> published = new ArrayList<>();
|
||||
private final Map<String, Instant> failed = new LinkedHashMap<>();
|
||||
private final List<String> dead = new ArrayList<>();
|
||||
private final List<String> released = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void append(ValidatedIntegrationEvent event) {
|
||||
@@ -85,7 +87,8 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort {
|
||||
row.leaseToken++;
|
||||
leases.add(
|
||||
new OutboxLease(
|
||||
new ClaimedOutboxEvent(row.event, row.status, row.attemptCount),
|
||||
new ClaimedOutboxEvent(
|
||||
row.event, row.status, row.attemptCount, row.deferredAttemptCount),
|
||||
owner,
|
||||
row.leaseToken));
|
||||
}
|
||||
@@ -110,6 +113,27 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort {
|
||||
return completion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt) {
|
||||
OutboxCompletion completion = complete(lease, OutboxEventStatus.FAILED, nextAttemptAt);
|
||||
if (completion == OutboxCompletion.APPLIED) {
|
||||
rows.get(lease.eventId()).deferredAttemptCount++;
|
||||
failed.put(lease.eventId(), nextAttemptAt);
|
||||
}
|
||||
return completion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OutboxCompletion releaseLease(OutboxLease lease, Instant claimableAt) {
|
||||
OutboxCompletion completion = complete(lease, OutboxEventStatus.PENDING, claimableAt);
|
||||
if (completion == OutboxCompletion.APPLIED) {
|
||||
Row row = rows.get(lease.eventId());
|
||||
row.attemptCount--;
|
||||
released.add(lease.eventId());
|
||||
}
|
||||
return completion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OutboxCompletion markDead(OutboxLease lease) {
|
||||
OutboxCompletion completion = complete(lease, OutboxEventStatus.DEAD, null);
|
||||
@@ -166,6 +190,11 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort {
|
||||
return row(eventId).attemptCount;
|
||||
}
|
||||
|
||||
/** Claims of the row that ended deferred ({@link #markDeferred}), outside the attempt budget. */
|
||||
public int deferredAttemptCount(String eventId) {
|
||||
return row(eventId).deferredAttemptCount;
|
||||
}
|
||||
|
||||
public Instant nextAttemptAt(String eventId) {
|
||||
return row(eventId).nextAttemptAt;
|
||||
}
|
||||
@@ -180,6 +209,11 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort {
|
||||
return new LinkedHashMap<>(failed);
|
||||
}
|
||||
|
||||
/** Event ids whose lease release applied, in order. */
|
||||
public List<String> released() {
|
||||
return List.copyOf(released);
|
||||
}
|
||||
|
||||
/** Event ids whose DEAD completion applied, in order. */
|
||||
public List<String> dead() {
|
||||
return List.copyOf(dead);
|
||||
@@ -197,6 +231,7 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort {
|
||||
private final ValidatedIntegrationEvent event;
|
||||
private OutboxEventStatus status = OutboxEventStatus.PENDING;
|
||||
private int attemptCount;
|
||||
private int deferredAttemptCount;
|
||||
private Instant nextAttemptAt;
|
||||
private String leaseOwner;
|
||||
private long leaseToken;
|
||||
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package dev.caskeleton.application.outbox.testkit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.application.messaging.event.AggregateIdentity;
|
||||
import dev.caskeleton.application.outbox.OutboxAggregateSequencePort;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* What every {@link OutboxAggregateSequencePort} promises, run against the in-memory fake and the
|
||||
* JPA adapter alike. Each test uses aggregates of its own, so a subclass may share one store.
|
||||
*/
|
||||
public abstract class OutboxAggregateSequenceContract {
|
||||
|
||||
protected abstract OutboxAggregateSequencePort sequences();
|
||||
|
||||
protected abstract TransactionPort transactions();
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 aggregate의 순서 번호는 1부터 커밋마다 하나씩 커진다")
|
||||
void anAggregatesNumbersStartAtOneAndGrowByOnePerCommittedWrite() {
|
||||
// given
|
||||
AggregateIdentity aggregate = aggregate();
|
||||
List<Long> numbers = new ArrayList<>();
|
||||
|
||||
// when
|
||||
for (int i = 0; i < 3; i++) {
|
||||
numbers.add(transactions().inWrite(() -> sequences().nextSequence(aggregate)));
|
||||
}
|
||||
|
||||
// then
|
||||
assertThat(numbers).containsExactly(1L, 2L, 3L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("aggregate마다 순서 번호를 따로 센다")
|
||||
void eachAggregateCountsOnItsOwn() {
|
||||
// given
|
||||
AggregateIdentity first = aggregate();
|
||||
AggregateIdentity second = aggregate();
|
||||
transactions().inWrite(() -> sequences().nextSequence(first));
|
||||
transactions().inWrite(() -> sequences().nextSequence(first));
|
||||
|
||||
// when
|
||||
long secondsFirst = transactions().inWrite(() -> sequences().nextSequence(second));
|
||||
|
||||
// then
|
||||
assertThat(secondsFirst).isEqualTo(1L);
|
||||
}
|
||||
|
||||
private static AggregateIdentity aggregate() {
|
||||
return new AggregateIdentity("default", "contract", "aggregate-" + UUID.randomUUID());
|
||||
}
|
||||
}
|
||||
+75
@@ -25,6 +25,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
@@ -155,6 +156,70 @@ public abstract class OutboxLeaseFencingContract {
|
||||
.isEqualTo(Map.entry(OutboxCompletion.STALE, OutboxEventStatus.PUBLISHED));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("놓은 claim은 시도로 세지 않고 곧바로 다시 claim할 수 있다")
|
||||
void aReleasedClaimIsClaimableAtOnceAndSpendsNoAttempt() {
|
||||
// given
|
||||
String eventId = appendEvent("release");
|
||||
OutboxLease lease = claim("relay-a", CLAIMED_AT);
|
||||
|
||||
// when
|
||||
OutboxCompletion released =
|
||||
transactions().inWrite(() -> store().releaseLease(lease, CLAIMED_AT));
|
||||
|
||||
// then: another relay takes it at the same instant, as its first attempt
|
||||
OutboxLease next = claim("relay-b", CLAIMED_AT);
|
||||
assertThat(List.of(released, statusOf(eventId)))
|
||||
.containsExactly(OutboxCompletion.APPLIED, OutboxEventStatus.IN_FLIGHT);
|
||||
assertThat(next.eventId()).isEqualTo(eventId);
|
||||
assertThat(next.event().attemptCount()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("다른 relay가 넘겨받은 claim은 놓을 수 없다")
|
||||
void aSupersededLeaseCannotReleaseTheRowItLost() {
|
||||
// given
|
||||
String eventId = appendEvent("release-stale");
|
||||
OutboxLease expired = claim("relay-a", CLAIMED_AT);
|
||||
claim("relay-b", AFTER_EXPIRY);
|
||||
|
||||
// when
|
||||
OutboxCompletion released =
|
||||
transactions().inWrite(() -> store().releaseLease(expired, AFTER_EXPIRY));
|
||||
|
||||
// then
|
||||
assertThat(List.of(released, statusOf(eventId)))
|
||||
.containsExactly(OutboxCompletion.STALE, OutboxEventStatus.IN_FLIGHT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("미룬 시도는 다음 claim에서 예산 밖으로 집계된다")
|
||||
void aDeferredClaimIsCountedOutsideTheAttemptBudget() {
|
||||
// given
|
||||
appendEvent("deferred");
|
||||
OutboxLease first = claim("relay-a", CLAIMED_AT);
|
||||
Instant retryAt = CLAIMED_AT.plusSeconds(30);
|
||||
|
||||
// when
|
||||
OutboxCompletion deferred = transactions().inWrite(() -> store().markDeferred(first, retryAt));
|
||||
|
||||
// then
|
||||
OutboxLease second = claim("relay-a", retryAt);
|
||||
assertThat(deferred).isEqualTo(OutboxCompletion.APPLIED);
|
||||
assertThat(
|
||||
List.of(
|
||||
second.event().attemptCount(),
|
||||
second.event().deferredAttemptCount(),
|
||||
second.event().budgetedAttemptCount()))
|
||||
.containsExactly(2, 1, 1);
|
||||
}
|
||||
|
||||
private OutboxLease claim(String owner, Instant now) {
|
||||
return transactions()
|
||||
.inWrite(() -> store().claimBatch(owner, 1, now, IN_FLIGHT_TIMEOUT))
|
||||
.getFirst();
|
||||
}
|
||||
|
||||
private String appendEvent(String scenario) {
|
||||
String eventId = "lease-fencing-" + scenario + "-" + UUID.randomUUID();
|
||||
transactions()
|
||||
@@ -241,6 +306,16 @@ public abstract class OutboxLeaseFencingContract {
|
||||
return count(delegate.markFailed(lease, nextAttemptAt));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt) {
|
||||
return count(delegate.markDeferred(lease, nextAttemptAt));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OutboxCompletion releaseLease(OutboxLease lease, Instant claimableAt) {
|
||||
return count(delegate.releaseLease(lease, claimableAt));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OutboxCompletion markDead(OutboxLease lease) {
|
||||
return count(delegate.markDead(lease));
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "urn:dev-caskeleton:contracts:messaging:testkit.encoder-contract:v1",
|
||||
"title": "Encoder contract kit payload v1",
|
||||
"type": "object",
|
||||
"required": ["name"],
|
||||
"properties": {
|
||||
"name": {"type": "string"}
|
||||
},
|
||||
"unevaluatedProperties": false
|
||||
}
|
||||
Reference in New Issue
Block a user