refactor: 부가 기능을 capability 모듈로 포장하고 기본 조립을 web-only로 전환

설계: docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md
계획/진행 기록: docs/superpowers/plans/2026-09-25-capability-module-packaging.md

- Wave 0: 규칙 고정(AGENTS.md capability 완료 기준·테스트 규칙) + 차단 결함 7건
  (compose overlay 검사, redis-sdk CI job, 적용된 V9/V13 원복 + V16, @EnableScheduling,
  messaging bridge 순서, prod 에러 상세 validator, sample loggers read-only)
- Wave 1: 데이터·보안 Critical 10건 (durable operation 25P02, operation 유스케이스 이동,
  outbox 재인코딩, Kafka TLS/SASL, 알림 트랜잭션, SNS 서명, tus checksum, GraphQL fragment,
  Redis lane, gRPC FAILED_TERMINAL)
- Wave 2: 리팩터링 잔재·실험용 자리 삭제, outbox v1 fencing(V17), 멱등성 V2 정본화
- Wave 3: 라이브러리형 코드 정리(동작하지 않는 설정·인터페이스·gate 제거, web-advanced 분리)
- Wave 4: capability 11개를 "있으면 켜짐" 모듈로 포장, 끄는 장치 제거, 기본 조립 web-only,
  qualificationBootJar 분리
- Wave 5: 빌드 로직 축소(17.2k -> 10.8k줄), sample 테스트 컨벤션 적용

삭제한 코드는 docs/capability-status.md "제거된 코드" 표에 복구 커밋(208077fd)과 함께 기록.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-25 12:49:07 +09:00
co-authored by Claude Opus 5.5
parent 208077fddf
commit 6d27356e2b
2822 changed files with 27992 additions and 166879 deletions
+21 -41
View File
@@ -73,37 +73,11 @@ Package root: `dev.caskeleton.application`.
| `messaging.event.ValidatedIntegrationEvent` | Stable semantic identities plus immutable exact encoded bytes and hashes, ready for a later durable append boundary. |
| `messaging.event.IntegrationEventEncoderPort` | Framework-free local draft-to-validated-event boundary implemented by an outbound adapter. |
## Notification canonical namespace (NOTIF-ADR-005)
## Notification (NOTIF-ADR-005)
`..notification.platform..` is canonical. The R1 types directly under
`dev.caskeleton.application.notification` remain and accept no new production consumers; their
per-type disposition is in `docs/notification/module-mapping.md`. Production dependencies between
the two namespaces are zero, enforced by
`NOTIFICATION_R1_AND_PLATFORM_DO_NOT_DEPEND_ON_EACH_OTHER`; the only permitted exception is
`dev.caskeleton.application.notification.compatibility.r1`.
## Notification R1 application boundary
- `dev.caskeleton.application.notification` owns only framework-free semantic values, code-owned
kind policy, narrow outbound ports, dispatch/receipt/admission/reconciliation orchestration and
writer-cutover command contracts.
- Feature/application code creates a typed `NotificationIntentDraft`; `NotificationPlanPort`
returns the application-owned immutable `NotificationFrozenPlan`, which is the only planning
handoff consumed by append or inline attempt ports. Provider SDK, transport DTO, persistence
entity, compiled adapter binding and raw recipient/template payload types are forbidden here.
- Provider calls run outside database transactions. Dispatch and reconciliation use bounded
claim/authorize/finalize transactions with opaque claim/version/execution tokens; an
`INDETERMINATE` submission is terminal and must not be blindly retried.
- Receipt reduction is order-independent and keeps delivery acceptance monotonic. Only hard bounce
and complaint facts may request technical suppression; consent/unsubscribe policy is outside this
capability.
- Writer-cutover operations that must prove a physical commit use `inRootWrite`. Route/profile
registries are application-owned exact inputs; signed inventory/quiescence verification is
delegated to narrow verifier ports and the persistence operation must enforce locked durable
state/journal invariants.
- This is the R1 application contract proven with fakes. It does not claim PostgreSQL schema/locking,
provider protocol, cryptographic verifier, or runtime wiring qualification; those belong to the
notification/persistence/bootstrap adapters.
`..notification.platform..` (leaf `application-notification`) is canonical. The R1 types directly
under `dev.caskeleton.application.notification` were removed on 2026-09-25; only the simple
`NotificationPort`, `Notification` and `NotificationChannel` remain there.
## Naming convention
@@ -177,18 +151,24 @@ loop outside the transaction boundary.
## Idempotency (KEYED) — feature-rate-limit-idempotency-contract
`@UseCaseCapability(idempotency = Idempotency.KEYED)` is now **supported** (the D14
freeze is lifted). A KEYED use case wraps its work with the `idempotency`-package
`IdempotencyExecutor`:
`@UseCaseCapability(idempotency = Idempotency.KEYED)` is **supported**. A KEYED use case wraps
its work with `dev.caskeleton.application.idempotency.IdempotencyExecutor` — the one owner-safe
generation; the V1 `IdempotencyScope`/`tryBegin` API is gone.
- **Key source**: the `Idempotency-Key` HTTP header, assembled by `adapter:inbound:web`'s
`IdempotencyKeySupport` into an `IdempotencyScope` of
`(authenticatedPrincipal, idempotencyKey, useCaseName)` (tenant 4-tuple when active).
- **Storage**: a DB table (`IdempotencyStore` port → `adapter-persistence`
`IdempotencyStoreAdapter` over `idempotency_record`); in-memory prod storage is forbidden.
- **TTL**: `APP_IDEMPOTENCY_TTL` (default 24h, ≤72h override).
- Concurrency (200ms in-flight wait → 409) and fingerprint mismatch (SHA-256 → 422)
are enforced by the executor; the codes live in `OperationalError`.
- **Scope**: the caller passes an `IdempotencyScopeDigest` — a versioned HMAC of
principal + client key + operation code, computed before the executor sees it. The raw
`Idempotency-Key` never reaches this layer or the store.
- **Store**: `IdempotencyStorePort`, contributed by exactly one provider selected with
`ca-skeleton.capabilities.idempotency.provider` (`redis` → `cache-redis`, `postgresql` →
`persistence-jpa`; default `disabled`). In-memory prod storage is forbidden.
- **Executor**: built once by app-bootstrap `IdempotencyProviderSelectionConfig` from
`IdempotencySettings` (processing lease 30s, replay TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h,
failure retention 24h). Do not construct it in a use case or a sample config.
- The action returns `IdempotentAction.Outcome` (`Success` / `RetryableNoEffect` /
`EffectUnknown`); a thrown exception counts as effect-unknown. In progress → 409
`IDEMPOTENT_IN_FLIGHT`, fingerprint mismatch (SHA-256) → 422 `IDEMPOTENT_REQUEST_MISMATCH`;
`IdempotencyUnavailableException` and `IdempotencyRecoveryRequiredException` mean the store
could not prove the outcome, so do not blindly retry.
The former ArchUnit freeze rule `inbound_port_implementations_do_not_declare_keyed_idempotency`
and its fixture were removed when this branch merged.
+80 -124
View File
@@ -14,11 +14,8 @@
`verifyApplicationCoreDependencyPurity`와 ArchUnit
`APPLICATION_HAS_NO_DIAGNOSTIC_FRAMEWORK`가 이 계약을 자동 검증한다.
Cache 진단도 같은 원칙을 따른다. `CacheObservationEvent`는 code-owned bounded cache name,
local/Redis tier, enum outcome과 finite duration/count만 표현하며 semantic key, user/tenant ID,
endpoint를 담지 않는다. `CacheObservationPort`는 이 event를 전달하는 framework-free 경계이고,
Micrometer meter/tag 렌더링은 Redis adapter가 소유한다. 관측 실패는 cache lookup/invalidation
결과를 바꾸지 않는다.
Cache도 같은 원칙을 따른다. `cache` 패키지에는 cache-redis가 구현하는 `CacheRegionPort`와 그
값 타입만 있다. Redis key, codec, Micrometer 렌더링은 adapter가 소유한다.
---
@@ -138,31 +135,6 @@ application/domain 을 프레임워크-free 로 유지하는 핵심 장치.
`@Transactional` 직접 사용, `inRootWrite` 의 ambient transaction 진입, `inNew` 의 per-record
루프 호출.
---
## Notification R1 오케스트레이션 경계
`dev.caskeleton.application.notification`은 알림 vendor 구현이 아니라 알림 capability의 순수
애플리케이션 계약이다.
- 입력은 typed recipient/template value와 코드 소유 `NotificationKindPolicy`로 제한한다. feature가
만든 `NotificationIntentDraft`는 `NotificationPlanPort`에서 immutable
`NotificationFrozenPlan`으로 고정되고, append/inline 포트는 이 plan만 소비한다.
- dispatch는 claim → reserve/authorize → provider call → terminal-once finalize 순서다. 짧은 DB
transaction 사이에서 provider를 호출하며, opaque claim/version/execution token으로 stale 결과를
거부한다. submission certainty가 `INDETERMINATE`면 blind retry나 fallback을 하지 않는다.
- receipt reducer는 fact 순서와 무관한 monotonic projection을 만든다. hard bounce/complaint만
technical suppression 후보이고, business consent/unsubscribe는 다른 capability가 소유한다.
- admission/reconciliation/maintenance는 bounded batch와 주입된 `Clock`을 사용한다. scheduler는
이 유스케이스만 호출하며 store/provider 포트를 직접 조율하지 않는다.
- legacy→canonical writer cutover는 exact route/generation/profile registry, root-only commit,
서명된 inventory/quiescence evidence와 closed transition action으로 표현한다. 애플리케이션은
verifier/operation 포트의 입력 계약을 강제하고, 실제 서명 검증·행 잠금·불변 journal·provider
egress 차단은 후속 adapter 구현이 증명해야 한다.
현재 증거 등급은 **R1 application contract with fakes**다. PostgreSQL DDL/locking, provider
protocol, receipt ingress, runtime wiring을 포함한 R2/R3 완료 주장이 아니다.
### TransactionMode
- `WRITE` / `READ_ONLY` / `REQUIRES_NEW`. TransactionPort API 와 UseCaseCapability 양쪽에서 쓰여,
@@ -236,52 +208,52 @@ protocol, receipt ingress, runtime wiring을 포함한 R2/R3 완료 주장이
## 멱등성 (idempotency)
application 계층이 in-flight 대기·replay **정책** 을 소유하고, 저장은
`IdempotencyStorePort` 로 위임한다.
application 계층이 claim·replay·복구 **정책** 을 소유하고, 저장은 `IdempotencyStorePort` 로
위임한다. 패키지는 `dev.caskeleton.application.idempotency` 하나다. 예전 V1(`IdempotencyScope`,
`tryBegin/complete/discard`)은 삭제됐고, owner-safe 계약이 유일한 세대다.
### IdempotencyExecutor
- application 유스케이스 경계에서 멱등 실행을 조율한다. 하나의 `IdempotencyScope` 에 대해 순서대로:
1. **claim** — store 유니크 제약 위의 atomic insert-or-read(D7). 이긴 caller 가 action 을
정확히 한 번 실행한다.
2. **fingerprint mismatch** — 같은 key, 다른 body(다른 fingerprint)인 live record 는
`IdempotencyRequestMismatchException` → 422(D8).
3. **replay** — `COMPLETED` record 는 저장된 응답을 codec 으로 재생(§B).
4. **in-flight wait** — 동시 `IN_FLIGHT` record 는 최대 `IN_FLIGHT_WAIT`(200ms) 동안 폴링하고,
여전히 미해결이면 `IdempotencyInFlightException` → 409(D7).
- claim 한 action 이 예외를 던지면 in-flight record 를 `discard` 한다 — 그래야 재시도가 TTL
만료까지 409 에 갇히지 않는다.
- **200ms 대기 창의 출처(표준이 강제한 값 아님 — 스켈레톤 기본 선택)**: 이 200ms 대기 창은
인용 가능한 표준이 강제하는 값이 아니다(IETF/Toss 는 즉시 409 를 권장). 표준의 운영 친화적
변형이다 — "표준 기반 + 운영 변형" 으로 설명해야지 "표준을 따른다" 고 말하면 안 된다. 블로킹
폴링이 요청 스레드를 점유하므로, 중복 도착이 몰리면 스레드 점유 vs 클라이언트 재시도 친화성의
트레이드오프가 있다(임계치는 부하 테스트로 검증 필요).
- 상수: `IN_FLIGHT_WAIT = 200ms`(D7), `MAX_TTL = 72h`(D6 하드 캡), `POLL_INTERVAL = 20ms`.
- package-private 한 `Sleeper` 주입 생성자가 따로 있는 이유: 테스트 `Sleeper` 가 mutable clock 을
전진시켜 실제 시간 블로킹 없이 in-flight wait 를 결정적으로 검증하기 위함.
- application 유스케이스 경계에서 멱등 실행을 조율한다. 입력은 `IdempotencyScopeDigest`,
`RequestFingerprint`, caller 가 응답 유실 뒤에도 보관하는 `IdempotencyClaimAttempt`
(`newAttempt(operationId)` 로 만든다), `IdempotentAction`, `IdempotentResponseCodec` 이다.
- 흐름: **claim → markExecutionStarted → action 실행 → complete(또는 markFailed)**.
- `COMPLETED` record 는 저장된 응답을 codec 으로 재생한다.
- 같은 scope 에 다른 fingerprint → `IdempotencyRequestMismatchException` → 422.
- 다른 owner 가 진행 중 → 기다리지 않고 바로 `IdempotencyInFlightException` → 409.
- store 응답이 유실(`INDETERMINATE`)되면 `inspect` 로 실제 상태를 읽어 이어가거나 멈춘다.
- 모든 상태 전이는 owner 핸들(owner token + attempt + operation ID + state revision)을
compare-and-set 으로 검증한다. 전이가 성공하면 revision 이 올라간 새 핸들을 다음 호출에 쓴다.
- action 결과는 `IdempotentAction.Outcome` 으로 분류한다. `RetryableNoEffect` 만 재시도 가능한
실패로 기록하고, `EffectUnknown` 이나 그냥 던진 예외는 "효과 불명"(`ABANDONED`)으로 남긴다.
한 번 실행됐을지 모르는 작업을 재시도로 두 번 돌리지 않기 위해서다.
- processing lease 와 replay TTL 은 따로 간다. 만료된 `CLAIMED` 만 다른 caller 가 가져갈 수 있고,
만료된 `EXECUTING` 은 `RECOVERY_REQUIRED` 로 닫는다.
- 생성은 app-bootstrap `IdempotencyProviderSelectionConfig` 가 한 번 한다(`IdempotencySettings`:
processing lease 30s, replay TTL 24h(최대 72h), failure retention 24h, codec id `json-v2`,
policy revision 2). 유스케이스나 샘플 설정이 직접 만들지 않는다.
- 이 계약은 요청 재생(replay) 근거를 남길 뿐이다. store 와 비즈니스 DB 사이의 exactly-once 를
보장하지 않는다.
### IdempotencyStorePort
- 멱등 record 저장 outbound 포트(D3). `adapter-persistence` 가 유니크 제약
`(tenant, principal, idempotency_key, use_case_name)` 위에 구현한다. 포트는 저장 primitive
(tryBegin/find/complete/discard)만 노출하고, 정책은 executor 가 가진다.
- **in-memory 프로덕션 구현 금지**: 계약상 내구성 있고 유일성을 강제하는 백킹 스토어가 필요하다.
Redis 는 내구 스토어 앞단의 선택적 캐시로만 허용된다.
- **만료 record 는 reclaimable**: `expiresAt <= now` 인 record 는 없는 것처럼 취급해야 한다.
`tryBegin` 은 만료된 죽은 행을 purge/replace 해서 새 claim 이 이기게 하고, `find` 는 만료된
record 를 absent 로 보아 만료 replay 를 거부한다(§E / TTL 경계).
- provider 중립 owner-safe 상태 기계 포트. 메서드: `newClaimAttempt`, `claim`,
`markExecutionStarted`, `renew`, `complete`, `markFailed`, `releaseBeforeExecution`, `inspect`.
- 상태: `CLAIMED` / `EXECUTING` / `COMPLETED` / `FAILED_RETRYABLE` / `ABANDONED`(`IdempotencyState`).
- 구현은 provider 하나만 붙는다: `redis`(`adapter:outbound:cache-redis`
`RedisIdempotencyStoreAdapter`) 또는 `postgresql`(`adapter:outbound:persistence-jpa`
`PostgreSqlOwnerSafeIdempotencyStore`). `ca-skeleton.capabilities.idempotency.provider` 로 고르고
기본값은 `disabled` 다. store 가 정확히 하나가 아니면 기동을 거부한다.
- **in-memory 프로덕션 구현 금지**. 테스트용 `InMemoryIdempotencyStore` 는 testFixtures 에만 있다.
### IdempotencyScope
### IdempotencyScopeDigest
- 멱등 요청의 정체성이자 계약의 SSOT scope 모양(D2). 기본은 triple
`(authenticatedPrincipal, idempotencyKey, useCaseName)`. 테넌트 격리가 활성이면 `tenant` 차원을
앞에 붙인 4-tuple 이 되고, single-tenant 모드에선 `tenant = null`.
- **여기서 막는 실패 모드**: `principal`/`useCaseName` 이 빠진 key 는 전역적으로 충돌해 다른
caller 의 응답을 재생할 수 있다. `of` 팩토리가 blank 필수 차원을 `IdempotencyScopeMissingException`
으로 거부해, scope 없는 key 가 store 에 닿지 못하게 막는다. 막으려는 실패 모드는 "scope 누락으로
인한 silent 전역 충돌"이다.
- `storageKey()` 는 진단/단일 컬럼 조회용으로 사람이 읽는 join 문자열일 뿐이다. 유일성은 차원
컬럼에 강제되지 이 문자열에 강제되지 않는다.
- 멱등 요청의 정체성. principal·클라이언트 key·operation code 를 **caller 가 먼저 versioned
HMAC-SHA-256 으로 digest** 한 값이다(`digest`, `keyDigestVersion`, `operationCode`).
- raw 클라이언트 key 와 principal 은 executor·store·로그·메트릭 어디에도 닿지 않는다. 예외
메시지의 진단 문자열도 이 digest 로만 만든다.
- digest 를 만드는 쪽(키 링, 버전 교체)은 adapter 나 유스케이스 소유다. 예: sample 의
`HmacPosterImageIdempotencyScopeDigester`.
### RequestFingerprint
@@ -296,48 +268,31 @@ application 계층이 in-flight 대기·replay **정책** 을 소유하고, 저
- `NoSuchAlgorithmException` catch 는 도달 불가다(SHA-256 은 모든 JDK 에 필수). 그래서
`IllegalStateException` 으로 감싼다.
### 멱등성 값/계약 타입 (Context · Record · StoredResponse · Codec · Status · Sleeper)
### 멱등성 값/계약 타입 (StoredResponse · Codec · Action)
- `IdempotencyContext` — executor 입력. scope + fingerprint + 선택적 per-use-case TTL
override(D6). 결제/송금 같은 장기 유스케이스가 72h 캡까지 override 가능하고, 캡 초과는 executor 가
거부한다.
- `IdempotencyRecord` — application 이 보는 영속 record. `COMPLETED` 면 반드시 response 를
동반해야 한다(생성자가 강제). adapter 가 테이블 행과 매핑한다.
- `StoredResponse` — 완료된 응답의 불투명 직렬화 표현으로, 중복 caller 에게 그대로 재생된다(§B).
**어디에** 물리 저장되는지(작으면 행 인라인 ≤8KB, 크면 object store + 행엔 ref 만 — §F/D9)는
전적으로 persistence adapter 관심사라 여기선 보이지 않는다 → application 계층을 transport·저장
중립으로 유지.
어디에 어떻게 저장되는지는 provider 관심사다. PostgreSQL store 는 8 KiB 이하 응답만 행에
inline 으로 저장하고, 넘으면 거부한다(별도 object store 경로는 없다).
- `IdempotentResponseCodec` — 유스케이스 결과를 `StoredResponse` payload 로 직렬화/역직렬화.
application 은 wire-format 중립이다 — 구체 JSON 인코딩은 `R` 의 응답 모양을 아는 `adapter-web`
caller 가 소유하고, executor 는 그 문자열을 store 로 왕복시키기만 한다.
- `IdempotencyStatus` — `IN_FLIGHT` / `COMPLETED` 두 값.
- `Sleeper` — `Thread.sleep` 우회 인터페이스. executor 의 in-flight 폴링 대기를 결정적으로
테스트하기 위함(테스트 Sleeper 가 실제 시간 블로킹 대신 mutable clock 전진).
application 은 wire-format 중립이다 — 구체 JSON 인코딩은 `R` 의 응답 모양을 아는 adapter 가
소유하고(예: web-advanced `JsonIdempotentResponseCodec`), executor 는 그 문자열을 store 로
왕복시키기만 한다.
- `IdempotentAction` — 실행할 작업. 결과를 `Outcome.Success` / `RetryableNoEffect` /
`EffectUnknown` 으로 돌려준다.
- complete/fail/release 재호출은 operation ID 와 result digest 가 같을 때만 이전 결과로 재생한다.
### 멱등성 예외 3종 (공통 패턴)
### 멱등성 예외 (공통 패턴)
- `IdempotencyRequestMismatchException`(422), `IdempotencyInFlightException`(409),
`IdempotencyScopeMissingException`(400, `VALIDATION_FAILED`).
- 셋 다 **프레임워크-free, application 소유**(`AuthorizationDeniedException` 선례). web adapter 가
경계에서 각각의 HTTP 코드로 매핑한다. 진단 메시지는 scope storage key / 누락 차원을 **로그용으로만**
담고, 클라이언트에는 핸들러가 고정 client-safe 메시지로 대체한다(fingerprint 자체는 노출 안 함).
- `IdempotencyRequestMismatchException`(422 `IDEMPOTENT_REQUEST_MISMATCH`),
`IdempotencyInFlightException`(409 `IDEMPOTENT_IN_FLIGHT`),
`IdempotencyUnavailableException`(store 에 닿지 못함),
`IdempotencyRecoveryRequiredException`(첫 시도가 효과를 냈는지 증명하지 못함).
- 모두 **프레임워크-free, application 소유**(`AuthorizationDeniedException` 선례). web adapter 가
경계에서 HTTP 코드로 매핑한다. 진단 메시지는 scope digest 만 **로그용으로** 담고, 클라이언트에는
핸들러가 고정 client-safe 메시지로 대체한다(fingerprint 자체는 노출 안 함).
- retryable: mismatch / in-flight 모두 `false`. 클라이언트는 body 를 고치거나 결과를 polling 해야지
단순 재시도를 하면 안 된다.
### Owner-safe idempotency V2
`idempotency.v2`는 V1의 scope-only `tryBegin/complete/discard`를 대체하는 additive contract다.
provider가 JPA인지 Redis인지와 무관하게 claim에는 secure owner token과 stable operation ID가
필요하고, 모든 mutation은 owner/attempt/claim-operation/state-revision을 검증한다.
- processing lease와 completed replay TTL을 분리한다.
- expired `CLAIMED`만 takeover하고 expired `EXECUTING`은 `RECOVERY_REQUIRED`로 닫는다.
- complete/fail/release는 operation ID와 result digest가 같은 재호출만 prior result로 replay한다.
- `SAME_STORE_TRANSACTIONAL` JPA profile의 response는 8 KiB 이하 inline 값만 지원한다.
- raw principal/client key는 versioned HMAC scope digest로 바꾼 뒤 adapter에 전달한다.
V1은 rolling migration compatibility를 위해 유지된다. 새 reliability profile이 V2 claim과 V1
scope-only mutation을 섞는 것은 금지한다.
단순 재시도를 하면 안 된다. recovery-required 는 재생도 재실행도 안전하지 않다 — 비즈니스
데이터로만 판단할 수 있다.
---
@@ -367,12 +322,20 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장.
아니면 그 aggregate 의 뒤 행들은 skip 한다. `DEAD` 행도 그 aggregate 큐를 막는다(strict
FIFO — 해제하려면 runbook 개입 필요).
- claim 후: `status = IN_FLIGHT`, `attempt_count += 1`,
`next_attempt_at = now + inFlightTimeout`.
`next_attempt_at = now + inFlightTimeout`, `lease_owner = owner`, `lease_token += 1`.
claim 결과는 행마다 `OutboxLease(event, owner, token)`이다.
- 순서: adapter 는 claim 쿼리에 `ORDER BY occurred_at ASC` 를 쓰는 게 좋고, relay 도 받은
배치를 방어적으로 재정렬한다.
- **in-flight timeout 재사용(I6)**: `next_attempt_at` 컬럼을 in-flight 고아 timeout 으로
재사용한다. relay 인스턴스가 죽어 `IN_FLIGHT` 로 남은 행이 `next_attempt_at` 을 지나면 다음
폴링에서 다시 claim 가능해진다. 별도 `claimed_at` 컬럼 없이 at-least-once 전달을 보장하는 트릭.
- **lease fencing**: in-flight timeout 뒤 다른 relay 가 행을 다시 claim 할 수 있으므로 완료
(`markPublished`/`markFailed`/`markDead`)는 lease 를 받아, 행이 아직 `IN_FLIGHT` 이고 owner·token
이 같을 때만 적용된다. 결과는 `OutboxCompletion.APPLIED`/`STALE` 이고 `STALE` 이면 아무것도 쓰지
않는다. 그래서 timeout 을 넘겨 멈췄던 relay 가 행을 넘겨받은 relay 의 결과를 덮지 못한다.
relay 는 `STALE` 을 `Outcome.STALE` 로 남기고 `reportStaleCompletion` 으로 알린 뒤 넘어간다.
owner 는 relay 인스턴스마다 한 번 만든 UUID 다. fake 는 testFixtures `InMemoryOutboxStore`,
계약은 `OutboxLeaseFencingContract`(fake 와 PostgreSQL adapter 가 같은 계약을 통과).
- `countByStatus` / `oldestUnpublishedAgeSecondsByEventType` 는 메트릭 게이지
(`outbox.pending.size`, `outbox.publisher.lag`)의 데이터 소스다. 트랜잭션 밖 read-only
(metric-scrape 경로)로 호출된다.
@@ -455,7 +418,8 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장.
공급한다(I12 — outbox core 는 ID 생성에 비의존). 권장 기본값은 `idempotencyKey = eventId`
(per-event dedup, CloudEvents-C2).
- `OutboxRelayResult` — relay 한 사이클의 결과. `claimedCount` + per-event outcome 목록. 내부
`Outcome` enum 이 `OutboxEventStatus` 의 5값을 재사용하지 않고 3값(PUBLISHED/FAILED/DEAD)을
`Outcome` enum 이 `OutboxEventStatus` 의 5값을 재사용하지 않고 4값(PUBLISHED/FAILED/DEAD/
STALE — 마지막은 lease 를 잃어 결과를 쓰지 못한 경우)을
따로 두는 이유: relay 관점은 "이번 실행에서 무슨 일이 있었나" 이지 "행의 현재 영속 상태" 가
아니다(후자는 store 가 5값으로 추적). 별도 enum 이 메트릭·스케줄러 로깅 consumer 에게 relay API
를 깔끔하게 유지해 준다.
@@ -466,25 +430,11 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장.
adapter에 전달하는 framework-free outbound contract. 구조화 ERROR 필드와 runbook 렌더링은
messaging adapter가 소유한다.
### Immutable outbox/polling delivery V2
### outbox V2 (삭제됨)
`outbox.v2`는 domain event intent와 delivery state를 분리한다.
- `NewOutboxEventV2`의 aggregate version과 deterministic ordinal이 ordering authority다.
- `OutboxAppendPortV2`는 caller의 primary write transaction에 참여하고 publication epoch와
authority를 DB control row에서 얻는다.
- immutable event ID 충돌과 aggregate ordering tuple 충돌은 서로 다른 outcome이다.
- `OutboxPollingDeliveryPortV2`는 publish 밖의 짧은 claim/completion transaction만 소유하고
owner/token/attempt/version/epoch CAS로 stale relay를 거절한다.
- broker publish와 DB completion 사이 ACK 유실은 stable event ID의 duplicate publish를 만들 수
있으므로 exactly-once delivery로 표현하지 않는다.
### Same-store inbox
`inbox.InboxStorePort`는 broker redelivery를 DB business mutation과 같은 transaction에서
deduplicate한다. `RECEIVED -> PROCESSING -> COMPLETED`가 기본이며 expired `PROCESSING`은 blind
takeover하지 않는다. broker ACK는 transaction commit 이후 adapter 바깥에서만 수행하고 remote
side effect는 outbox/workflow로 옮긴다.
`outbox.v2`(immutable storage + polling delivery 포트·유스케이스)는 어떤 composition 도 조립하지
않은 세대라 2026-09-25 에 삭제했다(`docs/capability-status.md` "제거된 코드"). 그 설계에서 가져온
owner/token CAS 는 위 `OutboxStorePort` 의 lease fencing 이다.
---
@@ -542,6 +492,12 @@ application 계층은 락 획득/해제 계약만 알고, 실제 구현은 adapt
---
## Notification R1
R1 오케스트레이션 타입(`dev.caskeleton.application.notification` 직속, production consumer 0건)은
2026-09-25에 삭제했다. canonical은 `..notification.platform..`이다(NOTIF-ADR-005). 직속 패키지에는
단순 알림 포트 `NotificationPort`·`Notification`·`NotificationChannel`만 남았다.
## 알림 포트 (notification)
### NotificationPort
+11 -15
View File
@@ -1,7 +1,6 @@
plugins {
id 'ca.java-library'
id 'java-test-fixtures'
id 'ca.strict-qualification'
}
// Framework-free application use-case contract. Runtime dependencies are project-only;
@@ -10,22 +9,19 @@ plugins {
dependencies {
implementation project(':shared-contract')
// Port contracts (`*Contract`) are abstract JUnit classes that fakes and adapters both extend.
testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api'
testFixturesImplementation 'org.assertj:assertj-core'
}
def messagingApplicationContractQualification = extensions.getByName('strictQualification').register(
'messagingApplicationContractQualificationTest',
sourceSets.test,
[
'dev.caskeleton.application.messaging.contract.IntegrationEventContractContributionTest',
// Half of the root `verifyMessagingContracts`: the integration-event contract, run by name, no skips.
strictTestLanes {
lane('messagingApplicationContractQualificationTest') {
description = 'Runs exact Messaging application contract qualification tests.'
requires 'dev.caskeleton.application.messaging.contract.IntegrationEventContractContributionTest',
'dev.caskeleton.application.messaging.event.IntegrationEventDraftTest',
'dev.caskeleton.application.messaging.event.ValidatedIntegrationEventTest'
],
rootProject.layout.buildDirectory.dir(
'test-results/messaging-evidence/application'),
rootProject.layout.buildDirectory.dir(
'test-results/messaging-evidence-binary/application'),
'Runs exact Messaging application contract qualification tests.'
)
messagingApplicationContractQualification.configure {
dependsOn ':prepareMessagingContractEvidence'
rejectSkipped = true
jvmArgs '-Duser.timezone=UTC'
}
}
+9 -9
View File
@@ -35,7 +35,7 @@ io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,redisPolic
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,redisPolicyContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
javax.inject:javax.inject:1=annotationProcessor,redisPolicyContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
jaxen:jaxen:2.0.6=spotbugs
net.bytebuddy:byte-buddy:1.17.8=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
net.bytebuddy:byte-buddy:1.17.8=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
net.jqwik:jqwik-api:1.9.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath
net.jqwik:jqwik-engine:1.9.1=redisPolicyContractTestRuntimeClasspath
net.jqwik:jqwik-time:1.9.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath
@@ -56,9 +56,9 @@ org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle
org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle
org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle
org.apache.xbean:xbean-reflect:3.7=checkstyle
org.apiguardian:apiguardian-api:1.1.2=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath,testCompileClasspath
org.apiguardian:apiguardian-api:1.1.2=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath
org.assertj:assertj-core:3.27.6=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath
org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath
org.assertj:assertj-core:3.27.7=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle
org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle
org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle
@@ -66,9 +66,9 @@ org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.javassist:javassist:3.28.0-GA=checkstyle
org.jspecify:jspecify:1.0.0=redisPolicyContractTestAnnotationProcessor,redisPolicyContractTestCompileClasspath
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath
org.junit.jupiter:junit-jupiter-api:6.0.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath
org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:6.0.1=redisPolicyContractTestRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:6.0.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath
@@ -76,16 +76,16 @@ org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeCla
org.junit.jupiter:junit-jupiter:6.0.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath
org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:6.0.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath
org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:6.0.1=redisPolicyContractTestRuntimeClasspath
org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.1=redisPolicyContractTestRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath
org.junit:junit-bom:6.0.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath
org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit:junit-bom:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
org.junit:junit-bom:6.1.0=spotbugs
org.mockito:mockito-core:5.20.0=mockitoAgent
org.opentest4j:opentest4j:1.3.0=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
org.opentest4j:opentest4j:1.3.0=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
org.ow2.asm:asm-analysis:9.10.1=spotbugs
org.ow2.asm:asm-commons:9.10.1=spotbugs
org.ow2.asm:asm-tree:9.10.1=spotbugs
@@ -97,4 +97,4 @@ org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.18=checkstyle
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
empty=compileClasspath,runtimeClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath
empty=compileClasspath,runtimeClasspath
@@ -1,457 +0,0 @@
package dev.caskeleton.application.cache;
import java.time.Clock;
import java.time.DateTimeException;
import java.time.Instant;
import java.util.Objects;
/**
* Framework-free cache-aside orchestration with bounded local coalescing and source concurrency.
* Construct one instance per semantic cache region so its policy and protection bounds are shared.
*
* <p>When optional refresh coordination is enabled, the soft-lease owner refreshes synchronously.
* This executor does not schedule an asynchronous stale-while-revalidate task. A valid stale
* contender or a valid stale request facing coordination failure returns immediately instead.
*
* @deprecated the shipped runtime does not compose this executor. The algorithm remains available
* as a verified reference, but callers must not assume template-level production support.
*/
@Deprecated
public final class CacheAsideExecutor<K, V> {
private final CacheAsidePolicy policy;
private final Clock clock;
private final CacheSingleFlight<K, SourceAttempt<V>> singleFlight;
private final CacheSourceBulkhead sourceBulkhead;
private final CacheRefreshCoordinationPort<K> refreshCoordinator;
private final CacheRefreshCoordinationPolicy refreshCoordinationPolicy;
public CacheAsideExecutor(CacheAsidePolicy policy, Clock clock) {
this(policy, clock, null, null);
}
public CacheAsideExecutor(
CacheAsidePolicy policy,
Clock clock,
CacheRefreshCoordinationPort<K> refreshCoordinator,
CacheRefreshCoordinationPolicy refreshCoordinationPolicy) {
this.policy = Objects.requireNonNull(policy, "policy must be non-null");
this.clock = Objects.requireNonNull(clock, "clock must be non-null");
this.refreshCoordinator = refreshCoordinator;
if (refreshCoordinator == null) {
if (refreshCoordinationPolicy != null) {
throw new IllegalArgumentException("refresh coordination policy requires a coordinator");
}
this.refreshCoordinationPolicy = null;
} else {
this.refreshCoordinationPolicy =
Objects.requireNonNull(
refreshCoordinationPolicy, "refreshCoordinationPolicy must be non-null")
.validateAgainst(policy);
}
singleFlight =
new CacheSingleFlight<>(policy.maximumInFlightSourceKeys(), policy.maximumWaitersPerKey());
sourceBulkhead = new CacheSourceBulkhead(policy.maximumConcurrentSourceLoads());
}
public CacheResult<V> getOrLoad(
K key, CacheRegionPort<K, V> region, CacheSourceLoader<K, V> sourceLoader) {
Objects.requireNonNull(key, "key must be non-null");
Objects.requireNonNull(region, "region must be non-null");
Objects.requireNonNull(sourceLoader, "sourceLoader must be non-null");
CacheLookup<V> lookup =
Objects.requireNonNull(region.lookup(key), "cache lookup must be non-null");
StaleCandidate<V> stale = null;
boolean hardMiss = false;
RefillCondition refillCondition = RefillCondition.absent(CacheWriteCondition.unavailable());
if (lookup instanceof CacheLookup.Hit<V> hit) {
if (hit.freshness() == CacheLookup.Freshness.FRESH) {
return new CacheResult.FreshHit<>(hit.value(), hit.sourceRevision());
}
if (!hit.observationToken().usable()) {
return new CacheResult.IncompatibleSchema<>(
CacheLookup.SchemaCategory.UNKNOWN_ENVELOPE, CacheLookup.SchemaPolicy.FAIL_FAST);
}
stale =
new StaleCandidate<>(
hit.value(), hit.sourceRevision(), hit.hardExpiresAt(), hit.observationToken());
refillCondition = RefillCondition.observed(hit.observationToken(), hit.writeCondition());
} else if (lookup instanceof CacheLookup.NegativeHit<V> negative) {
return new CacheResult.NegativeHit<>(negative.reason());
} else if (lookup instanceof CacheLookup.Miss<V> miss) {
refillCondition = RefillCondition.absent(miss.writeCondition());
hardMiss = true;
} else if (lookup instanceof CacheLookup.IncompatibleSchema<V> incompatible) {
if (incompatible.policy() == CacheLookup.SchemaPolicy.FAIL_FAST) {
return new CacheResult.IncompatibleSchema<>(incompatible.category(), incompatible.policy());
}
if (!incompatible.observationToken().usable()) {
return new CacheResult.IncompatibleSchema<>(
incompatible.category(), CacheLookup.SchemaPolicy.FAIL_FAST);
}
refillCondition =
RefillCondition.observed(incompatible.observationToken(), incompatible.writeCondition());
} else if (lookup instanceof CacheLookup.Unavailable<V> unavailable) {
refillCondition = RefillCondition.absent(unavailable.writeCondition());
}
RefillCondition selectedCondition = refillCondition;
StaleCandidate<V> selectedStale = stale;
boolean selectedHardMiss = hardMiss;
CacheSingleFlight.Outcome<SourceAttempt<V>> flight =
singleFlight.execute(
key,
policy.maximumWaitDuration(),
() ->
loadFromSource(
key, region, sourceLoader, selectedCondition, selectedStale, selectedHardMiss));
if (flight instanceof CacheSingleFlight.Rejected<SourceAttempt<V>> rejected) {
return new CacheResult.Rejected<>(
switch (rejected.reason()) {
case MAXIMUM_IN_FLIGHT_KEYS -> CacheResult.RejectionReason.MAXIMUM_IN_FLIGHT_KEYS;
case MAXIMUM_WAITERS -> CacheResult.RejectionReason.MAXIMUM_WAITERS;
case WAIT_TIMEOUT -> CacheResult.RejectionReason.WAIT_TIMEOUT;
});
}
if (flight instanceof CacheSingleFlight.Interrupted<SourceAttempt<V>>) {
return new CacheResult.Cancelled<>();
}
SourceAttempt<V> attempt = ((CacheSingleFlight.Completed<SourceAttempt<V>>) flight).value();
return toResult(attempt, stale);
}
int inFlightWaiterCount(K key) {
return singleFlight.waiterCount(key);
}
private SourceAttempt<V> loadFromSource(
K key,
CacheRegionPort<K, V> region,
CacheSourceLoader<K, V> sourceLoader,
RefillCondition refillCondition,
StaleCandidate<V> stale,
boolean hardMiss) {
CacheSourceBulkhead.Outcome<SourceAttempt<V>> admitted =
sourceBulkhead.execute(
policy.sourceAdmissionWait(),
() -> invokeSource(key, region, sourceLoader, refillCondition, stale, hardMiss));
if (admitted instanceof CacheSourceBulkhead.Rejected<SourceAttempt<V>>) {
return new SourceRejected<>();
}
if (admitted instanceof CacheSourceBulkhead.Interrupted<SourceAttempt<V>>) {
return new SourceInterrupted<>();
}
return ((CacheSourceBulkhead.Completed<SourceAttempt<V>>) admitted).value();
}
private SourceAttempt<V> invokeSource(
K key,
CacheRegionPort<K, V> region,
CacheSourceLoader<K, V> sourceLoader,
RefillCondition refillCondition,
StaleCandidate<V> stale,
boolean hardMiss) {
CacheRefreshClaimAttempt ownedAttempt = null;
RefillCondition selectedCondition = refillCondition;
try {
if (shouldCoordinate(stale, hardMiss)) {
CacheRefreshClaimAttempt attempt =
Objects.requireNonNull(
refreshCoordinator.newAttempt(), "cache refresh claim attempt must be non-null");
CacheRefreshClaimOutcome claim = claimWithOneUncertainRetry(key, attempt);
if (claim instanceof CacheRefreshClaimOutcome.Contended) {
SourceAttempt<V> deferred = staleDeferral(stale, claim);
if (deferred != null) {
return deferred;
}
if (hardMiss
&& refreshCoordinationPolicy.hardMissPolicy()
== CacheRefreshCoordinationPolicy.HardMissPolicy.BOUNDED_WAIT_THEN_SOURCE_LOAD) {
if (!boundedWait(refreshCoordinationPolicy.hardMissWait())) {
return new SourceInterrupted<>();
}
Recheck<V> recheck = recheck(region, key);
if (recheck.immediateResult() != null) {
return new ImmediateResult<>(recheck.immediateResult());
}
selectedCondition = recheck.refillCondition();
}
} else if (claim instanceof CacheRefreshClaimOutcome.Unavailable
|| claim instanceof CacheRefreshClaimOutcome.Indeterminate) {
SourceAttempt<V> deferred = staleDeferral(stale, claim);
if (deferred != null) {
return deferred;
}
} else if (claim instanceof CacheRefreshClaimOutcome.Claimed
|| claim instanceof CacheRefreshClaimOutcome.AlreadyOwned) {
ownedAttempt = attempt;
Recheck<V> recheck = recheck(region, key);
if (recheck.immediateResult() != null) {
return new ImmediateResult<>(recheck.immediateResult());
}
selectedCondition = recheck.refillCondition();
}
}
return invokeSourceDirect(key, region, sourceLoader, selectedCondition);
} finally {
if (ownedAttempt != null) {
Objects.requireNonNull(
refreshCoordinator.release(key, ownedAttempt),
"cache refresh release outcome must be non-null");
}
}
}
private SourceAttempt<V> invokeSourceDirect(
K key,
CacheRegionPort<K, V> region,
CacheSourceLoader<K, V> sourceLoader,
RefillCondition refillCondition) {
Instant deadline;
try {
deadline = clock.instant().plus(policy.sourceLoadDeadline());
} catch (DateTimeException exception) {
throw new IllegalStateException("cache source deadline cannot be represented", exception);
}
CacheCancellationToken cancellation = new CacheCancellationToken(deadline, clock);
if (cancellation.isInterrupted()) {
return new SourceInterrupted<>();
}
SourceLoadOutcome<V> outcome =
Objects.requireNonNull(
sourceLoader.load(key, cancellation), "source loader outcome must be non-null");
if (cancellation.isInterrupted() || outcome instanceof SourceLoadOutcome.Cancelled<V>) {
return new SourceInterrupted<>();
}
if (cancellation.isDeadlineExceeded()) {
return new SourceTimedOut<>();
}
if (outcome instanceof SourceLoadOutcome.Loaded<V> loaded) {
CacheRecordOutcome recorded =
Objects.requireNonNull(
region.record(
key,
loaded.value(),
new CacheRecordMetadata(
loaded.sourceRevision(),
refillCondition.intent(),
refillCondition.observationToken(),
refillCondition.writeCondition())),
"cache record outcome must be non-null");
return new SourceResolved<>(outcome, recorded);
}
if (outcome instanceof SourceLoadOutcome.AuthoritativeAbsent<V> absent) {
CacheRecordOutcome recorded =
Objects.requireNonNull(
region.recordAbsent(
key,
absent.reason(),
new CacheRecordMetadata(
absent.sourceRevision(),
refillCondition.intent(),
refillCondition.observationToken(),
refillCondition.writeCondition())),
"negative cache record outcome must be non-null");
return new SourceResolved<>(outcome, recorded);
}
return new SourceResolved<>(outcome, null);
}
private boolean shouldCoordinate(StaleCandidate<V> stale, boolean hardMiss) {
if (refreshCoordinator == null) {
return false;
}
return stale != null
|| (hardMiss
&& refreshCoordinationPolicy.hardMissPolicy()
== CacheRefreshCoordinationPolicy.HardMissPolicy.BOUNDED_WAIT_THEN_SOURCE_LOAD);
}
private CacheRefreshClaimOutcome claimWithOneUncertainRetry(
K key, CacheRefreshClaimAttempt attempt) {
CacheRefreshClaimOutcome first =
Objects.requireNonNull(
refreshCoordinator.claim(key, attempt, refreshCoordinationPolicy.leaseTimeToLive()),
"cache refresh claim outcome must be non-null");
if (first instanceof CacheRefreshClaimOutcome.Indeterminate) {
return Objects.requireNonNull(
refreshCoordinator.claim(key, attempt, refreshCoordinationPolicy.leaseTimeToLive()),
"cache refresh claim retry outcome must be non-null");
}
return first;
}
private SourceAttempt<V> staleDeferral(StaleCandidate<V> stale, CacheRefreshClaimOutcome claim) {
if (stale != null && clock.instant().isBefore(stale.hardExpiresAt())) {
CacheResult.RefreshDeferralReason reason =
claim instanceof CacheRefreshClaimOutcome.Contended
? CacheResult.RefreshDeferralReason.CONTENDED
: claim instanceof CacheRefreshClaimOutcome.Unavailable
? CacheResult.RefreshDeferralReason.COORDINATION_UNAVAILABLE
: CacheResult.RefreshDeferralReason.COORDINATION_INDETERMINATE;
return new ImmediateResult<>(
new CacheResult.StaleRefreshDeferred<>(stale.value(), stale.sourceRevision(), reason));
}
return null;
}
private boolean boundedWait(java.time.Duration duration) {
try {
long milliseconds = duration.toMillis();
int nanoseconds = (int) duration.minusMillis(milliseconds).toNanos();
Thread.sleep(milliseconds, nanoseconds);
return true;
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
return false;
}
}
private Recheck<V> recheck(CacheRegionPort<K, V> region, K key) {
CacheLookup<V> lookup =
Objects.requireNonNull(region.lookup(key), "cache recheck must be non-null");
if (lookup instanceof CacheLookup.Hit<V> hit) {
if (hit.freshness() == CacheLookup.Freshness.FRESH) {
return Recheck.immediate(new CacheResult.FreshHit<>(hit.value(), hit.sourceRevision()));
}
if (!hit.observationToken().usable()) {
return Recheck.immediate(
new CacheResult.IncompatibleSchema<>(
CacheLookup.SchemaCategory.UNKNOWN_ENVELOPE, CacheLookup.SchemaPolicy.FAIL_FAST));
}
return Recheck.refill(RefillCondition.observed(hit.observationToken(), hit.writeCondition()));
}
if (lookup instanceof CacheLookup.NegativeHit<V> negative) {
return Recheck.immediate(new CacheResult.NegativeHit<>(negative.reason()));
}
if (lookup instanceof CacheLookup.Miss<V> miss) {
return Recheck.refill(RefillCondition.absent(miss.writeCondition()));
}
if (lookup instanceof CacheLookup.IncompatibleSchema<V> incompatible) {
if (incompatible.policy() == CacheLookup.SchemaPolicy.FAIL_FAST
|| !incompatible.observationToken().usable()) {
return Recheck.immediate(
new CacheResult.IncompatibleSchema<>(
incompatible.category(), CacheLookup.SchemaPolicy.FAIL_FAST));
}
return Recheck.refill(
RefillCondition.observed(incompatible.observationToken(), incompatible.writeCondition()));
}
CacheLookup.Unavailable<V> unavailable = (CacheLookup.Unavailable<V>) lookup;
return Recheck.refill(RefillCondition.absent(unavailable.writeCondition()));
}
private CacheResult<V> toResult(SourceAttempt<V> attempt, StaleCandidate<V> stale) {
if (attempt instanceof ImmediateResult<V> immediate) {
return immediate.result();
}
if (attempt instanceof SourceRejected<V>) {
return new CacheResult.Rejected<>(CacheResult.RejectionReason.SOURCE_OVERLOADED);
}
if (attempt instanceof SourceTimedOut<V>) {
return new CacheResult.Rejected<>(CacheResult.RejectionReason.LOAD_TIMEOUT);
}
if (attempt instanceof SourceInterrupted<V>) {
return new CacheResult.Cancelled<>();
}
SourceResolved<V> resolved = (SourceResolved<V>) attempt;
SourceLoadOutcome<V> outcome = resolved.outcome();
if (outcome instanceof SourceLoadOutcome.Loaded<V> loaded) {
return new CacheResult.LoadedFromSource<>(
loaded.value(), loaded.sourceRevision(), resolved.recordOutcome());
}
if (outcome instanceof SourceLoadOutcome.AuthoritativeAbsent<V> absent) {
return new CacheResult.AuthoritativeAbsent<>(
absent.reason(), absent.sourceRevision(), resolved.recordOutcome());
}
if (outcome instanceof SourceLoadOutcome.TransientFailure<V> transientFailure) {
if (stale != null
&& policy.serveStaleOnTransientFailure()
&& clock.instant().isBefore(stale.hardExpiresAt())) {
return new CacheResult.StaleFallbackAfterTransientFailure<>(
stale.value(), stale.sourceRevision(), transientFailure.failure());
}
return new CacheResult.SourceFailed<>(
transientFailure.failure(), CacheResult.SourceFailureKind.TRANSIENT);
}
if (outcome instanceof SourceLoadOutcome.PermanentFailure<V> permanentFailure) {
return new CacheResult.SourceFailed<>(
permanentFailure.failure(), CacheResult.SourceFailureKind.PERMANENT);
}
return new CacheResult.Cancelled<>();
}
private sealed interface SourceAttempt<T>
permits SourceResolved, SourceRejected, SourceInterrupted, SourceTimedOut, ImmediateResult {}
private record SourceResolved<T>(SourceLoadOutcome<T> outcome, CacheRecordOutcome recordOutcome)
implements SourceAttempt<T> {
private SourceResolved {
Objects.requireNonNull(outcome, "outcome must be non-null");
}
}
private record SourceRejected<T>() implements SourceAttempt<T> {}
private record SourceInterrupted<T>() implements SourceAttempt<T> {}
private record SourceTimedOut<T>() implements SourceAttempt<T> {}
private record ImmediateResult<T>(CacheResult<T> result) implements SourceAttempt<T> {
private ImmediateResult {
Objects.requireNonNull(result, "result must be non-null");
}
}
private record StaleCandidate<T>(
T value,
String sourceRevision,
Instant hardExpiresAt,
CacheObservationToken observationToken) {
private StaleCandidate {
Objects.requireNonNull(value, "value must be non-null");
Objects.requireNonNull(sourceRevision, "sourceRevision must be non-null");
Objects.requireNonNull(hardExpiresAt, "hardExpiresAt must be non-null");
Objects.requireNonNull(observationToken, "observationToken must be non-null");
}
}
private record RefillCondition(
CacheRecordIntent intent,
CacheObservationToken observationToken,
CacheWriteCondition writeCondition) {
private RefillCondition {
Objects.requireNonNull(intent, "intent must be non-null");
Objects.requireNonNull(observationToken, "observationToken must be non-null");
Objects.requireNonNull(writeCondition, "writeCondition must be non-null");
}
private static RefillCondition absent(CacheWriteCondition writeCondition) {
return new RefillCondition(
CacheRecordIntent.ONLY_IF_ABSENT, CacheObservationToken.unavailable(), writeCondition);
}
private static RefillCondition observed(
CacheObservationToken token, CacheWriteCondition writeCondition) {
return new RefillCondition(CacheRecordIntent.ONLY_IF_OBSERVED, token, writeCondition);
}
}
private record Recheck<T>(RefillCondition refillCondition, CacheResult<T> immediateResult) {
private static <T> Recheck<T> refill(RefillCondition refillCondition) {
return new Recheck<>(
Objects.requireNonNull(refillCondition, "refillCondition must be non-null"), null);
}
private static <T> Recheck<T> immediate(CacheResult<T> result) {
return new Recheck<>(null, Objects.requireNonNull(result, "result must be non-null"));
}
}
}
@@ -1,54 +0,0 @@
package dev.caskeleton.application.cache;
import java.time.Duration;
import java.util.Objects;
/** Immutable per-region bounds for cache-aside fallback and local coalescing. */
public record CacheAsidePolicy(
int maximumInFlightSourceKeys,
int maximumWaitersPerKey,
int maximumConcurrentSourceLoads,
Duration sourceAdmissionWait,
Duration sourceLoadDeadline,
boolean serveStaleOnTransientFailure) {
private static final int MAXIMUM_COUNT_BOUND = 4096;
private static final Duration MAXIMUM_DURATION_BOUND = Duration.ofDays(30);
public CacheAsidePolicy {
requirePositiveBound(
maximumInFlightSourceKeys, "maximumInFlightSourceKeys", MAXIMUM_COUNT_BOUND);
if (maximumWaitersPerKey < 0 || maximumWaitersPerKey > MAXIMUM_COUNT_BOUND) {
throw new IllegalArgumentException(
"maximumWaitersPerKey must be in 0.." + MAXIMUM_COUNT_BOUND);
}
requirePositiveBound(
maximumConcurrentSourceLoads, "maximumConcurrentSourceLoads", MAXIMUM_COUNT_BOUND);
requireDuration(sourceAdmissionWait, "sourceAdmissionWait", true);
requireDuration(sourceLoadDeadline, "sourceLoadDeadline", false);
}
Duration maximumWaitDuration() {
return sourceAdmissionWait.plus(sourceLoadDeadline);
}
private static void requirePositiveBound(int value, String field, int maximum) {
if (value < 1 || value > maximum) {
throw new IllegalArgumentException(field + " must be in 1.." + maximum);
}
}
private static void requireDuration(Duration value, String field, boolean zeroAllowed) {
Objects.requireNonNull(value, field + " must be non-null");
if (value.isNegative()
|| (!zeroAllowed && value.isZero())
|| value.compareTo(MAXIMUM_DURATION_BOUND) > 0) {
throw new IllegalArgumentException(
field
+ " must be "
+ (zeroAllowed ? "non-negative" : "positive")
+ " and at most "
+ MAXIMUM_DURATION_BOUND);
}
}
}
@@ -1,36 +0,0 @@
package dev.caskeleton.application.cache;
import java.time.Clock;
import java.time.Instant;
import java.util.Objects;
/**
* Cooperative source-load cancellation signal. It observes the executing thread's interrupt flag
* and an immutable deadline; it cannot forcibly stop arbitrary source code.
*/
public final class CacheCancellationToken {
private final Instant deadline;
private final Clock clock;
CacheCancellationToken(Instant deadline, Clock clock) {
this.deadline = Objects.requireNonNull(deadline, "deadline must be non-null");
this.clock = Objects.requireNonNull(clock, "clock must be non-null");
}
public Instant deadline() {
return deadline;
}
public boolean isDeadlineExceeded() {
return !clock.instant().isBefore(deadline);
}
public boolean isInterrupted() {
return Thread.currentThread().isInterrupted();
}
public boolean isCancellationRequested() {
return isInterrupted() || isDeadlineExceeded();
}
}
@@ -1,97 +0,0 @@
package dev.caskeleton.application.cache;
import java.time.Duration;
import java.util.Objects;
/**
* Framework-free, cache-only diagnostic events.
*
* <p>Events intentionally omit semantic keys, tenant/user identifiers and provider endpoints.
* {@code cacheName} is a bounded code-owned name suitable for a low-cardinality metric tag.
*/
public sealed interface CacheObservationEvent {
String cacheName();
/** One lookup at a concrete cache tier. */
record Lookup(String cacheName, Tier tier, LookupResult result, Duration entryAge)
implements CacheObservationEvent {
public Lookup {
cacheName = boundedCacheName(cacheName);
Objects.requireNonNull(tier, "tier must be non-null");
Objects.requireNonNull(result, "result must be non-null");
Objects.requireNonNull(entryAge, "entryAge must be non-null");
if (entryAge.isNegative() || entryAge.compareTo(Duration.ofDays(30)) > 0) {
throw new IllegalArgumentException("entryAge must be between zero and 30 days");
}
}
}
/** A bounded local-tier eviction, flush, subscriber or generation reconciliation action. */
record LocalMaintenance(
String cacheName,
MaintenanceAction action,
MaintenanceResult result,
MaintenanceCause cause,
int affectedEntries)
implements CacheObservationEvent {
public LocalMaintenance {
cacheName = boundedCacheName(cacheName);
Objects.requireNonNull(action, "action must be non-null");
Objects.requireNonNull(result, "result must be non-null");
Objects.requireNonNull(cause, "cause must be non-null");
if (affectedEntries < 0 || affectedEntries > 1_000_000) {
throw new IllegalArgumentException("affectedEntries must be in 0..1000000");
}
}
}
enum Tier {
LOCAL_L1,
REDIS_L2
}
enum LookupResult {
HIT,
MISS,
ERROR,
BYPASS
}
enum MaintenanceAction {
EVICT,
FLUSH,
RECONCILE,
SUBSCRIBER_EVENT
}
enum MaintenanceResult {
SUCCESS,
FLUSHED,
DROPPED,
ERROR,
UNCHANGED
}
enum MaintenanceCause {
CARDINALITY,
WEIGHT,
TTL,
INVALIDATION,
GENERATION_CHANGED,
SUBSCRIBER_DISCONNECTED,
SUBSCRIBER_OVERFLOW,
MALFORMED_MESSAGE,
RECONCILIATION_FAILURE
}
private static String boundedCacheName(String value) {
if (value == null || !value.matches("[a-z][a-z0-9-]{0,62}")) {
throw new IllegalArgumentException(
"cacheName must be a code-owned lower-case slug with 1..63 characters");
}
return value;
}
}
@@ -1,8 +0,0 @@
package dev.caskeleton.application.cache;
/** Framework-free output boundary for low-cardinality cache diagnostics. */
@FunctionalInterface
public interface CacheObservationPort {
void observe(CacheObservationEvent event);
}
@@ -1,35 +0,0 @@
package dev.caskeleton.application.cache;
import java.util.Objects;
/** Owner plus operation identities that must be reused for an uncertain claim retry. */
public record CacheRefreshClaimAttempt(
CacheRefreshOwnerToken ownerToken, CacheRefreshOperationToken operationToken) {
private static final CacheRefreshClaimAttempt UNAVAILABLE =
new CacheRefreshClaimAttempt(
CacheRefreshOwnerToken.unavailable(), CacheRefreshOperationToken.unavailable());
public CacheRefreshClaimAttempt {
Objects.requireNonNull(ownerToken, "ownerToken must be non-null");
Objects.requireNonNull(operationToken, "operationToken must be non-null");
if (ownerToken.usable() != operationToken.usable()) {
throw new IllegalArgumentException("refresh claim attempt tokens must have equal usability");
}
}
public static CacheRefreshClaimAttempt unavailable() {
return UNAVAILABLE;
}
public boolean usable() {
return ownerToken.usable();
}
@Override
public String toString() {
return usable()
? "CacheRefreshClaimAttempt[redacted]"
: "CacheRefreshClaimAttempt[unavailable]";
}
}
@@ -1,42 +0,0 @@
package dev.caskeleton.application.cache;
import java.util.Objects;
/** Provider-neutral result of attempting to own a cache-refresh soft lease. */
public sealed interface CacheRefreshClaimOutcome
permits CacheRefreshClaimOutcome.Claimed,
CacheRefreshClaimOutcome.AlreadyOwned,
CacheRefreshClaimOutcome.Contended,
CacheRefreshClaimOutcome.Disabled,
CacheRefreshClaimOutcome.Unavailable,
CacheRefreshClaimOutcome.Indeterminate {
record Claimed(CacheRefreshClaimAttempt attempt) implements CacheRefreshClaimOutcome {
public Claimed {
requireUsable(attempt);
}
}
record AlreadyOwned(CacheRefreshClaimAttempt attempt) implements CacheRefreshClaimOutcome {
public AlreadyOwned {
requireUsable(attempt);
}
}
record Contended() implements CacheRefreshClaimOutcome {}
record Disabled() implements CacheRefreshClaimOutcome {}
record Unavailable() implements CacheRefreshClaimOutcome {}
record Indeterminate() implements CacheRefreshClaimOutcome {}
private static void requireUsable(CacheRefreshClaimAttempt attempt) {
Objects.requireNonNull(attempt, "attempt must be non-null");
if (!attempt.usable()) {
throw new IllegalArgumentException("owned refresh claim requires a usable attempt");
}
}
}
@@ -1,47 +0,0 @@
package dev.caskeleton.application.cache;
import java.time.Duration;
import java.util.Objects;
/** Finite soft-lease and hard-miss behavior for optional distributed refresh coordination. */
public record CacheRefreshCoordinationPolicy(
Duration leaseTimeToLive, HardMissPolicy hardMissPolicy, Duration hardMissWait) {
private static final Duration MAXIMUM_LEASE = Duration.ofMinutes(5);
private static final Duration MAXIMUM_HARD_MISS_WAIT = Duration.ofSeconds(5);
public CacheRefreshCoordinationPolicy {
Objects.requireNonNull(leaseTimeToLive, "leaseTimeToLive must be non-null");
Objects.requireNonNull(hardMissPolicy, "hardMissPolicy must be non-null");
Objects.requireNonNull(hardMissWait, "hardMissWait must be non-null");
if (leaseTimeToLive.isZero()
|| leaseTimeToLive.isNegative()
|| leaseTimeToLive.compareTo(MAXIMUM_LEASE) > 0) {
throw new IllegalArgumentException(
"refresh lease TTL must be positive and at most 5 minutes");
}
if (hardMissWait.isNegative() || hardMissWait.compareTo(MAXIMUM_HARD_MISS_WAIT) > 0) {
throw new IllegalArgumentException("hard miss wait must be between zero and 5 seconds");
}
if (hardMissPolicy == HardMissPolicy.NORMAL_SOURCE_LOAD && !hardMissWait.isZero()) {
throw new IllegalArgumentException("normal hard miss source load requires zero wait");
}
if (hardMissPolicy == HardMissPolicy.BOUNDED_WAIT_THEN_SOURCE_LOAD && hardMissWait.isZero()) {
throw new IllegalArgumentException("bounded hard miss wait must be positive");
}
}
public CacheRefreshCoordinationPolicy validateAgainst(CacheAsidePolicy cacheAsidePolicy) {
Objects.requireNonNull(cacheAsidePolicy, "cacheAsidePolicy must be non-null");
if (leaseTimeToLive.compareTo(cacheAsidePolicy.sourceLoadDeadline()) <= 0) {
throw new IllegalArgumentException(
"refresh lease TTL must be longer than the source load deadline");
}
return this;
}
public enum HardMissPolicy {
NORMAL_SOURCE_LOAD,
BOUNDED_WAIT_THEN_SOURCE_LOAD
}
}
@@ -1,20 +0,0 @@
package dev.caskeleton.application.cache;
import java.time.Duration;
/**
* Optional soft-lease coordination for cache refresh admission.
*
* <p>This port reduces duplicate refresh work. It is not a correctness lock and must not protect
* domain invariants. The claim owner performs its source refresh synchronously; only a stale
* contender or a stale request facing coordination failure returns immediately with a deferral
* result.
*/
public interface CacheRefreshCoordinationPort<K> {
CacheRefreshClaimAttempt newAttempt();
CacheRefreshClaimOutcome claim(K key, CacheRefreshClaimAttempt attempt, Duration leaseTimeToLive);
CacheRefreshReleaseOutcome release(K key, CacheRefreshClaimAttempt attempt);
}
@@ -1,62 +0,0 @@
package dev.caskeleton.application.cache;
import java.util.Objects;
/** Opaque idempotency identity reused when a refresh-claim response is uncertain. */
public final class CacheRefreshOperationToken {
private static final CacheRefreshOperationToken UNAVAILABLE = new CacheRefreshOperationToken();
private final String value;
public CacheRefreshOperationToken(String value) {
this.value = validate(value);
}
private CacheRefreshOperationToken() {
value = null;
}
public static CacheRefreshOperationToken unavailable() {
return UNAVAILABLE;
}
public boolean usable() {
return value != null;
}
public String value() {
if (!usable()) {
throw new IllegalStateException("cache refresh operation token is unavailable");
}
return value;
}
@Override
public boolean equals(Object candidate) {
return candidate instanceof CacheRefreshOperationToken other
&& Objects.equals(value, other.value);
}
@Override
public int hashCode() {
return Objects.hashCode(value);
}
@Override
public String toString() {
return usable()
? "CacheRefreshOperationToken[redacted]"
: "CacheRefreshOperationToken[unavailable]";
}
private static String validate(String value) {
if (value == null
|| !value.matches("[A-Za-z0-9_-]{16,128}")
|| value.codePoints().anyMatch(Character::isISOControl)) {
throw new IllegalArgumentException(
"operation token must contain 16..128 URL-safe non-control characters");
}
return value;
}
}
@@ -1,59 +0,0 @@
package dev.caskeleton.application.cache;
import java.util.Objects;
/** Opaque owner identity for one bounded cache-refresh soft lease. */
public final class CacheRefreshOwnerToken {
private static final CacheRefreshOwnerToken UNAVAILABLE = new CacheRefreshOwnerToken();
private final String value;
public CacheRefreshOwnerToken(String value) {
this.value = validate(value, "owner token");
}
private CacheRefreshOwnerToken() {
value = null;
}
public static CacheRefreshOwnerToken unavailable() {
return UNAVAILABLE;
}
public boolean usable() {
return value != null;
}
public String value() {
if (!usable()) {
throw new IllegalStateException("cache refresh owner token is unavailable");
}
return value;
}
@Override
public boolean equals(Object candidate) {
return candidate instanceof CacheRefreshOwnerToken other && Objects.equals(value, other.value);
}
@Override
public int hashCode() {
return Objects.hashCode(value);
}
@Override
public String toString() {
return usable() ? "CacheRefreshOwnerToken[redacted]" : "CacheRefreshOwnerToken[unavailable]";
}
private static String validate(String value, String field) {
if (value == null
|| !value.matches("[A-Za-z0-9_-]{16,128}")
|| value.codePoints().anyMatch(Character::isISOControl)) {
throw new IllegalArgumentException(
field + " must contain 16..128 URL-safe non-control characters");
}
return value;
}
}
@@ -1,23 +0,0 @@
package dev.caskeleton.application.cache;
/** Provider-neutral owner-safe release result for a cache-refresh soft lease. */
public sealed interface CacheRefreshReleaseOutcome
permits CacheRefreshReleaseOutcome.Released,
CacheRefreshReleaseOutcome.AlreadyReleased,
CacheRefreshReleaseOutcome.NotOwner,
CacheRefreshReleaseOutcome.Disabled,
CacheRefreshReleaseOutcome.Unavailable,
CacheRefreshReleaseOutcome.Indeterminate {
record Released() implements CacheRefreshReleaseOutcome {}
record AlreadyReleased() implements CacheRefreshReleaseOutcome {}
record NotOwner() implements CacheRefreshReleaseOutcome {}
record Disabled() implements CacheRefreshReleaseOutcome {}
record Unavailable() implements CacheRefreshReleaseOutcome {}
record Indeterminate() implements CacheRefreshReleaseOutcome {}
}
@@ -1,131 +0,0 @@
package dev.caskeleton.application.cache;
import java.util.Objects;
/** End-to-end cache-aside result without provider or transport types. */
public sealed interface CacheResult<V>
permits CacheResult.FreshHit,
CacheResult.NegativeHit,
CacheResult.LoadedFromSource,
CacheResult.AuthoritativeAbsent,
CacheResult.StaleFallbackAfterTransientFailure,
CacheResult.StaleRefreshDeferred,
CacheResult.SourceFailed,
CacheResult.Rejected,
CacheResult.Cancelled,
CacheResult.IncompatibleSchema {
record FreshHit<V>(V value, String sourceRevision) implements CacheResult<V> {
public FreshHit {
Objects.requireNonNull(value, "value must be non-null");
requireSourceRevision(sourceRevision);
}
}
record NegativeHit<V>(dev.caskeleton.application.cache.AuthoritativeAbsence reason)
implements CacheResult<V> {
public NegativeHit {
Objects.requireNonNull(reason, "reason must be non-null");
}
}
record LoadedFromSource<V>(V value, String sourceRevision, CacheRecordOutcome recordOutcome)
implements CacheResult<V> {
public LoadedFromSource {
Objects.requireNonNull(value, "value must be non-null");
requireSourceRevision(sourceRevision);
Objects.requireNonNull(recordOutcome, "recordOutcome must be non-null");
}
}
record AuthoritativeAbsent<V>(
dev.caskeleton.application.cache.AuthoritativeAbsence reason,
String sourceRevision,
CacheRecordOutcome recordOutcome)
implements CacheResult<V> {
public AuthoritativeAbsent {
Objects.requireNonNull(reason, "reason must be non-null");
requireSourceRevision(sourceRevision);
Objects.requireNonNull(recordOutcome, "recordOutcome must be non-null");
}
}
record StaleFallbackAfterTransientFailure<V>(
V value, String sourceRevision, SourceFailure failure) implements CacheResult<V> {
public StaleFallbackAfterTransientFailure {
Objects.requireNonNull(value, "value must be non-null");
requireSourceRevision(sourceRevision);
Objects.requireNonNull(failure, "failure must be non-null");
}
}
record StaleRefreshDeferred<V>(V value, String sourceRevision, RefreshDeferralReason reason)
implements CacheResult<V> {
public StaleRefreshDeferred {
Objects.requireNonNull(value, "value must be non-null");
requireSourceRevision(sourceRevision);
Objects.requireNonNull(reason, "reason must be non-null");
}
}
record SourceFailed<V>(SourceFailure failure, SourceFailureKind kind) implements CacheResult<V> {
public SourceFailed {
Objects.requireNonNull(failure, "failure must be non-null");
Objects.requireNonNull(kind, "kind must be non-null");
}
}
record Rejected<V>(RejectionReason reason) implements CacheResult<V> {
public Rejected {
Objects.requireNonNull(reason, "reason must be non-null");
}
}
record Cancelled<V>() implements CacheResult<V> {}
record IncompatibleSchema<V>(CacheLookup.SchemaCategory category, CacheLookup.SchemaPolicy policy)
implements CacheResult<V> {
public IncompatibleSchema {
Objects.requireNonNull(category, "category must be non-null");
Objects.requireNonNull(policy, "policy must be non-null");
}
}
enum SourceFailureKind {
TRANSIENT,
PERMANENT
}
enum RejectionReason {
MAXIMUM_IN_FLIGHT_KEYS,
MAXIMUM_WAITERS,
SOURCE_OVERLOADED,
WAIT_TIMEOUT,
LOAD_TIMEOUT
}
enum RefreshDeferralReason {
CONTENDED,
COORDINATION_UNAVAILABLE,
COORDINATION_INDETERMINATE
}
private static void requireSourceRevision(String sourceRevision) {
if (sourceRevision == null
|| sourceRevision.isBlank()
|| sourceRevision.length() > 128
|| sourceRevision.codePoints().anyMatch(Character::isISOControl)) {
throw new IllegalArgumentException(
"sourceRevision must contain 1..128 non-control characters");
}
}
}
@@ -1,210 +0,0 @@
package dev.caskeleton.application.cache;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
/** Bounded, synchronous local coalescing for one semantic cache region. */
public final class CacheSingleFlight<K, V> {
private static final int MAXIMUM_BOUND = 4096;
private final int maximumInFlightKeys;
private final int maximumWaitersPerKey;
private final LongSupplier monotonicTicker;
private final Map<K, Flight<V>> flights = new HashMap<>();
public CacheSingleFlight(int maximumInFlightKeys, int maximumWaitersPerKey) {
this(maximumInFlightKeys, maximumWaitersPerKey, System::nanoTime);
}
CacheSingleFlight(
int maximumInFlightKeys, int maximumWaitersPerKey, LongSupplier monotonicTicker) {
if (maximumInFlightKeys < 1 || maximumInFlightKeys > MAXIMUM_BOUND) {
throw new IllegalArgumentException("maximumInFlightKeys must be in 1.." + MAXIMUM_BOUND);
}
if (maximumWaitersPerKey < 0 || maximumWaitersPerKey > MAXIMUM_BOUND) {
throw new IllegalArgumentException("maximumWaitersPerKey must be in 0.." + MAXIMUM_BOUND);
}
this.maximumInFlightKeys = maximumInFlightKeys;
this.maximumWaitersPerKey = maximumWaitersPerKey;
this.monotonicTicker =
Objects.requireNonNull(monotonicTicker, "monotonicTicker must be non-null");
}
public Outcome<V> execute(K key, Duration waiterTimeout, Supplier<V> leaderAction) {
Objects.requireNonNull(key, "key must be non-null");
Objects.requireNonNull(waiterTimeout, "waiterTimeout must be non-null");
Objects.requireNonNull(leaderAction, "leaderAction must be non-null");
if (waiterTimeout.isNegative()) {
throw new IllegalArgumentException("waiterTimeout must be non-negative");
}
Flight<V> flight;
boolean leader;
synchronized (flights) {
long monotonicNow = monotonicTicker.getAsLong();
flight = flights.get(key);
if (flight != null && flight.isAbandonedAt(monotonicNow)) {
flights.remove(key, flight);
flight = null;
}
if (flight == null) {
if (flights.size() >= maximumInFlightKeys) {
flights.values().removeIf(candidate -> candidate.isAbandonedAt(monotonicNow));
if (flights.size() >= maximumInFlightKeys) {
return new Rejected<>(RejectionReason.MAXIMUM_IN_FLIGHT_KEYS);
}
}
flight = new Flight<>(deadlineFrom(monotonicNow, waiterTimeout));
flights.put(key, flight);
leader = true;
} else {
leader = false;
}
}
if (!leader) {
return await(flight, waiterTimeout);
}
try {
V value = Objects.requireNonNull(leaderAction.get(), "leader result must be non-null");
flight.result.complete(value);
return new Completed<>(value);
} catch (RuntimeException | Error failure) {
flight.result.completeExceptionally(failure);
throw failure;
} finally {
synchronized (flights) {
flights.remove(key, flight);
}
}
}
int inFlightCount() {
synchronized (flights) {
return flights.size();
}
}
int waiterCount(K key) {
synchronized (flights) {
Flight<V> flight = flights.get(key);
return flight == null ? 0 : flight.waiters.get();
}
}
private Outcome<V> await(Flight<V> flight, Duration waiterTimeout) {
if (Thread.currentThread().isInterrupted()) {
return new Interrupted<>();
}
if (!acquireWaiter(flight)) {
return new Rejected<>(RejectionReason.MAXIMUM_WAITERS);
}
try {
return new Completed<>(
flight.result.get(toNanosSaturated(waiterTimeout), TimeUnit.NANOSECONDS));
} catch (TimeoutException timeout) {
return new Rejected<>(RejectionReason.WAIT_TIMEOUT);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
return new Interrupted<>();
} catch (ExecutionException execution) {
return rethrow(execution.getCause());
} finally {
flight.waiters.decrementAndGet();
}
}
private boolean acquireWaiter(Flight<V> flight) {
while (true) {
int current = flight.waiters.get();
if (current >= maximumWaitersPerKey) {
return false;
}
if (flight.waiters.compareAndSet(current, current + 1)) {
return true;
}
}
}
private static long toNanosSaturated(Duration duration) {
try {
return duration.toNanos();
} catch (ArithmeticException overflow) {
return Long.MAX_VALUE;
}
}
private static long deadlineFrom(long monotonicNow, Duration timeout) {
long timeoutNanos = toNanosSaturated(timeout);
if (timeoutNanos == Long.MAX_VALUE) {
return Long.MAX_VALUE;
}
try {
return Math.addExact(monotonicNow, timeoutNanos);
} catch (ArithmeticException overflow) {
return Long.MAX_VALUE;
}
}
private static <T> Outcome<T> rethrow(Throwable cause) {
if (cause instanceof RuntimeException runtime) {
throw runtime;
}
if (cause instanceof Error error) {
throw error;
}
throw new IllegalStateException(
"single-flight completed with an unexpected checked failure", cause);
}
public sealed interface Outcome<T> permits Completed, Rejected, Interrupted {}
public record Completed<T>(T value) implements Outcome<T> {
public Completed {
Objects.requireNonNull(value, "value must be non-null");
}
}
public record Rejected<T>(RejectionReason reason) implements Outcome<T> {
public Rejected {
Objects.requireNonNull(reason, "reason must be non-null");
}
}
public record Interrupted<T>() implements Outcome<T> {}
public enum RejectionReason {
MAXIMUM_IN_FLIGHT_KEYS,
MAXIMUM_WAITERS,
WAIT_TIMEOUT
}
private static final class Flight<T> {
private final CompletableFuture<T> result = new CompletableFuture<>();
private final AtomicInteger waiters = new AtomicInteger();
private final long abandonAtNanos;
private Flight(long abandonAtNanos) {
this.abandonAtNanos = abandonAtNanos;
}
private boolean isAbandonedAt(long monotonicNow) {
return abandonAtNanos != Long.MAX_VALUE
&& monotonicNow - abandonAtNanos >= 0
&& !result.isDone();
}
}
}
@@ -1,69 +0,0 @@
package dev.caskeleton.application.cache;
import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
/** Bounded source concurrency admission shared by every key in one semantic cache region. */
public final class CacheSourceBulkhead {
private final Semaphore permits;
public CacheSourceBulkhead(int maximumConcurrentLoads) {
if (maximumConcurrentLoads < 1) {
throw new IllegalArgumentException("maximumConcurrentLoads must be positive");
}
permits = new Semaphore(maximumConcurrentLoads, true);
}
public <T> Outcome<T> execute(Duration admissionWait, Supplier<T> action) {
Objects.requireNonNull(admissionWait, "admissionWait must be non-null");
Objects.requireNonNull(action, "action must be non-null");
if (admissionWait.isNegative()) {
throw new IllegalArgumentException("admissionWait must be non-negative");
}
if (Thread.currentThread().isInterrupted()) {
return new Interrupted<>();
}
boolean acquired;
try {
acquired = permits.tryAcquire(toNanosSaturated(admissionWait), TimeUnit.NANOSECONDS);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
return new Interrupted<>();
}
if (!acquired) {
return new Rejected<>();
}
try {
return new Completed<>(
Objects.requireNonNull(action.get(), "source action result must be non-null"));
} finally {
permits.release();
}
}
private static long toNanosSaturated(Duration duration) {
try {
return duration.toNanos();
} catch (ArithmeticException overflow) {
return Long.MAX_VALUE;
}
}
public sealed interface Outcome<T> permits Completed, Rejected, Interrupted {}
public record Completed<T>(T value) implements Outcome<T> {
public Completed {
Objects.requireNonNull(value, "value must be non-null");
}
}
public record Rejected<T>() implements Outcome<T> {}
public record Interrupted<T>() implements Outcome<T> {}
}
@@ -1,8 +0,0 @@
package dev.caskeleton.application.cache;
/** Loads one semantic cache key from its authoritative source. */
@FunctionalInterface
public interface CacheSourceLoader<K, V> {
SourceLoadOutcome<V> load(K key, CacheCancellationToken cancellation);
}
@@ -1,18 +0,0 @@
package dev.caskeleton.application.cache;
/** Explicit no-op cache diagnostics adapter used when no metrics backend is installed. */
public final class DisabledCacheObservationPort implements CacheObservationPort {
private static final DisabledCacheObservationPort INSTANCE = new DisabledCacheObservationPort();
private DisabledCacheObservationPort() {}
public static DisabledCacheObservationPort instance() {
return INSTANCE;
}
@Override
public void observe(CacheObservationEvent event) {
// Diagnostics must never change cache semantics.
}
}
@@ -1,34 +0,0 @@
package dev.caskeleton.application.cache;
import java.time.Duration;
/** Explicit no-op refresh coordinator for deployments that disable distributed soft leases. */
public final class DisabledCacheRefreshCoordinationPort<K>
implements CacheRefreshCoordinationPort<K> {
private static final DisabledCacheRefreshCoordinationPort<?> INSTANCE =
new DisabledCacheRefreshCoordinationPort<>();
private DisabledCacheRefreshCoordinationPort() {}
@SuppressWarnings("unchecked")
public static <K> DisabledCacheRefreshCoordinationPort<K> instance() {
return (DisabledCacheRefreshCoordinationPort<K>) INSTANCE;
}
@Override
public CacheRefreshClaimAttempt newAttempt() {
return CacheRefreshClaimAttempt.unavailable();
}
@Override
public CacheRefreshClaimOutcome claim(
K key, CacheRefreshClaimAttempt attempt, Duration leaseTimeToLive) {
return new CacheRefreshClaimOutcome.Disabled();
}
@Override
public CacheRefreshReleaseOutcome release(K key, CacheRefreshClaimAttempt attempt) {
return new CacheRefreshReleaseOutcome.Disabled();
}
}
@@ -1,22 +0,0 @@
package dev.caskeleton.application.cache;
import java.util.Objects;
/**
* Bounded source failure classification with its original cause preserved for the application
* boundary. The cause message must not be copied into cache state, metrics, or tags.
*/
public record SourceFailure(String code, Throwable cause) {
public SourceFailure {
if (code == null || !code.matches("[A-Z][A-Z0-9_]{0,63}")) {
throw new IllegalArgumentException("code must be a bounded uppercase failure code");
}
Objects.requireNonNull(cause, "cause must be non-null");
}
@Override
public String toString() {
return "SourceFailure[code=" + code + ']';
}
}
@@ -1,56 +0,0 @@
package dev.caskeleton.application.cache;
import java.util.Objects;
/** Business-classified result of consulting a cache region's authoritative source. */
public sealed interface SourceLoadOutcome<V>
permits SourceLoadOutcome.Loaded,
SourceLoadOutcome.AuthoritativeAbsent,
SourceLoadOutcome.TransientFailure,
SourceLoadOutcome.PermanentFailure,
SourceLoadOutcome.Cancelled {
record Loaded<V>(V value, String sourceRevision) implements SourceLoadOutcome<V> {
public Loaded {
Objects.requireNonNull(value, "value must be non-null");
requireSourceRevision(sourceRevision);
}
}
record AuthoritativeAbsent<V>(
dev.caskeleton.application.cache.AuthoritativeAbsence reason, String sourceRevision)
implements SourceLoadOutcome<V> {
public AuthoritativeAbsent {
Objects.requireNonNull(reason, "reason must be non-null");
requireSourceRevision(sourceRevision);
}
}
record TransientFailure<V>(SourceFailure failure) implements SourceLoadOutcome<V> {
public TransientFailure {
Objects.requireNonNull(failure, "failure must be non-null");
}
}
record PermanentFailure<V>(SourceFailure failure) implements SourceLoadOutcome<V> {
public PermanentFailure {
Objects.requireNonNull(failure, "failure must be non-null");
}
}
record Cancelled<V>() implements SourceLoadOutcome<V> {}
private static void requireSourceRevision(String sourceRevision) {
if (sourceRevision == null
|| sourceRevision.isBlank()
|| sourceRevision.length() > 128
|| sourceRevision.codePoints().anyMatch(Character::isISOControl)) {
throw new IllegalArgumentException(
"sourceRevision must contain 1..128 non-control characters");
}
}
}
@@ -1,39 +0,0 @@
package dev.caskeleton.application.fileexport;
import dev.caskeleton.application.filepublication.PublishedFileReference;
import java.util.Objects;
/**
* Legacy receipt for a file written through {@link FileExportPort}.
*
* <p>The original contract exposed the server's absolute filesystem path. That made the application
* boundary depend on deployment topology and produced a value that is meaningless for SFTP, NFS
* aliases or clustered storage. The compatibility receipt now carries only an opaque publication
* reference.
*
* @param fileName the logical name the file was written under (never null/blank)
* @param reference an opaque reference that never exposes a filesystem path or provider location
* @param byteSize the written file size in bytes (never negative)
* @param rowCount the number of data rows written, excluding the header (never negative)
* @deprecated use the streaming {@link
* dev.caskeleton.application.filepublication.FilePublicationPort} contract instead
*/
@Deprecated(forRemoval = true)
public record ExportedFile(
String fileName, PublishedFileReference reference, long byteSize, long rowCount) {
public ExportedFile {
if (fileName == null || fileName.isBlank()) {
throw new IllegalArgumentException("ExportedFile.fileName must be non-null and non-blank");
}
Objects.requireNonNull(reference, "reference");
if (byteSize < 0) {
throw new IllegalArgumentException(
"ExportedFile.byteSize must be non-negative, was " + byteSize);
}
if (rowCount < 0) {
throw new IllegalArgumentException(
"ExportedFile.rowCount must be non-negative, was " + rowCount);
}
}
}
@@ -1,33 +0,0 @@
package dev.caskeleton.application.fileexport;
import java.util.List;
/**
* Legacy outbound port for exporting already-materialized tabular data as CSV.
*
* <p>This contract requires the caller to materialize every row in memory before the adapter is
* invoked. The replacement {@link dev.caskeleton.application.filepublication.FilePublicationPort}
* streams rows through a {@link dev.caskeleton.application.filepublication.TabularRowProducer} and
* returns an opaque publication reference.
*
* @deprecated use {@link dev.caskeleton.application.filepublication.FilePublicationPort}; this
* compatibility port retains whole-result materialization and will be removed
*/
@Deprecated(forRemoval = true)
@SuppressWarnings("removal")
public interface FileExportPort {
/**
* Writes {@code header} + {@code rows} as a CSV file named {@code fileName} under the adapter's
* configured base directory.
*
* <p>Every field is escaped per RFC-4180. A {@code null} field is written as an empty field. The
* file is UTF-8 encoded.
*
* @param fileName the target logical file name; must be non-null and non-blank
* @param header the column names written as the first line; must be non-null
* @param rows the already-materialized data rows; must be non-null
* @return a legacy receipt containing an opaque reference, byte size and row count
*/
ExportedFile exportCsv(String fileName, List<String> header, List<List<String>> rows);
}
@@ -1,65 +0,0 @@
package dev.caskeleton.application.filepublication;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/** Ordered, versioned schema for tabular publication. */
public record ExportSchema(String schemaId, int version, List<Column> columns) {
public ExportSchema {
schemaId = FilePublicationValues.requireOpaque("schemaId", schemaId, 128);
if (version < 1) {
throw new IllegalArgumentException("schema version must be >= 1");
}
if (columns == null || columns.isEmpty()) {
throw new IllegalArgumentException("schema columns must be non-empty");
}
columns = List.copyOf(columns);
Set<String> names = new HashSet<>();
for (Column column : columns) {
Objects.requireNonNull(column, "schema column must be non-null");
if (!names.add(column.name())) {
throw new IllegalArgumentException("duplicate schema column: " + column.name());
}
}
}
public record Column(
String name,
CellType cellType,
boolean nullable,
FormulaPolicy formulaPolicy,
int maximumUtf8Bytes) {
public Column {
name = FilePublicationValues.requireOpaque("column name", name, 128);
// The formula policy governs cell values; the header row had no policy at all, so a column
// named "=cmd|'/c calc'!A1" was written verbatim and executed by the spreadsheet that opened
// the export. Rejecting rather than mitigating is deliberate: prefixing a header with a quote
// would silently rename the column and break whatever parses it downstream.
FilePublicationValues.requireNotFormulaShaped("column name", name);
Objects.requireNonNull(cellType, "cellType must be non-null");
Objects.requireNonNull(formulaPolicy, "formulaPolicy must be non-null");
if (maximumUtf8Bytes < 1) {
throw new IllegalArgumentException("maximumUtf8Bytes must be >= 1");
}
}
}
public enum CellType {
TEXT,
INTEGER,
DECIMAL,
BOOLEAN,
DATE,
INSTANT
}
public enum FormulaPolicy {
ALLOW,
MITIGATE,
REJECT
}
}
@@ -1,11 +0,0 @@
package dev.caskeleton.application.filepublication;
/** Registered logical file destination; never a path, URI, host, or provider identifier. */
public record FileDestinationId(String value) {
public FileDestinationId {
if (value == null || !value.matches("[a-z][a-z0-9-]{0,62}")) {
throw new IllegalArgumentException("destinationId must match [a-z][a-z0-9-]{0,62}");
}
}
}
@@ -1,35 +0,0 @@
package dev.caskeleton.application.filepublication;
/**
* Provider-neutral publication failure. The reason is stable application-facing vocabulary; paths,
* credentials, and provider exception messages must not be embedded in it.
*/
public final class FilePublicationException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final Reason reason;
public FilePublicationException(Reason reason, String message) {
super(message);
this.reason = reason;
}
public FilePublicationException(Reason reason, String message, Throwable cause) {
super(message, cause);
this.reason = reason;
}
public Reason reason() {
return reason;
}
public enum Reason {
INVALID_REQUEST,
CONFLICT,
CAPACITY_EXCEEDED,
UNAVAILABLE,
CANCELLED,
PUBLISH_INDETERMINATE
}
}
@@ -1,10 +0,0 @@
package dev.caskeleton.application.filepublication;
/**
* Outbound application port for publishing a bounded tabular artifact to a registered logical
* destination.
*/
public interface FilePublicationPort {
FilePublishReceipt publish(FilePublishRequest request, TabularRowProducer producer);
}
@@ -1,45 +0,0 @@
package dev.caskeleton.application.filepublication;
final class FilePublicationValues {
private FilePublicationValues() {}
static String requireOpaque(String field, String value, int maximumLength) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(field + " must be non-null and non-blank");
}
String normalized = value.trim();
if (normalized.length() > maximumLength) {
throw new IllegalArgumentException(field + " exceeds " + maximumLength + " characters");
}
if (normalized.chars().anyMatch(Character::isISOControl)) {
throw new IllegalArgumentException(field + " must not contain control characters");
}
return normalized;
}
/**
* Refuses a value a spreadsheet would evaluate as a formula.
*
* <p>A CSV is data to the producer and a program to Excel, LibreOffice and Sheets: a field
* starting with {@code =}, {@code +}, {@code -}, {@code @}, a tab or a carriage return is
* evaluated on open, and {@code =cmd|'/c calc'!A1} is a remote-code-execution vector against
* whoever opens the report. Escaping belongs to cell values, where a leading quote is invisible;
* for identifiers such as a column name there is nothing to escape into, so it is refused.
*/
static void requireNotFormulaShaped(String field, String value) {
if (value.isEmpty()) {
return;
}
char first = value.charAt(0);
if (first == '='
|| first == '+'
|| first == '-'
|| first == '@'
|| first == '\t'
|| first == '\r') {
throw new IllegalArgumentException(
field + " must not start with a spreadsheet formula character (= + - @ tab CR)");
}
}
}
@@ -1,9 +0,0 @@
package dev.caskeleton.application.filepublication;
/** Stable opaque operation identity retained across resolution and retry. */
public record FilePublishOperationId(String value) {
public FilePublishOperationId {
value = FilePublicationValues.requireOpaque("operationId", value, 128);
}
}
@@ -1,53 +0,0 @@
package dev.caskeleton.application.filepublication;
import java.time.Instant;
import java.util.Objects;
/** Sanitized publication receipt. It intentionally contains no local/remote path or credential. */
public record FilePublishReceipt(
FilePublishOperationId operationId,
PublishedFileReference reference,
FileDestinationId destinationId,
String publishedFileName,
FileVersion version,
String formatProfileId,
String mediaType,
String charset,
long byteSize,
long dataRowCount,
int columnCount,
String sha256,
Instant publishedAt,
PublicationGuarantee publicationGuarantee,
DurabilityGuarantee durabilityGuarantee,
long formulaMitigatedCount) {
public FilePublishReceipt {
Objects.requireNonNull(operationId, "operationId must be non-null");
Objects.requireNonNull(reference, "reference must be non-null");
Objects.requireNonNull(destinationId, "destinationId must be non-null");
publishedFileName =
FilePublicationValues.requireOpaque("publishedFileName", publishedFileName, 256);
Objects.requireNonNull(version, "version must be non-null");
formatProfileId = FilePublicationValues.requireOpaque("formatProfileId", formatProfileId, 128);
mediaType = FilePublicationValues.requireOpaque("mediaType", mediaType, 128);
charset = FilePublicationValues.requireOpaque("charset", charset, 64);
sha256 = FilePublicationValues.requireOpaque("sha256", sha256, 64);
Objects.requireNonNull(publishedAt, "publishedAt must be non-null");
Objects.requireNonNull(publicationGuarantee, "publicationGuarantee must be non-null");
Objects.requireNonNull(durabilityGuarantee, "durabilityGuarantee must be non-null");
if (byteSize < 0 || dataRowCount < 0 || columnCount < 1 || formulaMitigatedCount < 0) {
throw new IllegalArgumentException("receipt counts and sizes are out of range");
}
}
public enum PublicationGuarantee {
UNIQUE_ATOMIC_CREATE
}
public enum DurabilityGuarantee {
PROCESS_LOCAL_SYNC,
FILE_AND_DIRECTORY_SYNC,
PROVIDER_ACK_ONLY
}
}
@@ -1,22 +0,0 @@
package dev.caskeleton.application.filepublication;
import java.util.Objects;
/** Provider-neutral publication intent. */
public record FilePublishRequest(
FilePublishOperationId operationId,
FileDestinationId destinationId,
LogicalFileName logicalFileName,
SourceRevision sourceRevision,
ExportSchema schema,
String formatProfileId) {
public FilePublishRequest {
Objects.requireNonNull(operationId, "operationId must be non-null");
Objects.requireNonNull(destinationId, "destinationId must be non-null");
Objects.requireNonNull(logicalFileName, "logicalFileName must be non-null");
Objects.requireNonNull(sourceRevision, "sourceRevision must be non-null");
Objects.requireNonNull(schema, "schema must be non-null");
formatProfileId = FilePublicationValues.requireOpaque("formatProfileId", formatProfileId, 128);
}
}
@@ -1,9 +0,0 @@
package dev.caskeleton.application.filepublication;
/** Opaque immutable version of a published artifact. */
public record FileVersion(String value) {
public FileVersion {
value = FilePublicationValues.requireOpaque("fileVersion", value, 128);
}
}
@@ -1,12 +0,0 @@
package dev.caskeleton.application.filepublication;
/** Display/naming input that cannot carry filesystem path syntax. */
public record LogicalFileName(String value) {
public LogicalFileName {
value = FilePublicationValues.requireOpaque("logicalFileName", value, 128);
if (value.contains("/") || value.contains("\\") || value.equals(".") || value.equals("..")) {
throw new IllegalArgumentException("logicalFileName must not contain path syntax");
}
}
}
@@ -1,9 +0,0 @@
package dev.caskeleton.application.filepublication;
/** Opaque reference that never exposes a filesystem path, host, or provider location. */
public record PublishedFileReference(String value) {
public PublishedFileReference {
value = FilePublicationValues.requireOpaque("publishedFileReference", value, 256);
}
}
@@ -1,9 +0,0 @@
package dev.caskeleton.application.filepublication;
/** Stable source snapshot or source fingerprint selected by the application. */
public record SourceRevision(String value) {
public SourceRevision {
value = FilePublicationValues.requireOpaque("sourceRevision", value, 256);
}
}
@@ -1,77 +0,0 @@
package dev.caskeleton.application.filepublication;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Objects;
/** Closed framework-free set of cells supported by the baseline tabular publisher. */
public sealed interface TabularCell {
ExportSchema.CellType cellType();
record TextCell(String value) implements TabularCell {
public TextCell {
Objects.requireNonNull(value, "text value must be non-null");
}
@Override
public ExportSchema.CellType cellType() {
return ExportSchema.CellType.TEXT;
}
}
record IntegerCell(long value) implements TabularCell {
@Override
public ExportSchema.CellType cellType() {
return ExportSchema.CellType.INTEGER;
}
}
record DecimalCell(BigDecimal value) implements TabularCell {
public DecimalCell {
Objects.requireNonNull(value, "decimal value must be non-null");
}
@Override
public ExportSchema.CellType cellType() {
return ExportSchema.CellType.DECIMAL;
}
}
record BooleanCell(boolean value) implements TabularCell {
@Override
public ExportSchema.CellType cellType() {
return ExportSchema.CellType.BOOLEAN;
}
}
record DateCell(LocalDate value) implements TabularCell {
public DateCell {
Objects.requireNonNull(value, "date value must be non-null");
}
@Override
public ExportSchema.CellType cellType() {
return ExportSchema.CellType.DATE;
}
}
record InstantCell(Instant value) implements TabularCell {
public InstantCell {
Objects.requireNonNull(value, "instant value must be non-null");
}
@Override
public ExportSchema.CellType cellType() {
return ExportSchema.CellType.INSTANT;
}
}
record NullCell() implements TabularCell {
@Override
public ExportSchema.CellType cellType() {
throw new IllegalStateException("null cells do not have a concrete cell type");
}
}
}
@@ -1,16 +0,0 @@
package dev.caskeleton.application.filepublication;
import java.util.List;
import java.util.Objects;
/** Immutable ordered row. */
public record TabularRow(List<TabularCell> cells) {
public TabularRow {
Objects.requireNonNull(cells, "cells must be non-null");
cells = List.copyOf(cells);
if (cells.stream().anyMatch(Objects::isNull)) {
throw new IllegalArgumentException("cells must not contain null; use NullCell");
}
}
}
@@ -1,8 +0,0 @@
package dev.caskeleton.application.filepublication;
/** Synchronous single-attempt producer for bounded row-by-row publication. */
@FunctionalInterface
public interface TabularRowProducer {
void produce(TabularRowSink sink);
}
@@ -1,9 +0,0 @@
package dev.caskeleton.application.filepublication;
/** Attempt-scoped non-thread-safe sink owned by the file publication adapter. */
public interface TabularRowSink {
void write(TabularRow row);
void checkpoint();
}
@@ -1,4 +1,4 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
import dev.caskeleton.application.transaction.OperationId;
import java.util.Objects;
@@ -1,6 +1,5 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
import dev.caskeleton.application.idempotency.StoredResponse;
import dev.caskeleton.application.transaction.OperationId;
import java.time.Duration;
import java.time.Instant;
@@ -1,6 +1,5 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
import dev.caskeleton.application.idempotency.RequestFingerprint;
import java.time.Duration;
import java.util.Objects;
@@ -1,4 +1,4 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
/** Outcomes of an owner-safe EXECUTING to COMPLETED transition. */
public enum IdempotencyCompleteOutcome {
@@ -1,33 +0,0 @@
package dev.caskeleton.application.idempotency;
import java.time.Duration;
import java.util.Objects;
/**
* The per-request inputs to {@link IdempotencyExecutor#execute}: the request {@link
* IdempotencyScope identity}, its body {@link RequestFingerprint}, and an optional per-use-case TTL
* override (≤ 72h, enforced by the executor — see {@link #withTtl}).
*
* @param scope request identity (triple or tenant 4-tuple)
* @param fingerprint SHA-256 of the request body
* @param ttlOverride per-use-case TTL, or {@code null} to use the configured default
*/
public record IdempotencyContext(
IdempotencyScope scope, RequestFingerprint fingerprint, Duration ttlOverride) {
public IdempotencyContext {
Objects.requireNonNull(scope, "scope");
Objects.requireNonNull(fingerprint, "fingerprint");
}
/** Context using the executor's configured default TTL. */
public static IdempotencyContext of(IdempotencyScope scope, RequestFingerprint fingerprint) {
return new IdempotencyContext(scope, fingerprint, null);
}
/** Context with a per-use-case TTL override (must be ≤ 72h, enforced by the executor). */
public static IdempotencyContext withTtl(
IdempotencyScope scope, RequestFingerprint fingerprint, Duration ttl) {
return new IdempotencyContext(scope, fingerprint, Objects.requireNonNull(ttl, "ttl"));
}
}
@@ -1,123 +1,315 @@
package dev.caskeleton.application.idempotency;
import java.time.Clock;
import dev.caskeleton.application.transaction.OperationId;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
/**
* Orchestrates idempotent execution at the application use case boundary. For a single {@link
* IdempotencyScope} it runs, in order: claim (atomic {@link IdempotencyStorePort#tryBegin
* insert-or-read}, winner runs the action once) → fingerprint mismatch ({@link
* IdempotencyRequestMismatchException}, 422) → replay of a {@link IdempotencyStatus#COMPLETED}
* record → in-flight wait up to {@link #IN_FLIGHT_WAIT} then {@link IdempotencyInFlightException}
* (409). A throwing action is {@link IdempotencyStorePort#discard discarded} so the request can be
* retried. See README for the policy details and the rationale behind the 200ms wait window.
* Owner-safe request-replay lifecycle over {@link IdempotencyStorePort}.
*
* <p>This contract threads the owner handle through every mutation: a confirmed transition returns
* the owner with its state revision advanced, and the next call must present <em>that</em> handle.
* Re-using the claim's original owner would present a stale revision, which the store is built to
* refuse — that refusal is the whole point of the compare-and-set, so a caller that defeats it has
* an owner-safe store and no owner safety.
*
* <p>The action runs only after a confirmed start. This preserves request-replay evidence; it does
* not create a cross-store exactly-once boundary, and nothing here should be read as claiming one.
*/
public final class IdempotencyExecutor {
/** In-flight wait window before a concurrent duplicate gets 409. */
public static final Duration IN_FLIGHT_WAIT = Duration.ofMillis(200);
/** Hard cap: a per-use-case TTL override may not exceed 72h. */
public static final Duration MAX_TTL = Duration.ofDays(3);
private static final Duration POLL_INTERVAL = Duration.ofMillis(20);
private final IdempotencyStorePort store;
private final Clock clock;
private final Duration defaultTtl;
private final Sleeper sleeper;
private final Duration processingLeaseTtl;
private final Duration replayTtl;
private final Duration failureRetention;
private final String responseCodecId;
private final int policyRevision;
public IdempotencyExecutor(IdempotencyStorePort store, Clock clock, Duration defaultTtl) {
this(store, clock, defaultTtl, Sleeper.realtime());
}
// Visible for testing: a test Sleeper advances a mutable clock so the in-flight
// wait is deterministic without blocking real time.
IdempotencyExecutor(
IdempotencyStorePort store, Clock clock, Duration defaultTtl, Sleeper sleeper) {
this.store = Objects.requireNonNull(store, "store");
this.clock = Objects.requireNonNull(clock, "clock");
this.defaultTtl = requireSaneTtl(defaultTtl);
this.sleeper = Objects.requireNonNull(sleeper, "sleeper");
/**
* Creates the executor.
*
* @param store the owner-safe store
* @param processingLeaseTtl how long a claim holds the record before another caller may take over
* @param replayTtl how long a completed response is replayable
* @param failureRetention how long a failed attempt's evidence is kept
* @param responseCodecId the identifier of the codec the stored payload was written with
* @param policyRevision the replay policy revision this deployment enforces
*/
public IdempotencyExecutor(
IdempotencyStorePort store,
Duration processingLeaseTtl,
Duration replayTtl,
Duration failureRetention,
String responseCodecId,
int policyRevision) {
this.store = Objects.requireNonNull(store, "store must be non-null");
this.processingLeaseTtl =
Objects.requireNonNull(processingLeaseTtl, "processing lease TTL must be non-null");
this.replayTtl = Objects.requireNonNull(replayTtl, "replay TTL must be non-null");
this.failureRetention =
Objects.requireNonNull(failureRetention, "failure retention must be non-null");
this.responseCodecId =
Objects.requireNonNull(responseCodecId, "response codec identifier must be non-null");
this.policyRevision = policyRevision;
if (failureRetention.isZero() || failureRetention.isNegative()) {
throw new IllegalArgumentException("the failure retention must be positive");
}
}
/**
* Execute {@code action} idempotently under {@code context}, replaying a prior response when the
* scope has already been seen.
* Mints the attempt a caller retains across a lost response.
*
* @throws IdempotencyRequestMismatchException same key, different body (422)
* @throws IdempotencyInFlightException a duplicate is still in flight (409)
* @param operationId the caller's operation identifier
* @return the claim attempt
*/
public IdempotencyClaimAttempt newAttempt(OperationId operationId) {
return store.newClaimAttempt(operationId);
}
/**
* Claims the scope, runs the action once, and stores its response for replay.
*
* @param scope the digested scope; the raw client key never reaches this class
* @param fingerprint the request fingerprint a replay is checked against
* @param attempt the retained claim attempt
* @param action the action to run at most once
* @param codec serialises and deserialises the action's result
* @param <R> the action's result type
* @return the action's result, or the replayed one
*/
public <R> R execute(
IdempotencyContext context, Supplier<R> action, IdempotentResponseCodec<R> codec) {
Objects.requireNonNull(context, "context");
Objects.requireNonNull(action, "action");
Objects.requireNonNull(codec, "codec");
IdempotencyScopeDigest scope,
RequestFingerprint fingerprint,
IdempotencyClaimAttempt attempt,
IdempotentAction<R> action,
IdempotentResponseCodec<R> codec) {
Objects.requireNonNull(action, "action must be non-null");
Objects.requireNonNull(codec, "codec must be non-null");
IdempotencyClaimRequest request =
new IdempotencyClaimRequest(
scope,
fingerprint,
attempt,
processingLeaseTtl,
replayTtl,
responseCodecId,
policyRevision);
Duration ttl =
requireSaneTtl(context.ttlOverride() != null ? context.ttlOverride() : defaultTtl);
IdempotencyScope scope = context.scope();
RequestFingerprint fingerprint = context.fingerprint();
Instant deadline = clock.instant().plus(IN_FLIGHT_WAIT);
while (true) {
Instant now = clock.instant();
Optional<IdempotencyRecord> existing = store.find(scope, now);
if (existing.isEmpty()) {
// No live record — try to claim the scope and own the execution.
if (store.tryBegin(scope, fingerprint, now.plus(ttl))) {
return runAndComplete(scope, action, codec);
}
// Lost the claim race (another caller inserted concurrently); loop to
// read their record. Bounded by the in-flight deadline below.
if (!now.isBefore(deadline)) {
throw new IdempotencyInFlightException(scope);
}
sleeper.sleep(POLL_INTERVAL);
continue;
}
IdempotencyRecord record = existing.get();
// Mismatch is terminal regardless of status: same key, different body.
if (!record.fingerprint().equals(fingerprint)) {
throw new IdempotencyRequestMismatchException(scope);
}
if (record.status() == IdempotencyStatus.COMPLETED) {
return codec.deserialize(record.response().payload());
}
// IN_FLIGHT by another caller — wait out the window then surface 409.
if (!now.isBefore(deadline)) {
throw new IdempotencyInFlightException(scope);
}
sleeper.sleep(POLL_INTERVAL);
}
return switch (store.claim(request)) {
case IdempotencyClaimOutcome.CompletedReplay replay ->
codec.deserialize(replay.response().payload());
case IdempotencyClaimOutcome.FingerprintMismatch ignored ->
throw IdempotencyRequestMismatchException.forScopeDigest(diagnostic(scope));
case IdempotencyClaimOutcome.InProgress ignored ->
throw IdempotencyInFlightException.forScopeDigest(diagnostic(scope));
case IdempotencyClaimOutcome.RecoveryRequired ignored ->
throw recovery("claim requires reconciliation");
case IdempotencyClaimOutcome.OwnerOperationConflict ignored ->
throw recovery("claim requires reconciliation");
case IdempotencyClaimOutcome.Unavailable ignored ->
throw new IdempotencyUnavailableException();
// The response was lost, not the attempt. The retained attempt is what makes the record
// findable, so the only safe move is to ask the store what actually happened.
case IdempotencyClaimOutcome.Indeterminate ignored -> reconcile(request, action, codec);
case IdempotencyClaimOutcome.Acquired acquired ->
startAndRun(request, acquired.owner(), action, codec, false);
case IdempotencyClaimOutcome.ReplayedAcquire replayed ->
startAndRun(request, replayed.owner(), action, codec, false);
case IdempotencyClaimOutcome.TakenOverClaimed takenOver ->
startAndRun(request, takenOver.owner(), action, codec, false);
};
}
private <R> R runAndComplete(
IdempotencyScope scope, Supplier<R> action, IdempotentResponseCodec<R> codec) {
private <R> R reconcile(
IdempotencyClaimRequest request,
IdempotentAction<R> action,
IdempotentResponseCodec<R> codec) {
IdempotencyInspection inspection = inspect(request);
return switch (inspection.outcome()) {
case CLAIMED_SAME_OPERATION ->
startAndRun(request, requireOwner(inspection), action, codec, false);
case EXECUTING_SAME_OPERATION -> runStarted(request, requireOwner(inspection), action, codec);
case COMPLETED_REPLAY -> codec.deserialize(requireResponse(inspection).payload());
case FINGERPRINT_MISMATCH ->
throw IdempotencyRequestMismatchException.forScopeDigest(diagnostic(request.scope()));
case IN_PROGRESS_OTHER ->
throw IdempotencyInFlightException.forScopeDigest(diagnostic(request.scope()));
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
// ABSENT, FAILED_RETRYABLE, ABANDONED and OPERATION_CONFLICT all mean the same thing here:
// this caller cannot prove what happened to its own attempt, and guessing is the one thing an
// owner-safe store exists to prevent.
default -> throw recovery("an indeterminate claim could not be resumed safely");
};
}
private <R> R startAndRun(
IdempotencyClaimRequest request,
IdempotencyOwner owner,
IdempotentAction<R> action,
IdempotentResponseCodec<R> codec,
boolean alreadyRetried) {
IdempotencyMutationResult<IdempotencyStartOutcome> started =
store.markExecutionStarted(owner, request.claimAttempt().operationId());
return switch (started.outcome()) {
// The owner handle from the transition, not the one from the claim: the state revision has
// advanced and the next compare-and-set is against the new one.
case STARTED, ALREADY_STARTED_SAME_OPERATION ->
runStarted(request, advanced(started, owner), action, codec);
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
case INDETERMINATE -> {
if (alreadyRetried) {
throw recovery("execution start stayed indeterminate after reconciliation");
}
yield resumeAfterIndeterminateStart(request, action, codec);
}
default -> throw recovery("execution start was not confirmed for this exact operation");
};
}
private <R> R resumeAfterIndeterminateStart(
IdempotencyClaimRequest request,
IdempotentAction<R> action,
IdempotentResponseCodec<R> codec) {
IdempotencyInspection inspection = inspect(request);
return switch (inspection.outcome()) {
case CLAIMED_SAME_OPERATION ->
startAndRun(request, requireOwner(inspection), action, codec, true);
case EXECUTING_SAME_OPERATION -> runStarted(request, requireOwner(inspection), action, codec);
case COMPLETED_REPLAY -> codec.deserialize(requireResponse(inspection).payload());
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
default -> throw recovery("execution start is indeterminate");
};
}
private <R> R runStarted(
IdempotencyClaimRequest request,
IdempotencyOwner owner,
IdempotentAction<R> action,
IdempotentResponseCodec<R> codec) {
OperationId operationId = request.claimAttempt().operationId();
IdempotentAction.Outcome<R> outcome;
try {
R result = action.get();
store.complete(scope, new StoredResponse(codec.serialize(result)));
return result;
} catch (RuntimeException e) {
store.discard(scope);
throw e;
outcome = Objects.requireNonNull(action.run(), "action outcome must be non-null");
} catch (RuntimeException failure) {
// The action threw without saying whether it had an effect, so the record must not say
// "retryable": that would invite a second execution of something that may already have run.
preserveUnknown(owner, operationId);
throw failure;
}
return switch (outcome) {
case IdempotentAction.Outcome.Success<R> success ->
complete(request, owner, success.result(), codec, false);
case IdempotentAction.Outcome.RetryableNoEffect<R> retryable -> {
store.markFailed(
owner,
IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE,
failureRetention,
operationId);
throw retryable.failure();
}
case IdempotentAction.Outcome.EffectUnknown<R> unknown -> {
preserveUnknown(owner, operationId);
throw unknown.failure();
}
};
}
private static Duration requireSaneTtl(Duration ttl) {
Objects.requireNonNull(ttl, "ttl");
if (ttl.isZero() || ttl.isNegative()) {
throw new IllegalArgumentException("idempotency TTL must be positive, was " + ttl);
}
if (ttl.compareTo(MAX_TTL) > 0) {
throw new IllegalArgumentException("idempotency TTL exceeds the 72h cap (D6), was " + ttl);
}
return ttl;
private <R> R complete(
IdempotencyClaimRequest request,
IdempotencyOwner owner,
R result,
IdempotentResponseCodec<R> codec,
boolean alreadyRetried) {
StoredResponse response = new StoredResponse(codec.serialize(result));
return switch (store.complete(
owner, response, replayTtl, request.claimAttempt().operationId())) {
case COMPLETED, ALREADY_COMPLETED_SAME_RESULT -> result;
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
case INDETERMINATE -> reconcileCompletion(request, result, codec, alreadyRetried);
default -> throw recovery("completion was not confirmed");
};
}
/**
* Resolves a completion whose response was lost.
*
* <p>Deliberately does not carry the caller's owner handle forward: after an indeterminate
* completion the caller's handle may already be stale, and the only handle worth presenting is
* the one the store reports now.
*/
private <R> R reconcileCompletion(
IdempotencyClaimRequest request,
R result,
IdempotentResponseCodec<R> codec,
boolean alreadyRetried) {
IdempotencyInspection inspection = inspect(request);
return switch (inspection.outcome()) {
case COMPLETED_REPLAY -> {
StoredResponse stored = requireResponse(inspection);
if (stored.payload().equals(codec.serialize(result))) {
yield result;
}
// The stored response is somebody else's answer to this scope. Returning either one would
// be asserting a fact this caller cannot establish.
throw recovery("the completed response conflicts with the one this caller produced");
}
case EXECUTING_SAME_OPERATION -> {
if (alreadyRetried) {
throw recovery("completion stayed indeterminate after reconciliation");
}
yield complete(request, requireOwner(inspection), result, codec, true);
}
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
default -> throw recovery("the completion response is indeterminate and was not reconciled");
};
}
private void preserveUnknown(IdempotencyOwner owner, OperationId operationId) {
store.markFailed(
owner,
IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED,
failureRetention,
operationId);
}
private IdempotencyInspection inspect(IdempotencyClaimRequest request) {
return store.inspect(
new IdempotencyInspectionRequest(
request.scope(), request.requestFingerprint(), request.claimAttempt()));
}
private static IdempotencyOwner advanced(
IdempotencyMutationResult<IdempotencyStartOutcome> transition, IdempotencyOwner fallback) {
return transition.owner().orElse(fallback);
}
private static IdempotencyOwner requireOwner(IdempotencyInspection inspection) {
Optional<IdempotencyOwner> owner = inspection.owner();
return owner.orElseThrow(
() ->
recovery(
"the store reported "
+ inspection.outcome()
+ " without the owner handle it needs"));
}
private static StoredResponse requireResponse(IdempotencyInspection inspection) {
return inspection
.response()
.orElseThrow(() -> recovery("the store reported a completed replay with no response"));
}
/**
* Renders the scope for a diagnostic. Every component is already opaque — the raw client key and
* principal were digested before the scope was constructed — so this is safe to log, and it is
* the only scope identity this lifecycle ever holds.
*/
private static String diagnostic(IdempotencyScopeDigest scope) {
return scope.operationCode() + "::v" + scope.keyDigestVersion() + "::" + scope.digest();
}
private static IdempotencyRecoveryRequiredException recovery(String message) {
return new IdempotencyRecoveryRequiredException(message);
}
}
@@ -1,4 +1,4 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
/** Outcomes of an owner-safe failure transition. */
public enum IdempotencyFailOutcome {
@@ -1,4 +1,4 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
/** Whether a failed action is proven retryable or requires explicit effect reconciliation. */
public enum IdempotencyFailureDisposition {
@@ -1,40 +1,27 @@
package dev.caskeleton.application.idempotency;
/**
* Raised when a concurrent request for the same {@link IdempotencyScope} is still processing after
* the in-flight wait window elapses. Framework-free, application-owned; the web adapter maps it to
* a {@code IDEMPOTENT_IN_FLIGHT} 409 (retryable=false — the client polls). The diagnostic carries
* the scope storage key for logs only. See README.
* Raised when another attempt still holds the same {@link IdempotencyScopeDigest}. Framework-free,
* application-owned; the web adapter maps it to a {@code IDEMPOTENT_IN_FLIGHT} 409 (retryable=false
* — the client polls). The message carries only the opaque scope digest, for logs.
*/
public class IdempotencyInFlightException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final transient IdempotencyScope scope;
public IdempotencyInFlightException(IdempotencyScope scope) {
this(scope == null ? "<null>" : scope.storageKey(), scope);
}
/**
* Creates the exception for the owner-safe lifecycle, which never holds the raw scope: the
* principal and the client key are digested before they reach the store, so the opaque digest
* diagnostic is the only identity available. {@link #scope()} is {@code null} on this path, as it
* already is for any deserialized instance — the field is {@code transient}.
* Creates the exception from the opaque digest diagnostic — the only scope identity the
* owner-safe lifecycle holds, since the principal and client key are digested before they reach
* the store.
*
* @param scopeDigestDiagnostic opaque scope-digest diagnostic, for logs only
* @return the exception
*/
public static IdempotencyInFlightException forScopeDigest(String scopeDigestDiagnostic) {
return new IdempotencyInFlightException(scopeDigestDiagnostic, null);
return new IdempotencyInFlightException(scopeDigestDiagnostic);
}
private IdempotencyInFlightException(String scopeDiagnostic, IdempotencyScope scope) {
private IdempotencyInFlightException(String scopeDiagnostic) {
super("idempotent request still in flight: " + scopeDiagnostic);
this.scope = scope;
}
public IdempotencyScope scope() {
return scope;
}
}
@@ -1,6 +1,5 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
import dev.caskeleton.application.idempotency.StoredResponse;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
@@ -1,6 +1,6 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
/** Recovery-safe classifications returned by {@link IdempotencyStorePortV2#inspect}. */
/** Recovery-safe classifications returned by {@link IdempotencyStorePort#inspect}. */
public enum IdempotencyInspectionOutcome {
ABSENT,
CLAIMED_SAME_OPERATION,
@@ -1,6 +1,5 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
import dev.caskeleton.application.idempotency.RequestFingerprint;
import java.util.Objects;
/** Read-only recovery request after a claim or transition response was lost. */
@@ -1,4 +1,4 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
import java.util.Objects;
import java.util.Optional;
@@ -1,4 +1,4 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
import dev.caskeleton.application.transaction.OperationId;
import java.util.Objects;
@@ -1,39 +0,0 @@
package dev.caskeleton.application.idempotency;
import java.time.Instant;
import java.util.Objects;
/**
* A persisted idempotency record as seen by the application layer; the persistence adapter maps it
* to and from table rows.
*
* @param scope the request identity (triple or tenant 4-tuple)
* @param fingerprint SHA-256 of the original request body
* @param status lifecycle state
* @param response the stored response — present only when {@code status == COMPLETED}
* @param createdAt when the record was first claimed
* @param expiresAt TTL boundary; a record at/after this instant is treated as absent
*/
public record IdempotencyRecord(
IdempotencyScope scope,
RequestFingerprint fingerprint,
IdempotencyStatus status,
StoredResponse response,
Instant createdAt,
Instant expiresAt) {
public IdempotencyRecord {
Objects.requireNonNull(scope, "scope");
Objects.requireNonNull(fingerprint, "fingerprint");
Objects.requireNonNull(status, "status");
Objects.requireNonNull(createdAt, "createdAt");
Objects.requireNonNull(expiresAt, "expiresAt");
if (status == IdempotencyStatus.COMPLETED && response == null) {
throw new IllegalArgumentException("a COMPLETED record must carry a stored response");
}
}
public boolean isExpiredAt(Instant now) {
return !now.isBefore(expiresAt);
}
}
@@ -1,4 +1,4 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
/** Outcomes of releasing a claim only while business execution has not started. */
public enum IdempotencyReleaseOutcome {
@@ -1,4 +1,4 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
/** Outcomes of an owner-safe processing lease renewal. */
public enum IdempotencyRenewOutcome {
@@ -2,39 +2,27 @@ package dev.caskeleton.application.idempotency;
/**
* Raised when an {@code Idempotency-Key} is reused with a different request body (same {@link
* IdempotencyScope}, different {@link RequestFingerprint}). Framework-free, application-owned; the
* web adapter maps it to a {@code IDEMPOTENT_REQUEST_MISMATCH} 422 (retryable=false). The
* diagnostic carries the scope storage key for logs only. See README.
* IdempotencyScopeDigest}, different {@link RequestFingerprint}). Framework-free,
* application-owned; the web adapter maps it to a {@code IDEMPOTENT_REQUEST_MISMATCH} 422
* (retryable=false). The message carries only the opaque scope digest, for logs.
*/
public class IdempotencyRequestMismatchException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final transient IdempotencyScope scope;
public IdempotencyRequestMismatchException(IdempotencyScope scope) {
this(scope == null ? "<null>" : scope.storageKey(), scope);
}
/**
* Creates the exception for the owner-safe lifecycle, which never holds the raw scope: the
* principal and the client key are digested before they reach the store, so the opaque digest
* diagnostic is the only identity available. {@link #scope()} is {@code null} on this path, as it
* already is for any deserialized instance — the field is {@code transient}.
* Creates the exception from the opaque digest diagnostic — the only scope identity the
* owner-safe lifecycle holds, since the principal and client key are digested before they reach
* the store.
*
* @param scopeDigestDiagnostic opaque scope-digest diagnostic, for logs only
* @return the exception
*/
public static IdempotencyRequestMismatchException forScopeDigest(String scopeDigestDiagnostic) {
return new IdempotencyRequestMismatchException(scopeDigestDiagnostic, null);
return new IdempotencyRequestMismatchException(scopeDigestDiagnostic);
}
private IdempotencyRequestMismatchException(String scopeDiagnostic, IdempotencyScope scope) {
private IdempotencyRequestMismatchException(String scopeDiagnostic) {
super("idempotency key reused with a different request body: " + scopeDiagnostic);
this.scope = scope;
}
public IdempotencyScope scope() {
return scope;
}
}
@@ -1,54 +0,0 @@
package dev.caskeleton.application.idempotency;
/**
* Identity of an idempotent request: the triple {@code (principal, idempotencyKey, useCaseName)},
* or a 4-tuple with a leading {@code tenant} when tenant isolation is active ({@code null}
* otherwise). The {@link #of} factory rejects blank required dimensions with {@link
* IdempotencyScopeMissingException}. See README for the global-collision failure mode.
*
* @param tenant tenant id, or {@code null} in single-tenant mode
* @param principal authenticated principal (pseudonymized)
* @param idempotencyKey the client-supplied {@code Idempotency-Key} value
* @param useCaseName the {@code application-core} use case identifier
*/
public record IdempotencyScope(
String tenant, String principal, String idempotencyKey, String useCaseName) {
/** Single-tenant triple scope. */
public static IdempotencyScope of(String principal, String idempotencyKey, String useCaseName) {
return of(null, principal, idempotencyKey, useCaseName);
}
/**
* Tenant-aware scope. {@code tenant} may be {@code null} (single-tenant); the other three
* dimensions are mandatory and rejected when blank.
*/
public static IdempotencyScope of(
String tenant, String principal, String idempotencyKey, String useCaseName) {
requirePresent("principal", principal);
requirePresent("idempotencyKey", idempotencyKey);
requirePresent("useCaseName", useCaseName);
String normalizedTenant = (tenant == null || tenant.isBlank()) ? null : tenant;
return new IdempotencyScope(normalizedTenant, principal, idempotencyKey, useCaseName);
}
private static void requirePresent(String dimension, String value) {
if (value == null || value.isBlank()) {
throw new IdempotencyScopeMissingException(dimension);
}
}
/** True when this scope carries a tenant dimension (4-tuple form). */
public boolean isTenantScoped() {
return tenant != null;
}
/**
* Stable storage key for diagnostics / single-column lookups. The persistence adapter enforces
* uniqueness on the dimension columns, not on this string; this is a human-readable join only.
*/
public String storageKey() {
String prefix = tenant == null ? "" : tenant + "::";
return prefix + principal + "::" + idempotencyKey + "::" + useCaseName;
}
}
@@ -1,4 +1,4 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
import java.util.Objects;
import java.util.regex.Pattern;
@@ -1,22 +0,0 @@
package dev.caskeleton.application.idempotency;
/**
* Raised when an idempotency request omits a required scope dimension. Framework-free,
* application-owned; the web adapter maps it to a {@code VALIDATION_FAILED} 400. The diagnostic
* names the missing dimension for logs only. See README.
*/
public class IdempotencyScopeMissingException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final String missingDimension;
public IdempotencyScopeMissingException(String missingDimension) {
super("idempotency scope is incomplete: '" + missingDimension + "' is blank");
this.missingDimension = missingDimension;
}
public String missingDimension() {
return missingDimension;
}
}
@@ -1,4 +1,4 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
/** Outcomes of the CLAIMED to EXECUTING owner-safe transition. */
public enum IdempotencyStartOutcome {
@@ -1,6 +1,6 @@
package dev.caskeleton.application.idempotency.v2;
package dev.caskeleton.application.idempotency;
/** Owner-safe idempotency V2 state machine. */
/** Owner-safe idempotency state machine. */
public enum IdempotencyState {
CLAIMED,
EXECUTING,
@@ -1,15 +0,0 @@
package dev.caskeleton.application.idempotency;
/**
* Lifecycle of an idempotency record.
*
* <ul>
* <li>{@link #IN_FLIGHT} — a caller has claimed the scope and is executing the action; concurrent
* arrivals wait then receive 409.
* <li>{@link #COMPLETED} — the action finished and the response is stored for replay.
* </ul>
*/
public enum IdempotencyStatus {
IN_FLIGHT,
COMPLETED
}
@@ -1,43 +1,36 @@
package dev.caskeleton.application.idempotency;
import java.time.Instant;
import java.util.Optional;
import dev.caskeleton.application.transaction.OperationId;
import java.time.Duration;
/**
* Outbound port for idempotency record storage, implemented by {@code adapter-persistence} over a
* DB table unique on {@code (tenant, principal, idempotency_key, use_case_name)}. The {@link
* IdempotencyExecutor} owns the wait/replay policy; this port exposes only storage primitives. See
* README (in-memory production impls forbidden; Redis cache-only).
* Provider-neutral owner-safe idempotency state machine.
*
* <p>Providers (Redis, PostgreSQL) contribute only this store; the {@link IdempotencyExecutor} that
* drives it is assembled once by the composition root.
*/
public interface IdempotencyStorePort {
/**
* Atomically claim the scope by inserting an {@link IdempotencyStatus#IN_FLIGHT} record. Returns
* {@code true} when this caller won the claim, {@code false} when a live record already exists
* (the unique constraint is the arbiter — race-safe). An expired record must be treated as
* reclaimable. See README.
*
* @param scope the request identity
* @param fingerprint SHA-256 of the request body
* @param expiresAt TTL boundary for the new record
*/
boolean tryBegin(IdempotencyScope scope, RequestFingerprint fingerprint, Instant expiresAt);
IdempotencyClaimAttempt newClaimAttempt(OperationId operationId);
/**
* Read the current live record for a scope. A record at/after its {@code expiresAt} must be
* treated as absent (expired replay is refused).
*/
Optional<IdempotencyRecord> find(IdempotencyScope scope, Instant now);
IdempotencyClaimOutcome claim(IdempotencyClaimRequest request);
/**
* Transition the in-flight record for {@code scope} to {@link IdempotencyStatus#COMPLETED},
* persisting the response for replay.
*/
void complete(IdempotencyScope scope, StoredResponse response);
IdempotencyMutationResult<IdempotencyStartOutcome> markExecutionStarted(
IdempotencyOwner owner, OperationId operationId);
/**
* Remove the in-flight record for {@code scope} so the original request can be retried. Called
* when the claimed action throws (a stuck IN_FLIGHT row would 409 every retry).
*/
void discard(IdempotencyScope scope);
IdempotencyMutationResult<IdempotencyRenewOutcome> renew(
IdempotencyOwner owner, Duration processingLeaseTtl, OperationId operationId);
IdempotencyCompleteOutcome complete(
IdempotencyOwner owner, StoredResponse response, Duration replayTtl, OperationId operationId);
IdempotencyFailOutcome markFailed(
IdempotencyOwner owner,
IdempotencyFailureDisposition disposition,
Duration retention,
OperationId operationId);
IdempotencyReleaseOutcome releaseBeforeExecution(IdempotencyOwner owner, OperationId operationId);
IdempotencyInspection inspect(IdempotencyInspectionRequest request);
}
@@ -5,8 +5,8 @@ import java.util.Objects;
/**
* Explicitly classifies action effects after execution has started.
*
* <p>An ordinary thrown exception is intentionally not classified as no-effect; the v2 executor
* treats it as effect-unknown and preserves recovery evidence.
* <p>An ordinary thrown exception is intentionally not classified as no-effect; the executor treats
* it as effect-unknown and preserves recovery evidence.
*/
@FunctionalInterface
public interface IdempotentAction<R> {
@@ -6,7 +6,7 @@ import java.util.HexFormat;
import java.util.Objects;
/**
* SHA-256 fingerprint of a request body. Same {@link IdempotencyScope} but a different body
* SHA-256 fingerprint of a request body. Same {@link IdempotencyScopeDigest} but a different body
* (different fingerprint) is a client bug, rejected by the executor with {@link
* IdempotencyRequestMismatchException} (422); a null/empty body hashes as a zero-length payload.
* The raw transmitted bytes are hashed — no canonicalization. See README for the SHA-256 choice and
@@ -1,25 +0,0 @@
package dev.caskeleton.application.idempotency;
import java.time.Duration;
/**
* Indirection over {@code Thread.sleep} so the {@link IdempotencyExecutor}'s in-flight poll wait is
* deterministically testable (a test {@code Sleeper} can advance a mutable clock instead of
* blocking real time).
*/
@FunctionalInterface
public interface Sleeper {
void sleep(Duration duration);
/** Real-time sleeper that restores the interrupt flag and stops waiting on interruption. */
static Sleeper realtime() {
return duration -> {
try {
Thread.sleep(Math.max(0L, duration.toMillis()));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
}
}
@@ -1,328 +0,0 @@
package dev.caskeleton.application.idempotency.v2;
import dev.caskeleton.application.idempotency.IdempotencyInFlightException;
import dev.caskeleton.application.idempotency.IdempotencyRecoveryRequiredException;
import dev.caskeleton.application.idempotency.IdempotencyRequestMismatchException;
import dev.caskeleton.application.idempotency.IdempotencyUnavailableException;
import dev.caskeleton.application.idempotency.IdempotentAction;
import dev.caskeleton.application.idempotency.IdempotentResponseCodec;
import dev.caskeleton.application.idempotency.RequestFingerprint;
import dev.caskeleton.application.idempotency.StoredResponse;
import dev.caskeleton.application.transaction.OperationId;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;
/**
* Owner-safe request-replay lifecycle, over the contract the providers actually implement.
*
* <p>There were two V2 store contracts with the same name in neighbouring packages, and this
* orchestration was written against the one nothing implements. Both owner-safe stores — PostgreSQL
* and Redis — implement {@link IdempotencyStorePortV2} here, so selecting a V2 provider required a
* bean that could not exist and the executor could never be composed at all.
*
* <p>Porting it was not a rename. This contract threads the owner handle through every mutation: a
* confirmed transition returns the owner with its state revision advanced, and the next call must
* present <em>that</em> handle. Re-using the claim's original owner would present a stale revision,
* which the store is built to refuse — that refusal is the whole point of the compare-and-set, so a
* caller that defeats it has an owner-safe store and no owner safety.
*
* <p>The action runs only after a confirmed start. This preserves request-replay evidence; it does
* not create a cross-store exactly-once boundary, and nothing here should be read as claiming one.
*/
public final class IdempotencyExecutorV2 {
private final IdempotencyStorePortV2 store;
private final Duration processingLeaseTtl;
private final Duration replayTtl;
private final Duration failureRetention;
private final String responseCodecId;
private final int policyRevision;
/**
* Creates the executor.
*
* @param store the owner-safe store
* @param processingLeaseTtl how long a claim holds the record before another caller may take over
* @param replayTtl how long a completed response is replayable
* @param failureRetention how long a failed attempt's evidence is kept
* @param responseCodecId the identifier of the codec the stored payload was written with
* @param policyRevision the replay policy revision this deployment enforces
*/
public IdempotencyExecutorV2(
IdempotencyStorePortV2 store,
Duration processingLeaseTtl,
Duration replayTtl,
Duration failureRetention,
String responseCodecId,
int policyRevision) {
this.store = Objects.requireNonNull(store, "store must be non-null");
this.processingLeaseTtl =
Objects.requireNonNull(processingLeaseTtl, "processing lease TTL must be non-null");
this.replayTtl = Objects.requireNonNull(replayTtl, "replay TTL must be non-null");
this.failureRetention =
Objects.requireNonNull(failureRetention, "failure retention must be non-null");
this.responseCodecId =
Objects.requireNonNull(responseCodecId, "response codec identifier must be non-null");
this.policyRevision = policyRevision;
if (failureRetention.isZero() || failureRetention.isNegative()) {
throw new IllegalArgumentException("the failure retention must be positive");
}
}
/**
* Mints the attempt a caller retains across a lost response.
*
* @param operationId the caller's operation identifier
* @return the claim attempt
*/
public IdempotencyClaimAttempt newAttempt(OperationId operationId) {
return store.newClaimAttempt(operationId);
}
/**
* Claims the scope, runs the action once, and stores its response for replay.
*
* @param scope the digested scope; the raw client key never reaches this class
* @param fingerprint the request fingerprint a replay is checked against
* @param attempt the retained claim attempt
* @param action the action to run at most once
* @param codec serialises and deserialises the action's result
* @param <R> the action's result type
* @return the action's result, or the replayed one
*/
public <R> R execute(
IdempotencyScopeDigest scope,
RequestFingerprint fingerprint,
IdempotencyClaimAttempt attempt,
IdempotentAction<R> action,
IdempotentResponseCodec<R> codec) {
Objects.requireNonNull(action, "action must be non-null");
Objects.requireNonNull(codec, "codec must be non-null");
IdempotencyClaimRequest request =
new IdempotencyClaimRequest(
scope,
fingerprint,
attempt,
processingLeaseTtl,
replayTtl,
responseCodecId,
policyRevision);
return switch (store.claim(request)) {
case IdempotencyClaimOutcome.CompletedReplay replay ->
codec.deserialize(replay.response().payload());
case IdempotencyClaimOutcome.FingerprintMismatch ignored ->
throw IdempotencyRequestMismatchException.forScopeDigest(diagnostic(scope));
case IdempotencyClaimOutcome.InProgress ignored ->
throw IdempotencyInFlightException.forScopeDigest(diagnostic(scope));
case IdempotencyClaimOutcome.RecoveryRequired ignored ->
throw recovery("claim requires reconciliation");
case IdempotencyClaimOutcome.OwnerOperationConflict ignored ->
throw recovery("claim requires reconciliation");
case IdempotencyClaimOutcome.Unavailable ignored ->
throw new IdempotencyUnavailableException();
// The response was lost, not the attempt. The retained attempt is what makes the record
// findable, so the only safe move is to ask the store what actually happened.
case IdempotencyClaimOutcome.Indeterminate ignored -> reconcile(request, action, codec);
case IdempotencyClaimOutcome.Acquired acquired ->
startAndRun(request, acquired.owner(), action, codec, false);
case IdempotencyClaimOutcome.ReplayedAcquire replayed ->
startAndRun(request, replayed.owner(), action, codec, false);
case IdempotencyClaimOutcome.TakenOverClaimed takenOver ->
startAndRun(request, takenOver.owner(), action, codec, false);
};
}
private <R> R reconcile(
IdempotencyClaimRequest request,
IdempotentAction<R> action,
IdempotentResponseCodec<R> codec) {
IdempotencyInspection inspection = inspect(request);
return switch (inspection.outcome()) {
case CLAIMED_SAME_OPERATION ->
startAndRun(request, requireOwner(inspection), action, codec, false);
case EXECUTING_SAME_OPERATION -> runStarted(request, requireOwner(inspection), action, codec);
case COMPLETED_REPLAY -> codec.deserialize(requireResponse(inspection).payload());
case FINGERPRINT_MISMATCH ->
throw IdempotencyRequestMismatchException.forScopeDigest(diagnostic(request.scope()));
case IN_PROGRESS_OTHER ->
throw IdempotencyInFlightException.forScopeDigest(diagnostic(request.scope()));
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
// ABSENT, FAILED_RETRYABLE, ABANDONED and OPERATION_CONFLICT all mean the same thing here:
// this caller cannot prove what happened to its own attempt, and guessing is the one thing an
// owner-safe store exists to prevent.
default -> throw recovery("an indeterminate claim could not be resumed safely");
};
}
private <R> R startAndRun(
IdempotencyClaimRequest request,
IdempotencyOwner owner,
IdempotentAction<R> action,
IdempotentResponseCodec<R> codec,
boolean alreadyRetried) {
IdempotencyMutationResult<IdempotencyStartOutcome> started =
store.markExecutionStarted(owner, request.claimAttempt().operationId());
return switch (started.outcome()) {
// The owner handle from the transition, not the one from the claim: the state revision has
// advanced and the next compare-and-set is against the new one.
case STARTED, ALREADY_STARTED_SAME_OPERATION ->
runStarted(request, advanced(started, owner), action, codec);
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
case INDETERMINATE -> {
if (alreadyRetried) {
throw recovery("execution start stayed indeterminate after reconciliation");
}
yield resumeAfterIndeterminateStart(request, action, codec);
}
default -> throw recovery("execution start was not confirmed for this exact operation");
};
}
private <R> R resumeAfterIndeterminateStart(
IdempotencyClaimRequest request,
IdempotentAction<R> action,
IdempotentResponseCodec<R> codec) {
IdempotencyInspection inspection = inspect(request);
return switch (inspection.outcome()) {
case CLAIMED_SAME_OPERATION ->
startAndRun(request, requireOwner(inspection), action, codec, true);
case EXECUTING_SAME_OPERATION -> runStarted(request, requireOwner(inspection), action, codec);
case COMPLETED_REPLAY -> codec.deserialize(requireResponse(inspection).payload());
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
default -> throw recovery("execution start is indeterminate");
};
}
private <R> R runStarted(
IdempotencyClaimRequest request,
IdempotencyOwner owner,
IdempotentAction<R> action,
IdempotentResponseCodec<R> codec) {
OperationId operationId = request.claimAttempt().operationId();
IdempotentAction.Outcome<R> outcome;
try {
outcome = Objects.requireNonNull(action.run(), "action outcome must be non-null");
} catch (RuntimeException failure) {
// The action threw without saying whether it had an effect, so the record must not say
// "retryable": that would invite a second execution of something that may already have run.
preserveUnknown(owner, operationId);
throw failure;
}
return switch (outcome) {
case IdempotentAction.Outcome.Success<R> success ->
complete(request, owner, success.result(), codec, false);
case IdempotentAction.Outcome.RetryableNoEffect<R> retryable -> {
store.markFailed(
owner,
IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE,
failureRetention,
operationId);
throw retryable.failure();
}
case IdempotentAction.Outcome.EffectUnknown<R> unknown -> {
preserveUnknown(owner, operationId);
throw unknown.failure();
}
};
}
private <R> R complete(
IdempotencyClaimRequest request,
IdempotencyOwner owner,
R result,
IdempotentResponseCodec<R> codec,
boolean alreadyRetried) {
StoredResponse response = new StoredResponse(codec.serialize(result));
return switch (store.complete(
owner, response, replayTtl, request.claimAttempt().operationId())) {
case COMPLETED, ALREADY_COMPLETED_SAME_RESULT -> result;
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
case INDETERMINATE -> reconcileCompletion(request, result, codec, alreadyRetried);
default -> throw recovery("completion was not confirmed");
};
}
/**
* Resolves a completion whose response was lost.
*
* <p>Deliberately does not carry the caller's owner handle forward: after an indeterminate
* completion the caller's handle may already be stale, and the only handle worth presenting is
* the one the store reports now.
*/
private <R> R reconcileCompletion(
IdempotencyClaimRequest request,
R result,
IdempotentResponseCodec<R> codec,
boolean alreadyRetried) {
IdempotencyInspection inspection = inspect(request);
return switch (inspection.outcome()) {
case COMPLETED_REPLAY -> {
StoredResponse stored = requireResponse(inspection);
if (stored.payload().equals(codec.serialize(result))) {
yield result;
}
// The stored response is somebody else's answer to this scope. Returning either one would
// be asserting a fact this caller cannot establish.
throw recovery("the completed response conflicts with the one this caller produced");
}
case EXECUTING_SAME_OPERATION -> {
if (alreadyRetried) {
throw recovery("completion stayed indeterminate after reconciliation");
}
yield complete(request, requireOwner(inspection), result, codec, true);
}
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
default -> throw recovery("the completion response is indeterminate and was not reconciled");
};
}
private void preserveUnknown(IdempotencyOwner owner, OperationId operationId) {
store.markFailed(
owner,
IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED,
failureRetention,
operationId);
}
private IdempotencyInspection inspect(IdempotencyClaimRequest request) {
return store.inspect(
new IdempotencyInspectionRequest(
request.scope(), request.requestFingerprint(), request.claimAttempt()));
}
private static IdempotencyOwner advanced(
IdempotencyMutationResult<IdempotencyStartOutcome> transition, IdempotencyOwner fallback) {
return transition.owner().orElse(fallback);
}
private static IdempotencyOwner requireOwner(IdempotencyInspection inspection) {
Optional<IdempotencyOwner> owner = inspection.owner();
return owner.orElseThrow(
() ->
recovery(
"the store reported "
+ inspection.outcome()
+ " without the owner handle it needs"));
}
private static StoredResponse requireResponse(IdempotencyInspection inspection) {
return inspection
.response()
.orElseThrow(() -> recovery("the store reported a completed replay with no response"));
}
/**
* Renders the scope for a diagnostic. Every component is already opaque — the raw client key and
* principal were digested before the scope was constructed — so this is safe to log, and it is
* the only scope identity this lifecycle ever holds.
*/
private static String diagnostic(IdempotencyScopeDigest scope) {
return scope.operationCode() + "::v" + scope.keyDigestVersion() + "::" + scope.digest();
}
private static IdempotencyRecoveryRequiredException recovery(String message) {
return new IdempotencyRecoveryRequiredException(message);
}
}
@@ -1,37 +0,0 @@
package dev.caskeleton.application.idempotency.v2;
import dev.caskeleton.application.idempotency.StoredResponse;
import dev.caskeleton.application.transaction.OperationId;
import java.time.Duration;
/**
* Provider-neutral owner-safe idempotency state machine.
*
* <p>V1 remains source-compatible during migration, but new reliability profiles must use this
* complete contract rather than combining V2 claim with scope-only V1 mutations.
*/
public interface IdempotencyStorePortV2 {
IdempotencyClaimAttempt newClaimAttempt(OperationId operationId);
IdempotencyClaimOutcome claim(IdempotencyClaimRequest request);
IdempotencyMutationResult<IdempotencyStartOutcome> markExecutionStarted(
IdempotencyOwner owner, OperationId operationId);
IdempotencyMutationResult<IdempotencyRenewOutcome> renew(
IdempotencyOwner owner, Duration processingLeaseTtl, OperationId operationId);
IdempotencyCompleteOutcome complete(
IdempotencyOwner owner, StoredResponse response, Duration replayTtl, OperationId operationId);
IdempotencyFailOutcome markFailed(
IdempotencyOwner owner,
IdempotencyFailureDisposition disposition,
Duration retention,
OperationId operationId);
IdempotencyReleaseOutcome releaseBeforeExecution(IdempotencyOwner owner, OperationId operationId);
IdempotencyInspection inspect(IdempotencyInspectionRequest request);
}
@@ -1,20 +0,0 @@
package dev.caskeleton.application.inbox;
import dev.caskeleton.application.transaction.OperationId;
import java.util.Objects;
import java.util.regex.Pattern;
/** Caller-retained inbox claim identity used to replay a lost claim response. */
public record InboxClaimAttempt(String ownerToken, OperationId operationId) {
private static final Pattern TOKEN = Pattern.compile("[0-9a-f]{64}");
public InboxClaimAttempt {
Objects.requireNonNull(ownerToken, "ownerToken");
Objects.requireNonNull(operationId, "operationId");
if (!TOKEN.matcher(ownerToken).matches()) {
throw new IllegalArgumentException(
"owner token must be a 64-character lowercase hexadecimal value");
}
}
}
@@ -1,40 +0,0 @@
package dev.caskeleton.application.inbox;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
/** Exhaustive atomic inbox claim classification. */
public sealed interface InboxClaimOutcome {
record Acquired(InboxOwner owner, Instant leaseUntil) implements InboxClaimOutcome {
public Acquired {
Objects.requireNonNull(owner, "owner");
Objects.requireNonNull(leaseUntil, "leaseUntil");
}
}
record ReplayedAcquire(InboxOwner owner, Instant leaseUntil) implements InboxClaimOutcome {
public ReplayedAcquire {
Objects.requireNonNull(owner, "owner");
Objects.requireNonNull(leaseUntil, "leaseUntil");
}
}
record TakenOver(InboxOwner owner, Instant leaseUntil) implements InboxClaimOutcome {
public TakenOver {
Objects.requireNonNull(owner, "owner");
Objects.requireNonNull(leaseUntil, "leaseUntil");
}
}
record Completed() implements InboxClaimOutcome {}
record InProgress(Duration retryAfter, long attempt) implements InboxClaimOutcome {}
record RecoveryRequired(long attempt) implements InboxClaimOutcome {}
record IntentMismatch() implements InboxClaimOutcome {}
record OwnerOperationConflict() implements InboxClaimOutcome {}
}
@@ -1,35 +0,0 @@
package dev.caskeleton.application.inbox;
import java.time.Duration;
import java.util.Objects;
import java.util.regex.Pattern;
/** Atomic inbox claim request with separate processing and terminal retention windows. */
public record InboxClaimRequest(
InboxScopeDigest scope,
String messageIntentDigest,
InboxClaimAttempt claimAttempt,
Duration processingLease,
Duration terminalRetention) {
private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}");
public InboxClaimRequest {
Objects.requireNonNull(scope, "scope");
Objects.requireNonNull(messageIntentDigest, "messageIntentDigest");
Objects.requireNonNull(claimAttempt, "claimAttempt");
if (!DIGEST.matcher(messageIntentDigest).matches()) {
throw new IllegalArgumentException(
"message intent digest must be a 64-character lowercase hexadecimal value");
}
requirePositiveBounded("processing lease", processingLease, Duration.ofHours(1));
requirePositiveBounded("terminal retention", terminalRetention, Duration.ofDays(30));
}
private static void requirePositiveBounded(String name, Duration value, Duration maximum) {
Objects.requireNonNull(value, name);
if (value.isZero() || value.isNegative() || value.compareTo(maximum) > 0) {
throw new IllegalArgumentException(name + " must be positive and at most " + maximum);
}
}
}
@@ -1,32 +0,0 @@
package dev.caskeleton.application.inbox;
import dev.caskeleton.application.transaction.OperationId;
import java.util.Objects;
/** Full owner/attempt/claim-operation/state-revision CAS tuple for one inbox message. */
public record InboxOwner(
InboxScopeDigest scope,
String ownerToken,
long attempt,
long stateRevision,
OperationId claimOperationId) {
public InboxOwner {
Objects.requireNonNull(scope, "scope");
Objects.requireNonNull(ownerToken, "ownerToken");
Objects.requireNonNull(claimOperationId, "claimOperationId");
if (ownerToken.isBlank() || ownerToken.length() > 128) {
throw new IllegalArgumentException("owner token must contain 1-128 characters");
}
if (attempt < 1) {
throw new IllegalArgumentException("attempt must be positive");
}
if (stateRevision < 0) {
throw new IllegalArgumentException("state revision must be non-negative");
}
}
public InboxOwner withStateRevision(long revision) {
return new InboxOwner(scope, ownerToken, attempt, revision, claimOperationId);
}
}
@@ -1,20 +0,0 @@
package dev.caskeleton.application.inbox;
import java.util.Objects;
import java.util.Optional;
/** Transition outcome and updated owner handle while ownership remains live. */
public record InboxOwnerTransition(InboxTransitionOutcome outcome, Optional<InboxOwner> owner) {
public InboxOwnerTransition {
Objects.requireNonNull(outcome, "outcome");
Objects.requireNonNull(owner, "owner");
boolean mustCarryOwner = outcome == InboxTransitionOutcome.PROCESSING_STARTED;
if (mustCarryOwner != owner.isPresent()) {
throw new IllegalArgumentException(
mustCarryOwner
? "PROCESSING_STARTED must carry an updated owner"
: outcome + " must not carry an owner");
}
}
}
@@ -1,18 +0,0 @@
package dev.caskeleton.application.inbox;
import java.util.Objects;
import java.util.regex.Pattern;
/** Versioned canonical digest of consumer-group, handler, tenant, and message ID scope. */
public record InboxScopeDigest(String value) {
private static final Pattern LOWERCASE_SHA_256 = Pattern.compile("[0-9a-f]{64}");
public InboxScopeDigest {
Objects.requireNonNull(value, "value");
if (!LOWERCASE_SHA_256.matcher(value).matches()) {
throw new IllegalArgumentException(
"inbox scope must be a 64-character lowercase hexadecimal digest");
}
}
}
@@ -1,10 +0,0 @@
package dev.caskeleton.application.inbox;
/** Same-store inbox lifecycle. */
public enum InboxState {
RECEIVED,
PROCESSING,
COMPLETED,
RETRYABLE,
DEAD
}
@@ -1,23 +0,0 @@
package dev.caskeleton.application.inbox;
import dev.caskeleton.application.transaction.OperationId;
import java.time.Duration;
/**
* Owner-safe same-store inbox state machine. Broker ACK must happen only after transaction commit.
*/
public interface InboxStorePort {
InboxClaimAttempt newClaimAttempt(OperationId operationId);
InboxClaimOutcome claim(InboxClaimRequest request);
InboxOwnerTransition markProcessing(InboxOwner owner, OperationId operationId);
InboxTransitionOutcome complete(InboxOwner owner, OperationId operationId);
InboxTransitionOutcome markRetryable(
InboxOwner owner, Duration retention, OperationId operationId);
InboxTransitionOutcome markDead(InboxOwner owner, Duration retention, OperationId operationId);
}
@@ -1,15 +0,0 @@
package dev.caskeleton.application.inbox;
/** Owner-safe inbox transition classification. */
public enum InboxTransitionOutcome {
PROCESSING_STARTED,
COMPLETED,
RETRYABLE,
DEAD,
ALREADY_APPLIED_SAME_OPERATION,
RESULT_CONFLICT,
ABSENT,
NOT_OWNER,
INVALID_STATE,
STALE_REVISION
}
@@ -1,228 +0,0 @@
package dev.caskeleton.application.lease;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
/**
* Bounded renewal scheduler for efficiency leases.
*
* <p>A watchdog reduces duplicate work only. It does not remove process pauses, Redis failover, or
* the requirement for a correctness authority at the protected resource.
*
* @deprecated the shipped runtime does not compose this scheduler. Keep it as a verified reference
* only unless an application explicitly owns its lifecycle and integration.
*/
@Deprecated
public final class LeaseWatchdog implements AutoCloseable {
private static final int MAXIMUM_WORKERS = 32;
private static final int MAXIMUM_REGISTRATIONS = 100_000;
private final ScheduledThreadPoolExecutor scheduler;
private final int maximumRegistrations;
private final Clock clock;
private final AtomicInteger registrations = new AtomicInteger();
private final AtomicBoolean closed = new AtomicBoolean();
private final Set<Registration> active = ConcurrentHashMap.newKeySet();
public LeaseWatchdog(int workerThreads, int maximumRegistrations, Clock clock) {
if (workerThreads < 1 || workerThreads > MAXIMUM_WORKERS) {
throw new IllegalArgumentException("workerThreads must be in 1..32");
}
if (maximumRegistrations < 1 || maximumRegistrations > MAXIMUM_REGISTRATIONS) {
throw new IllegalArgumentException("maximumRegistrations must be in 1..100000");
}
this.maximumRegistrations = maximumRegistrations;
this.clock = Objects.requireNonNull(clock, "clock must be non-null");
this.scheduler =
new ScheduledThreadPoolExecutor(
workerThreads,
daemonThreadFactory(),
new java.util.concurrent.ThreadPoolExecutor.AbortPolicy());
this.scheduler.setRemoveOnCancelPolicy(true);
this.scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
this.scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
}
public Registration watch(
LeaseHandle handle,
Duration leaseTtl,
Duration cadence,
Instant applicationDeadline,
Runnable cancelWork,
Consumer<LeaseState> lostListener) {
Objects.requireNonNull(handle, "handle must be non-null");
Duration boundedLeaseTtl =
LeaseValidation.positiveBounded(leaseTtl, LeaseValidation.MAXIMUM_LEASE, "leaseTtl");
Duration boundedCadence = LeaseValidation.positiveBounded(cadence, boundedLeaseTtl, "cadence");
if (boundedCadence.compareTo(boundedLeaseTtl.dividedBy(2)) > 0) {
throw new IllegalArgumentException("cadence must not exceed half of leaseTtl");
}
Objects.requireNonNull(applicationDeadline, "applicationDeadline must be non-null");
if (!applicationDeadline.isAfter(clock.instant())) {
throw new IllegalArgumentException("applicationDeadline must be in the future");
}
Objects.requireNonNull(cancelWork, "cancelWork must be non-null");
Objects.requireNonNull(lostListener, "lostListener must be non-null");
reserve();
Registration registration =
new Registration(handle, boundedLeaseTtl, applicationDeadline, cancelWork, lostListener);
active.add(registration);
try {
registration.future =
scheduler.scheduleWithFixedDelay(
registration::runOnce,
boundedCadence.toMillis(),
boundedCadence.toMillis(),
TimeUnit.MILLISECONDS);
return registration;
} catch (RuntimeException failure) {
registration.close();
throw failure;
}
}
private void reserve() {
while (true) {
if (closed.get()) {
throw new RejectedExecutionException("lease watchdog is closed");
}
int current = registrations.get();
if (current >= maximumRegistrations) {
throw new RejectedExecutionException("lease watchdog registration bound reached");
}
if (registrations.compareAndSet(current, current + 1)) {
if (closed.get()) {
registrations.decrementAndGet();
throw new RejectedExecutionException("lease watchdog is closed");
}
return;
}
}
}
int activeRegistrations() {
return registrations.get();
}
@Override
public void close() {
if (closed.compareAndSet(false, true)) {
for (Registration registration : active.toArray(Registration[]::new)) {
registration.close();
}
// shutdownNow() returns the tasks it cancelled before they ran. Nothing here can act on
// them, but the value has to be read rather than discarded, or the ignored-return-value
// check reads this as a call made purely for its side effect.
List<Runnable> cancelled = scheduler.shutdownNow();
cancelled.clear();
}
}
public final class Registration implements AutoCloseable {
private final LeaseHandle handle;
private final Duration leaseTtl;
private final Instant applicationDeadline;
private final Runnable cancelWork;
private final Consumer<LeaseState> lostListener;
private final AtomicBoolean registrationClosed = new AtomicBoolean();
private final AtomicBoolean lossReported = new AtomicBoolean();
private volatile ScheduledFuture<?> future;
private Registration(
LeaseHandle handle,
Duration leaseTtl,
Instant applicationDeadline,
Runnable cancelWork,
Consumer<LeaseState> lostListener) {
this.handle = handle;
this.leaseTtl = leaseTtl;
this.applicationDeadline = applicationDeadline;
this.cancelWork = cancelWork;
this.lostListener = lostListener;
}
private void runOnce() {
if (registrationClosed.get()) {
return;
}
if (!applicationDeadline.isAfter(clock.instant())) {
terminateLost(LeaseState.LOST);
return;
}
LeaseState before = handle.state();
if (before != LeaseState.ACTIVE || handle.remainingValidity().isZero()) {
terminateLost(before == LeaseState.ACTIVE ? LeaseState.LOST : before);
return;
}
LeaseRenewOutcome outcome;
try {
outcome = Objects.requireNonNull(handle.renew(leaseTtl), "renew outcome must be non-null");
} catch (RuntimeException failure) {
terminateLost(LeaseState.UNKNOWN);
return;
}
if (!(outcome instanceof LeaseRenewOutcome.Renewed) || handle.state() != LeaseState.ACTIVE) {
LeaseState state = handle.state();
terminateLost(state == LeaseState.ACTIVE ? LeaseState.LOST : state);
}
}
void runOnceForTest() {
runOnce();
}
public boolean closed() {
return registrationClosed.get();
}
private void terminateLost(LeaseState state) {
if (lossReported.compareAndSet(false, true)) {
try {
cancelWork.run();
} finally {
try {
lostListener.accept(state);
} finally {
close();
}
}
}
}
@Override
public void close() {
if (registrationClosed.compareAndSet(false, true)) {
ScheduledFuture<?> scheduled = future;
if (scheduled != null) {
scheduled.cancel(false);
}
active.remove(this);
registrations.decrementAndGet();
}
}
}
private static ThreadFactory daemonThreadFactory() {
AtomicInteger sequence = new AtomicInteger();
return runnable -> {
Thread thread = new Thread(runnable, "ca-lease-watchdog-" + sequence.incrementAndGet());
thread.setDaemon(true);
return thread;
};
}
}
@@ -0,0 +1,19 @@
package dev.caskeleton.application.operation;
import dev.caskeleton.application.command.Command;
import java.util.Objects;
/**
* A caller asking to cancel one operation.
*
* @param operationId the identity to cancel
* @param principal the authenticated caller, or null when the caller is not authenticated
* @param tenantId the caller's tenant, or null when the request is not tenant scoped
*/
public record CancelDurableOperationCommand(
DurableOperationId operationId, String principal, String tenantId) implements Command {
public CancelDurableOperationCommand {
Objects.requireNonNull(operationId, "operationId");
}
}
@@ -0,0 +1,70 @@
package dev.caskeleton.application.operation;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.time.Clock;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
/**
* Cancels one operation for the caller that submitted it.
*
* <p>The result is empty when the caller may not see the operation, which is the same answer as for
* one that does not exist; otherwise it says whether this call moved it to CANCELED. A repeat, or a
* cancel of work that already finished, is {@code false}, never an error.
*/
@RequiresPermission("operation:cancel")
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.WRITE_REPOSITORY)
// Not final: @RequiresPermission is applied through a CGLIB proxy
// (RequiresPermissionProxyabilityTest).
public class CancelDurableOperationUseCase
implements CommandUseCase<CancelDurableOperationCommand, Optional<Boolean>> {
private final DurableOperationStorePort operations;
private final TransactionPort transactions;
private final Clock clock;
/**
* A use case over the operation store.
*
* @param operations where operations are recorded
* @param transactions opens the write transaction
* @param clock the cancellation clock
*/
public CancelDurableOperationUseCase(
DurableOperationStorePort operations, TransactionPort transactions, Clock clock) {
this.operations = Objects.requireNonNull(operations, "operations");
this.transactions = Objects.requireNonNull(transactions, "transactions");
this.clock = Objects.requireNonNull(clock, "clock");
}
@Override
public Optional<Boolean> handle(CancelDurableOperationCommand command) {
Objects.requireNonNull(command, "command");
if (command.principal() == null) {
return Optional.empty();
}
return transactions.inWrite(
() -> {
Instant now = clock.instant();
// The store's own state predicate decides whether the cancel lands: the operation can
// finish between this read and the cancel, and only the store can refuse that race.
return operations
.find(command.operationId(), command.principal(), now)
.filter(
operation ->
DurableOperationAccessPolicy.mayAccess(
operation, command.principal(), command.tenantId()))
.map(visible -> operations.cancel(command.operationId(), command.principal(), now));
});
}
}
@@ -0,0 +1,29 @@
package dev.caskeleton.application.operation;
import java.util.Objects;
/**
* Who may read or cancel an operation: the principal that submitted it, in the tenant it was
* submitted in.
*
* <p>Object-level, not route-level. Being allowed to call the operation route says nothing about
* being allowed to see this operation, and a failed one carries its problem detail. A caller that
* fails this check is answered exactly as if the operation did not exist, so a guessed id is not an
* oracle for what other callers or tenants are running.
*/
final class DurableOperationAccessPolicy {
private DurableOperationAccessPolicy() {}
/**
* Whether this caller may see this operation.
*
* @param operation the stored operation
* @param principal the authenticated caller, or null when the caller is not authenticated
* @param tenantId the caller's tenant, or null when the request is not tenant scoped
*/
static boolean mayAccess(DurableOperation operation, String principal, String tenantId) {
return operation.principal().equals(principal)
&& Objects.equals(operation.tenantId(), tenantId);
}
}
@@ -0,0 +1,19 @@
package dev.caskeleton.application.operation;
import dev.caskeleton.application.query.Query;
import java.util.Objects;
/**
* A caller asking to read one operation.
*
* @param operationId the identity being polled
* @param principal the authenticated caller, or null when the caller is not authenticated
* @param tenantId the caller's tenant, or null when the request is not tenant scoped
*/
public record GetDurableOperationQuery(
DurableOperationId operationId, String principal, String tenantId) implements Query {
public GetDurableOperationQuery {
Objects.requireNonNull(operationId, "operationId");
}
}
@@ -0,0 +1,52 @@
package dev.caskeleton.application.operation;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.QueryUseCase;
import java.time.Clock;
import java.util.Objects;
import java.util.Optional;
/** Reads one operation for the caller that submitted it; anyone else is told it does not exist. */
@UseCaseCapability(
transactionMode = TransactionMode.READ_ONLY,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.READ_REPOSITORY)
public final class GetDurableOperationUseCase
implements QueryUseCase<GetDurableOperationQuery, Optional<DurableOperation>> {
private final DurableOperationStorePort operations;
private final TransactionPort transactions;
private final Clock clock;
/**
* A use case over the operation store.
*
* @param operations where operations are recorded
* @param transactions opens the read transaction
* @param clock the clock expiry is judged against
*/
public GetDurableOperationUseCase(
DurableOperationStorePort operations, TransactionPort transactions, Clock clock) {
this.operations = Objects.requireNonNull(operations, "operations");
this.transactions = Objects.requireNonNull(transactions, "transactions");
this.clock = Objects.requireNonNull(clock, "clock");
}
@Override
public Optional<DurableOperation> handle(GetDurableOperationQuery query) {
Objects.requireNonNull(query, "query");
if (query.principal() == null) {
return Optional.empty();
}
return transactions
.inRead(() -> operations.find(query.operationId(), query.principal(), clock.instant()))
.filter(
operation ->
DurableOperationAccessPolicy.mayAccess(
operation, query.principal(), query.tenantId()));
}
}
@@ -0,0 +1,14 @@
package dev.caskeleton.application.outbox;
/** What a completion ({@code markPublished} / {@code markFailed} / {@code markDead}) achieved. */
public enum OutboxCompletion {
/** The lease still held the row; the row took the new state. */
APPLIED,
/**
* The lease no longer held the row — it expired and another relay claimed the row, or the row was
* already completed. Nothing was written.
*/
STALE
}
@@ -0,0 +1,35 @@
package dev.caskeleton.application.outbox;
import java.util.Objects;
/**
* One relay's claim on one outbox row, as returned by {@link OutboxStorePort#claimBatch}.
*
* <p>A claim expires after the in-flight timeout and another relay may then take the row. The
* {@code token} is the fence: every claim increments it and a completion names the token it holds,
* so the relay that stalled past its claim finds nothing left to complete instead of overwriting
* the result of the relay that took over.
*
* <p>Kept apart from {@link ClaimedOutboxEvent} on purpose: the broker adapter receives the event,
* and the claim is store bookkeeping it has no use for.
*
* @param event the claimed row
* @param owner the relay instance that holds the claim
* @param token the fencing token this claim was granted
*/
public record OutboxLease(ClaimedOutboxEvent event, String owner, long token) {
public OutboxLease {
Objects.requireNonNull(event, "event must not be null");
if (owner == null || owner.isBlank()) {
throw new IllegalArgumentException("owner must not be blank");
}
if (token < 1) {
throw new IllegalArgumentException("token must be >= 1, was " + token);
}
}
public String eventId() {
return event.eventId();
}
}
@@ -10,4 +10,17 @@ package dev.caskeleton.application.outbox;
public interface OutboxRelayFailureReportPort {
void report(OutboxRelayFailureReport report);
/**
* Reports a completion this relay could not write because its claim had been superseded: the
* claim outlived the in-flight timeout and another relay took the row. Nothing was persisted, so
* this is not a FAILED/DEAD transition; it says the timeout is shorter than a relay stall and the
* broker may have seen the event twice.
*
* @param eventId the event whose completion was refused
* @param eventType the logical event type
* @param attempted the outcome this relay tried to write
*/
default void reportStaleCompletion(
String eventId, String eventType, OutboxRelayResult.Outcome attempted) {}
}
@@ -41,7 +41,8 @@ public record OutboxRelayResult(int claimedCount, List<EventOutcome> outcomes) {
*
* <p>Three values mirror the three terminal states reachable in a single relay cycle: broker ack
* ({@link #PUBLISHED}), transient failure below the retry cap ({@link #FAILED}), or retry cap
* exhausted ({@link #DEAD}).
* exhausted ({@link #DEAD}). The fourth, {@link #STALE}, records a result this relay was no
* longer allowed to write.
*/
public enum Outcome {
@@ -52,6 +53,13 @@ public record OutboxRelayResult(int claimedCount, List<EventOutcome> outcomes) {
FAILED,
/** All retry attempts exhausted; row transitions to DEAD. */
DEAD
DEAD,
/**
* This relay's claim expired and another relay took the row over before the result could be
* 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
}
}
@@ -9,49 +9,56 @@ import java.util.Map;
* Outbound port for relay-side access to the outbox store. All mutating operations ({@link
* #claimBatch}, {@link #markPublished}, {@link #markFailed}, {@link #markDead}) must be called
* inside a {@code TransactionPort.inWrite(...)} boundary owned by the relay; implementations must
* not open their own transaction. See README for the claim/FIFO/in-flight-timeout semantics.
* not open their own transaction. A completion applies only while the relay's {@link OutboxLease}
* still holds the row, so a relay that stalled past its claim cannot overwrite the relay that took
* the row over. See README for the claim/FIFO/in-flight-timeout/lease semantics.
*/
public interface OutboxStorePort {
/**
* Atomically claims up to {@code batchSize} eligible rows and transitions them to {@link
* OutboxEventStatus#IN_FLIGHT}. Must be called inside {@code TransactionPort.inWrite(...)}. See
* README for eligibility and the FIFO gate.
* Atomically claims up to {@code batchSize} eligible rows for {@code owner} and transitions them
* to {@link OutboxEventStatus#IN_FLIGHT}. While the row lock is held each claimed row records
* {@code owner} and increments its fencing token. Must be called inside {@code
* TransactionPort.inWrite(...)}. See README for eligibility and the FIFO gate.
*
* @param owner the claiming relay instance; stable for the relay's lifetime
* @param batchSize maximum number of events to claim
* @param now current wall-clock time used for eligibility checks
* @param inFlightTimeout duration after which an IN_FLIGHT orphan becomes re-claimable
* @return claimed events ({@code status = IN_FLIGHT}, incremented {@code attemptCount}); empty if
* none
* @return one lease per claimed event ({@code status = IN_FLIGHT}, incremented {@code
* attemptCount}); empty if none
*/
List<ClaimedOutboxEvent> claimBatch(int batchSize, Instant now, Duration inFlightTimeout);
List<OutboxLease> claimBatch(String owner, int batchSize, Instant now, Duration inFlightTimeout);
/**
* Marks the event as successfully published. Must be called inside {@code
* Marks the leased event as successfully published. Must be called inside {@code
* TransactionPort.inWrite(...)} after a successful publish.
*
* @param eventId the identifier of the event to mark published
* @param lease the claim this relay holds
* @return {@link OutboxCompletion#STALE}, writing nothing, when the lease no longer holds the row
*/
void markPublished(String eventId);
OutboxCompletion markPublished(OutboxLease lease);
/**
* Marks the event as failed and schedules the next retry attempt. Must be called inside {@code
* TransactionPort.inWrite(...)} when a publish fails transiently and {@code attemptCount <
* 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}.
*
* @param eventId the identifier of the event to mark failed
* @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
*/
void markFailed(String eventId, Instant nextAttemptAt);
OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt);
/**
* Marks the 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
* 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
* manually resolved (see README).
*
* @param eventId the identifier of the event to dead-letter
* @param lease the claim this relay holds
* @return {@link OutboxCompletion#STALE}, writing nothing, when the lease no longer holds the row
*/
void markDead(String eventId);
OutboxCompletion markDead(OutboxLease lease);
/**
* Returns a count of rows grouped by {@link OutboxEventStatus} — gauge source for the {@code
@@ -22,9 +22,11 @@ import java.util.function.Supplier;
* <em>outside</em> any transaction and drive the PUBLISHED / FAILED / DEAD state machine per
* result. Confirmed failure transitions are reported through a typed outbound port and publish
* failures are never rethrown; a status-update failure after a successful publish propagates and
* the row is recovered via the in-flight timeout. 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.
* 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.
*/
@RequiresPermission("outbox:relay")
@UseCaseCapability(
@@ -44,6 +46,9 @@ public class PublishPendingOutboxEventsUseCase
private final int batchSize;
private final Duration inFlightTimeout;
/** The lease owner this relay instance claims under: one per instance, fixed for its lifetime. */
private final String relayOwner;
/**
* Constructs the relay use case with all required collaborators (wired manually by {@code
* app-bootstrap}; see README).
@@ -56,6 +61,8 @@ public class PublishPendingOutboxEventsUseCase
* @param clock wall-clock source (injected for testability)
* @param batchSize maximum events to claim per relay cycle
* @param inFlightTimeout how long a claimed row stays IN_FLIGHT before re-claim
* @param relayOwner lease owner id, unique per relay instance (the composition root generates it;
* identifier generation stays out of the application layer)
*/
public PublishPendingOutboxEventsUseCase(
OutboxStorePort store,
@@ -65,7 +72,8 @@ public class PublishPendingOutboxEventsUseCase
OutboxBackoffPolicy backoffPolicy,
Clock clock,
int batchSize,
Duration inFlightTimeout) {
Duration inFlightTimeout,
String relayOwner) {
this.store = Objects.requireNonNull(store, "store must not be null");
this.publishPort = Objects.requireNonNull(publishPort, "publishPort must not be null");
this.failureReporter =
@@ -79,6 +87,10 @@ public class PublishPendingOutboxEventsUseCase
this.batchSize = batchSize;
this.inFlightTimeout =
Objects.requireNonNull(inFlightTimeout, "inFlightTimeout must not be null");
if (relayOwner == null || relayOwner.isBlank()) {
throw new IllegalArgumentException("relayOwner must not be blank");
}
this.relayOwner = relayOwner;
}
@Override
@@ -87,8 +99,8 @@ public class PublishPendingOutboxEventsUseCase
Instant now = clock.instant();
// Step 1: Claim a batch inside a short write transaction.
List<ClaimedOutboxEvent> claimed =
tx.inWrite(() -> store.claimBatch(batchSize, now, inFlightTimeout));
List<OutboxLease> claimed =
tx.inWrite(() -> store.claimBatch(relayOwner, batchSize, now, inFlightTimeout));
if (claimed.isEmpty()) {
return new OutboxRelayResult(0, List.of());
@@ -96,14 +108,15 @@ public class PublishPendingOutboxEventsUseCase
// Step 2: Defensive sort by occurredAt ascending (relay enforces FIFO even if the adapter does
// not).
List<ClaimedOutboxEvent> sorted = new ArrayList<>(claimed);
sorted.sort(Comparator.comparing(ClaimedOutboxEvent::occurredAt));
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.
List<OutboxRelayResult.EventOutcome> outcomes = new ArrayList<>(sorted.size());
for (ClaimedOutboxEvent event : sorted) {
OutboxRelayResult.Outcome outcome = publishOne(event, now);
outcomes.add(new OutboxRelayResult.EventOutcome(event.eventId(), event.eventType(), outcome));
for (OutboxLease lease : sorted) {
OutboxRelayResult.Outcome outcome = publishOne(lease, now);
outcomes.add(
new OutboxRelayResult.EventOutcome(lease.eventId(), lease.event().eventType(), outcome));
}
return new OutboxRelayResult(claimed.size(), outcomes);
@@ -115,7 +128,8 @@ public class PublishPendingOutboxEventsUseCase
* successful publish is NOT caught — it propagates so the row is recovered via the in-flight
* timeout. See README for both failure modes.
*/
private OutboxRelayResult.Outcome publishOne(ClaimedOutboxEvent event, Instant now) {
private OutboxRelayResult.Outcome publishOne(OutboxLease lease, Instant now) {
ClaimedOutboxEvent event = lease.event();
OutboxPublishOutcome achieved;
try {
// The four-valued call, not the throwing one. An adapter that cannot tell an ambiguous
@@ -124,22 +138,24 @@ public class PublishPendingOutboxEventsUseCase
achieved = publishPort.publishForOutcome(event);
} catch (RuntimeException publishEx) {
// Publish failure: drive FAILED/DEAD state machine + typed report; do NOT rethrow.
return handlePublishFailure(event, now, publishEx);
return handlePublishFailure(lease, now, publishEx);
}
if (achieved == OutboxPublishOutcome.AMBIGUOUS) {
// The message left this process and no acknowledgement arrived, so it may be stored. Treated
// as retryable and reported as such: the duplicate risk is the caller's to bound with an
// idempotency key, and the alternative — parking it — loses a message that was delivered.
return handlePublishFailure(event, now, new OutboxPublishAmbiguousException());
return handlePublishFailure(lease, now, new OutboxPublishAmbiguousException());
}
if (achieved != OutboxPublishOutcome.CONFIRMED) {
// Definite refusal. Retrying the same payload fails the same way, so the attempt budget is
// not spent on it; the row is dead-lettered now rather than after the timer runs out.
return deadLetter(event, new OutboxPublishRefusedException(achieved));
return deadLetter(lease, new OutboxPublishRefusedException(achieved));
}
// markPublished failure (if any) propagates: the row stays IN_FLIGHT and is
// recovered via the orphan visibility-timeout reclaim path.
tx.inWrite(() -> store.markPublished(event.eventId()));
if (tx.inWrite(() -> store.markPublished(lease)) == OutboxCompletion.STALE) {
return stale(lease, OutboxRelayResult.Outcome.PUBLISHED);
}
return OutboxRelayResult.Outcome.PUBLISHED;
}
@@ -149,15 +165,18 @@ public class PublishPendingOutboxEventsUseCase
* failure is contained and cannot change the persisted outcome. See README.
*/
private OutboxRelayResult.Outcome handlePublishFailure(
ClaimedOutboxEvent event, Instant now, RuntimeException cause) {
OutboxLease lease, Instant now, RuntimeException cause) {
ClaimedOutboxEvent event = lease.event();
if (event.attemptCount() >= backoffPolicy.maxAttempts()) {
// All attempts exhausted — DEAD-letter the event.
return deadLetter(event, cause);
return deadLetter(lease, cause);
} else {
// Transient failure — schedule retry with exponential backoff.
Instant nextAttemptAt = backoffPolicy.nextAttemptAt(event.attemptCount(), now);
tx.inWrite(() -> store.markFailed(event.eventId(), nextAttemptAt));
if (tx.inWrite(() -> store.markFailed(lease, nextAttemptAt)) == OutboxCompletion.STALE) {
return stale(lease, OutboxRelayResult.Outcome.FAILED);
}
reportFailure(
() ->
OutboxRelayFailureReport.retryableFailure(
@@ -172,8 +191,11 @@ public class PublishPendingOutboxEventsUseCase
}
}
private OutboxRelayResult.Outcome deadLetter(ClaimedOutboxEvent event, RuntimeException cause) {
tx.inWrite(() -> store.markDead(event.eventId()));
private OutboxRelayResult.Outcome deadLetter(OutboxLease lease, RuntimeException cause) {
ClaimedOutboxEvent event = lease.event();
if (tx.inWrite(() -> store.markDead(lease)) == OutboxCompletion.STALE) {
return stale(lease, OutboxRelayResult.Outcome.DEAD);
}
reportFailure(
() ->
OutboxRelayFailureReport.deadLetter(
@@ -186,6 +208,19 @@ public class PublishPendingOutboxEventsUseCase
return OutboxRelayResult.Outcome.DEAD;
}
/**
* The claim expired and another relay took the row, so this relay's result was not written and
* must not be reported as a transition. The row belongs to the relay that holds it now.
*/
private OutboxRelayResult.Outcome stale(OutboxLease lease, OutboxRelayResult.Outcome attempted) {
try {
failureReporter.reportStaleCompletion(lease.eventId(), lease.event().eventType(), attempted);
} catch (RuntimeException ignored) {
// Diagnostics are non-authoritative, as for reportFailure.
}
return OutboxRelayResult.Outcome.STALE;
}
private void reportFailure(Supplier<OutboxRelayFailureReport> reportFactory) {
try {
failureReporter.report(reportFactory.get());
@@ -1,20 +0,0 @@
package dev.caskeleton.application.outbox.v2;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import java.time.Instant;
import java.util.Objects;
/** Exact canonical event plus mutable delivery ownership and immutable DB creation facts. */
public record ClaimedOutboxDelivery(
OutboxDeliveryOwner owner,
ValidatedIntegrationEvent event,
Instant eventCreatedAt,
Instant deliveryCreatedAt) {
public ClaimedOutboxDelivery {
Objects.requireNonNull(owner, "owner");
Objects.requireNonNull(event, "event");
Objects.requireNonNull(eventCreatedAt, "eventCreatedAt");
Objects.requireNonNull(deliveryCreatedAt, "deliveryCreatedAt");
}
}
@@ -1,70 +0,0 @@
package dev.caskeleton.application.outbox.v2;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import java.util.Objects;
/**
* Owner-safe V2 append intent.
*
* <p>The canonical integration event is the semantic and wire authority. This wrapper exists only
* because the V2 append port returns an owner-safe append receipt; it must not grow a second raw
* event model.
*/
public record NewOutboxEventV2(ValidatedIntegrationEvent event) {
public NewOutboxEventV2 {
Objects.requireNonNull(event, "event");
}
public String eventId() {
return event.eventId().value();
}
public String aggregateType() {
return event.aggregate().aggregateType();
}
public String aggregateId() {
return event.aggregate().aggregateId();
}
public long aggregateVersion() {
return event.order().sequence();
}
public int eventOrdinal() {
return event.order().eventIndex();
}
public String eventType() {
return event.contractId().value();
}
public int eventSchema() {
return event.payloadVersion();
}
public String logicalDestination() {
return event.logicalDestinationId().value();
}
public String partitionKey() {
return event.partitionKeyText();
}
public String contentType() {
return event.contentType();
}
public String correlationId() {
return event.correlationId();
}
public String causationId() {
return event.causationId().orElse(null);
}
public java.time.Instant occurredAt() {
return event.occurredAt();
}
}
@@ -1,9 +0,0 @@
package dev.caskeleton.application.outbox.v2;
/** Conflict-safe result of immutable identity plus event-envelope append. */
public enum OutboxAppendOutcome {
APPENDED,
ALREADY_APPENDED_SAME_EVENT,
EVENT_ID_CONFLICT,
AGGREGATE_ORDER_CONFLICT
}
@@ -1,12 +0,0 @@
package dev.caskeleton.application.outbox.v2;
/**
* Same-store immutable outbox append.
*
* <p>The implementation must participate in the caller's active primary read-write transaction; it
* must never open a repository-local transaction.
*/
public interface OutboxAppendPortV2 {
OutboxAppendReceipt append(NewOutboxEventV2 event);
}
@@ -1,23 +0,0 @@
package dev.caskeleton.application.outbox.v2;
import java.time.LocalDate;
import java.util.Objects;
/** Database-authoritative routing receipt for one immutable event append. */
public record OutboxAppendReceipt(
OutboxAppendOutcome outcome,
String eventId,
LocalDate retentionBucket,
long publicationEpoch,
OutboxDispatchAuthority dispatchAuthority) {
public OutboxAppendReceipt {
Objects.requireNonNull(outcome, "outcome");
Objects.requireNonNull(eventId, "eventId");
Objects.requireNonNull(retentionBucket, "retentionBucket");
Objects.requireNonNull(dispatchAuthority, "dispatchAuthority");
if (publicationEpoch < 1) {
throw new IllegalArgumentException("publication epoch must be positive");
}
}
}
@@ -1,26 +0,0 @@
package dev.caskeleton.application.outbox.v2;
import java.time.Duration;
/** Bounded strict-order polling claim request. */
public record OutboxDeliveryClaimRequest(
String destination, String claimOwner, int batchSize, Duration claimLease) {
public OutboxDeliveryClaimRequest {
if (destination == null || destination.isBlank()) {
throw new IllegalArgumentException("destination must be present");
}
if (claimOwner == null || claimOwner.isBlank() || claimOwner.length() > 128) {
throw new IllegalArgumentException("claim owner must contain 1-128 characters");
}
if (batchSize < 1 || batchSize > 100) {
throw new IllegalArgumentException("batch size must be between 1 and 100");
}
if (claimLease == null
|| claimLease.isZero()
|| claimLease.isNegative()
|| claimLease.compareTo(Duration.ofMinutes(5)) > 0) {
throw new IllegalArgumentException("claim lease must be positive and at most PT5M");
}
}
}
@@ -1,45 +0,0 @@
package dev.caskeleton.application.outbox.v2;
import java.time.LocalDate;
import java.util.Objects;
import java.util.regex.Pattern;
/** Full owner/token/status-version CAS handle for one destination delivery. */
public record OutboxDeliveryOwner(
LocalDate retentionBucket,
String eventId,
String destination,
String claimOwner,
String claimToken,
int attempt,
long version,
long publicationEpoch) {
private static final Pattern CLAIM_TOKEN = Pattern.compile("[0-9a-f]{64}");
public OutboxDeliveryOwner {
Objects.requireNonNull(retentionBucket, "retentionBucket");
requirePresent(eventId, "event ID");
requirePresent(destination, "destination");
requirePresent(claimOwner, "claim owner");
if (claimToken == null || !CLAIM_TOKEN.matcher(claimToken).matches()) {
throw new IllegalArgumentException(
"claim token must be a 64-character lowercase hexadecimal value");
}
if (attempt < 1) {
throw new IllegalArgumentException("attempt must be positive");
}
if (version < 1) {
throw new IllegalArgumentException("version must be positive");
}
if (publicationEpoch < 1) {
throw new IllegalArgumentException("publication epoch must be positive");
}
}
private static void requirePresent(String value, String name) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(name + " must be present");
}
}
}

Some files were not shown because too many files have changed in this diff Show More