review-followup Wave 3 라운드 4(P30): caller 트랜잭션 guard(결정 33), persistence 명시적 조립, 보안 파일 primitive, sample 기능별 패키지

- 결정 33: persistence-notification·persistence-fileserver → persistence-jpa edge, 모든 JPA store 쓰기에 `CallerTransaction.require`
  (그 전에 트랜잭션 밖에서 쓰던 호출자 2곳 수정 — fileserver staging 정리 P30-new-1, 알림 Blocked roll-up P30-new-2)
- objectstorage local-dev provider가 디렉터리 핸들 primitive로만 파일 접근(objectstorage → support edge) — 쓰기 중 상위 디렉터리를
  symlink로 바꾸면 루트 밖에 게시되던 결함 재현 FAIL→PASS
- persistence-jpa 8개 패키지 component scan → 명시적 bean 선언, Mongo 조립의 반복 enabled 스위치 제거(S2-#8a)
- 새 notification 제출은 공용 tenant 문법(저장된 값은 기존 규칙으로 읽음), redis-session이 tenant 저장·복원(snapshot v2, v1 읽기 유지)
- sample 애플리케이션 코드를 worklog·poster·posterimage·event 패키지로, 패키지 순환 금지 테스트

검증: ./gradlew check architectureCheck verifyDependencyLocks verifyPublicPathSnapshot --continue 통과(675 task).
묶음 worktree(같은 기준 커밋)에서 PG lane(jpaPlatformContract 221·Migration 45·fileserver·idempotency·outbox·lock),
Mongo 실제 lane 6개, objectstorage mainCheck(MinIO), sample integration·system·messaging contract, app-bootstrap integrationTest 통과

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
donghyeon-ka
2026-09-29 15:55:12 +09:00
co-authored by Claude Opus 5.5
parent f860e417a1
commit 8bbf1bf01d
183 changed files with 1872 additions and 856 deletions
+1 -2
View File
@@ -5,7 +5,7 @@
# root yet.
# Update only after review with:
# ./gradlew :adapter:outbound:persistence-jpa:updateJpaApiSurface -PapproveJpaApiSurfaceChange
# types: 167
# types: 166
dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName
dev.caskeleton.adapter.outbound.persistence.api.capability.CapabilitySupport
dev.caskeleton.adapter.outbound.persistence.api.capability.JpaCapability
@@ -49,7 +49,6 @@ dev.caskeleton.adapter.outbound.persistence.cache.CacheRegionCatalog
dev.caskeleton.adapter.outbound.persistence.cache.HibernateCacheGuard
dev.caskeleton.adapter.outbound.persistence.cache.HibernateCachePolicy
dev.caskeleton.adapter.outbound.persistence.cache.HibernateCacheSettings
dev.caskeleton.adapter.outbound.persistence.config.JpaAdapterComponentsConfig
dev.caskeleton.adapter.outbound.persistence.config.PersistenceJpaConfig
dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings
dev.caskeleton.adapter.outbound.persistence.envers.EntityRevision
+6
View File
@@ -513,3 +513,9 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap
| `FileserverDownloadLifecycleConfiguration`, `FileserverMaintenanceServiceConfiguration`의 admin 서비스 bean | `src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/` | `36ba0810` | application use case 조립을 composition root(`composition:fileserver-platform`)로 |
| `FileserverUploadServiceConfiguration`(→ `FileserverUploadSupportConfiguration`로 개명, 서비스 bean은 use case 설정으로) | `src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/` | `36ba0810` | 같음 |
| `ca.auxiliary-source-set` 플러그인(`AuxiliarySourceSetPlugin`·`Extension`·`Spec`)과 `AuxiliarySourceSetConventionTest` | `src/build-logic/src/{main,test}/java/dev/caskeleton/buildlogic/auxiliary/` | `4f4bd1fd` | Gradle `jvm-test-suite`로 대체(BUILD-O3-5) |
| `JpaAdapterComponentsConfig` | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfig.java` | `0ebb77b5` | 8개 패키지 `@ComponentScan` → `autoconfigure/JpaAdapterBeansConfig`의 명시적 `@Bean`(S2-#8a, `66263858`) |
| `JpaAdapterComponentsConfigTest` | `src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfigTest.java` | `0ebb77b5` | 스캔 대상 패키지 목록을 고정하던 테스트 — 스캔 삭제로 대상 없음, `JpaAdapterBeansConfigTest`로 대체 |
| `IdempotencyActivationContractTest` | `src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyActivationContractTest.java` | `0ebb77b5` | `IdempotencyReaper` 클래스의 `@ConditionalOnProperty`를 읽던 테스트 — 조건이 bean 설정으로 옮겨가 `IdempotencyReaperWiringTest`(실제 context)로 대체 |
| `PersistenceEntityScanCoverageTest.operationAndLiveEventAdaptersAreScanned` | `src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceEntityScanCoverageTest.java` | `0ebb77b5` | 같은 이유(스캔 목록 고정) — `JpaAdapterBeansConfigTest.everyAdapterTheScanUsedToRegisterIsDeclaredAsABean`로 대체 |
| `MongoPlatformWiringTest.theMappingConfigurationCarriesThePlatformSwitch`·`thePlatformIsOffUnlessTheSwitchIsOn` | `src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformWiringTest.java` | `0ebb77b5` | 반복 스위치를 고정하던 테스트 — 반복 조건을 없애고 ArchUnit 두 규칙으로 대체 |
| `PortfolioEventContracts` | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContracts.java` | `0ebb77b5` | 공유 registry가 `event` → 모든 기능 역방향 의존 — `poster/PosterEventContracts`·`posterimage/PosterImageEventContracts`로 분할, `all()`은 테스트로(S6-#10a, `62a669c8`) |
@@ -690,7 +690,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| X1-지도-자연키 생성-또는-반환 | 권고 | durable operation을 notification 방식(`ON CONFLICT`)으로, upsert executor 삭제 (= E-2) | 완료 | `DurableOperationJpaRepository.java:48` `ON CONFLICT … DO NOTHING`, `DurableOperationStoreAdapter.java:46-58` 삽입 후 재조회, upsert 실행기 7종 삭제(`docs/capability-status.md:158`), 커밋 `6d27356e` | - | - |
| X1-지도-Inbox / 소비자 dedup | 권고 | app-core inbox 삭제, 나머지(messaging inbox·notification ledger) 유지 | 완료 | `application/inbox/`·`PostgreSqlSameStoreInboxAdapter` 삭제(`docs/capability-status.md:155`), mongo change stream dedup 삭제(`:151`); application-core 패키지 목록에 `inbox` 없음, 커밋 `6d27356e` | - | - |
| X1-지도-lock / lease / fencing | 권고 | 미사용 포트·claim executor 삭제, fencing은 contract kit로 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): 소유자 결정 8대로 lock·lease 포트 유지. claim executor·`CacheRefreshCoordinationPort`·`LeaseWatchdog`는 이미 `208077fd`에서 삭제돼 남은 미사용 포트 없음. fencing은 contract kit로(P22 W2 `7f39bfda`): `application-core/src/testFixtures/.../lease/testkit/DistributedLeaseContract.java`(밀려난 holder의 renew·release는 NotOwner이고 후임의 lease를 건드리지 않는다, 같은 attempt 재acquire는 replay, 이중 release는 AlreadyAbsent — 7건)를 fake `InMemoryDistributedLease`(`InMemoryDistributedLeaseContractTest`), Redis 어댑터+in-memory 명령(`RedisDistributedLeaseContractTest`), 실제 Redis(`LiveRedisDistributedLeaseContractTest`, standalone lane)가 모두 통과. lock 포트의 공통 계약(JDBC 어댑터 포함)은 Wave 4 범위로 남김 | - | 결정(2026-09-25): lock·lease 유지, 쓰지 않는 claim executor만 삭제, fencing은 계약 테스트로 |
| X1-지도-caller 트랜잭션 guard | 권고 | 9벌 복사 → persistence-jpa helper 1개 (= E-3) | 남음 | persistence-jpa 복사본 4벌 + guard 없는 곳 10개(세부 X1-#4)<br>Wave 3 W3-P19: 미완 — X1-#4와 같음(persistence-jpa는 완료, notification store 9개는 edge 결정 필요) / 결정 33(2026-09-29): edge 추가로 결정 → P30 | W3 | X1-#4 |
| X1-지도-caller 트랜잭션 guard | 권고 | 9벌 복사 → persistence-jpa helper 1개 (= E-3) | 완료 | Wave 3 W3-P30 (Wave 3 라운드 4 커밋): X1-#4와 같음(커밋 `4de7717d`) — persistence-jpa 4곳은 P19 `080cc6aa`, notification·fileserver store는 이번에 같은 `CallerTransaction` 하나로. 남은 복사본: messaging vendored 2벌(`JdbcOutboxRepository`·`JdbcInboxRepository`, 현황표대로 유지) | - | X1-#4 |
| X1-지도-Backoff 계산식 | 권고 | 10개, "full jitter" 뜻 3가지 → shared-contract `Backoff` | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): X1-#9 | - | X1-#9 |
| X1-지도-Rate limit | 권고 | web 전용 병렬 타입 세트 삭제 (= I-8 일부) | 완료 | `WebRateLimiter`·web `RateLimitDecision`·`RateLimitFailurePolicy`·`WebMvcThrottleFilter` 삭제(`docs/capability-status.md:99`); 남은 경로 `RateLimitWebConfig.java:22` → `EdgeRateLimitTransportBridge` → shared `EdgeRateLimitPort`, 커밋 `6d27356e` | - | - |
| X1-지도-Admission / in-flight | 권고 | 유지하되 gRPC check-then-increment는 `Semaphore`로 (= N-5) | 완료 | Wave 1–2 P5 (fcddab7e·Wave 2 커밋): N-5a와 같은 수정. `Semaphore` 대신 한 락: in-flight와 queued 두 카운터를 한 결정에서 함께 봐야 해서 semaphore 두 개로는 원자적으로 안 된다. `GrpcAdmissionController.java:52`, `GrpcAdmissionControllerTest` | - | X1-#10a |
@@ -714,7 +714,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| X1-#3b | Required | 포트별 contract kit를 소유 leaf testFixtures에 두고 fake와 실제 adapter가 같이 실행 | 남음 | 있음: `DurableOperationStoreContract`, `OutboxLeaseFencingContract`, `GrpcOperationLedgerContract`(grpc-core-api testFixtures), sample `WorkLogRepositoryContract`. 없음: `IdempotencyStorePort`(testFixtures `InMemoryIdempotencyStore`, `RedisIdempotencyStoreAdapter`, `PostgreSqlOwnerSafeIdempotencyStore`가 공통 계약 없이 따로 테스트), `RecipientLeaseStorePort`(PG 전용 `PostgreSqlRecipientLeaseFencingIntegrationTest`만), tus upload, Redis gateway | W4 | application-core testFixtures `IdempotencyStoreContract`(구현 3개 상속), application-notification testFixtures `RecipientLeaseStoreContract`(fake + `JpaRecipientLeaseStore`)부터 추가(`AGENTS.md:218` 기준 5) |
| X1-#3c | Required | `ObjectControlStore` fake 7개 → `@TempDir` 위 `LocalDevObjectControlStore` | 남음 | objectstorage 테스트 source set에 `implements ObjectControlStore` 7개 | W4 | fake 7개를 `LocalDevObjectControlStore`(`@TempDir`)로 교체 |
| X1-#3d | Required | `DistributedLockPortContractTest`가 테스트 안에서 만든 fake를 검증 | 남음 | `application-core/src/test/.../lock/DistributedLockPortContractTest.java:46` `FakeDistributedLockPort` | W4 | X1-#6b 결정에 따라 테스트 삭제, 또는 testFixtures 추상 계약으로 바꿔 `LockRegistryDistributedLockAdapter`가 상속 |
| X1-#4 / S2-#6b | Required | caller 트랜잭션 guard 9벌 복사 → persistence-jpa `CallerTransaction.require` 하나 (= E-3) | 남음 | 복사본 4벌: `OutboxStoreAdapter.java:131`, `DurableOperationStoreAdapter.java:170`, `JpaLiveEventReplayAdapter.java:164`, `IdempotencyCapabilityGuard.java:93`(읽기 전용 변형 `JpaStreamScope.java:28` 별도). guard 0: `CanonicalOutboxAppendAdapter`, notification JPA store 9개(`persistence/notification/platform/*Store.java`, `@Transactional`도 0). messaging 2벌(`JdbcOutboxRepository.java:229`, `JdbcInboxRepository.java:102`)은 vendored라 유지<br>S2-#6b: `persistence-jpa/.../outbox/OutboxStoreAdapter.java:131`, `operation/DurableOperationStoreAdapter.java:170`, `liveevent/JpaLiveEventReplayAdapter.java:164`, `postgresql/idempotency/IdempotencyCapabilityGuard.java:93`; `outbox/CanonicalOutboxAppendAdapter.java`는 guard 0(조용한 dual-write)<br>Wave 3 W3-P19: 미완 — persistence-jpa 복사본 4벌 + 읽기 전용 변형(`JpaStreamScope`, 삭제)은 `CallerTransaction` 하나로 교체(커밋 `080cc6aa`). 남은 것: notification JPA store 9개의 guard — P23에서 `adapter:outbound:persistence-notification` leaf로 추출됐고 그 leaf의 허용 edge는 application-core·application-notification뿐이라 persistence-jpa `CallerTransaction`을 쓸 수 없다. 사유: 결정 필요 — persistence-notification에 persistence-jpa(또는 adapter:outbound:support로 guard 이동 후 support) edge를 줄지. 새 복사본을 만들지 않았다. 승인자: 저장소 소유자 결정 필요 / 결정 33(2026-09-29): edge 추가로 결정 → P30 | W3 | persistence-jpa `transaction` 패키지에 `CallerTransaction.require(String op)` 추가, 복사본 4곳 교체 + `CanonicalOutboxAppendAdapter.append`와 notification store 9개의 쓰기 메서드에 호출 추가<br>S2-#6b: persistence-jpa에 `CallerTransaction.require(op)` 하나 두고 4곳 교체 + `CanonicalOutboxAppendAdapter.append`에 적용 |
| X1-#4 / S2-#6b | Required | caller 트랜잭션 guard 9벌 복사 → persistence-jpa `CallerTransaction.require` 하나 (= E-3) | 완료 | Wave 3 W3-P30 (Wave 3 라운드 4 커밋): 커밋 `4de7717d`(결정 33). registry `adapter-outbound-persistence-notification`·`adapter-outbound-persistence-fileserver` → `adapter-outbound-persistence-jpa` edge 추가, 두 leaf `build.gradle`에 `implementation project(':adapter:outbound:persistence-jpa')`(+ lockfile 재작성). 복사본 guard는 두 leaf에 없었음(새로 만들지 않음) — 모든 JPA store 쓰기 메서드 첫 줄이 `CallerTransaction.require("<store> <method>")`: notification `JpaAdminOperationStore`·`JpaContactPointStore`·`JpaDeliveryAttemptStore`·`JpaNotificationRequestStore`·`JpaNotificationSideEffect`·`JpaPolicyStores`(Preferences·Consents·DeduplicationClaims)·`JpaProviderEventLedger`·`JpaRecipientDeliveryStore`·`JpaRecipientLeaseStore`(renew·release·expireOverdue)·`JpaSuppressionStore`·`JpaTemplateRegistry`·`inbox/JpaNotificationInbox`; fileserver `JpaCleanupQueue`·`JpaFileMetadata`·`JpaFileQuota`·`JpaQuotaCommit`·`JpaQuotaReclaim`·`JpaRecoveryQueue`·`JpaUploadSession`. **guard 없음(의도):** `JpaRecipientLeaseStore.claim` — 스케줄러(`NotificationSchedulerWorker.java:79`)가 use case 전에 부르는 단일 CTE(선택·잠금·fence를 한 문장으로)라 함께 원자적이어야 할 두 번째 쓰기가 없음(주석으로 명시); `JdbcReconciliationJobStore`는 JDBC(워커가 트랜잭션 없이 claimDue/reschedule/complete)라 대상 밖. 호출자 감사(모든 쓰기 메서드의 production 호출자가 `inWrite`/`inNew` 안인지)로 트랜잭션 밖 호출 2곳을 찾아 먼저 고침 — 아래 P30-new-1·P30-new-2. **재현(실제 store, 실제 PG):** `PostgreSqlFileserverMetadataStoreIntegrationTest.aMetadataInsertOutsideACallerTransactionIsRefused` FAIL(`Expecting actual not to be null` — 트랜잭션 밖 insert가 그대로 커밋) → PASS, `PostgreSqlNotificationBackgroundPassIntegrationTest.aRecipientTransitionOutsideACallerTransactionIsRefused` FAIL(같은 메시지) → PASS. 비Spring `EntityManager.getTransaction()`으로 store를 부르던 PG 테스트 2개(`PostgreSqlRecipientLeaseFencingIntegrationTest`, `PostgreSqlNotificationPersistenceUnitIntegrationTest.adminClaimCompletesInPlaceAndReplays`)는 guard가 볼 수 없는 트랜잭션이라 production처럼 `JpaTransactionManager` + shared EntityManager로 바꿈(스케줄러처럼 트랜잭션 밖 `claim`도 shared EM에서 PASS 확인). 검증: `postgresqlFileserverMetadataIntegrationTest` 16, `postgresqlFileserverReclamationIntegrationTest` 15, `jpaPlatformContractTest` 221, `jpaPlatformMigrationTest` 45 전부 PASS; persistence-notification·persistence-fileserver·persistence-jpa·application-notification(223)·application-fileserver(267)·adapter:outbound:notification·adapter:outbound:fileserver·web-fileserver·web-notification·composition fileserver/notification `check` PASS | - | persistence-jpa `transaction` 패키지에 `CallerTransaction.require(String op)` 추가, 복사본 4곳 교체 + `CanonicalOutboxAppendAdapter.append`와 notification store 9개의 쓰기 메서드에 호출 추가<br>S2-#6b: persistence-jpa에 `CallerTransaction.require(op)` 하나 두고 4곳 교체 + `CanonicalOutboxAppendAdapter.append`에 적용 |
| X1-#5 | Required | web 병렬 rate-limit 타입·throttle filter 삭제 (= I-8 일부) | 완료 | `docs/capability-status.md:99-100`, `WebRateLimiter`·`WebMvcThrottleFilter`·`ThrottleProblemWriter` main 참조 0, 남은 경로 `RateLimitWebConfig.java:22` → `EdgeRateLimitPort`, 커밋 `6d27356e` | - | - |
| X1-#6a | Required | 범용 claim executor(`PostgreSqlWorkClaimExecutor`·`WorkQueue*`) 삭제 | 완료 | `docs/capability-status.md:157`, main 참조 0, 커밋 `6d27356e` | - | - |
| X1-#6b | Required | lock과 lease 중 하나만 남김 | 남음 | `DistributedLockPort`(구현 `LockRegistryDistributedLockAdapter`, 참조는 `StartupSafetyValidator.java:51` 존재 검사뿐), `DistributedLeasePort`(구현 `RedisDistributedLeaseAdapter`, 소비자 0). `CacheRefreshCoordinationPort`는 삭제(`docs/capability-status.md:152`). `LeaseAttempt`·`IdempotencyClaimAttempt` 같은 구조 그대로 | W4 | 결정(2026-09-25): lock·lease 둘 다 유지(S1-#3b와 같은 작업) |
@@ -821,7 +821,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S2-#6a | Required | owner-lease claim 절차·`digestFields` 복사(inbox·polling) | 해당 없음(코드 삭제) | `PostgreSqlSameStoreInboxAdapter`·`PostgreSqlPollingDeliveryAdapter`·`PostgreSqlImmutableOutboxAppendAdapter` 삭제(「제거된 코드」 same-store inbox, JPA outbox V2 adapter 행). claim 절차는 멱등성 store에만 남음 | - | - |
| S2-#6c | Required | `capability_schema_registry` 확인 SQL 복사 | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): 추출 뒤 persistence-jpa 안의 `capability_schema_registry` 확인 SQL은 `PostgreSqlOwnerSafeIdempotencyStore.java:66` 하나뿐. notification 사본(`persistence-notification/.../NotificationSchemaActivation.java:29`)은 fileserver와 같은 처지(jpa edge 없는 capability leaf)가 되어 행의 "fileserver는 자기 사본 유지" 규칙을 그대로 따름. 두 capability의 공용화(support로)는 P18(idempotency 이동)·P24(fileserver)와 겹쳐 이번에 하지 않음 | - | persistence-jpa 안 2곳은 `CapabilitySchemaRequirement` record 하나로, fileserver는 jpa edge가 없어 자기 사본 유지(또는 support로) |
| S2-#7 | Required | JPA 플랫폼 라이브러리가 지원 표면 밖 | 완료 | 단일 구현 인터페이스 8개 grep 0(「제거된 코드」 work-claim·upsert 실행기, 단일 구현 인터페이스 행), 남은 라이브러리는 소유자 결정(Wave 3)대로 `adapter/outbound/persistence-jpa/README.md:61` 라이브러리 API 표에 명시. main 26.3k→20.0k줄 | - | - |
| S2-#8a | Consider | 조립 방식 3가지, 게이트 반복 | 남음 | `persistence-jpa/.../config/JpaAdapterComponentsConfig.java`(스캔 stereotype 16개), `notification/configuration/NotificationJpaPersistenceFacade.java`, `persistence-fileserver/.../FileserverJpaPersistenceConfig.java` + fileserver main `@ConditionalOnProperty` 10개, Mongo 6개<br>Wave 3 W3-P23: 미완 — 이유: 알림은 이미 feature config의 명시적 `@Bean` 한 방식(`NotificationJpaPersistenceFacade`, 이번에 이 leaf의 auto-configuration root로). 남은 대상 — `JpaAdapterComponentsConfig`의 stereotype 스캔(outbox·idempotency·lock 등), `persistence-fileserver`의 `@ComponentScan`+클래스별 `@ConditionalOnProperty`, Mongo — 은 동시에 도는 P18(outbox·멱등성 패키지 이동)·P24(fileserver)가 같은 파일을 옮기고 있어 충돌을 피해 손대지 않음. 통합 뒤 한 묶음으로<br>Wave 3 W3-P28: 미완 — 한 것(P28 W3 `537310f9`): persistence-fileserver의 `@ComponentScan` + store 9개 클래스별 `@Repository`·`@ConditionalOnProperty`를 없애고, 조건 한 곳(`FileserverJpaPersistenceConfig`, 이 leaf의 `AutoConfiguration.imports` root) + 명시적 `@Bean` 설정 둘(`FileserverJpaMetadataStoreConfig`·`FileserverJpaQueueStoreConfig`)을 `@Import` — notification(`NotificationJpaPersistenceFacade`)과 같은 방식. web-fileserver 컨트롤러 4개·예외 처리기가 조립 root가 이미 거는 `app.fileserver-platform.enabled`를 반복하던 것 삭제(tus·draft12·admin은 자기 스위치만). 검증: persistence-fileserver·web-fileserver·composition fileserver `check`, PG lane `postgresqlFileserver{Metadata,Reclamation}IntegrationTest` 15·15, `FileserverCompositionIntegrationTest` 3 PASS. 남은 것: persistence-jpa `JpaAdapterComponentsConfig`의 8개 패키지 stereotype 스캔. 이유: 스캔이 있는 까닭이 이 leaf의 패키지 경계 목록(`JpaModuleBoundaryTest.PACKAGE_CATALOG`)이 `config`/`autoconfigure` → `audit`·`failure`·`liveevent`·`lock`·`operation`·`outbox` edge를 허용하지 않기 때문이다 — 명시적 `@Bean`으로 바꾸려면 (a) `autoconfigure`에 6개 edge를 추가하거나 (b) 패키지마다 capability 스위치를 반복하는 auto-configuration을 두어야 해서 leaf 내부 모듈 지도 결정이 먼저다(`JpaAdapterComponentsConfigTest`·`PersistenceEntityScanCoverageTest`가 스캔 계약을 고정). Mongo는 이미 자기 `AutoConfiguration.imports` 둘 + `@Bean` 방식이라 변경 없음(남은 것은 `MongoPlatformAutoConfiguration`의 bean별 조건 반복 19개) | W3 | feature config별 명시적 `@Bean` 한 방식으로, 클래스별 stereotype·조건 제거 |
| S2-#8a | Consider | 조립 방식 3가지, 게이트 반복 | 완료 | Wave 3 W3-P30 (Wave 3 라운드 4 커밋): 커밋 `66263858`·`792cfd9a`. **persistence-jpa:** `config/JpaAdapterComponentsConfig`(8개 패키지 `@ComponentScan`) 삭제 → `autoconfigure/JpaAdapterBeansConfig`(package-private, `PersistenceJpaAutoConfiguration`만 `@Import`)가 bean을 하나씩 선언: `StandardSqlStateErrorMapping`·`PersistenceExceptionTranslator`·`SpringTransaction`·`DomainContextAuditContext`·`JpaDurableOperationStore` + 스위치별 nested 설정 `Outbox`(`JpaOutboxStore`·`OutboxReaper`, outbox 스위치 한 번)·`LiveEventReplay`(`JpaLiveEventReplay`, replay·vendor 조건 한 번) + `DistributedLockPersistenceConfig` import; `IdempotencyReaper`는 nested `IdempotencyExpiry`(provider=postgresql 조건 한 번; 처음엔 `PostgreSqlIdempotencyStoreConfig`에 두었다가 그 설정이 JPA 없이 조립되는 sample `SampleIdempotencyReplayIntegrationTest`가 깨져 후속 커밋 `792cfd9a`로 옮김). 10개 클래스에서 `@Component`/`@Repository`·클래스별 `@ConditionalOnProperty`·생성자 `@Value` 제거(키는 bean 메서드로 옮겼을 뿐 이름 그대로). P28이 막힌 지점(패키지 지도): `JpaModuleBoundaryTest.PACKAGE_CATALOG`의 `autoconfigure`에 `audit`·`failure`·`liveevent`·`lock`·`operation`·`outbox` edge 6개 추가(선택지 (a) — leaf의 조립 root가 자기가 만드는 것을 이름으로 안다; 역방향 edge 없음, DAG 테스트 통과). 새 공개 타입 없이(설정은 package-private) JPA API surface는 `JpaAdapterComponentsConfig` 1개 제거로 재승인(`updateJpaApiSurface -PapproveJpaApiSurfaceChange`). 테스트: `JpaAdapterBeansConfigTest`(`everyAdapterTheScanUsedToRegisterIsDeclaredAsABean`, ArchUnit `noProductionClassCarriesAScanStereotype`), 스캔 계약을 고정하던 `JpaAdapterComponentsConfigTest`·`PersistenceEntityScanCoverageTest.operationAndLiveEventAdaptersAreScanned`·`IdempotencyActivationContractTest` 삭제/대체(`IdempotencyReaperWiringTest.thePostgresqlSelectionHasTheExpiredRecordReaper`·`otherSelectionsHaveNoReaper`), `OutboxReaperWiringTest`·`OutboxSwitchWiringContractTest`·`JpaLiveEventReplayActivationTest`는 nested 설정을 보도록 `autoconfigure` 테스트 패키지로 이동. `:adapter:outbound:persistence-jpa:check` 497 PASS. **Mongo:** root(`MongoRootAutoConfiguration`)가 import하는 5개 설정(`MongoPersistenceConfig`·`MongoPlatformAutoConfiguration`·`MongoDriverObservabilityAutoConfiguration`·`MongoMappingConfiguration`·`MongoPlatformHealthConfiguration`)에서 반복된 `ca-skeleton.persistence-mongo.enabled` 조건 4벌과 `@Configuration` stereotype을 제거 — `@Import`는 stereotype 없는 클래스도 설정으로 처리하므로 조립은 같고, 스캔이 이 leaf에 닿아도 root(스위치 보유) 말고는 등록할 것이 없다(반복 조건이 있던 이유 자체를 구조로 없앰). `MongoPlatformWiringTest`의 반복 조건 고정 테스트 2개를 ArchUnit `everyClassAScanCouldRegisterCarriesTheMongoSwitch`·`theImportedConfigurationsCarryNoStereotype`로 교체. bean별 `@ConditionalOnMissingBean`(override 지점)은 라이브러리 계약이라 유지. `:adapter:outbound:persistence-mongo:check` 78 PASS, 실제 lane `mongoStableContractTest` 465·`mongoReplicaSetTest` 7·`mongoMigrationTest` 9·`mongoCompatibilityTest` 2·`mongoSecurityIntegrationTest` 10·`mongoFailoverTest` 6 PASS(`mongoPerformanceTest`는 성능 lane이라 실행 안 함). 남은 문서: `docs/study/postgresql-jpa-walkthrough.ko.md`가 삭제된 `JpaAdapterComponentsConfig`를 설명(Wave 5 문서 갱신 대상, 손대지 않음) | - | feature config별 명시적 `@Bean` 한 방식으로, 클래스별 stereotype·조건 제거 |
| S2-#8b | Consider | "두 조립 루트가 `dev.caskeleton.adapter`를 스캔한다" 서술이 사실과 다름 | 남음 | `persistence-jpa/.../postgresql/idempotency/PostgreSqlOwnerSafeIdempotencyStore.java:53`, `src/test/.../CandidateAdapterCompositionTest.java:10-18`(현재 `CaSkeletonApplication`은 scan 제외식 없음, sample은 `SamplePortfolioApplication.java:31-40`처럼 좁게 스캔) | W5 | 잘못된 단락 삭제, 전제가 사라진 `CandidateAdapterCompositionTest` 삭제 또는 현재 조립 기준으로 재작성 |
| S2-#9a | Consider | 무관한 `inbox` 패키지 2개 | 해당 없음(코드 삭제) | `postgresql/inbox` 삭제(「제거된 코드」 same-store inbox 행) | - | - |
| S2-#9b | Consider | feature가 vendor별로 흩어짐 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): 이동만 했다(`910ab7ab`). 새 패키지는 `persistence/outbox/{jpa(+entity),postgresql,h2}`, `persistence/idempotency/{jpa(+entity),postgresql}`다. JPA API surface는 `updateJpaApiSurface -PapproveJpaApiSurfaceChange`로 다시 승인했다. `JpaModuleBoundaryTest`에 autoconfigure→idempotency edge를 기록했다. `verifyJpaApiSurface`·`verifyJpaReadinessRegistry` PASS. | - | feature 기준 패키지(`outbox/{jpa,postgresql,h2}`, `idempotency/{jpa,postgresql}`)로 이동만 |
@@ -907,7 +907,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S4-#17a | Nit | fileserver `*Config`/`*Configuration` 혼재, 클래스 이름의 버전 라벨 | 해당 없음(코드 삭제) | 루트 `*Config`(`FileserverR2Config` 등)와 `R2PublishedReferenceCodec` 삭제. 남은 fileserver 설정 8개는 모두 `*Configuration` | - | - |
| S4-#17b | Nit | notification `*ProviderProperties`는 `@ConfigurationProperties`가 아닌 파생 값 | 남음 | `Apns`/`Fcm`/`Ses`/`Smtp`/`Twilio`/`WebPushProviderProperties` 6개. 어느 것도 `@ConfigurationProperties`가 아님 | W5 | #3a 이후 남는 `Ses`·`SmtpProviderProperties`를 `*ProviderProfile`로 이름 변경 |
| S4-lead-1 | 권고 | 손으로 만든 canonical JSON codec이 3개 leaf에 있음 (= X1-8) | 해당 없음(코드 삭제) | fileserver 2벌·messaging `DeterministicEnvelopeWriter` 삭제. 남은 건 objectstorage `control/CanonicalJson{Reader,Writer}.java` 하나라 중복 아님 | - | - |
| S4-lead-2 | 권고 | 로컬 보안 파일시스템 primitive가 fileserver·objectstorage에 따로 있음 | 남음 | fileserver `platform/local/SafeFileChannelFactory.java:250`(`SecureDirectoryStream`)·`SecureDirectoryWalk.java`. objectstorage `filesystem/LocalObjectPathGuard.java:62-117`은 경로 검사 후 사용 방식(`rejectExistingLinks` → 생성). 방식과 검사가 다름. objectstorage는 `adapter-outbound-support` edge가 없음<br>Wave 3 W3-P24: 미완 — 이유: fileserver primitive 중 `SecureDirectoryWalk`는 JDK만 쓰지만 `SafeFileChannelFactory`는 `IOException`을 Fileserver 에러 코드로 바꾸는 번역을 품고 있어, support로 올리려면 에러 어휘를 떼어 내야 한다. 그리고 objectstorage `LocalObjectPathGuard`는 Path를 돌려주고 호출자(`LocalDevObjectDataStore`·`LocalDevObjectControlStore`·`LocalObjectStreamTransfer`, 약 520줄)가 `Files.*`로 여는 구조라, primitive를 쓰려면 이 I/O를 fd 기준(`SecureDirectoryStream`) 연산으로 다시 써야 한다. registry edge 추가만으로는 끝나지 않는 보안 민감 재작성이라 별도 묶음(권고 행)으로 남김<br>Wave 3 W3-P28: 미완 — 한 것(P28 W3 `da49df6c`): fileserver의 descriptor 기반 primitive를 `adapter/outbound/support/.../support/filesystem/SecureDirectoryWalk.java`(이동, public)·`SecureFileAccess.java`(신규: createNew·openForRead/Write·deleteRegularFile·readAttributes·isRegularFile·createParentDirectories)로 올리고, 거부를 에러 코드 없는 타입 있는 `IOException`(`SymbolicComponentException`·`PathEscapeException`·`NotRegularFileException`)으로. fileserver `SafeFileChannelFactory`는 위임 + `LocalStorageFailures` 번역만(P24 메모대로 번역 분리). 테스트: `SecureFileAccessTest` 8건(symlink leaf·symlink 디렉터리 component·`..` 탈출·create-only 충돌·symlink delete 거부·열린 뒤 디렉터리를 link로 바꾸는 race `aDirectorySwappedForALinkAfterItWasOpenedDoesNotRedirectTheOperation`), `SecureDirectoryWalkTest` 2건(support로 이동), `LocalStorageFailuresTest` 2건 FAIL→PASS(P28-new-1). fileserver·support `check`, PG lane `postgresqlFileserver{Migration,Metadata,Reclamation}IntegrationTest` 6·15·15 PASS. 남은 것: objectstorage `LocalObjectPathGuard`를 이 primitive로 바꾸는 재작성(과 objectstorage→support registry edge). 이유: local-dev provider의 쓰기는 "없거나 완전한" 게시를 위해 임시 파일을 `Files.createLink`(link(2))로 create-only 연결하는데, `SecureDirectoryStream`에는 linkat이 없고 `move`는 기존 대상을 덮어쓴다(renameat2 NOREPLACE 미노출). descriptor 기반으로 바꾸면 create-only 원자 게시를 잃거나(대상 선점 후 덮어쓰기 — 읽는 쪽이 빈/부분 객체를 볼 수 있음) native 호출이 필요해 설계 결정이 먼저다. 읽기·retire 경로만 바꾸면 쓰기 경로의 race가 남아 "한 primitive"가 되지 않으므로 이번 묶음에서는 손대지 않음(대상은 local-dev 전용 provider) | W3 | fileserver 쪽 primitive를 `adapter:outbound:support`로 올리고, objectstorage에 support edge를 추가해서 `LocalObjectPathGuard`가 그것을 쓴다(registry 수정 포함) |
| S4-lead-2 | 권고 | 로컬 보안 파일시스템 primitive가 fileserver·objectstorage에 따로 있음 | 완료 | Wave 3 W3-P30 (Wave 3 라운드 4 커밋): 커밋 `33a9528b`. `objectstorage/.../filesystem/LocalObjectPathGuard.java`는 키→경로를 어휘적으로만 풀고(경로로는 아무것도 열지 않음), 열기(`openForRead`)·임시 파일 생성(`createTemporaryFile`→`SecureFileAccess.createNew`)·권한(`makeReadOnly`)·게시(`publishExclusive`/`replace`)·삭제(`deleteRegularFile`)는 전부 `adapter:outbound:support`의 `SecureFileAccess`/`SecureDirectoryWalk`(P28이 올린 primitive)로. `LocalDevObjectDataStore`·`LocalDevObjectControlStore`·`LocalObjectStreamTransfer`는 Path 대신 열린 `FileChannel`을 쓴다; `transfer`는 사전조건(길이·digest) 검사와 읽기를 한 descriptor로 한다(이전: `inspect`가 열고 닫은 뒤 경로로 다시 엶). registry `adapter-outbound-objectstorage` → `adapter-outbound-support` edge 추가(+ leaf CLAUDE.md 허용 목록). **P28이 막힌 지점(create-only 게시)의 해법:** JDK에 `linkat`·`renameat2(NOREPLACE)`가 없어, 검증된 대상 부모 descriptor 하나를 잡은 채 부재 확인 → descriptor 기준 rename을 JVM 내 key stripe lock 안에서 한다. provider는 이미 단일 프로세스로 선언돼 있어(`LocalDevObjectStorageProvider` javadoc "Bounded single-process", `MULTI_NODE_LINEARIZABLE_CAS` UNSUPPORTED, control store "does not claim multi-node linearizability") 같은 root를 공유하는 두 프로세스 사이 create-only는 주장하지 않는다(이전 link(2)는 프로세스 간에도 배타적이었음 — local-dev 전용이라 수용, 다르게 원하면 소유자 결정). 디렉터리 생성은 JDK에 `mkdirat`이 없어 경로 기반 그대로(링크 거부 후 mkdir) — 그 경로로 여는 것은 없다. **테스트(먼저 작성, 기존 코드로 실행):** `LocalDevObjectStorageConfinementTest` 6건 — `aDataKeyThatClimbsOutOfTheRootIsRefused` PASS, `anObjectWhoseParentDirectoryIsASymbolicLinkIsNotReadThroughIt` PASS, `aSymbolicLinkLeafIsNeverFollowedOnRead` PASS, `retiringThroughALinkedParentDeletesNothingOutsideTheRoot` PASS, `aControlRecordThatIsASymbolicLinkIsNotRead` PASS, **`aParentDirectorySwappedForALinkWhileTheObjectIsWrittenDoesNotPublishOutsideTheRoot` FAIL**(`Expecting actual: ["0000000000000004", "moved"] to contain exactly: ["moved"]` — 쓰는 동안 부모를 링크로 바꾸자 root 밖에 객체가 게시됨) → 변경 후 6건 PASS. 읽기 쪽 TOCTOU는 결정적으로 끼워 넣을 hook이 없어 테스트 대신 구조(한 descriptor로 검사+읽기)로 막음. 검증: `:adapter:outbound:objectstorage:check` PASS, `mainCheck`(`objectStorageMinioContractTest` 1, `objectStorageMinioFaultTest` 6) PASS, lock 변화 없음 | - | fileserver 쪽 primitive를 `adapter:outbound:support`로 올리고, objectstorage에 support edge를 추가해서 `LocalObjectPathGuard`가 그것을 쓴다(registry 수정 포함) |
| S4-lead-3 | 권고 | notification 자체 JDK HTTP gateway·SigV4 서명기 vs httpclient leaf·AWS SDK | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): 소유자 결정 17. `SesNotificationProviderAdapter.java:113` `client.sendEmail`(AWS SDK v2 `sesv2` 2.30.0, 카탈로그 `awsSdk`·SDK BOM, objectstorage와 같은 버전). client는 `SesClients.java`: SDK 재시도 끔(`:54` `AwsRetryStrategy.doNotRetry()`), 기본 자격 증명 체인 대신 던지는 provider, 설정 endpoint(라우팅 가드 통과)를 `endpointOverride`, Apache client(redirect 안 따라감). 자격 증명은 기존 계약 유지(설정 `access-key-id` + `ProviderCredentialManager`의 프로필·세대별 secret)로 요청마다 `AwsRequestOverrideConfiguration`에 실음. `JdkNotificationHttpGateway`·`NotificationHttpGateway/Request/Response/TransportException`·`AwsSignatureV4Signer`·`notificationHttpGateway` bean 삭제. SNS 인증서 fetch는 callback 설정 안의 redirect 없음·64KiB 상한 JDK 요청. 검증: SDK client를 로컬 HTTP 가짜(`ProviderFaultHarness`)에 `endpointOverride`로 붙인 계약 테스트 `SesNotificationProviderAdapterTest` 17건(수락·거절·응답 유실=AMBIGUOUS·throttle·첨부 raw MIME·프로필별 서명·경로 `/v2/email/outbound-emails`) + 새 `theSdkRetriesNothingSoAServerErrorIsOneRequest`·`aMessageRejectedAnswerIsAPermanentRejection` PASS, `CrossProviderContractSuiteTest` 5건 PASS. env 키·설정 키 변경 없음 | - | 결정(2026-09-25): AWS SDK(sesv2)로 교체, 자체 JDK gateway·SigV4 서명기 삭제 |
| S4-lead-4a | 권고 | adapter `LocalJsonSchemaRegistry` vs vendored `messaging-schema-json` | 해당 없음(코드 삭제) | `LocalJsonSchemaRegistry` grep 0건. 「제거된 코드」 표 123행 | - | - |
| S4-lead-4b | 권고 | `adapter:outbound:messaging-kafka`(R0 seam) vs vendored `messaging/messaging-kafka` | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **삭제:** `core/MessageBroker` 계열(MessageBroker, MessagePublisher, OutboundMessage, OutboundMessagePublisher, DisabledMessagePublisher)과 `OutboxEnvelopeJson`, `adapter:outbound:messaging-kafka`의 Java 코드 전부.<br>**relay 경로:** relay는 claim한 row의 `ValidatedIntegrationEvent`를 bridge로만 보낸다(`OutboxMessagePublishAdapter(IntegrationEventPublishPort)`, `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapter.java:23`).<br>**leaf를 남긴 이유:** 계획은 leaf 삭제였다. 대신 bridge+starter-kafka를 싣는 코드 없는 capability 묶음으로 남겼다. 한 줄 선택이 유지되고, bridge leaf는 broker 중립으로 남는다.<br>**테스트:** `KafkaCapabilityActivationTest` PASS. | - | legacy `OutboxEvent`에 canonical metadata를 채우는 migration 후 relay를 bridge로 바꾸고 `adapter:outbound:messaging-kafka`와 `core/MessageBroker` 계열 삭제 |
@@ -982,7 +982,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S6-#7 | Required | sample이 bootstrap 인프라를 복사, 이미 갈라짐 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **새 leaf `composition:service-runtime`**(`dev.caskeleton.composition.runtime`, edge application-core, shared-contract, adapter-outbound-support, adapter-outbound-identifier):<br>- 원본을 app-bootstrap에서 옮겼다: `tracing`(TracingConfig 외 5), `metrics`(MetricsContractConfig+filter 2), `context`(DomainContextConfig/Settings), `logging`(PseudonymizationConfig, PrivacySettings), `management/security`(ManagementSecurityConfig).<br>- 모두 이 모듈의 `AutoConfiguration.imports`로, sampling bridge는 `spring.factories`로 등록한다.<br>- app-bootstrap과 sample이 `runtimeOnly project(':composition:service-runtime')`를 쓴다.<br>**sample:** 복사본 10개와 `spring.factories`를 삭제했다. 원본을 쓰므로 `staging=0.10` 분기도 사라졌다.<br>**sample actuator chain:** 복사본이 아니라 공개 데모라는 샘플만의 결정이라 남겼다. bean 이름을 `actuatorSecurityFilterChain`으로 바꿔 공용 chain이 물러나게 했다(`ConditionalOnMissingBean(name)`).<br>**테스트:** `ServiceRuntimeRegistrationTest` 4개(신규), 옮긴 테스트 9 클래스 — `:composition:service-runtime:test` 86 PASS. `ActuatorSecurityHttpTest`, `DefaultCompositionBootTest`, `StartupOrderContractTest`, `ConfigurationNamespaceContractTest` 갱신 후 PASS. | - | 소유자 결정대로 멱등성 executor·outbox relay 조립을 `composition:*` 모듈로 옮겨 두 root가 함께 쓰고, tracing·logging·metrics·context·management는 공용 library leaf로(registry edge 추가), staging 분기 삭제 |
| S6-#8 | Required | sample root가 다른 leaf 패키지를 넓게 scan | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `SamplePortfolioApplication`: `@ComponentScan("dev.caskeleton.sample")`·`@ConfigurationPropertiesScan("dev.caskeleton.sample")`, 제외는 `WebSecurityAutoConfiguration` 하나(`SamplePortfolioApplication.java:31-32`). web·objectstorage는 각 auto-config로. `SamplePublicAccessSecurityConfigTest.sampleCompositionRootExcludesOnlyTheWebSecurityRoot`·`sampleCompositionRootScansOnlyTheSamplePackage`(옛 exclude-filter 단언 대체). sample `test`·`integrationTest` 51·`systemTest` 3·`webSystemTest` 5 PASS | - | scan을 `dev.caskeleton.sample`로 좁히고 web·identifier·objectstorage는 각 leaf auto-config로 받기(보안 설정 2개는 exclude/property로 끔) |
| S6-#9 | Required | sample `application.yml` 중 읽는 코드 없는 블록 | 남음 | 326줄 중 약 101줄: `src/sample-portfolio/src/main/resources/application.yml:150-177`(capabilities.cache), `:180-181`(bootstrap), `:210-226`(logging), `:255-279`(app.cache.redis), `:280-283`(messaging), `:284-288`(notification), `:289-308`(outbound.http). sample classpath에 해당 binder 없음(`src/sample-portfolio/build.gradle:48-83`) | W5 | 해당 블록 삭제 |
| S6-#10a | Consider | sample 대표 예제가 poster-image에 묻힘, 패키지 종류별·기능별 혼재 | 남음 | poster 관련 main 약 5.9k줄 vs WorkLog 약 2.2k줄. `SP/application/`에 `command/query/event/port/exception`과 `poster/posterimage/worklog` 공존<br>Wave 3 W3-P25: 미완 — 이유: 기능별 패키지 재배치와 poster-image 별도 sample 모듈 분리는 sample 전체 파일 이동(+`modules.json` leaf 등록)이라, 동시에 도는 P18(sample outbox·멱등성·`PosterEventPublisher`)·P24(object storage)와 같은 파일을 대량으로 겹친다. 통합 뒤 단독 작업으로 넘김. 이번 묶음에서 legacy 모드 삭제(S6-#10b)로 poster 표면은 줄었다<br>Wave 3 W3-P28: 미완 — / P28 에이전트가 세션 재시작으로 중단(미커밋) — P30으로 | W3 | 기능별 패키지로 정리, poster-image는 objectstorage 검증용 별도 sample 모듈로 이동 |
| S6-#10a | Consider | sample 대표 예제가 poster-image에 묻힘, 패키지 종류별·기능별 혼재 | 완료(패키지 재배치; 모듈 분리는 하지 않음) | Wave 3 W3-P30 (Wave 3 라운드 4 커밋): 커밋 `62a669c8`. `sample-portfolio/.../application/`이 종류별(`command`·`query`·`exception`·`port`·`event`) + 기능별 혼재에서 기능별 3개 + 공유 1개로: `worklog`(23 파일 — use case·command·query·예외·`RepoStatsPort`·`WorkLogSummaryQueryPort`·`WorkLogReserved*` payload), `poster`(20 — lifecycle use case·command·query·예외·`PosterEventPublisher`·payload·`PosterEventContracts`), `posterimage`(40 — 이미지 use case 6개를 `poster`에서 옮김, command·query·예외·이미지 이벤트·`PosterImageEventContracts`), `event`(2 — 기능이 공유하는 `PortfolioEventContract`·`PortfolioEventOutbox`). 공유 registry `PortfolioEventContracts`는 `event` → 모든 기능의 역방향 edge라 기능별 상수 클래스로 나누고, 전체 목록(`all()`, main 호출자 0)은 그것을 쓰던 `PortfolioEventContractsTest`로. `posterimage` → `poster` edge(`PosterEventPublisher.AGGREGATE_TYPE`)는 상수를 이미지 쪽에 두고 `PosterImagePublicationEventPublisherTest.imageEventsAreOrderedOnThePostersOwnStream`로 같음 고정. 가드: `SampleArchitectureTest.applicationFeaturePackagesAreFreeOfCycles`(ArchUnit slices). 테스트도 대상과 같은 패키지로 이동, `messagingSampleContractQualificationTest` lane의 클래스 이름·README·CLAUDE.md 갱신. **poster-image 별도 sample 모듈:** 하지 않음(작게 판단) — `DeletePosterUseCase`가 이미지 retirement(`RetirePosterImageUseCase`)를 같은 트랜잭션에서 부르고 도메인 `PosterImageAttachment`가 `Poster` 애그리거트 안에 있어, 모듈로 떼면 poster → 이미지 seam(포트)과 registry leaf·조립이 새로 필요하다. 패키지 경계(순환 없음)로 먼저 고정. 검증: `:sample-portfolio:check`(test 295), `messagingSampleContractQualificationTest` 22, `integrationTest` 51, `systemTest` 3 PASS | - | 기능별 패키지로 정리, poster-image는 objectstorage 검증용 별도 sample 모듈로 이동 |
| S6-#10b | Consider | poster-image legacy API 모드 | 해당 없음(코드 삭제) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `d54909c4`: `LegacyPosterImageController`·`UploadPosterImageUseCase`·`UploadPosterImageCommand`·`LegacyPosterImageAttachment`·`PosterImageApiConfig`·`PosterImageApiSettings`(LEGACY 모드)·`Poster.attachImage`·`Poster.imageKey()`·dual-read `rehydrate` 삭제. `PosterEntity`는 `image_key`를 매핑하지 않고, CAS attach가 `image_key = NULL`로 pre-V8 행을 정규 경로로 받는다(`PosterImageAttachmentCasRepository.java:32`). `PosterRepositoryAdapterIntegrationTest.aPreV8RawKeyRowReadsBackWithoutAnImage`·`canonicalAttachClearsAPreV8RawKeyOnTheSameRow` PASS(삭제에 따른 새 동작이라 FAIL 재현 없음). `PosterResponse.imageKey` wire 이름은 유지하고 published reference를 싣는다. sample `local` 프로필·systemTest yml의 `mode: legacy`·`object-storage.legacy` 블록 삭제 | - | legacy 모드와 전용 타입 삭제 |
| S6-#10c | Consider | 상태 머신이 application 계층, use case 생성자 14개 | 완료(부분 수정 방향 변경) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `PublishPosterImageUseCase` 설정값 인자(destination·epoch·intentTtl·handoffLease)를 `PosterImagePublicationParameters` record 하나로(생성자 14→11, 양수 검증). 상태 머신(`PosterImageUploadIntent`)의 domain 이동은 하지 않음: 필드가 `application-objectstorage`·`application-core` 값 타입(`ObjectOperationKey`, `ObjectStageHandle`, `ObjectVersionToken`, `ObjectContentIdentity`, `ObjectMediaType`, `RequestFingerprint`)이라 domain으로 옮기면 domain→application 의존이 생긴다(HARD-STOP 1과 같은 방향 위반). sample `test` PASS | - | 상태 머신을 domain으로, 설정값 인자(TTL·lease·epoch·destination)를 record 하나로 |
| S6-#10d | Consider | `WorkLogSortField`(domain)가 HTTP 이름과 persistence 이름을 같이 앎 | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `WorkLogSortField`·`PosterSortField`는 논리 필드만. 요청 이름은 web mapper `SORT_FIELDS`(`WorkLogWebMapper.java:24`, `PosterWebMapper.java:19`), persistence 속성은 `sortProperty`(`WorkLogPersistenceMapper.java:57`, `PosterPersistenceMapper.java:38`). 계약 테스트·integration 51 PASS | - | 요청 이름 매핑은 web mapper로, persistence 이름은 persistence mapper로; domain enum은 논리 필드만 |
@@ -1219,8 +1219,11 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검
| P22-new-2 | 발견 | `infra/redis-sdk/acl/application.acl`·`all-accounts.acl`이 pub/sub 삭제 뒤에도 `+@pubsub`·`&prod:*`를 준다(최소 권한 위반, fixture). | 남음 | Wave 3 P22 결과 파일 | W3 | ACL fixture에서 제거 후 topology lane 재실행. P20 |
| P22-new-3 | 발견 | redis-sdk 공개 API가 runtime 타입을 노출하면서 runtime을 `implementation`으로만 의존. `ca.spring-library`에 `api` 구성이 없어 한 줄로 못 고침. | 완료 | Wave 3 W3-P29 (Wave 3 라운드 3 커밋): `3967c9ef`. redis-sdk만 `java-library` + `api project(':adapter:outbound:redis-runtime')` / 통합 검증 통과(redis-sdk java-library + api redis-runtime) | - | 컨벤션에 `java-library` 적용 또는 공개 표면에서 runtime 타입 제거. P29 |
| ORCH-new-4 | 발견 | redis-sdk `RedisSdkModuleBoundaryTest`·`RedisSupportMatrixTest`가 옛 split package(`redis-runtime/.../redis/sdk`)를 훑음 — P22 worktree에서 통과, main 통합에서 `NoSuchFileException`(ORCH-new-2와 같은 유형: 저장소 파일을 읽지만 test inputs 미선언). | 남음 | 경로는 통합 때 수정(`redis-sdk` 하나) | W4 | 읽는 파일을 test `inputs`로 선언 |
| P19-new-1 | 발견 | notification `platform.api.TenantId`가 비어 있지 않음·100자 이하만 검사 — web·GraphQL이 거부하는 tenant(공백·줄바꿈·경로 문자)를 받는다. 강화하면 이미 저장된 행을 못 읽을 수 있다. | 남음 | Wave 3 P19 결과 파일 | W3 | 읽기는 관대하게, 새 쓰기만 공용 `TenantId` 문법으로. P30 |
| P19-new-2 | 발견 | redis-session 인증 경로(`PrimitiveSessionSecurityContextRepository.java:116`)가 세션에 tenant를 저장하지 않아 JWT 경로와 달리 principal에 tenant가 없다. | 남음 | Wave 3 P19 결과 파일 | W3 | 세션 저장·복원에 tenant 포함. P30 |
| P19-new-1 | 발견 | notification `platform.api.TenantId`가 비어 있지 않음·100자 이하만 검사 — web·GraphQL이 거부하는 tenant(공백·줄바꿈·경로 문자)를 받는다. 강화하면 이미 저장된 행을 못 읽을 수 있다. | 완료 | Wave 3 W3-P30 (Wave 3 라운드 4 커밋): 커밋 `1fc862a8`. `application-notification/.../platform/api/TenantId.java`는 그대로(저장된 행을 읽는 타입 — 이전 규칙으로 쓴 행도 읽힘, `NotificationSubmissionServiceTest.aTenantStoredUnderTheOldRuleIsStillReadable`). 새 쓰기만 `dispatch/WritableTenant.require`(package-private)로 application-core `TenantId` 문법(`[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`)을 요구, 어긋나면 `NotificationValidationException`(`VALIDATION_FAILED`, 다른 제출 검증과 같은 코드): `NotificationSubmissionService.prepare`(submit·schedule 공통 첫 단계), `AcceptNotificationApplicationUseCase.handle`(첫 쓰기인 연락처 등록 전). 테스트: `NotificationSubmissionServiceTest.aSubmissionForATenantOutsideTheTransportGrammarIsRefused`(공백·줄바꿈·`../`·`/`·선행 `-` 5건) FAIL(`Expecting actual not to be null`) → PASS, `AcceptNotificationApplicationUseCaseTest.anAcceptanceForATenantOutsideTheTransportGrammarRegistersNothing` FAIL → PASS. 기본 단일 tenant `"default"`(`NotificationPlatformCodecConfig.java:57`)는 문법 안. 검증: application-notification 230, adapter:outbound:notification·web-notification·composition notification `check` PASS | - | 읽기는 관대하게, 새 쓰기만 공용 `TenantId` 문법으로. P30 |
| P19-new-2 | 발견 | redis-session 인증 경로(`PrimitiveSessionSecurityContextRepository.java:116`)가 세션에 tenant를 저장하지 않아 JWT 경로와 달리 principal에 tenant가 없다. | 완료 | Wave 3 W3-P30 (Wave 3 라운드 4 커밋): 커밋 `6708c681`. `adapter/inbound/web/.../auth/PrimitiveSessionSecurityContextRepository.java` snapshot `VERSION` 1→2: `AuthenticatedPrincipal.tenant()`를 선택 텍스트(최대 64바이트)로 쓰고, 읽을 때 `TenantId.optional`로 재검증해 `new AuthenticatedPrincipal(id, email, roles, tenant)`로 복원(JWT 경로와 같은 principal). 형식이 틀린 tenant는 기존 손상 snapshot과 같이 폐기(fail closed). version 1 snapshot은 계속 읽고 tenant 없이 복원(배포 중 세션이 끊기지 않음). 테스트: `PrimitiveSessionSecurityContextRepositoryTest.aSessionRestoresThePrincipalsTenant` FAIL(`... tenant=Optional.empty`) → PASS, `aSnapshotWrittenBeforeTheTenantRestoresAPrincipalWithoutOne` PASS. 검증: `:adapter:inbound:web:check` PASS | - | 세션 저장·복원에 tenant 포함. P30 |
| P19-new-3 | 발견 | `docs/study/postgresql-jpa-walkthrough.ko.md:818`이 삭제된 `JpaStreamScope`를 설명. | 남음 | Wave 3 P19 결과 파일 | W5 | 결정 6: 현재 코드 기준으로 |
| P28-new-1 | 발견 | fileserver `AtomicMoveContentPublisher`·`ContentPublishVerification`이 보안 walk를 직접 불러 거부를 번역하지 않고 내보냈다. | 완료 | Wave 3 P28 `da49df6c` | - | - |
| ORCH-new-5 | 발견 | P18의 V19가 persistence-jpa `postgresqlMigrationIntegrationTest` 기대값(버전 목록·제약 목록, legacy 미발행 행 삽입)에 반영되지 않았다 — P18 게이트에 이 lane이 없었다. messaging `OutboxPostgresIT`는 P29의 jvm-test-suite 전환 뒤 main 리소스가 jar로 와서 migration 목록을 `File`로 못 읽었다. | 완료 | Wave 3 라운드 3 통합: V19·제약 추가, legacy 행은 PUBLISHED로(V19가 미발행 legacy 행을 거부하는 것이 의도), jar/디렉터리 모두 읽는 목록 조회 — `integrationCheck` 통과 | - | - |
| P30-new-1 | 발견 | fileserver `DefaultCleanupService.cleanStaging`이 `claimForCleanup`(JPA `@Modifying` update)을 트랜잭션 밖에서 불러 실제 store에서는 세션 있는 staging 정리가 매번 실패·재시도 후 포기됐다. | 완료 | Wave 3 P30 `4de7717d`: guard 추가 전 호출자를 트랜잭션 안으로 | - | - |
| P30-new-2 | 발견 | notification dispatch Blocked 분기가 recipient 전이 트랜잭션을 닫은 뒤 request 상태 roll-up을 트랜잭션 밖에서 실행. | 완료 | Wave 3 P30 `4de7717d` | - | - |
| P30-new-3 | 발견 | objectstorage local-dev provider의 create-only 게시가 이제 한 프로세스 안에서만 보장된다(JDK에 디렉터리 핸들 기준 create-only rename·link가 없어 검증된 부모에서 부재 확인+rename, JVM 단위 lock). 예전 hard-link 방식은 프로세스 간에도 보장했다. provider는 단일 프로세스·local-dev 전용으로 선언돼 있다. | 남음 | Wave 3 P30 결과 파일 | W5 | provider README에 단일 프로세스 보장 범위 명시 |
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.inbound.web.auth;
import dev.caskeleton.application.tenant.TenantId;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
@@ -18,6 +19,7 @@ import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
@@ -43,7 +45,15 @@ final class PrimitiveSessionSecurityContextRepository implements SecurityContext
static final String SNAPSHOT_ATTRIBUTE = "dev.caskeleton.security.PRIMITIVE_SECURITY_CONTEXT_V1";
private static final int MAGIC = 0x43534543;
private static final int VERSION = 1;
/**
* Version 2 adds the tenant (review P19-new-2); version 1 snapshots, written before it, are still
* read and restore a principal without one, as they always did.
*/
private static final int VERSION = 2;
private static final int VERSION_WITHOUT_TENANT = 1;
private static final int MAXIMUM_TENANT_BYTES = 64;
private static final int MAXIMUM_SNAPSHOT_BYTES = 16_384;
private static final int MAXIMUM_PRINCIPAL_BYTES = 256;
private static final int MAXIMUM_EMAIL_BYTES = 320;
@@ -113,7 +123,8 @@ final class PrimitiveSessionSecurityContextRepository implements SecurityContext
try {
PrimitiveAuthentication decoded = decode(snapshot);
AuthenticatedPrincipal principal =
new AuthenticatedPrincipal(decoded.principalId, decoded.email, decoded.roles);
new AuthenticatedPrincipal(
decoded.principalId, decoded.email, decoded.roles, decoded.tenant);
List<GrantedAuthority> authorities =
decoded.authorities.stream()
.map(SimpleGrantedAuthority::new)
@@ -148,6 +159,11 @@ final class PrimitiveSessionSecurityContextRepository implements SecurityContext
writeNullableText(output, principal.email(), MAXIMUM_EMAIL_BYTES, "email");
writeTokens(output, roles);
writeTokens(output, authorities);
writeNullableText(
output,
principal.tenant().map(TenantId::value).orElse(null),
MAXIMUM_TENANT_BYTES,
"tenant");
}
byte[] snapshot = bytes.toByteArray();
if (snapshot.length > MAXIMUM_SNAPSHOT_BYTES) {
@@ -164,17 +180,27 @@ final class PrimitiveSessionSecurityContextRepository implements SecurityContext
throw invalidSnapshot();
}
try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(snapshot.clone()))) {
if (input.readInt() != MAGIC || input.readUnsignedByte() != VERSION) {
if (input.readInt() != MAGIC) {
throw invalidSnapshot();
}
int version = input.readUnsignedByte();
if (version != VERSION && version != VERSION_WITHOUT_TENANT) {
throw invalidSnapshot();
}
String principalId = readText(input, MAXIMUM_PRINCIPAL_BYTES);
String email = readNullableText(input, MAXIMUM_EMAIL_BYTES);
Set<String> roles = readTokens(input, MAXIMUM_ROLES);
Set<String> authorities = readTokens(input, MAXIMUM_AUTHORITIES);
// Re-validated on the way in: a tenant is a security boundary, and the session store is
// outside this process.
Optional<TenantId> tenant =
version == VERSION
? TenantId.optional(readNullableText(input, MAXIMUM_TENANT_BYTES))
: Optional.empty();
if (input.available() != 0) {
throw invalidSnapshot();
}
return new PrimitiveAuthentication(principalId, email, roles, authorities);
return new PrimitiveAuthentication(principalId, email, roles, authorities, tenant);
} catch (IOException | IllegalArgumentException exception) {
throw invalidSnapshot();
}
@@ -315,13 +341,19 @@ final class PrimitiveSessionSecurityContextRepository implements SecurityContext
private final String email;
private final Set<String> roles;
private final Set<String> authorities;
private final Optional<TenantId> tenant;
private PrimitiveAuthentication(
String principalId, String email, Set<String> roles, Set<String> authorities) {
String principalId,
String email,
Set<String> roles,
Set<String> authorities,
Optional<TenantId> tenant) {
this.principalId = principalId;
this.email = email;
this.roles = roles;
this.authorities = authorities;
this.tenant = tenant;
}
}
}
@@ -3,6 +3,8 @@ package dev.caskeleton.adapter.inbound.web.auth;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.application.tenant.TenantId;
import java.util.Optional;
import java.util.Set;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
@@ -57,6 +59,78 @@ class PrimitiveSessionSecurityContextRepositoryTest {
.containsExactlyInAnyOrder("ROLE_OPERATOR", "worklog:read");
}
/**
* The session path restores the same principal the JWT path builds, tenant included; it used to
* drop the tenant, so a session-authenticated request saw none (review P19-new-2).
*/
@Test
void aSessionRestoresThePrincipalsTenant() {
// given
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
AuthenticatedPrincipal principal =
new AuthenticatedPrincipal(
"idp-user-7",
"tenant-user@example.test",
Set.of("operator"),
Optional.of(new TenantId("tenant-a")));
var context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(
UsernamePasswordAuthenticationToken.authenticated(
principal, null, Set.of(new SimpleGrantedAuthority("ROLE_OPERATOR"))));
repository.saveContext(context, request, response);
// when
Object restored =
repository
.loadContext(new HttpRequestResponseHolder(request, response))
.getAuthentication()
.getPrincipal();
// then
assertThat(restored).isEqualTo(principal);
}
/** A session written before the tenant was stored is still honoured, as it was before. */
@Test
void aSnapshotWrittenBeforeTheTenantRestoresAPrincipalWithoutOne() throws Exception {
// given
java.io.ByteArrayOutputStream bytes = new java.io.ByteArrayOutputStream();
try (java.io.DataOutputStream output = new java.io.DataOutputStream(bytes)) {
output.writeInt(0x43534543);
output.writeByte(1);
writeText(output, "idp-user-v1");
output.writeBoolean(false);
output.writeInt(1);
writeText(output, "operator");
output.writeInt(1);
writeText(output, "ROLE_OPERATOR");
}
MockHttpServletRequest request = new MockHttpServletRequest();
request
.getSession(true)
.setAttribute(
PrimitiveSessionSecurityContextRepository.SNAPSHOT_ATTRIBUTE, bytes.toByteArray());
// when
Object restored =
repository
.loadContext(new HttpRequestResponseHolder(request, new MockHttpServletResponse()))
.getAuthentication()
.getPrincipal();
// then
assertThat(restored)
.isEqualTo(new AuthenticatedPrincipal("idp-user-v1", null, Set.of("operator")));
}
private static void writeText(java.io.DataOutputStream output, String value)
throws java.io.IOException {
byte[] encoded = value.getBytes(java.nio.charset.StandardCharsets.UTF_8);
output.writeInt(encoded.length);
output.write(encoded);
}
@Test
void savesThePrimitiveSnapshotBeforeAResponseCommitRequiresANewSession() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
+4 -1
View File
@@ -25,7 +25,10 @@ readiness live in [README.md](README.md) and
## Allowed
- Project dependencies are exactly those allowed by the `adapter-outbound-objectstorage` entry in
`src/config/architecture/modules.json`; currently application-core and shared-contract.
`src/config/architecture/modules.json`; currently application-core, shared-contract,
application-objectstorage and the registered support edge (`adapter:outbound:support`, whose
descriptor-based `SecureFileAccess`/`SecureDirectoryWalk` every local-dev file access goes
through).
- Provider SDK/configuration types stay within this leaf.
- Provider contributions may describe support without side effects and may construct resources
only after exact selection.
@@ -52,6 +52,9 @@ dependencies {
implementation project(':application-core')
implementation project(':application-objectstorage')
implementation project(':shared-contract')
// The local-development provider opens, publishes and deletes through directory descriptors
// (SecureFileAccess / SecureDirectoryWalk), the one primitive fileserver uses too (S4-lead-2).
implementation project(':adapter:outbound:support')
implementation 'org.springframework.boot:spring-boot-autoconfigure'
implementation 'org.slf4j:slf4j-api'
@@ -7,12 +7,10 @@ import dev.caskeleton.adapter.outbound.objectstorage.control.ObjectControlRecord
import dev.caskeleton.adapter.outbound.objectstorage.control.ObjectControlStore;
import dev.caskeleton.adapter.outbound.objectstorage.control.ObjectControlVersion;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.Optional;
/**
@@ -34,11 +32,15 @@ public final class LocalDevObjectControlStore implements ObjectControlStore {
@Override
public Optional<StoredControlRecord> read(String key) {
Path target = pathGuard.resolveControl(key, false);
if (!Files.isRegularFile(target, java.nio.file.LinkOption.NOFOLLOW_LINKS)) {
return Optional.empty();
}
try {
byte[] encoded = Files.readAllBytes(target);
Optional<FileChannel> opened = pathGuard.openForRead(target);
if (opened.isEmpty()) {
return Optional.empty();
}
byte[] encoded;
try (FileChannel channel = opened.get()) {
encoded = Channels.newInputStream(channel).readAllBytes();
}
ObjectControlRecord record = codec.decode(encoded);
return Optional.of(
new StoredControlRecord(ObjectControlVersion.of(codec.sha256Hex(encoded)), record));
@@ -48,9 +50,10 @@ public final class LocalDevObjectControlStore implements ObjectControlStore {
}
/**
* Writes the whole record to a private temporary file, forces it, and only then links it into
* place. A concurrent reader sees no file or the complete record, and a crash mid-write leaves an
* orphan under {@code .tmp} instead of a truncated record that decodes as corrupt forever.
* Writes the whole record to a private temporary file, forces it, and only then publishes it
* create-only. A concurrent reader sees no file or the complete record, and a crash mid-write
* leaves an orphan under {@code .tmp} instead of a truncated record that decodes as corrupt
* forever.
*/
@Override
public StoredControlRecord create(String key, ObjectControlRecord record) {
@@ -58,22 +61,16 @@ public final class LocalDevObjectControlStore implements ObjectControlStore {
byte[] encoded = codec.encode(record);
Path temporary = null;
try {
temporary = pathGuard.createTemporaryFile();
try (FileChannel channel =
FileChannel.open(
temporary, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
writeFully(channel, encoded);
channel.force(true);
}
Files.createLink(target, temporary);
LocalObjectPathGuard.applyFilePermissions(target, false);
temporary = stage(encoded);
pathGuard.publishExclusive(temporary, target);
temporary = null;
return new StoredControlRecord(ObjectControlVersion.of(codec.sha256Hex(encoded)), record);
} catch (FileAlreadyExistsException exception) {
throw new ObjectControlConflictException("local control record already exists");
} catch (IOException exception) {
throw new IllegalStateException("local control create failed", exception);
} finally {
deleteTemporary(temporary);
pathGuard.deleteQuietly(temporary);
}
}
@@ -91,34 +88,32 @@ public final class LocalDevObjectControlStore implements ObjectControlStore {
Path target = pathGuard.resolveControl(key, false);
Path temporary = null;
try {
temporary = pathGuard.createTemporaryFile();
try (FileChannel channel =
FileChannel.open(
temporary, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
writeFully(channel, replacement);
channel.force(true);
}
Files.move(
temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
LocalObjectPathGuard.applyFilePermissions(target, false);
temporary = stage(replacement);
pathGuard.replace(temporary, target);
temporary = null;
return new StoredControlRecord(
ObjectControlVersion.of(codec.sha256Hex(replacement)), mutation.replacement());
} catch (IOException exception) {
throw new IllegalStateException("local control CAS failed", exception);
} finally {
deleteTemporary(temporary);
pathGuard.deleteQuietly(temporary);
}
}
}
private static void deleteTemporary(Path temporary) {
if (temporary == null) {
return;
}
/** A forced, read-only temporary copy of {@code bytes}, ready to publish. */
private Path stage(byte[] bytes) throws IOException {
LocalObjectPathGuard.TemporaryFile staged = pathGuard.createTemporaryFile();
try {
Files.deleteIfExists(temporary);
} catch (IOException ignored) {
// Report-first local reconciliation owns any bounded .tmp orphan.
try (FileChannel channel = staged.channel()) {
writeFully(channel, bytes);
channel.force(true);
}
pathGuard.makeReadOnly(staged.path());
return staged.path();
} catch (IOException | RuntimeException failure) {
pathGuard.deleteQuietly(staged.path());
throw failure;
}
}
@@ -16,15 +16,15 @@ import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Optional;
/** Immutable local data objects using staged writes and exclusive hard-link publication. */
/**
* Immutable local data objects: staged writes, create-only publication and every access through
* directory descriptors ({@link LocalObjectPathGuard}).
*/
public final class LocalDevObjectDataStore {
private final LocalObjectPathGuard pathGuard;
@@ -49,22 +49,22 @@ public final class LocalDevObjectDataStore {
Path target = pathGuard.resolveData(operation.canonicalDataKey(), true);
Path temporary = null;
try {
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
if (pathGuard.exists(target)) {
throw conflict();
}
temporary = pathGuard.createTemporaryFile();
ObjectContentIdentity identity = streamTransfer.write(temporary, operation, producer);
LocalObjectPathGuard.TemporaryFile staged = pathGuard.createTemporaryFile();
temporary = staged.path();
ObjectContentIdentity identity;
try (FileChannel channel = staged.channel()) {
identity = streamTransfer.write(channel, temporary, operation, producer);
}
pathGuard.makeReadOnly(temporary);
try {
Files.createLink(target, temporary);
pathGuard.publishExclusive(temporary, target);
} catch (FileAlreadyExistsException exception) {
throw conflict();
} catch (UnsupportedOperationException exception) {
throw new ObjectStorageProviderException(
ObjectStorageProviderException.Failure.UNSUPPORTED,
"local filesystem cannot prove immutable create",
exception);
}
LocalObjectPathGuard.applyFilePermissions(target, false);
temporary = null;
return stored(operation.canonicalDataKey(), identity);
} catch (ObjectStorageProviderException exception) {
throw exception;
@@ -74,47 +74,21 @@ public final class LocalDevObjectDataStore {
"local immutable create failed",
exception);
} finally {
if (temporary != null) {
try {
Files.deleteIfExists(temporary);
} catch (IOException ignored) {
// A bounded local-dev orphan remains under .tmp for report-first startup reconciliation.
}
}
// A bounded local-dev orphan remains under .tmp for report-first startup reconciliation.
pathGuard.deleteQuietly(temporary);
}
}
public Optional<ObjectStorageProvider.StoredData> inspect(String canonicalDataKey) {
Path source = pathGuard.resolveData(canonicalDataKey, false);
if (!Files.isRegularFile(source, LinkOption.NOFOLLOW_LINKS)) {
return Optional.empty();
}
try {
MessageDigest digest = Sha256.newMessageDigest();
long size = 0;
ByteBuffer buffer = ByteBuffer.allocate(64 * 1024);
try (FileChannel channel = FileChannel.open(source, StandardOpenOption.READ)) {
for (int count = channel.read(buffer); count >= 0; count = channel.read(buffer)) {
if (count == 0) {
continue;
}
size = Math.addExact(size, count);
if (size > maximumObjectBytes) {
throw new ObjectStorageProviderException(
ObjectStorageProviderException.Failure.CORRUPT_DATA,
"local object exceeds its configured bound");
}
digest.update(buffer.array(), 0, count);
buffer.clear();
}
Optional<FileChannel> opened = pathGuard.openForRead(source);
if (opened.isEmpty()) {
return Optional.empty();
}
try (FileChannel channel = opened.get()) {
return Optional.of(stored(canonicalDataKey, identityOf(channel)));
}
ObjectContentIdentity identity =
new ObjectContentIdentity(
size,
ObjectDigest.of(
dev.caskeleton.application.objectstorage.model.ObjectDigestAlgorithm.SHA_256,
Base64.getEncoder().encodeToString(digest.digest())));
return Optional.of(stored(canonicalDataKey, identity));
} catch (ObjectStorageProviderException exception) {
throw exception;
} catch (IOException | ArithmeticException exception) {
@@ -125,23 +99,43 @@ public final class LocalDevObjectDataStore {
}
}
/**
* Verifies and streams one open file.
*
* <p>The precondition is checked against the same descriptor the bytes are then read from: the
* file cannot be swapped between the check and the read.
*/
public void transfer(
ObjectStorageProvider.ReadOperation operation, ObjectContentConsumer consumer) {
ObjectStorageProvider.StoredData actual =
inspect(operation.canonicalDataKey())
.orElseThrow(
() ->
new ObjectStorageProviderException(
ObjectStorageProviderException.Failure.NOT_FOUND,
"local object is absent"));
if (!actual.exactVersion().equals(operation.exactVersion())
|| !actual.contentIdentity().equals(operation.contentIdentity())) {
throw new ObjectStorageProviderException(
ObjectStorageProviderException.Failure.PRECONDITION_FAILED,
"local read precondition failed");
}
Path source = pathGuard.resolveData(operation.canonicalDataKey(), false);
streamTransfer.read(source, operation, consumer);
Optional<FileChannel> opened;
try {
opened = pathGuard.openForRead(source);
} catch (IOException exception) {
throw new ObjectStorageProviderException(
ObjectStorageProviderException.Failure.IO_FAILURE, "local data read failed", exception);
}
FileChannel channel =
opened.orElseThrow(
() ->
new ObjectStorageProviderException(
ObjectStorageProviderException.Failure.NOT_FOUND, "local object is absent"));
try (channel) {
ObjectStorageProvider.StoredData actual =
stored(operation.canonicalDataKey(), identityOf(channel));
if (!actual.exactVersion().equals(operation.exactVersion())
|| !actual.contentIdentity().equals(operation.contentIdentity())) {
throw new ObjectStorageProviderException(
ObjectStorageProviderException.Failure.PRECONDITION_FAILED,
"local read precondition failed");
}
streamTransfer.read(channel, operation, consumer);
} catch (ObjectStorageProviderException exception) {
throw exception;
} catch (IOException | ArithmeticException exception) {
throw new ObjectStorageProviderException(
ObjectStorageProviderException.Failure.IO_FAILURE, "local data read failed", exception);
}
}
public boolean retire(ObjectStorageProvider.RetireOperation operation) {
@@ -151,7 +145,7 @@ public final class LocalDevObjectDataStore {
}
Path target = pathGuard.resolveData(operation.canonicalDataKey(), false);
try {
return Files.deleteIfExists(target);
return pathGuard.deleteRegularFile(target);
} catch (IOException exception) {
throw new ObjectStorageProviderException(
ObjectStorageProviderException.Failure.IO_FAILURE,
@@ -160,6 +154,31 @@ public final class LocalDevObjectDataStore {
}
}
private ObjectContentIdentity identityOf(FileChannel channel) throws IOException {
MessageDigest digest = Sha256.newMessageDigest();
long size = 0;
ByteBuffer buffer = ByteBuffer.allocate(64 * 1024);
channel.position(0);
for (int count = channel.read(buffer); count >= 0; count = channel.read(buffer)) {
if (count == 0) {
continue;
}
size = Math.addExact(size, count);
if (size > maximumObjectBytes) {
throw new ObjectStorageProviderException(
ObjectStorageProviderException.Failure.CORRUPT_DATA,
"local object exceeds its configured bound");
}
digest.update(buffer.array(), 0, count);
buffer.clear();
}
return new ObjectContentIdentity(
size,
ObjectDigest.of(
dev.caskeleton.application.objectstorage.model.ObjectDigestAlgorithm.SHA_256,
Base64.getEncoder().encodeToString(digest.digest())));
}
private static ObjectStorageProvider.StoredData stored(
String canonicalDataKey, ObjectContentIdentity identity) {
return new ObjectStorageProvider.StoredData(
@@ -1,18 +1,53 @@
package dev.caskeleton.adapter.outbound.objectstorage.filesystem;
import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProviderOperation;
import dev.caskeleton.adapter.outbound.support.filesystem.SecureDirectoryWalk;
import dev.caskeleton.adapter.outbound.support.filesystem.SecureFileAccess;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.util.EnumSet;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
/** Strict root confinement and symlink rejection for the local-development provider. */
/**
* Root confinement for the local-development provider: key-to-path resolution, and every open,
* publication and deletion through directory descriptors.
*
* <p>Resolution is lexical only — a key maps to a path strictly below the root. It proves nothing
* about what is on disk, and nothing is ever opened through the path it returns. Every access goes
* through {@link SecureFileAccess} / {@link SecureDirectoryWalk} (the primitive fileserver uses),
* which descend one directory at a time with {@code NOFOLLOW_LINKS}: a symbolic link anywhere below
* the root is refused, and a directory swapped for a link after it was looked at is not followed,
* because what was verified and what is used are the same descriptor (review S4-lead-2).
*
* <p>Publication used to be {@code link(2)} of a temporary file onto the target path — create-only,
* but resolved by pathname, so a parent swapped for a link between the check and the link published
* the object outside the root. The JDK offers no descriptor-relative {@code linkat} or {@code
* renameat2(NOREPLACE)}, so create-only publication is now a descriptor-relative rename done while
* holding the target's verified parent and a key stripe lock, after checking absence through that
* same parent. The lock is per JVM: this provider is single-process by declaration (it reports
* {@code MULTI_NODE_LINEARIZABLE_CAS} unsupported and its control store says so), and exclusivity
* between two processes sharing one local root is not claimed.
*
* <p>Refusals surface as {@link IllegalArgumentException}, as the pathname checks did: they are
* permanent rejections of what is on disk, not outages.
*/
public final class LocalObjectPathGuard {
private static final int MAXIMUM_CONTROL_KEY_LENGTH = 512;
private static final int PUBLICATION_STRIPES = 256;
private static final Object[] PUBLICATION_LOCKS = publicationLocks();
private static final EnumSet<PosixFilePermission> READ_ONLY_FILE =
EnumSet.of(PosixFilePermission.OWNER_READ);
private final Path root;
@@ -31,6 +66,10 @@ public final class LocalObjectPathGuard {
} catch (IOException exception) {
throw new IllegalArgumentException("local object-storage root is unavailable", exception);
}
if (!SecureDirectoryWalk.isSupported(root)) {
throw new IllegalArgumentException(
"local object-storage root does not support descriptor-relative access");
}
}
public Path resolveData(String canonicalDataKey, boolean createParents) {
@@ -48,37 +87,156 @@ public final class LocalObjectPathGuard {
return resolve(canonicalControlKey + ".record", createParents);
}
public Path createTemporaryFile() throws IOException {
Path temporaryRoot = resolve(".tmp/object", true).getParent();
Path temporary = Files.createTempFile(temporaryRoot, "pending-", ".tmp");
applyFilePermissions(temporary, true);
return temporary;
/** A new private file under {@code .tmp}, created exclusively and opened for writing. */
public TemporaryFile createTemporaryFile() throws IOException {
Path temporary = resolve(".tmp/pending-" + UUID.randomUUID() + ".tmp", true);
return new TemporaryFile(
temporary, refusing(() -> SecureFileAccess.createNew(root, temporary)));
}
/**
* Opens a regular file for reading.
*
* @return empty when nothing, or something other than a regular file, has that name
* @throws IllegalArgumentException when a component or the leaf is a symbolic link
*/
public Optional<FileChannel> openForRead(Path target) throws IOException {
try {
return Optional.of(refusing(() -> SecureFileAccess.openForRead(root, target)));
} catch (NoSuchFileException | SecureFileAccess.NotRegularFileException absent) {
return Optional.empty();
}
}
/**
* True when something already has the name, without following a link.
*
* @throws IllegalArgumentException when a component or the leaf is a symbolic link
*/
public boolean exists(Path target) throws IOException {
try {
BasicFileAttributes attributes =
refusing(() -> SecureFileAccess.readAttributes(root, target));
if (attributes.isSymbolicLink()) {
throw new IllegalArgumentException("local object target cannot be a symbolic link");
}
return true;
} catch (NoSuchFileException absent) {
return false;
}
}
/** Makes a file owner-read-only through its verified parent. */
public void makeReadOnly(Path file) throws IOException {
refusing(
() ->
SecureDirectoryWalk.inParentOf(
root,
file,
(directory, leaf) -> {
PosixFileAttributeView view =
directory.getFileAttributeView(
leaf, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
if (view != null) {
view.setPermissions(READ_ONLY_FILE);
}
return null;
}));
}
/**
* Renames {@code temporary} onto {@code target} only if nothing has that name yet.
*
* <p>The absence check and the rename run against one verified descriptor of the target's parent,
* under the target's stripe lock, so no writer in this process can slip between them and no
* swapped directory can redirect the rename.
*
* @throws FileAlreadyExistsException when the target already exists
*/
public void publishExclusive(Path temporary, Path target) throws IOException {
synchronized (PUBLICATION_LOCKS[Math.floorMod(target.hashCode(), PUBLICATION_STRIPES)]) {
refusing(
() ->
SecureDirectoryWalk.inParentOf(
root,
target,
(targetDirectory, targetLeaf) -> {
if (present(targetDirectory, targetLeaf)) {
throw new FileAlreadyExistsException(targetLeaf.toString());
}
return SecureDirectoryWalk.inParentOf(
root,
temporary,
(sourceDirectory, sourceLeaf) -> {
sourceDirectory.move(sourceLeaf, targetDirectory, targetLeaf);
return null;
});
}));
}
}
/** Atomically replaces {@code target} with {@code temporary} through verified descriptors. */
public void replace(Path temporary, Path target) throws IOException {
synchronized (PUBLICATION_LOCKS[Math.floorMod(target.hashCode(), PUBLICATION_STRIPES)]) {
refusing(
() -> {
SecureDirectoryWalk.move(root, temporary, target);
return null;
});
}
}
/**
* Deletes a regular file through its verified parent.
*
* @return true when this call deleted it, false when it was already gone
*/
public boolean deleteRegularFile(Path target) throws IOException {
return refusing(() -> SecureFileAccess.deleteRegularFile(root, target));
}
/** Deletes a temporary file, leaving a bounded orphan under {@code .tmp} if that fails. */
public void deleteQuietly(Path temporary) {
if (temporary == null) {
return;
}
try {
deleteRegularFile(temporary);
} catch (IOException | RuntimeException ignored) {
// Report-first local reconciliation owns any bounded .tmp orphan.
}
}
public Path root() {
return root;
}
private Path resolve(String canonicalKey, boolean createParents) {
Path target = root.resolve(canonicalKey).normalize();
/** An exclusively created temporary file and its open channel; the caller closes the channel. */
public record TemporaryFile(Path path, FileChannel channel) {}
private Path resolve(String relativeKey, boolean createParents) {
Path target = root.resolve(relativeKey).normalize();
if (!target.startsWith(root) || target.equals(root)) {
throw new IllegalArgumentException("local object key escapes the configured root");
}
Path parent = target.getParent();
try {
if (createParents) {
createParentsWithoutLinks(parent);
if (createParents) {
try {
createParentsWithoutLinks(target.getParent());
} catch (IOException exception) {
throw new IllegalArgumentException(
"local object path cannot be resolved safely", exception);
}
rejectExistingLinks(parent);
if (Files.isSymbolicLink(target)) {
throw new IllegalArgumentException("local object target cannot be a symbolic link");
}
return target;
} catch (IOException exception) {
throw new IllegalArgumentException("local object path cannot be resolved safely", exception);
}
return target;
}
/**
* Creates missing directories, refusing a link on the way.
*
* <p>Pathname-based, because the JDK has no descriptor-relative {@code mkdirat}. What makes that
* acceptable is that nothing is opened through these paths: a component swapped for a link after
* this ran is refused by the descriptor walk every access takes.
*/
private void createParentsWithoutLinks(Path parent) throws IOException {
Path current = root;
for (Path segment : root.relativize(parent)) {
@@ -90,7 +248,7 @@ public final class LocalObjectPathGuard {
try {
Files.createDirectory(current);
applyDirectoryPermissions(current);
} catch (java.nio.file.FileAlreadyExistsException race) {
} catch (FileAlreadyExistsException race) {
if (!Files.isDirectory(current, LinkOption.NOFOLLOW_LINKS)
|| Files.isSymbolicLink(current)) {
throw new IllegalArgumentException("local object parent must be a directory", race);
@@ -102,20 +260,35 @@ public final class LocalObjectPathGuard {
}
}
private void rejectExistingLinks(Path parent) throws IOException {
Path current = root;
for (Path segment : root.relativize(parent)) {
current = current.resolve(segment);
if (Files.isSymbolicLink(current)) {
throw new IllegalArgumentException("local object parent cannot be a symbolic link");
}
if (Files.exists(current, LinkOption.NOFOLLOW_LINKS)
&& !Files.isDirectory(current, LinkOption.NOFOLLOW_LINKS)) {
throw new IllegalArgumentException("local object parent must be a directory");
}
private static boolean present(java.nio.file.SecureDirectoryStream<Path> directory, Path leaf)
throws IOException {
try {
directory
.getFileAttributeView(leaf, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS)
.readAttributes();
return true;
} catch (NoSuchFileException absent) {
return false;
}
}
/** Runs a descriptor operation, turning its typed refusals into permanent rejections. */
private static <T> T refusing(DescriptorOperation<T> operation) throws IOException {
try {
return operation.run();
} catch (SecureDirectoryWalk.SymbolicComponentException refused) {
throw new IllegalArgumentException(
"local object path cannot contain a symbolic link", refused);
} catch (SecureDirectoryWalk.PathEscapeException refused) {
throw new IllegalArgumentException("local object key escapes the configured root", refused);
}
}
@FunctionalInterface
private interface DescriptorOperation<T> {
T run() throws IOException;
}
private static void requireCanonicalControlKey(String key) {
if (key == null
|| key.length() > MAXIMUM_CONTROL_KEY_LENGTH
@@ -135,16 +308,6 @@ public final class LocalObjectPathGuard {
}
}
static void applyFilePermissions(Path file, boolean writable) throws IOException {
if (Files.getFileStore(file).supportsFileAttributeView("posix")) {
EnumSet<PosixFilePermission> permissions = EnumSet.of(PosixFilePermission.OWNER_READ);
if (writable) {
permissions.add(PosixFilePermission.OWNER_WRITE);
}
Files.setPosixFilePermissions(file, permissions);
}
}
private static void applyDirectoryPermissions(Path directory) throws IOException {
if (Files.getFileStore(directory).supportsFileAttributeView("posix")) {
Files.setPosixFilePermissions(
@@ -155,4 +318,10 @@ public final class LocalObjectPathGuard {
PosixFilePermission.OWNER_EXECUTE));
}
}
private static Object[] publicationLocks() {
Object[] stripes = new Object[PUBLICATION_STRIPES];
java.util.Arrays.setAll(stripes, ignored -> new Object());
return stripes;
}
}
@@ -20,7 +20,6 @@ import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Objects;
@@ -34,8 +33,15 @@ public final class LocalObjectStreamTransfer {
this.faultInjector = Objects.requireNonNull(faultInjector, "faultInjector must be non-null");
}
/**
* Writes the produced content into {@code channel}, an exclusively created temporary file the
* caller opened and closes; {@code temporary} names it for the fault injector only.
*/
public ObjectContentIdentity write(
Path temporary, ObjectStorageProviderOperation operation, ObjectContentProducer producer)
FileChannel channel,
Path temporary,
ObjectStorageProviderOperation operation,
ObjectContentProducer producer)
throws IOException {
Objects.requireNonNull(producer, "producer must be non-null");
requireActive(operation.budget(), operation.cancellation().isCancelled());
@@ -44,51 +50,47 @@ public final class LocalObjectStreamTransfer {
ObjectContentProductionContext context =
ObjectContentProductionContext.open(
operation.budget(), operation.cancellation(), operation.maximumChunkBytes());
try (FileChannel channel =
FileChannel.open(
temporary, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
ObjectChunkSink sink =
ObjectChunkSink.scoped(
context,
(bytes, offset, length) -> {
requireActive(operation.budget(), operation.cancellation().isCancelled());
long next;
try {
next = Math.addExact(written[0], length);
} catch (ArithmeticException exception) {
throw new ObjectChunkWriteException("content length overflows", exception);
}
if (next > operation.maximumObjectBytes()
|| next > operation.expectedContentIdentity().exactLength()) {
throw new ObjectChunkWriteException("producer exceeded the bounded content size");
}
ByteBuffer buffer = ByteBuffer.wrap(bytes, offset, length);
try {
while (buffer.hasRemaining()) {
int count = channel.write(buffer);
if (count <= 0) {
throw new IOException("local write made no progress");
}
ObjectChunkSink sink =
ObjectChunkSink.scoped(
context,
(bytes, offset, length) -> {
requireActive(operation.budget(), operation.cancellation().isCancelled());
long next;
try {
next = Math.addExact(written[0], length);
} catch (ArithmeticException exception) {
throw new ObjectChunkWriteException("content length overflows", exception);
}
if (next > operation.maximumObjectBytes()
|| next > operation.expectedContentIdentity().exactLength()) {
throw new ObjectChunkWriteException("producer exceeded the bounded content size");
}
ByteBuffer buffer = ByteBuffer.wrap(bytes, offset, length);
try {
while (buffer.hasRemaining()) {
int count = channel.write(buffer);
if (count <= 0) {
throw new IOException("local write made no progress");
}
} catch (IOException exception) {
throw new ObjectChunkWriteException("local data write failed", exception);
}
digest.update(bytes, offset, length);
written[0] = next;
});
try {
producer.produce(context, sink);
} catch (ObjectContentProductionException | RuntimeException exception) {
throw new ObjectStorageProviderException(
ObjectStorageProviderException.Failure.IO_FAILURE,
"bounded content production failed",
exception);
} finally {
context.invalidate();
}
channel.force(true);
faultInjector.afterWrite(written[0], temporary);
} catch (IOException exception) {
throw new ObjectChunkWriteException("local data write failed", exception);
}
digest.update(bytes, offset, length);
written[0] = next;
});
try {
producer.produce(context, sink);
} catch (ObjectContentProductionException | RuntimeException exception) {
throw new ObjectStorageProviderException(
ObjectStorageProviderException.Failure.IO_FAILURE,
"bounded content production failed",
exception);
} finally {
context.invalidate();
}
channel.force(true);
faultInjector.afterWrite(written[0], temporary);
ObjectContentIdentity observed =
new ObjectContentIdentity(
written[0],
@@ -103,8 +105,11 @@ public final class LocalObjectStreamTransfer {
return observed;
}
/** Streams the requested range of {@code channel}, which the caller opened and closes. */
public void read(
Path source, ObjectStorageProvider.ReadOperation operation, ObjectContentConsumer consumer) {
FileChannel channel,
ObjectStorageProvider.ReadOperation operation,
ObjectContentConsumer consumer) {
Objects.requireNonNull(consumer, "consumer must be non-null");
requireActive(operation.budget(), operation.cancellation().isCancelled());
ObjectContentReadContext context =
@@ -115,7 +120,7 @@ public final class LocalObjectStreamTransfer {
operation.contentIdentity(),
operation.exactVersion(),
operation.range());
try (FileChannel channel = FileChannel.open(source, StandardOpenOption.READ)) {
try {
channel.position(operation.range().offset());
long[] remaining = {operation.range().length()};
ObjectChunkSource chunkSource =
@@ -0,0 +1,198 @@
package dev.caskeleton.adapter.outbound.objectstorage.filesystem;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.objectstorage.contract.ObjectStorageProviderContract;
import dev.caskeleton.adapter.outbound.objectstorage.control.CanonicalJsonObjectControlRecordCodec;
import dev.caskeleton.adapter.outbound.objectstorage.control.ObjectReferenceRecord;
import dev.caskeleton.adapter.outbound.objectstorage.kernel.PublishedReferenceState;
import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProvider;
import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProviderOperation;
import dev.caskeleton.application.objectstorage.identity.ObjectId;
import dev.caskeleton.application.objectstorage.identity.ObjectReference;
import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* The local-development provider never reads, writes, publishes or deletes anything outside its
* root — not through a key, not through a symbolic link planted below the root, and not through a
* directory swapped for a link after the provider looked at it (review S4-lead-2).
*/
class LocalDevObjectStorageConfinementTest {
private static final byte[] CONTENT = {1, 2, 3};
private static final byte[] OUTSIDE_CONTENT = {9, 9, 9};
@TempDir Path base;
private Path root;
private Path outside;
@BeforeEach
void directories() throws IOException {
root = Files.createDirectory(base.resolve("root"));
outside = Files.createDirectory(base.resolve("outside"));
}
@Test
void aDataKeyThatClimbsOutOfTheRootIsRefused() {
// given
LocalDevObjectStorageProvider provider =
provider(LocalObjectStreamTransfer.FaultInjector.none());
// when
Throwable refused = catchThrowable(() -> provider.inspect("data/v1/../../../outside/x"));
// then
assertThat(refused)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("data key is not canonical");
}
@Test
void anObjectWhoseParentDirectoryIsASymbolicLinkIsNotReadThroughIt() throws IOException {
// given
LocalDevObjectStorageProvider provider =
provider(LocalObjectStreamTransfer.FaultInjector.none());
ObjectStorageProvider.StoredData stored = provider.create(operation(1), producer());
Path parent = physical(stored.canonicalDataKey()).getParent();
Files.move(parent, outside.resolve("moved"));
Files.createSymbolicLink(parent, outside.resolve("moved"));
// when
Throwable refused = catchThrowable(() -> provider.inspect(stored.canonicalDataKey()));
// then
assertThat(refused)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("symbolic link");
}
@Test
void aSymbolicLinkLeafIsNeverFollowedOnRead() throws IOException {
// given
LocalDevObjectStorageProvider provider =
provider(LocalObjectStreamTransfer.FaultInjector.none());
ObjectStorageProvider.StoredData stored = provider.create(operation(2), producer());
Path leaf = physical(stored.canonicalDataKey());
Files.delete(leaf);
Files.createSymbolicLink(leaf, Files.write(outside.resolve("secret"), OUTSIDE_CONTENT));
// when
Throwable refused = catchThrowable(() -> provider.inspect(stored.canonicalDataKey()));
// then
assertThat(refused)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("symbolic link");
}
@Test
void retiringThroughALinkedParentDeletesNothingOutsideTheRoot() throws IOException {
// given
LocalDevObjectStorageProvider provider =
provider(LocalObjectStreamTransfer.FaultInjector.none());
ObjectStorageProvider.StoredData stored = provider.create(operation(3), producer());
Path parent = physical(stored.canonicalDataKey()).getParent();
Files.move(parent, outside.resolve("moved"));
Files.createSymbolicLink(parent, outside.resolve("moved"));
// when
Throwable ignored =
catchThrowable(
() ->
provider.retire(
new ObjectStorageProvider.RetireOperation(
stored.canonicalDataKey(), stored.exactVersion())));
// then
assertThat(outside.resolve("moved").resolve(physical(stored.canonicalDataKey()).getFileName()))
.exists();
}
@Test
void aParentDirectorySwappedForALinkWhileTheObjectIsWrittenDoesNotPublishOutsideTheRoot() {
// given
ObjectStorageProviderOperation operation = operation(4);
Path parent = physical(operation.canonicalDataKey()).getParent();
LocalDevObjectStorageProvider provider =
provider(
(written, temporary) -> {
// The provider has already checked the target's directories; swap one now.
Files.move(parent, outside.resolve("moved"));
Files.createSymbolicLink(parent, outside);
});
// when
Throwable ignored = catchThrowable(() -> provider.create(operation, producer()));
// then
assertThat(listing(outside)).containsExactly("moved");
}
@Test
void aControlRecordThatIsASymbolicLinkIsNotRead() throws IOException {
// given
LocalObjectPathGuard guard = new LocalObjectPathGuard(root);
LocalDevObjectControlStore store =
new LocalDevObjectControlStore(guard, new CanonicalJsonObjectControlRecordCodec());
String key = "control/v1/references/0123456789ab/aa/reference";
store.create(key, referenceRecord());
Path physical = guard.resolveControl(key, false);
Files.delete(physical);
Files.createSymbolicLink(physical, Files.write(outside.resolve("record"), OUTSIDE_CONTENT));
// when
Throwable refused = catchThrowable(() -> store.read(key));
// then
assertThat(refused)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("symbolic link");
}
private LocalDevObjectStorageProvider provider(
LocalObjectStreamTransfer.FaultInjector faultInjector) {
return new LocalDevObjectStorageProvider(root, 1024, 64, faultInjector);
}
private Path physical(String canonicalDataKey) {
return root.resolve(canonicalDataKey);
}
private static ObjectStorageProviderOperation operation(int generation) {
return ObjectStorageProviderContract.operation(generation, CONTENT, () -> false);
}
private static dev.caskeleton.application.objectstorage.content.ObjectContentProducer producer() {
return ObjectStorageProviderContract.producer(CONTENT);
}
private static java.util.List<String> listing(Path directory) {
try (Stream<Path> entries = Files.list(directory)) {
return entries.map(entry -> entry.getFileName().toString()).sorted().toList();
} catch (IOException exception) {
throw new java.io.UncheckedIOException(exception);
}
}
private static ObjectReferenceRecord referenceRecord() {
return new ObjectReferenceRecord(
1,
"reference",
1,
ObjectReference.parse("osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"),
ObjectId.parse("0123456789abcdefghjkmnpqrs"),
ObjectVersionToken.parse("osv1.0123456789ab.0123456789abcdefghjkmnpqrs.6678c6821f"),
PublishedReferenceState.PUBLISHED,
Instant.EPOCH);
}
}
@@ -12,12 +12,14 @@ plugins {
//
// The package turned out to be entirely self-contained — it imports `application.fileserver`, JPA,
// Hibernate, Spring Data and JDBC, and not one type from any other `persistence.*` package — so
// extracting it needed no seam and no new abstraction. It does not depend on `persistence-jpa`
// either: it contributes entities and repositories to whatever persistence unit the application
// already has.
// extracting it needed no seam and no new abstraction. It contributes entities and repositories to
// whatever persistence unit the application already has. Its one `persistence-jpa` import is
// `CallerTransaction`: every store write joins the use case's transaction, and the guard that
// refuses a write without one lives there, once (owner decision 33, review X1-#4).
dependencies {
implementation project(':application-core')
implementation project(':application-fileserver')
implementation project(':adapter:outbound:persistence-jpa')
implementation 'org.springframework.boot:spring-boot-autoconfigure'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
@@ -4,7 +4,10 @@
biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=compileClasspath,testCompileClasspath
ch.qos.logback:logback-classic:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
ch.qos.logback:logback-core:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-annotations:2.21=testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-annotations:2.21=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-core:2.21.5=runtimeClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-databind:2.21.5=runtimeClasspath,testRuntimeClasspath
com.fasterxml.jackson:jackson-bom:2.21.5=runtimeClasspath,testRuntimeClasspath
com.fasterxml:classmate:1.7.3=runtimeClasspath,testRuntimeClasspath
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor
@@ -30,6 +33,7 @@ com.google.guava:guava:33.6.0-jre=checkstyle
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor
com.h2database:h2:2.4.240=runtimeClasspath,testRuntimeClasspath
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
@@ -44,7 +48,9 @@ info.picocli:picocli:4.7.7=checkstyle
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-core:1.16.7=runtimeClasspath,testRuntimeClasspath
io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.projectreactor:reactor-core:3.8.7=runtimeClasspath,testRuntimeClasspath
jakarta.activation:jakarta.activation-api:2.1.4=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
jakarta.inject:jakarta.inject-api:2.0.1=runtimeClasspath,testRuntimeClasspath
@@ -55,6 +61,7 @@ javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor
jaxen:jaxen:2.0.6=spotbugs
net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath
net.bytebuddy:byte-buddy:1.17.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
net.logstash.logback:logstash-logback-encoder:8.0=runtimeClasspath,testRuntimeClasspath
net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath
net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
@@ -80,16 +87,20 @@ org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
org.aspectj:aspectjweaver:1.9.25.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath
org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath
org.checkerframework:checker-qual:3.55.1=runtimeClasspath,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
org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.eclipse.angus:angus-activation:2.0.3=runtimeClasspath,testRuntimeClasspath
org.flywaydb:flyway-core:11.14.1=runtimeClasspath,testRuntimeClasspath
org.flywaydb:flyway-database-postgresql:11.14.1=runtimeClasspath,testRuntimeClasspath
org.glassfish.jaxb:jaxb-core:4.0.9=runtimeClasspath,testRuntimeClasspath
org.glassfish.jaxb:jaxb-runtime:4.0.9=runtimeClasspath,testRuntimeClasspath
org.glassfish.jaxb:txw2:4.0.9=runtimeClasspath,testRuntimeClasspath
org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath
org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath
org.hibernate.models:hibernate-models:1.0.1=runtimeClasspath,testRuntimeClasspath
org.hibernate.orm:hibernate-core:7.2.24.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.javassist:javassist:3.28.0-GA=checkstyle
@@ -104,6 +115,7 @@ org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath
org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit:junit-bom:6.1.0=spotbugs
org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath
org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath
org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath
org.objenesis:objenesis:3.3=testRuntimeClasspath
@@ -119,6 +131,8 @@ org.ow2.asm:asm-util:9.10.1=spotbugs
org.ow2.asm:asm:9.10.1=spotbugs
org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor
org.postgresql:postgresql:42.7.13=runtimeClasspath,testRuntimeClasspath
org.reactivestreams:reactive-streams:1.0.4=runtimeClasspath,testRuntimeClasspath
org.reflections:reflections:0.10.2=checkstyle
org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath
org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -128,6 +142,7 @@ org.slf4j:slf4j-simple:2.0.18=checkstyle
org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-data-commons:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-data-jpa:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-flyway:4.0.8=runtimeClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-hibernate:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath
@@ -138,6 +153,7 @@ org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,t
org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-sql:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-data-jpa:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-flyway:4.0.8=runtimeClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jdbc:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -158,6 +174,8 @@ org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRunti
org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.data:spring-data-commons:4.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.data:spring-data-jpa:4.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.integration:spring-integration-core:7.0.6=runtimeClasspath,testRuntimeClasspath
org.springframework.integration:spring-integration-jdbc:7.0.6=runtimeClasspath,testRuntimeClasspath
org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-aspects:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -165,6 +183,7 @@ org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testC
org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-jdbc:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-messaging:7.0.9=runtimeClasspath,testRuntimeClasspath
org.springframework:spring-orm:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-tx:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.fileserver;
import dev.caskeleton.adapter.outbound.persistence.fileserver.entity.CleanupItemEntity;
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileserverCleanupRepository;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.fileserver.api.ContentKey;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.api.UploadId;
@@ -50,6 +51,7 @@ public class JpaCleanupQueue implements CleanupQueuePort {
@Override
public void enqueue(CleanupRequest request) {
CallerTransaction.require("cleanup queue enqueue");
Instant now = clock.instant();
items.save(
new CleanupItemEntity(
@@ -97,6 +99,7 @@ public class JpaCleanupQueue implements CleanupQueuePort {
@Override
public List<CleanupItem> claimDue(Instant now, int limit) {
CallerTransaction.require("cleanup queue claimDue");
if (limit < 1) {
throw new IllegalArgumentException("limit must be positive");
}
@@ -116,6 +119,7 @@ public class JpaCleanupQueue implements CleanupQueuePort {
@Override
public int reclaimExpiredClaims(Instant now, int limit) {
CallerTransaction.require("cleanup queue reclaimExpiredClaims");
if (limit < 1) {
throw new IllegalArgumentException("limit must be positive");
}
@@ -133,12 +137,14 @@ public class JpaCleanupQueue implements CleanupQueuePort {
@Override
public void markDone(CleanupItem item) {
CallerTransaction.require("cleanup queue markDone");
Instant now = clock.instant();
settle(item.cleanupId(), STATUS_DONE, now, null, now);
}
@Override
public void markFailed(CleanupItem item, String reasonCode, Instant nextAttemptAt) {
CallerTransaction.require("cleanup queue markFailed");
Instant now = clock.instant();
boolean exhausted = item.attempt() + 1 >= MAXIMUM_ATTEMPTS;
settle(
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.persistence.fileserver;
import dev.caskeleton.adapter.outbound.persistence.fileserver.entity.FileEntity;
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileTransitionRepository;
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.JpaFileRepository;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.fileserver.api.ContentKey;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.api.FileState;
@@ -59,6 +60,7 @@ public class JpaFileMetadata implements FileMetadataPort {
@Override
public FileRecord insert(FileRecordDraft draft) {
CallerTransaction.require("file metadata insert");
Instant now = clock.instant();
FileEntity entity =
new FileEntity(
@@ -86,6 +88,7 @@ public class JpaFileMetadata implements FileMetadataPort {
FileState expectedState,
FileState targetState,
FileRecordMutation mutation) {
CallerTransaction.require("file metadata transition");
expectedState.requireTransitionTo(targetState);
Instant now = clock.instant();
int updated =
@@ -110,6 +113,7 @@ public class JpaFileMetadata implements FileMetadataPort {
@Override
public FileRecord markDeleting(FileId fileId, long expectedVersion) {
CallerTransaction.require("file metadata markDeleting");
int updated =
transitions.markDeleting(fileId.value(), expectedVersion, deletableStates, clock.instant());
if (updated == 0) {
@@ -121,6 +125,7 @@ public class JpaFileMetadata implements FileMetadataPort {
@Override
public FileRecord relocate(
FileId fileId, long expectedVersion, StorageNamespace targetNamespace) {
CallerTransaction.require("file metadata relocate");
int updated =
transitions.relocate(
fileId.value(), expectedVersion, targetNamespace.value(), clock.instant());
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.fileserver;
import dev.caskeleton.adapter.outbound.persistence.fileserver.entity.QuotaReservationEntity;
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileserverQuotaRepository;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
import dev.caskeleton.application.fileserver.api.error.FileserverException;
import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext;
@@ -32,6 +33,7 @@ public class JpaFileQuota implements FileQuotaPort {
@Override
public QuotaReservation reserve(QuotaScope scope, long expectedBytes, Duration ttl) {
CallerTransaction.require("file quota reserve");
if (expectedBytes < 0) {
throw new IllegalArgumentException("expectedBytes must not be negative");
}
@@ -50,6 +52,7 @@ public class JpaFileQuota implements FileQuotaPort {
@Override
public void extend(QuotaReservation reservation, long additionalBytes) {
CallerTransaction.require("file quota extend");
if (additionalBytes < 0) {
throw new IllegalArgumentException("additionalBytes must not be negative");
}
@@ -62,6 +65,7 @@ public class JpaFileQuota implements FileQuotaPort {
@Override
public void commit(QuotaReservation reservation, long actualBytes) {
CallerTransaction.require("file quota commit");
if (actualBytes < 0) {
throw new IllegalArgumentException("actualBytes must not be negative");
}
@@ -73,6 +77,7 @@ public class JpaFileQuota implements FileQuotaPort {
@Override
public void release(QuotaReservation reservation) {
CallerTransaction.require("file quota release");
reservations.release(reservation.reservationId(), clock.instant());
}
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.fileserver;
import dev.caskeleton.adapter.outbound.persistence.fileserver.entity.QuotaReservationEntity;
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileserverQuotaRepository;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort;
import dev.caskeleton.application.fileserver.api.metadata.FileRecord;
import dev.caskeleton.application.fileserver.api.metadata.QuotaScope;
@@ -49,6 +50,7 @@ public class JpaQuotaCommit implements QuotaCommitPort {
@Override
public void commit(UploadSession session, long actualBytes) {
CallerTransaction.require("quota commit commit");
if (actualBytes < 0) {
throw new IllegalArgumentException("actualBytes must not be negative");
}
@@ -67,6 +69,7 @@ public class JpaQuotaCommit implements QuotaCommitPort {
@Override
public void release(UploadSession session) {
CallerTransaction.require("quota commit release");
Optional<QuotaScope> scope = scopeOf(session);
if (scope.isEmpty()) {
return;
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.fileserver;
import dev.caskeleton.adapter.outbound.persistence.fileserver.entity.QuotaReservationEntity;
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileserverQuotaRepository;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.fileserver.api.metadata.QuotaScope;
import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort;
import java.time.Clock;
@@ -38,6 +39,7 @@ public class JpaQuotaReclaim implements QuotaReclaimPort {
@Override
public void reclaim(QuotaScope scope, long bytes) {
CallerTransaction.require("quota reclaim reclaim");
if (bytes < 0) {
throw new IllegalArgumentException("bytes must not be negative");
}
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.fileserver;
import dev.caskeleton.adapter.outbound.persistence.fileserver.entity.RecoveryItemEntity;
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileserverRecoveryRepository;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.recovery.ReconciliationStatus;
import dev.caskeleton.application.fileserver.recovery.RecoveryQueuePort;
@@ -37,6 +38,7 @@ public class JpaRecoveryQueue implements RecoveryQueuePort {
@Override
public void enqueue(FileId fileId, String reasonCode) {
CallerTransaction.require("recovery queue enqueue");
Instant now = clock.instant();
if (items.refreshPending(fileId.value(), reasonCode, now) > 0) {
return;
@@ -58,6 +60,7 @@ public class JpaRecoveryQueue implements RecoveryQueuePort {
@Override
public void resolve(FileId fileId, ReconciliationStatus status) {
CallerTransaction.require("recovery queue resolve");
items.resolvePending(fileId.value(), status.name(), clock.instant());
}
}
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.persistence.fileserver;
import dev.caskeleton.adapter.outbound.persistence.fileserver.entity.UploadSessionEntity;
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.JpaUploadSessionRepository;
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.UploadLeaseRepository;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.fileserver.api.UploadId;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
import dev.caskeleton.application.fileserver.api.error.FileserverException;
@@ -45,6 +46,7 @@ public class JpaUploadSession implements UploadSessionPort {
@Override
public UploadSession create(UploadSessionDraft draft) {
CallerTransaction.require("upload session create");
UploadSessionEntity entity =
new UploadSessionEntity(
draft.uploadId().value(),
@@ -64,6 +66,7 @@ public class JpaUploadSession implements UploadSessionPort {
@Override
public WriterLease acquireLease(
UploadId uploadId, String owner, Instant now, Duration leaseDuration, long expectedVersion) {
CallerTransaction.require("upload session acquireLease");
UUID token = UUID.randomUUID();
Instant leaseUntil = now.plus(leaseDuration);
int updated =
@@ -78,6 +81,7 @@ public class JpaUploadSession implements UploadSessionPort {
/** Extends an already-held lease; a writer that lost the lease can never renew it. */
@Override
public WriterLease renewLease(WriterLease lease, Instant now, Duration leaseDuration) {
CallerTransaction.require("upload session renewLease");
Instant leaseUntil = now.plus(leaseDuration);
int updated = leases.renewLease(lease.uploadId().value(), lease.token(), leaseUntil, now);
if (updated == 0) {
@@ -91,6 +95,7 @@ public class JpaUploadSession implements UploadSessionPort {
@Override
public UploadSession commitOffset(
UploadId uploadId, WriterLease lease, long expectedOffset, long committedOffset) {
CallerTransaction.require("upload session commitOffset");
Instant now = clock.instant();
int updated =
leases.commitOffset(uploadId.value(), lease.token(), expectedOffset, committedOffset, now);
@@ -106,16 +111,19 @@ public class JpaUploadSession implements UploadSessionPort {
@Override
public void releaseLease(UploadId uploadId, WriterLease lease) {
CallerTransaction.require("upload session releaseLease");
leases.releaseLease(uploadId.value(), lease.token(), clock.instant());
}
@Override
public boolean terminate(UploadId uploadId) {
CallerTransaction.require("upload session terminate");
return leases.terminate(uploadId.value(), clock.instant()) == 1;
}
@Override
public boolean claimForCleanup(UploadId uploadId, Instant now) {
CallerTransaction.require("upload session claimForCleanup");
return leases.claimForCleanup(uploadId.value(), now) == 1;
}
@@ -2,14 +2,12 @@ package dev.caskeleton.adapter.outbound.persistence.audit;
import dev.caskeleton.shared.concurrency.DomainContextKey;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import org.springframework.stereotype.Component;
/**
* Default {@link AuditContextPort}: reads the audit actor from the runtime-context-propagation seam
* ({@link DomainContextPropagator}) and falls back to {@code "system"}. The canonical actor key is
* isolated behind {@link #ACTOR_KEY} so a future key change touches one class (see README "audit").
*/
@Component
public class DomainContextAuditContext implements AuditContextPort {
static final String SYSTEM_ACTOR = "system";
@@ -0,0 +1,153 @@
package dev.caskeleton.adapter.outbound.persistence.autoconfigure;
import dev.caskeleton.adapter.outbound.persistence.audit.DomainContextAuditContext;
import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator;
import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping;
import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping;
import dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyReaper;
import dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyRecordJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.liveevent.JpaLiveEventReplay;
import dev.caskeleton.adapter.outbound.persistence.liveevent.LiveEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.lock.DistributedLockPersistenceConfig;
import dev.caskeleton.adapter.outbound.persistence.operation.DurableOperationJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.operation.JpaDurableOperationStore;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxReaper;
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import java.time.Clock;
import java.time.Duration;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.transaction.PlatformTransactionManager;
/**
* The JPA adapter's beans, declared one by one (review S2-#8a).
*
* <p>They used to be eight {@code @Component}/{@code @Repository} classes reached by a component
* scan of eight packages ({@code config.JpaAdapterComponentsConfig}), each carrying its own
* {@code @ConditionalOnProperty}. That was the third way this repository assembled persistence —
* notification and fileserver declare every bean in a configuration their leaf's auto-configuration
* imports — and it hid what the leaf contributes behind a package list. Now the answer is here: the
* always-present beans below, and one nested configuration per switched feature (outbox, live-event
* replay) that holds its condition once; the distributed lock keeps its own configuration. It is
* imported only by {@link PersistenceJpaAutoConfiguration}, which carries the JPA capability
* switch, so off is still structural. The PostgreSQL idempotency store itself is in {@link
* PostgreSqlIdempotencyStoreConfig}; its reaper, a JPA-repository bean, is here.
*
* <p>Package-private like the rest of this package, so the leaf's public surface does not grow by
* wiring. The keys in the conditions are the ones the classes carried; this change moves them, it
* does not rename them.
*/
@Configuration(proxyBeanMethods = false)
@Import({
DistributedLockPersistenceConfig.class,
JpaAdapterBeansConfig.Outbox.class,
JpaAdapterBeansConfig.LiveEventReplay.class,
JpaAdapterBeansConfig.IdempotencyExpiry.class
})
class JpaAdapterBeansConfig {
@Bean
StandardSqlStateErrorMapping standardSqlStateErrorMapping() {
return new StandardSqlStateErrorMapping();
}
@Bean
PersistenceExceptionTranslator persistenceExceptionTranslator(
List<SqlStateErrorMapping> mappings) {
return new PersistenceExceptionTranslator(mappings);
}
@Bean
SpringTransaction springTransaction(
PlatformTransactionManager transactionManager,
PersistenceExceptionTranslator exceptionTranslator) {
return new SpringTransaction(transactionManager, exceptionTranslator);
}
@Bean
DomainContextAuditContext domainContextAuditContext(DomainContextPropagator propagator) {
return new DomainContextAuditContext(propagator);
}
@Bean
JpaDurableOperationStore jpaDurableOperationStore(DurableOperationJpaRepository repository) {
return new JpaDurableOperationStore(repository);
}
/**
* The transactional outbox's store and its retention reaper, behind the outbox switch. The claim
* repository comes from the vendor configuration (PostgreSQL or H2).
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "ca-skeleton.outbox", name = "enabled", havingValue = "true")
static class Outbox {
@Bean
JpaOutboxStore jpaOutboxStore(
OutboxEventJpaRepository repository, OutboxClaimRepository claimRepository) {
return new JpaOutboxStore(repository, claimRepository);
}
// One reaper-local value; the outbox settings are declared and validated once, in
// composition:outbox-relay OutboxSettings.
@Bean
OutboxReaper outboxReaper(
OutboxEventJpaRepository repository,
Clock clock,
@Value("${ca-skeleton.outbox.published-retention:P7D}") Duration retention) {
return new OutboxReaper(repository, clock, retention);
}
}
/**
* Retained live-event history: on when replay is switched on, and only on PostgreSQL (the
* position allocator is an {@code INSERT … ON CONFLICT … RETURNING}). The retention has no
* default on purpose: a replay window nobody chose is one nobody sized.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(
prefix = "ca-skeleton.realtime.replay",
name = "enabled",
havingValue = "true")
@ConditionalOnProperty(
prefix = "ca-skeleton.persistence",
name = "vendor",
havingValue = "postgresql",
matchIfMissing = true)
static class LiveEventReplay {
@Bean
JpaLiveEventReplay jpaLiveEventReplay(
LiveEventJpaRepository repository,
JdbcOperations jdbc,
Clock clock,
@Value("${ca-skeleton.realtime.replay.retention}") Duration retention) {
return new JpaLiveEventReplay(repository, jdbc, clock, retention);
}
}
/**
* Purges expired owner-safe idempotency rows, for the PostgreSQL provider only. Scheduling is
* enabled by {@link PostgreSqlIdempotencyStoreConfig}, which carries the same condition.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(
name = "ca-skeleton.capabilities.idempotency.provider",
havingValue = "postgresql")
static class IdempotencyExpiry {
@Bean
IdempotencyReaper idempotencyReaper(IdempotencyRecordJpaRepository repository, Clock clock) {
return new IdempotencyReaper(repository, clock);
}
}
}
@@ -1,6 +1,5 @@
package dev.caskeleton.adapter.outbound.persistence.autoconfigure;
import dev.caskeleton.adapter.outbound.persistence.config.JpaAdapterComponentsConfig;
import dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings;
import dev.caskeleton.adapter.outbound.persistence.h2.H2PersistenceConfig;
import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlPersistenceConfig;
@@ -24,7 +23,7 @@ import org.springframework.context.annotation.Import;
matchIfMissing = true)
@EnableConfigurationProperties(PersistenceVendorSettings.class)
@Import({
JpaAdapterComponentsConfig.class,
JpaAdapterBeansConfig.class,
PostgreSqlPersistenceConfig.class,
H2PersistenceConfig.class,
PostgreSqlIdempotencyStoreConfig.class
@@ -12,8 +12,10 @@ import org.springframework.scheduling.annotation.EnableScheduling;
/**
* The PostgreSQL idempotency provider: the owner-safe store, the schema stream it needs, and (via
* {@code @EnableScheduling}) the scanned {@code IdempotencyReaper} that purges expired rows. The
* executor that drives the store is assembled once by the composition root.
* {@code @EnableScheduling}) the {@code IdempotencyReaper} that purges expired rows — declared
* beside the other JPA-repository beans in {@link JpaAdapterBeansConfig}, since this store is JDBC
* and assembles without a persistence unit. The executor that drives the store is assembled once by
* the composition root.
*/
@Configuration(proxyBeanMethods = false)
@EnableScheduling
@@ -1,75 +0,0 @@
package dev.caskeleton.adapter.outbound.persistence.config;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
/**
* Registers the JPA adapter's scanned components, which nothing registered (JPA-INT-006).
*
* <p>The composition root's {@code @ComponentScan} excludes {@code
* dev.caskeleton.adapter.outbound.persistence.**} by regex, and that exclusion is correct: it is
* what makes an optional capability optional, so a deployment with JPA off assembles no persistence
* beans rather than assembling them and hoping each one remembered to carry the switch.
*
* <p>What was missing is the other half. Eight classes in this leaf are written as scanned
* components — {@code SpringTransaction}, {@code PersistenceExceptionTranslator}, {@code
* StandardSqlStateErrorMapping}, {@code DomainContextAuditContext}, the idempotency store and its
* reaper, and the outbox store and its reaper — and once the broad scan stopped reaching them,
* nothing else did. They are annotated {@code @Component} and {@code @Repository} and were beans in
* no running application: {@code TransactionPort} in particular had no implementation at all, so
* every use case that opens a transaction had no port to open it with.
*
* <p>It surfaced as an unsatisfied dependency the first time a capability that needs a transaction
* was actually assembled — the notification orchestrator, in the local-notification-ingest lane —
* rather than as anything a unit test could see, because each of these classes is constructed
* directly by its own tests.
*
* <p>So the scan is restored, narrowed to the packages it should always have covered and reachable
* only through the leaf's own {@code PersistenceJpaAutoConfiguration}, which carries the JPA
* capability switch. Off is still structural.
*
* <p>Two packages are deliberately absent:
*
* <ul>
* <li>{@code ..persistence.fileserver} — gated on its own capability switch, scanned by {@code
* FileserverJpaPersistenceConfig} in the {@code persistence-fileserver} leaf;
* <li>{@code ..persistence.notification} — assembled explicitly, bean by bean, by {@code
* NotificationJpaPersistenceFacade} in the {@code persistence-notification} leaf.
* </ul>
*
* <p>Components under these packages keep their own {@code @ConditionalOnProperty} guards; being
* scanned makes them candidates, not unconditional beans.
*
* <p>{@code ..persistence.lock} is in the list for the same reason and with the same history.
* {@code DistributedLockPersistenceConfig} owns both lock providers — the in-process registry and
* the JDBC one — and was registered by nothing but a test calling {@code ctx.register(...)}. So a
* single-instance deployment had no {@code DistributedLockPort} at all, and a multi-instance one
* could not start: the composition root's own {@code DistributedLockConfig} asks for a bean
* qualified {@code jdbcDistributedLock} that only that configuration declares.
*
* <p>Each package's {@code @ConfigurationProperties} type is enabled by a configuration inside that
* same package — {@code DistributedLockPersistenceConfig} for {@code LockSettings} — rather than
* from here. Enabling it centrally would give {@code config} an edge to {@code lock} that the
* module map does not grant it, and the map is right: this class knows which packages to scan, not
* what is inside them. They need enabling at all because {@code @ConfigurationPropertiesScan}
* excludes this tree as deliberately as {@code @ComponentScan} does.
*/
@Configuration(proxyBeanMethods = false)
@ComponentScan(
basePackages = {
"dev.caskeleton.adapter.outbound.persistence.audit",
"dev.caskeleton.adapter.outbound.persistence.failure",
"dev.caskeleton.adapter.outbound.persistence.idempotency",
"dev.caskeleton.adapter.outbound.persistence.liveevent",
"dev.caskeleton.adapter.outbound.persistence.lock",
"dev.caskeleton.adapter.outbound.persistence.operation",
"dev.caskeleton.adapter.outbound.persistence.outbox",
"dev.caskeleton.adapter.outbound.persistence.transaction"
},
// Boot's hook for keeping a test's own configuration classes out of an application scan — the
// filter @SpringBootApplication declares for the same reason.
excludeFilters =
@ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class))
public class JpaAdapterComponentsConfig {}
@@ -10,7 +10,6 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
/**
* Classifies a Spring {@link DataAccessException} into a framework-neutral {@link OperationalError}
@@ -19,7 +18,6 @@ import org.springframework.stereotype.Component;
* SqlStateErrorMapping} SPI beans. See README "failure" for the SPI/fallback rationale and
* CLAUDE.md for the SQLState → Error Code matrix.
*/
@Component
public class PersistenceExceptionTranslator {
/** SQLState class prefix for connection failures → {@code DB_UNAVAILABLE}. */
@@ -2,7 +2,6 @@ package dev.caskeleton.adapter.outbound.persistence.failure;
import dev.caskeleton.shared.error.OperationalError;
import java.util.Map;
import org.springframework.stereotype.Component;
/**
* Core {@link SqlStateErrorMapping}: the portable, vendor-neutral SQLState rows every RDBMS
@@ -13,7 +12,6 @@ import org.springframework.stereotype.Component;
* {@code PostgreSqlState} — refers to them rather than repeating the literals, so {@code 40001} is
* written once, not once per table that happens to need it.
*/
@Component
public class StandardSqlStateErrorMapping implements SqlStateErrorMapping {
/** {@code 40001} serialization_failure. */
@@ -3,9 +3,7 @@ package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa;
import java.time.Clock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/**
@@ -13,10 +11,6 @@ import org.springframework.transaction.annotation.Transactional;
* moves {@code expires_at} forward on every completion and failure, and a claim is reset in place
* rather than re-inserted, so this is the only thing that bounds table growth.
*/
@Component
@ConditionalOnProperty(
name = "ca-skeleton.capabilities.idempotency.provider",
havingValue = "postgresql")
public class IdempotencyReaper {
private static final Logger log = LoggerFactory.getLogger(IdempotencyReaper.class);
@@ -12,11 +12,8 @@ import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.domain.Limit;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.stereotype.Repository;
/**
* Retained live-event history, on PostgreSQL.
@@ -36,16 +33,6 @@ import org.springframework.stereotype.Repository;
* The counter update and event insert share this method's transaction, so a failed event insert
* also rolls the allocation back.
*/
@Repository
@ConditionalOnProperty(
prefix = "ca-skeleton.realtime.replay",
name = "enabled",
havingValue = "true")
@ConditionalOnProperty(
prefix = "ca-skeleton.persistence",
name = "vendor",
havingValue = "postgresql",
matchIfMissing = true)
public class JpaLiveEventReplay implements LiveEventReplayPort {
/** The most one replay call will load, whatever the caller asks for. */
@@ -74,10 +61,7 @@ public class JpaLiveEventReplay implements LiveEventReplayPort {
* @param retention how long an appended event stays replayable
*/
public JpaLiveEventReplay(
LiveEventJpaRepository repository,
JdbcOperations jdbc,
Clock clock,
@Value("${ca-skeleton.realtime.replay.retention}") Duration retention) {
LiveEventJpaRepository repository, JdbcOperations jdbc, Clock clock, Duration retention) {
this.repository = Objects.requireNonNull(repository, "repository");
this.jdbc = Objects.requireNonNull(jdbc, "jdbc");
this.clock = Objects.requireNonNull(clock, "clock");
@@ -16,7 +16,6 @@ import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Repository;
/**
* The PostgreSQL-backed {@link DurableOperationStorePort}.
@@ -26,7 +25,6 @@ import org.springframework.stereotype.Repository;
* a window between the read and the write in which another worker can take the lease, and the
* lost-update it produces is exactly the case this store exists to prevent.
*/
@Repository
public class JpaDurableOperationStore implements DurableOperationStorePort {
private final DurableOperationJpaRepository repository;
@@ -28,8 +28,6 @@ import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Repository;
/**
* JPA-backed {@link OutboxAppendPort} + {@link OutboxStorePort}. {@link #append} and the claim/mark
@@ -43,8 +41,6 @@ import org.springframework.stereotype.Repository;
* columns repeat the contract id, aggregate id and correlation id for the claim gate and the
* metrics queries.
*/
@Repository
@ConditionalOnProperty(prefix = "ca-skeleton.outbox", name = "enabled", havingValue = "true")
public class JpaOutboxStore implements OutboxAppendPort, OutboxStorePort {
private static final Logger log = LoggerFactory.getLogger(JpaOutboxStore.class);
@@ -5,10 +5,7 @@ import java.time.Duration;
import java.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* Periodically purges PUBLISHED outbox rows older than the configured retention period, bounding
@@ -17,8 +14,6 @@ import org.springframework.stereotype.Component;
* <p>Deletes in batches of {@link #BATCH_SIZE}, each committed on its own, until a batch comes back
* short.
*/
@Component
@ConditionalOnProperty(prefix = "ca-skeleton.outbox", name = "enabled", havingValue = "true")
public class OutboxReaper {
/** Rows per delete statement and transaction. */
@@ -31,12 +26,7 @@ public class OutboxReaper {
private final Clock clock;
private final Duration retention;
// @Value is acceptable for this single reaper-local value; the settings are declared and
// validated once, in composition:outbox-relay OutboxSettings.
public OutboxReaper(
OutboxEventJpaRepository repository,
Clock clock,
@Value("${ca-skeleton.outbox.published-retention:P7D}") Duration retention) {
public OutboxReaper(OutboxEventJpaRepository repository, Clock clock, Duration retention) {
this.repository = repository;
this.clock = clock;
this.retention = retention;
@@ -8,8 +8,6 @@ import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import java.util.Locale;
import java.util.function.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionSynchronizationManager;
@@ -20,7 +18,6 @@ import org.springframework.transaction.support.TransactionTemplate;
* pinned to {@link Isolation#READ_COMMITTED}. See README "transaction" for why the templates are
* pre-built (mutable-template race) and CLAUDE.md for the mode table.
*/
@Component
public class SpringTransaction implements TransactionPort {
/** Upper bound on one {@link #inNew} transaction; the former compensation budget. */
@@ -35,7 +32,6 @@ public class SpringTransaction implements TransactionPort {
this(transactionManager, defaultExceptionTranslator());
}
@Autowired
public SpringTransaction(
PlatformTransactionManager transactionManager,
PersistenceExceptionTranslator exceptionTranslator) {
@@ -193,6 +193,21 @@ class PostgreSqlFileserverMetadataStoreIntegrationTest {
.contains(new FileOwner("user-1", Optional.of("tenant-a")));
}
/**
* A store write joins the use case's transaction; called without one, each statement would commit
* on its own and the write it belongs with would commit separately (review X1-#4, decision 33).
*/
@Test
void aMetadataInsertOutsideACallerTransactionIsRefused() {
// when
Throwable refused = catchThrowable(() -> files.insert(draft(FileId.of(UUID.randomUUID()))));
// then
assertThat(refused)
.isInstanceOf(IllegalStateException.class)
.hasMessage("file metadata insert requires an active caller transaction");
}
/** The deletable states come from the transition table, which has no VERIFYING -> DELETING. */
@Test
void aRecordInAStateWithNoDeletingEdgeIsNotMarkedDeleting() {
@@ -1,6 +1,7 @@
package dev.caskeleton.adapter.outbound.persistence.readiness;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderEventReplayWorker;
import dev.caskeleton.adapter.outbound.persistence.notification.platform.DeliveryAttemptJpaRepository;
@@ -17,8 +18,10 @@ import dev.caskeleton.application.notification.platform.api.NormalizedEventType;
import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent;
import dev.caskeleton.application.notification.platform.api.ProviderId;
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId;
import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome;
import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel;
import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState;
import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot;
import dev.caskeleton.application.notification.platform.callback.DeliveryProjection;
import dev.caskeleton.application.notification.platform.callback.ProjectionResult;
@@ -238,6 +241,32 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest {
.containsExactly(attempt.toString(), "FAILED", "IllegalStateException");
}
/**
* A store write joins the caller's transaction; without one each statement commits on its own
* (review X1-#4, decision 33). The passes above prove the production paths open one.
*/
@Test
void aRecipientTransitionOutsideACallerTransactionIsRefused() {
// given
UUID delivery = insertDelivery("READY_TO_DISPATCH", null, null);
JpaRecipientDeliveryStore store =
deliveries(context.getBean(RecipientDeliveryJpaRepository.class));
// when
Throwable refused =
catchThrowable(
() ->
store.transition(
new RecipientDeliveryId(delivery),
RecipientDeliveryState.CANCELED,
Optional.empty()));
// then
assertThat(refused)
.isInstanceOf(IllegalStateException.class)
.hasMessage("recipient delivery transition requires an active caller transaction");
}
private LeaseRecoveryService recovery() {
return new LeaseRecoveryService(
new JpaRecipientLeaseStore(context.getBean(RecipientDeliveryJpaRepository.class), clock),
@@ -26,8 +26,11 @@ import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.SharedEntityManagerCreator;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.support.TransactionTemplate;
/**
* Hibernate's own verdict on the notification mapping, against the migrated schema.
@@ -110,8 +113,11 @@ class PostgreSqlNotificationPersistenceUnitIntegrationTest {
try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) {
migrate(database);
JdbcTemplate jdbc = new JdbcTemplate(database.dataSource());
try (EntityManagerFactory emf = entityManagerFactory(database.dataSource());
EntityManager entityManager = emf.createEntityManager()) {
try (EntityManagerFactory emf = entityManagerFactory(database.dataSource())) {
// Spring-managed, as in production: the store refuses a write outside a caller transaction
// (CallerTransaction), and one opened on a private EntityManager is invisible to it.
EntityManager entityManager = SharedEntityManagerCreator.createSharedEntityManager(emf);
TransactionTemplate transactions = new TransactionTemplate(new JpaTransactionManager(emf));
AdminAuditJpaRepository repository =
new JpaRepositoryFactory(entityManager).getRepository(AdminAuditJpaRepository.class);
AtomicLong ids = new AtomicLong();
@@ -132,17 +138,19 @@ class PostgreSqlNotificationPersistenceUnitIntegrationTest {
Optional.empty(),
List.of("done"));
entityManager.getTransaction().begin();
AdminOperationClaim first = store.claim("op-1", fingerprint, actor, "ADMIN_PROVIDER_STATE");
AdminOperationClaim first =
transactions.execute(
status -> {
AdminOperationClaim claimed =
store.claim("op-1", fingerprint, actor, "ADMIN_PROVIDER_STATE");
store.save(result, actor, "ADMIN_PROVIDER_STATE");
return claimed;
});
assertThat(first.outcome()).isEqualTo(AdminOperationClaim.Outcome.CLAIMED);
store.save(result, actor, "ADMIN_PROVIDER_STATE");
entityManager.getTransaction().commit();
entityManager.clear();
entityManager.getTransaction().begin();
AdminOperationClaim second =
store.claim("op-1", fingerprint, actor, "ADMIN_PROVIDER_STATE");
entityManager.getTransaction().commit();
transactions.execute(
status -> store.claim("op-1", fingerprint, actor, "ADMIN_PROVIDER_STATE"));
assertThat(second.outcome()).isEqualTo(AdminOperationClaim.Outcome.REPLAY);
assertThat(second.existing()).isPresent();
@@ -20,8 +20,11 @@ import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.SharedEntityManagerCreator;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.support.TransactionTemplate;
/**
* Two workers, one job, and the write that has to lose.
@@ -224,10 +227,17 @@ class PostgreSqlRecipientLeaseFencingIntegrationTest {
}
}
/** A migrated database plus the real repository, built without a Spring context. */
/**
* A migrated database plus the real repository, built without a Spring context.
*
* <p>The repository runs on the shared, transaction-bound entity manager and transactions come
* from a {@link JpaTransactionManager}, as in production: the lease store's writes refuse to run
* outside a caller transaction ({@code CallerTransaction}), and a transaction opened on a private
* {@code EntityManager} is not one Spring can see.
*/
private record Fixture(
DataSource dataSource,
EntityManager entityManager,
TransactionTemplate transactions,
RecipientDeliveryJpaRepository repository) {
static Fixture migrated(PostgreSqlReadinessSupport database) {
@@ -269,11 +279,12 @@ class PostgreSqlRecipientLeaseFencingIntegrationTest {
"hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect"));
factoryBean.afterPropertiesSet();
EntityManagerFactory factory = factoryBean.getObject();
EntityManager entityManager = factory.createEntityManager();
EntityManager sharedEntityManager =
SharedEntityManagerCreator.createSharedEntityManager(factory);
return new Fixture(
database.dataSource(),
entityManager,
new JpaRepositoryFactory(entityManager)
new TransactionTemplate(new JpaTransactionManager(factory)),
new JpaRepositoryFactory(sharedEntityManager)
.getRepository(RecipientDeliveryJpaRepository.class));
}
@@ -289,21 +300,10 @@ class PostgreSqlRecipientLeaseFencingIntegrationTest {
}
/**
* Runs a modifying repository call inside a transaction.
*
* <p>Production supplies one through the application's transaction port; without a Spring
* context this test has to open it, and a modifying JPA query genuinely requires one.
* Runs a lease write inside a caller transaction, as the application's transaction port does.
*/
<T> T inTransaction(java.util.function.Supplier<T> work) {
entityManager.getTransaction().begin();
try {
T result = work.get();
entityManager.getTransaction().commit();
return result;
} catch (RuntimeException failure) {
entityManager.getTransaction().rollback();
throw failure;
}
return transactions.execute(status -> work.get());
}
UUID insertDueJob() {
@@ -76,13 +76,22 @@ class JpaModuleBoundaryTest {
"autoconfigure",
Set.of(
"api",
// audit, failure, liveevent, lock, operation and outbox: the adapters a component
// scan of eight packages used to register are declared bean by bean in
// JpaAdapterBeansConfig (review S2-#8a), so the leaf's root names what it builds.
"audit",
"config",
"failure",
"h2",
"hibernate",
// The PostgreSQL idempotency store, which lives with its feature
// (idempotency.postgresql) and is registered from here.
"idempotency",
"liveevent",
"lock",
"observation",
"operation",
"outbox",
"postgresql",
"security",
"transaction")),
@@ -0,0 +1,36 @@
package dev.caskeleton.adapter.outbound.persistence.autoconfigure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyReaper;
import dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyRecordJpaRepository;
import java.time.Clock;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
/** The expired-row reaper exists for the PostgreSQL idempotency provider and for no other. */
class IdempotencyReaperWiringTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner()
.withUserConfiguration(JpaAdapterBeansConfig.IdempotencyExpiry.class)
.withBean(
IdempotencyRecordJpaRepository.class,
() -> mock(IdempotencyRecordJpaRepository.class))
.withBean(Clock.class, Clock::systemUTC);
@Test
void thePostgresqlSelectionHasTheExpiredRecordReaper() {
runner
.withPropertyValues("ca-skeleton.capabilities.idempotency.provider=postgresql")
.run(context -> assertThat(context).hasSingleBean(IdempotencyReaper.class));
}
@Test
void otherSelectionsHaveNoReaper() {
runner
.withPropertyValues("ca-skeleton.capabilities.idempotency.provider=redis")
.run(context -> assertThat(context).doesNotHaveBean(IdempotencyReaper.class));
}
}
@@ -0,0 +1,75 @@
package dev.caskeleton.adapter.outbound.persistence.autoconfigure;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static org.assertj.core.api.Assertions.assertThat;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.core.importer.ImportOption;
import dev.caskeleton.adapter.outbound.persistence.audit.DomainContextAuditContext;
import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator;
import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping;
import dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyReaper;
import dev.caskeleton.adapter.outbound.persistence.liveevent.JpaLiveEventReplay;
import dev.caskeleton.adapter.outbound.persistence.operation.JpaDurableOperationStore;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxReaper;
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction;
import java.lang.reflect.Method;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
/** The JPA adapter declares its beans one by one; nothing in it waits to be scanned (S2-#8a). */
class JpaAdapterBeansConfigTest {
private static final JavaClasses PRODUCTION_CLASSES =
new ClassFileImporter()
.withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
.importPackages("dev.caskeleton.adapter.outbound.persistence");
@Test
void everyAdapterTheScanUsedToRegisterIsDeclaredAsABean() {
// when
Stream<Class<?>> declared =
Stream.of(
JpaAdapterBeansConfig.class,
JpaAdapterBeansConfig.Outbox.class,
JpaAdapterBeansConfig.LiveEventReplay.class,
JpaAdapterBeansConfig.IdempotencyExpiry.class)
.flatMap(type -> Stream.of(type.getDeclaredMethods()))
.filter(method -> method.isAnnotationPresent(Bean.class))
.map(Method::getReturnType);
// then
assertThat(declared)
.contains(
StandardSqlStateErrorMapping.class,
PersistenceExceptionTranslator.class,
SpringTransaction.class,
DomainContextAuditContext.class,
JpaDurableOperationStore.class,
JpaOutboxStore.class,
OutboxReaper.class,
JpaLiveEventReplay.class,
IdempotencyReaper.class);
}
@Test
void noProductionClassCarriesAScanStereotype() {
noClasses()
.should()
.beAnnotatedWith(Component.class)
.orShould()
.beAnnotatedWith(Repository.class)
.orShould()
.beAnnotatedWith(Service.class)
.because(
"the leaf's beans are declared in its auto-configuration; a stereotype here would be"
+ " registered only by whichever scan happened to reach it")
.check(PRODUCTION_CLASSES);
}
}
@@ -1,8 +1,10 @@
package dev.caskeleton.adapter.outbound.persistence.liveevent;
package dev.caskeleton.adapter.outbound.persistence.autoconfigure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import dev.caskeleton.adapter.outbound.persistence.liveevent.JpaLiveEventReplay;
import dev.caskeleton.adapter.outbound.persistence.liveevent.LiveEventJpaRepository;
import java.time.Clock;
import org.junit.jupiter.api.Test;
import org.springframework.boot.convert.ApplicationConversionService;
@@ -72,7 +74,7 @@ class JpaLiveEventReplayActivationTest {
}
@Configuration(proxyBeanMethods = false)
@Import(JpaLiveEventReplay.class)
@Import(JpaAdapterBeansConfig.LiveEventReplay.class)
static class TestConfig {
@Bean
@@ -1,9 +1,11 @@
package dev.caskeleton.adapter.outbound.persistence.outbox.jpa;
package dev.caskeleton.adapter.outbound.persistence.autoconfigure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import java.lang.reflect.Constructor;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxReaper;
import java.lang.reflect.Parameter;
import java.time.Clock;
import java.time.Duration;
@@ -44,6 +46,11 @@ class OutboxReaperWiringTest {
return mock(OutboxEventJpaRepository.class);
}
@Bean
OutboxClaimRepository outboxClaimRepository() {
return mock(OutboxClaimRepository.class);
}
@Bean
Clock clock() {
return Clock.systemUTC();
@@ -70,7 +77,7 @@ class OutboxReaperWiringTest {
ctx ->
ctx.getBeanFactory()
.setConversionService(ApplicationConversionService.getSharedInstance()))
.withUserConfiguration(MinimalConfig.class, OutboxReaper.class);
.withUserConfiguration(MinimalConfig.class, JpaAdapterBeansConfig.Outbox.class);
// -----------------------------------------------------------------------
// 1. Spring wiring — context must start with default P7D retention
@@ -120,12 +127,15 @@ class OutboxReaperWiringTest {
"${ca-skeleton.outbox.published-retention:P7D}";
@Test
void durationRetentionConstructorParameterCarriesValueAnnotationWithExactExpression() {
Constructor<?>[] ctors = OutboxReaper.class.getDeclaredConstructors();
assertThat(ctors).as("OutboxReaper must have exactly one constructor").hasSize(1);
Constructor<?> ctor = ctors[0];
Parameter[] params = ctor.getParameters();
void durationRetentionBeanParameterCarriesValueAnnotationWithExactExpression()
throws NoSuchMethodException {
// The reaper is built by the outbox configuration (review S2-#8a); the key lives on its bean
// method.
Parameter[] params =
JpaAdapterBeansConfig.Outbox.class
.getDeclaredMethod(
"outboxReaper", OutboxEventJpaRepository.class, Clock.class, Duration.class)
.getParameters();
// Find the Duration parameter
Parameter retentionParam = null;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.outbox.jpa;
package dev.caskeleton.adapter.outbound.persistence.autoconfigure;
import static org.assertj.core.api.Assertions.assertThat;
@@ -10,9 +10,9 @@ import org.springframework.core.annotation.AnnotatedElementUtils;
class OutboxSwitchWiringContractTest {
@Test
void legacyStoreAndReaperRequireTheOutboxSwitch() {
assertOutboxSwitch(JpaOutboxStore.class);
assertOutboxSwitch(OutboxReaper.class);
void theStoreAndReaperConfigurationRequiresTheOutboxSwitch() {
// Both beans are declared by one configuration, which holds the switch once (review S2-#8a).
assertOutboxSwitch(JpaAdapterBeansConfig.Outbox.class);
}
private static void assertOutboxSwitch(Class<?> type) {
@@ -2,7 +2,6 @@ package dev.caskeleton.adapter.outbound.persistence.autoconfigure;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.config.JpaAdapterComponentsConfig;
import dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings;
import dev.caskeleton.adapter.outbound.persistence.h2.H2PersistenceConfig;
import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlPersistenceConfig;
@@ -64,7 +63,7 @@ class PersistenceJpaAutoConfigurationTest {
assertThat(Arrays.asList(imports.value()))
.contains(
JpaAdapterComponentsConfig.class,
JpaAdapterBeansConfig.class,
PostgreSqlPersistenceConfig.class,
H2PersistenceConfig.class,
// No FileserverJpaPersistenceConfig. The Fileserver capability's persistence is its own
@@ -1,21 +0,0 @@
package dev.caskeleton.adapter.outbound.persistence.config;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.ComponentScan;
class JpaAdapterComponentsConfigTest {
@Test
void operationAndLiveEventAdaptersAreInsideTheCapabilityOwnedComponentScan() {
ComponentScan scan = JpaAdapterComponentsConfig.class.getAnnotation(ComponentScan.class);
assertThat(scan).isNotNull();
assertThat(Arrays.asList(scan.basePackages()))
.contains(
"dev.caskeleton.adapter.outbound.persistence.operation",
"dev.caskeleton.adapter.outbound.persistence.liveevent");
}
}
@@ -13,7 +13,6 @@ import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.persistence.autoconfigure.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/**
@@ -72,18 +71,6 @@ class PersistenceEntityScanCoverageTest {
.isEmpty();
}
@Test
@DisplayName("always-installed port adapters are included in the component scan")
void operationAndLiveEventAdaptersAreScanned() {
List<String> componentPackages =
List.of(JpaAdapterComponentsConfig.class.getAnnotation(ComponentScan.class).basePackages());
assertThat(componentPackages)
.contains(
"dev.caskeleton.adapter.outbound.persistence.operation",
"dev.caskeleton.adapter.outbound.persistence.liveevent");
}
@Test
@DisplayName("the always-installed scan never names the persistence root")
void theRootIsNeverScanned() {
@@ -1,24 +0,0 @@
package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
class IdempotencyActivationContractTest {
@Test
void reaperRunsOnlyWhenThePostgresqlProviderIsSelected() {
// when
ConditionalOnProperty condition =
IdempotencyReaper.class.getAnnotation(ConditionalOnProperty.class);
// then
assertThat(condition)
.extracting(
c -> c.name()[0],
ConditionalOnProperty::havingValue,
ConditionalOnProperty::matchIfMissing)
.containsExactly("ca-skeleton.capabilities.idempotency.provider", "postgresql", false);
}
}
@@ -1,11 +1,9 @@
package dev.caskeleton.adapter.outbound.mongo;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.data.mongodb.autoconfigure.DataMongoAutoConfiguration;
import org.springframework.boot.mongodb.autoconfigure.MongoAutoConfiguration;
import org.springframework.context.annotation.Configuration;
/**
* Opt-in wiring for MongoDB infrastructure. The configuration, Mongo client, and template activate
@@ -17,12 +15,10 @@ import org.springframework.context.annotation.Configuration;
* on the classpath. A consuming project adds its document, repository, and mapping adapter in this
* leaf and explicitly owns any repository scanning it requires.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(
prefix = "ca-skeleton.persistence-mongo",
name = "enabled",
havingValue = "true",
matchIfMissing = true)
// Deliberately not a @Configuration (review S2-#8a). The capability switch is
// MongoRootAutoConfiguration's alone, and this class is reached only through that root's
// @Import, which processes it all the same. Without a stereotype, a component scan that reaches
// this leaf cannot register it apart from the root — the reason it used to repeat the switch.
@EnableConfigurationProperties(MongoPersistenceSettings.class)
@ImportAutoConfiguration({MongoAutoConfiguration.class, DataMongoAutoConfiguration.class})
public class MongoPersistenceConfig {}
@@ -4,10 +4,12 @@ import dev.caskeleton.adapter.outbound.mongo.autoconfigure.MongoPlatformHealthIn
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** Internal Actuator health composition for the Mongo platform. */
@Configuration(proxyBeanMethods = false)
// Deliberately not a @Configuration (review S2-#8a). The capability switch is
// MongoRootAutoConfiguration's alone, and this class is reached only through that root's
// @Import, which processes it all the same. Without a stereotype, a component scan that reaches
// this leaf cannot register it apart from the root — the reason it used to repeat the switch.
class MongoPlatformHealthConfiguration {
@Bean("mongoPlatformHealthContributor")
@@ -4,7 +4,6 @@ import dev.caskeleton.adapter.outbound.mongo.observation.MongoDriverObservabilit
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.mongodb.autoconfigure.MongoClientSettingsBuilderCustomizer;
import org.springframework.context.annotation.Bean;
@@ -24,12 +23,10 @@ import org.springframework.context.annotation.Bean;
* different things on purpose, and neither is derived from the other, so a command appears once in
* each rather than twice in one.
*/
@org.springframework.context.annotation.Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(
prefix = "ca-skeleton.persistence-mongo",
name = "enabled",
havingValue = "true",
matchIfMissing = true)
// Deliberately not a @Configuration (review S2-#8a). The capability switch is
// MongoRootAutoConfiguration's alone, and this class is reached only through that root's
// @Import, which processes it all the same. Without a stereotype, a component scan that reaches
// this leaf cannot register it apart from the root — the reason it used to repeat the switch.
public class MongoDriverObservabilityAutoConfiguration {
/** The customizer Boot applies when it builds the client. */
@@ -20,7 +20,6 @@ import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
@@ -38,13 +37,11 @@ import org.springframework.data.mongodb.core.MongoTemplate;
* absent for the same reason, and deliberately: it is constructed by a migration or deployment job
* with its own credential.
*/
@org.springframework.context.annotation.Configuration(proxyBeanMethods = false)
// Deliberately not a @Configuration (review S2-#8a). The capability switch is
// MongoRootAutoConfiguration's alone, and this class is reached only through that root's
// @Import, which processes it all the same. Without a stereotype, a component scan that reaches
// this leaf cannot register it apart from the root — the reason it used to repeat the switch.
@ConditionalOnClass(MongoTemplate.class)
@ConditionalOnProperty(
prefix = "ca-skeleton.persistence-mongo",
name = "enabled",
havingValue = "true",
matchIfMissing = true)
@EnableConfigurationProperties(MongoPlatformSettings.class)
@Import(MongoMappingConfiguration.class)
public class MongoPlatformAutoConfiguration {
@@ -5,9 +5,7 @@ import dev.caskeleton.adapter.outbound.mongo.mapping.type.MongoTypeMetadataRegis
import dev.caskeleton.adapter.outbound.mongo.mapping.type.PolicyAwareMongoTypeMapper;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
@@ -20,16 +18,10 @@ import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
* guard runs at wiring time so a manifest that asks for {@code LocalDateTime} without a registered
* converter fails before the first document is written rather than after.
*/
@Configuration(proxyBeanMethods = false)
// Carries the platform's own condition, not only the auto-configuration's. This class is an
// ordinary @Configuration, so an application whose component scan reaches this leaf finds it
// directly — and then a deployment with the master flag off still built mapping beans for a
// platform it had switched off.
@ConditionalOnProperty(
prefix = "ca-skeleton.persistence-mongo",
name = "enabled",
havingValue = "true",
matchIfMissing = true)
// Deliberately not a @Configuration (review S2-#8a). The capability switch is
// MongoRootAutoConfiguration's alone, and this class is reached only through that root's
// @Import, which processes it all the same. Without a stereotype, a component scan that reaches
// this leaf cannot register it apart from the root — the reason it used to repeat the switch.
public class MongoMappingConfiguration {
/** The deployment's representation manifest. Override the bean to change it deliberately. */
@@ -1,11 +1,20 @@
package dev.caskeleton.adapter.outbound.mongo.autoconfigure;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.mongo.mapping.MongoMappingConfiguration;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.lang.ArchCondition;
import com.tngtech.archunit.lang.ConditionEvents;
import com.tngtech.archunit.lang.SimpleConditionEvent;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
/**
* What the README says the auto-configuration registers, and what it did.
@@ -15,9 +24,11 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
* constructed them directly, and no application context ever ran them. A deployment could enable
* the platform against a topology it does not support and find out at the first transaction.
*
* <p>The mapping configuration had the opposite problem. It is an ordinary {@code @Configuration},
* so an application whose component scan reaches this leaf found it directly — and a deployment
* with the master flag off still built mapping beans for a platform it had switched off.
* <p>The mapping configuration had the opposite problem. It was an ordinary {@code @Configuration},
* so an application whose component scan reached this leaf found it directly — and a deployment
* with the master flag off still built mapping beans for a platform it had switched off. It used to
* repeat the switch; now nothing below the root carries a stereotype, so the root's switch is the
* only one and a scan has nothing else to find (review S2-#8a).
*/
class MongoPlatformWiringTest {
@@ -52,29 +63,57 @@ class MongoPlatformWiringTest {
.contains("mongoAtomicOperations", "mongoBulkExecutor", "mongoAtomicPolicyRegistry");
}
/**
* The one switch: whatever a component scan could register is switched itself.
*
* <p>Only the two {@code AutoConfiguration.imports} entries carry a stereotype; everything they
* import is a plain class the import processes, so a scan that reaches this leaf cannot build a
* Mongo bean for a platform that is off.
*/
@Test
@DisplayName("the mapping configuration carries the platform's own switch")
void theMappingConfigurationCarriesThePlatformSwitch() {
ConditionalOnProperty condition =
MongoMappingConfiguration.class.getAnnotation(ConditionalOnProperty.class);
assertThat(condition)
.as("a component scan that reaches this leaf finds this class directly")
.isNotNull();
assertThat(condition.prefix()).isEqualTo("ca-skeleton.persistence-mongo");
assertThat(condition.name()).containsExactly("enabled");
assertThat(condition.havingValue()).isEqualTo("true");
void everyClassAScanCouldRegisterCarriesTheMongoSwitch() {
classes()
.that()
.areMetaAnnotatedWith(Component.class)
.should(carryTheMongoSwitch())
.check(PRODUCTION_CLASSES);
}
@Test
@DisplayName("the platform itself is off unless the switch is on")
void thePlatformIsOffUnlessTheSwitchIsOn() {
ConditionalOnProperty condition =
MongoPlatformAutoConfiguration.class.getAnnotation(ConditionalOnProperty.class);
void theImportedConfigurationsCarryNoStereotype() {
noClasses()
.that()
.haveNameMatching(
"dev\\.caskeleton\\.adapter\\.outbound\\.mongo\\.("
+ "autoconfigure\\.MongoPlatformAutoConfiguration"
+ "|autoconfigure\\.MongoDriverObservabilityAutoConfiguration"
+ "|mapping\\.MongoMappingConfiguration"
+ "|MongoPersistenceConfig"
+ "|MongoPlatformHealthConfiguration)")
.should()
.beMetaAnnotatedWith(Component.class)
.check(PRODUCTION_CLASSES);
}
assertThat(condition).isNotNull();
assertThat(condition.havingValue())
.as("no matchIfMissing: a platform this large is opt-in")
.isEqualTo("true");
private static final JavaClasses PRODUCTION_CLASSES =
new ClassFileImporter()
.withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
.importPackages("dev.caskeleton.adapter.outbound.mongo");
private static ArchCondition<JavaClass> carryTheMongoSwitch() {
return new ArchCondition<>("carry ca-skeleton.persistence-mongo.enabled") {
@Override
public void check(JavaClass javaClass, ConditionEvents events) {
ConditionalOnProperty condition =
javaClass.reflect().getAnnotation(ConditionalOnProperty.class);
boolean switched =
condition != null
&& condition.prefix().equals("ca-skeleton.persistence-mongo")
&& java.util.Arrays.asList(condition.name()).equals(java.util.List.of("enabled"));
events.add(
new SimpleConditionEvent(
javaClass, switched, javaClass.getName() + " is registrable without the switch"));
}
};
}
}
@@ -12,8 +12,10 @@ plugins {
//
// The package was self-contained — it imported `application.notification`, JPA, Hibernate, Spring
// Data, JDBC and Flyway, and not one type from any other `persistence.*` package — so the move
// needed no seam. It does not depend on `persistence-jpa`: it contributes entities, repositories
// and stores to whatever persistence unit the application already has.
// needed no seam. It contributes entities, repositories and stores to whatever persistence unit the
// application already has. Its one `persistence-jpa` import is `CallerTransaction`: every store
// write joins the use case's transaction, and the guard that refuses a write without one lives
// there, once (owner decision 33, review X1-#4).
//
// The migrations moved with their bytes and their classpath location unchanged
// (`db/migration/jpa/notification-platform`), so Flyway computes the same version and checksum
@@ -22,6 +24,7 @@ plugins {
dependencies {
implementation project(':application-core')
implementation project(':application-notification')
implementation project(':adapter:outbound:persistence-jpa')
implementation 'org.springframework.boot:spring-boot-autoconfigure'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
@@ -33,6 +33,7 @@ com.google.guava:guava:33.6.0-jre=checkstyle
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor
com.h2database:h2:2.4.240=runtimeClasspath,testRuntimeClasspath
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
@@ -47,7 +48,9 @@ info.picocli:picocli:4.7.7=checkstyle
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-core:1.16.7=runtimeClasspath,testRuntimeClasspath
io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.projectreactor:reactor-core:3.8.7=runtimeClasspath,testRuntimeClasspath
jakarta.activation:jakarta.activation-api:2.1.4=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
jakarta.inject:jakarta.inject-api:2.0.1=runtimeClasspath,testRuntimeClasspath
@@ -58,6 +61,7 @@ javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor
jaxen:jaxen:2.0.6=spotbugs
net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath
net.bytebuddy:byte-buddy:1.17.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
net.logstash.logback:logstash-logback-encoder:8.0=runtimeClasspath,testRuntimeClasspath
net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath
net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
@@ -83,6 +87,7 @@ org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
org.aspectj:aspectjweaver:1.9.25.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath
org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath
org.checkerframework:checker-qual:3.55.1=runtimeClasspath,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
@@ -90,10 +95,12 @@ org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.eclipse.angus:angus-activation:2.0.3=runtimeClasspath,testRuntimeClasspath
org.flywaydb:flyway-core:11.14.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.flywaydb:flyway-database-postgresql:11.14.1=runtimeClasspath,testRuntimeClasspath
org.glassfish.jaxb:jaxb-core:4.0.9=runtimeClasspath,testRuntimeClasspath
org.glassfish.jaxb:jaxb-runtime:4.0.9=runtimeClasspath,testRuntimeClasspath
org.glassfish.jaxb:txw2:4.0.9=runtimeClasspath,testRuntimeClasspath
org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath
org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath
org.hibernate.models:hibernate-models:1.0.1=runtimeClasspath,testRuntimeClasspath
org.hibernate.orm:hibernate-core:7.2.24.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.javassist:javassist:3.28.0-GA=checkstyle
@@ -108,6 +115,7 @@ org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath
org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit:junit-bom:6.1.0=spotbugs
org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath
org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath
org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath
org.objenesis:objenesis:3.3=testRuntimeClasspath
@@ -123,6 +131,8 @@ org.ow2.asm:asm-util:9.10.1=spotbugs
org.ow2.asm:asm:9.10.1=spotbugs
org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor
org.postgresql:postgresql:42.7.13=runtimeClasspath,testRuntimeClasspath
org.reactivestreams:reactive-streams:1.0.4=runtimeClasspath,testRuntimeClasspath
org.reflections:reflections:0.10.2=checkstyle
org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath
org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -132,6 +142,7 @@ org.slf4j:slf4j-simple:2.0.18=checkstyle
org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-data-commons:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-data-jpa:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-flyway:4.0.8=runtimeClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-hibernate:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath
@@ -142,6 +153,7 @@ org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,t
org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-sql:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-data-jpa:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-flyway:4.0.8=runtimeClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jdbc:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -162,6 +174,8 @@ org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRunti
org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.data:spring-data-commons:4.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.data:spring-data-jpa:4.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.integration:spring-integration-core:7.0.6=runtimeClasspath,testRuntimeClasspath
org.springframework.integration:spring-integration-jdbc:7.0.6=runtimeClasspath,testRuntimeClasspath
org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-aspects:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -169,6 +183,7 @@ org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testC
org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-jdbc:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-messaging:7.0.9=runtimeClasspath,testRuntimeClasspath
org.springframework:spring-orm:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-tx:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.notification.platform;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.notification.platform.admin.AdminActor;
import dev.caskeleton.application.notification.platform.admin.AdminOperationResult;
import dev.caskeleton.application.notification.platform.admin.AdminOperationStorePort;
@@ -32,6 +33,7 @@ public final class JpaAdminOperationStore implements AdminOperationStorePort {
@Override
public dev.caskeleton.application.notification.platform.admin.AdminOperationClaim claim(
String operationId, String commandFingerprint, AdminActor actor, String action) {
CallerTransaction.require("admin operation claim");
Objects.requireNonNull(operationId, "operationId");
Objects.requireNonNull(commandFingerprint, "commandFingerprint");
Objects.requireNonNull(actor, "actor");
@@ -90,6 +92,7 @@ public final class JpaAdminOperationStore implements AdminOperationStorePort {
@Override
public AdminOperationResult save(AdminOperationResult result, AdminActor actor, String action) {
CallerTransaction.require("admin operation save");
Objects.requireNonNull(result, "result");
Objects.requireNonNull(actor, "actor");
Objects.requireNonNull(action, "action");
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.notification.platform;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.notification.platform.api.ContactPointId;
import dev.caskeleton.application.notification.platform.api.TenantId;
import dev.caskeleton.application.notification.platform.contact.ContactPointStatus;
@@ -38,6 +39,7 @@ public final class JpaContactPointStore implements ContactPointStorePort {
@Override
public ContactPointRecord save(ContactPointRecord record) {
CallerTransaction.require("contact point save");
Objects.requireNonNull(record, "record");
return contactPoints
.findByTenantIdAndId(record.tenantId().value(), record.id().value())
@@ -57,6 +59,7 @@ public final class JpaContactPointStore implements ContactPointStorePort {
@Override
public ContactPointRecord updateStatus(
TenantId tenantId, ContactPointId id, ContactPointStatus status, String reasonCode) {
CallerTransaction.require("contact point updateStatus");
Objects.requireNonNull(status, "status");
Objects.requireNonNull(reasonCode, "reasonCode");
ContactPointEntity entity =
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.notification.platform;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.notification.platform.api.ContactPointId;
import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId;
import dev.caskeleton.application.notification.platform.api.NotificationId;
@@ -58,12 +59,14 @@ public final class JpaDeliveryAttemptStore
@Override
public DeliveryAttemptRecord insertDispatching(DeliveryAttemptRecord attempt) {
CallerTransaction.require("delivery attempt insertDispatching");
Objects.requireNonNull(attempt, "attempt");
return toRecord(attempts.saveAndFlush(toEntity(attempt)));
}
@Override
public DeliveryAttemptRecord recordOutcome(DeliveryAttemptRecord attempt) {
CallerTransaction.require("delivery attempt recordOutcome");
Objects.requireNonNull(attempt, "attempt");
DeliveryAttemptEntity entity =
attempts
@@ -181,6 +184,7 @@ public final class JpaDeliveryAttemptStore
@Override
public boolean claimSuppressionSideEffect(DeliveryAttemptId attemptId) {
CallerTransaction.require("delivery attempt claimSuppressionSideEffect");
Objects.requireNonNull(attemptId, "attemptId");
return attempts
.findById(attemptId.value())
@@ -197,6 +201,7 @@ public final class JpaDeliveryAttemptStore
@Override
public void save(DeliveryAttemptId attemptId, DeliveryProjection projection) {
CallerTransaction.require("delivery attempt save");
Objects.requireNonNull(attemptId, "attemptId");
Objects.requireNonNull(projection, "projection");
DeliveryAttemptEntity entity =
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.notification.platform;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.notification.platform.api.NotificationId;
import dev.caskeleton.application.notification.platform.api.RequestStatus;
import dev.caskeleton.application.notification.platform.api.TenantId;
@@ -41,6 +42,7 @@ public final class JpaNotificationRequestStore implements NotificationRequestSto
@Override
public NotificationRequestInsertOutcome insert(
NotificationRequestRecord request, List<RecipientDeliveryRecord> jobs) {
CallerTransaction.require("notification request insert");
Objects.requireNonNull(request, "request");
Objects.requireNonNull(jobs, "jobs");
@@ -128,6 +130,7 @@ public final class JpaNotificationRequestStore implements NotificationRequestSto
@Override
public NotificationRequestRecord updateStatus(
TenantId tenantId, NotificationId notificationId, RequestStatus status) {
CallerTransaction.require("notification request updateStatus");
Objects.requireNonNull(tenantId, "tenantId");
Objects.requireNonNull(notificationId, "notificationId");
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.notification.platform;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot;
import dev.caskeleton.application.notification.platform.callback.NotificationSideEffectPort;
import dev.caskeleton.application.notification.platform.callback.SuppressionFacts;
@@ -38,6 +39,7 @@ public final class JpaNotificationSideEffect implements NotificationSideEffectPo
@Override
public void apply(DeliveryAttemptSnapshot attempt, SuppressionFacts facts) {
CallerTransaction.require("notification side effect apply");
Objects.requireNonNull(attempt, "attempt");
Objects.requireNonNull(facts, "facts");
if (!facts.requiresSuppression()) {
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.notification.platform;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.notification.platform.api.NotificationId;
import dev.caskeleton.application.notification.platform.api.TenantId;
import dev.caskeleton.application.notification.platform.api.routing.Channel;
@@ -47,6 +48,7 @@ public final class JpaPolicyStores {
@Override
public PreferenceRecord save(PreferenceRecord record) {
CallerTransaction.require("preference save");
Objects.requireNonNull(record, "record");
String preferred = encode(record.preferredOrder());
String muted = encode(List.copyOf(record.mutedChannels()));
@@ -116,6 +118,7 @@ public final class JpaPolicyStores {
@Override
public ConsentRecord save(ConsentRecord record) {
CallerTransaction.require("consent save");
Objects.requireNonNull(record, "record");
return toRecord(
consents.saveAndFlush(
@@ -159,6 +162,7 @@ public final class JpaPolicyStores {
@Override
public DeduplicationResult insertOrFind(
RecipientIdentity recipient, String dedupKey, long windowBucket, NotificationId candidate) {
CallerTransaction.require("deduplication claim insertOrFind");
Objects.requireNonNull(recipient, "recipient");
Objects.requireNonNull(dedupKey, "dedupKey");
Objects.requireNonNull(candidate, "candidate");
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.notification.platform;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId;
import dev.caskeleton.application.notification.platform.api.NormalizedEventType;
import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent;
@@ -60,11 +61,13 @@ public final class JpaProviderEventLedger implements ProviderEventLedger {
@Override
public AppendEventResult append(VerifiedProviderEvent event) {
CallerTransaction.require("provider event append");
return appendAll(List.of(event));
}
@Override
public AppendEventResult appendAll(List<VerifiedProviderEvent> batch) {
CallerTransaction.require("provider event appendAll");
Objects.requireNonNull(batch, "batch");
List<ProviderEventRecord> created = new ArrayList<>();
List<ProviderEventRecord> duplicates = new ArrayList<>();
@@ -134,6 +137,7 @@ public final class JpaProviderEventLedger implements ProviderEventLedger {
@Override
public void markApplied(ProviderEventRecordId eventId, ProjectionResult result) {
CallerTransaction.require("provider event markApplied");
Objects.requireNonNull(eventId, "eventId");
Objects.requireNonNull(result, "result");
transitionFromPending(
@@ -144,6 +148,7 @@ public final class JpaProviderEventLedger implements ProviderEventLedger {
@Override
public void markFailed(ProviderEventRecordId eventId, String errorCode) {
CallerTransaction.require("provider event markFailed");
Objects.requireNonNull(eventId, "eventId");
Objects.requireNonNull(errorCode, "errorCode");
// The event stays. A failed projection is a bug to fix and replay, not a reason to lose the
@@ -188,6 +193,7 @@ public final class JpaProviderEventLedger implements ProviderEventLedger {
dev.caskeleton.application.notification.platform.api.ProviderProfileId providerProfileId,
String providerRequestId,
DeliveryAttemptId attemptId) {
CallerTransaction.require("provider event bindUnmatched");
Objects.requireNonNull(providerProfileId, "providerProfileId");
Objects.requireNonNull(providerRequestId, "providerRequestId");
Objects.requireNonNull(attemptId, "attemptId");
@@ -210,6 +216,7 @@ public final class JpaProviderEventLedger implements ProviderEventLedger {
@Override
public boolean bindAttempt(ProviderEventRecordId eventId, DeliveryAttemptId attemptId) {
CallerTransaction.require("provider event bindAttempt");
Objects.requireNonNull(eventId, "eventId");
Objects.requireNonNull(attemptId, "attemptId");
// The same compare-and-set the dispatch-side bind uses: whoever matched the event first keeps
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.notification.platform;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId;
import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState;
import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord;
@@ -31,6 +32,7 @@ public final class JpaRecipientDeliveryStore implements RecipientDeliveryStorePo
@Override
public RecipientDeliveryRecord save(RecipientDeliveryRecord record) {
CallerTransaction.require("recipient delivery save");
Objects.requireNonNull(record, "record");
RecipientDeliveryEntity entity =
recipients
@@ -54,6 +56,7 @@ public final class JpaRecipientDeliveryStore implements RecipientDeliveryStorePo
@Override
public RecipientDeliveryRecord transition(
RecipientDeliveryId id, RecipientDeliveryState state, Optional<Instant> nextDispatchAt) {
CallerTransaction.require("recipient delivery transition");
Objects.requireNonNull(id, "id");
Objects.requireNonNull(state, "state");
Objects.requireNonNull(nextDispatchAt, "nextDispatchAt");
@@ -68,6 +71,7 @@ public final class JpaRecipientDeliveryStore implements RecipientDeliveryStorePo
@Override
public Optional<RecipientDeliveryRecord> saveHeldBy(
RecipientDeliveryRecord record, RecipientLease lease) {
CallerTransaction.require("recipient delivery saveHeldBy");
Objects.requireNonNull(record, "record");
Objects.requireNonNull(lease, "lease");
// One conditional statement rather than findById → mutate → saveAndFlush. The read-modify-write
@@ -99,6 +103,7 @@ public final class JpaRecipientDeliveryStore implements RecipientDeliveryStorePo
RecipientDeliveryState state,
Optional<Instant> nextDispatchAt,
RecipientLease lease) {
CallerTransaction.require("recipient delivery transitionHeldBy");
Objects.requireNonNull(id, "id");
Objects.requireNonNull(state, "state");
Objects.requireNonNull(nextDispatchAt, "nextDispatchAt");
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.notification.platform;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId;
import dev.caskeleton.application.notification.platform.dispatch.RecipientLease;
import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort;
@@ -34,6 +35,11 @@ public final class JpaRecipientLeaseStore implements RecipientLeaseStorePort {
this.clock = Objects.requireNonNull(clock, "clock");
}
/**
* The one write here without {@code CallerTransaction.require}: the scheduler claims before any
* use case runs, and the claim is a single CTE statement that selects, locks and fences its rows
* by itself — there is no second write it has to be atomic with.
*/
@Override
public List<RecipientLease> claim(String workerId, int limit, Duration leaseDuration) {
Objects.requireNonNull(workerId, "workerId");
@@ -57,6 +63,7 @@ public final class JpaRecipientLeaseStore implements RecipientLeaseStorePort {
@Override
public Optional<RecipientLease> renew(RecipientLease lease, Duration leaseDuration) {
CallerTransaction.require("recipient lease renew");
Objects.requireNonNull(lease, "lease");
Objects.requireNonNull(leaseDuration, "leaseDuration");
Instant now = clock.instant();
@@ -75,6 +82,7 @@ public final class JpaRecipientLeaseStore implements RecipientLeaseStorePort {
@Override
public void release(RecipientLease lease) {
CallerTransaction.require("recipient lease release");
Objects.requireNonNull(lease, "lease");
// Scoped to owner and fence: a worker that lost its lease must not release the one that
// replaced it, and an owner string shared by two incarnations does not distinguish them.
@@ -92,6 +100,7 @@ public final class JpaRecipientLeaseStore implements RecipientLeaseStorePort {
@Override
public int expireOverdue(int limit) {
CallerTransaction.require("recipient lease expireOverdue");
if (limit < 1) {
throw new IllegalArgumentException("limit");
}
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.notification.platform;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.notification.platform.api.TenantId;
import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort;
import dev.caskeleton.application.notification.platform.policy.SuppressionEntry;
@@ -45,6 +46,7 @@ public final class JpaSuppressionStore implements SuppressionStorePort {
@Override
public SuppressionEntry upsert(SuppressionEntry entry) {
CallerTransaction.require("suppression upsert");
Objects.requireNonNull(entry, "entry");
return suppressions
.findByTenantIdAndNormalizedTargetHmacAndReason(
@@ -63,6 +65,7 @@ public final class JpaSuppressionStore implements SuppressionStorePort {
@Override
public Optional<SuppressionEntry> remove(TenantId tenantId, SuppressionId id) {
CallerTransaction.require("suppression remove");
Objects.requireNonNull(tenantId, "tenantId");
Objects.requireNonNull(id, "id");
return suppressions
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.notification.platform;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.notification.platform.api.TemplateSelection;
import dev.caskeleton.application.notification.platform.api.TenantId;
import dev.caskeleton.application.notification.platform.api.error.FailureCategory;
@@ -108,6 +109,7 @@ public final class JpaTemplateRegistry implements TemplateRegistry {
@Override
public void publish(NotificationTemplateVersion version) {
CallerTransaction.require("template publish");
Objects.requireNonNull(version, "version");
TenantId tenant = tenants.currentTenant();
@@ -144,6 +146,7 @@ public final class JpaTemplateRegistry implements TemplateRegistry {
@Override
public void disable(String templateId, long version) {
CallerTransaction.require("template disable");
Objects.requireNonNull(templateId, "templateId");
TenantId tenant = tenants.currentTenant();
Instant disabledAt = clock.instant();
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.notification.platform.api.NotificationId;
import dev.caskeleton.application.notification.platform.api.TenantId;
import dev.caskeleton.application.notification.platform.api.content.InAppContent;
@@ -57,6 +58,7 @@ public final class JpaNotificationInbox implements NotificationInbox {
@Override
public InboxItemId create(CreateInboxItemCommand command) {
CallerTransaction.require("inbox create");
Objects.requireNonNull(command, "command");
Instant now = clock.instant();
InboxItemEntity stored =
@@ -117,6 +119,7 @@ public final class JpaNotificationInbox implements NotificationInbox {
@Override
public InboxMutationResult markSeen(InboxItemId id, InboxPrincipal principal) {
CallerTransaction.require("inbox markSeen");
InboxItemEntity entity = require(id, principal);
boolean changed = entity.markSeen(clock.instant());
items.saveAndFlush(entity);
@@ -125,6 +128,7 @@ public final class JpaNotificationInbox implements NotificationInbox {
@Override
public InboxMutationResult markRead(InboxItemId id, InboxPrincipal principal) {
CallerTransaction.require("inbox markRead");
InboxItemEntity entity = require(id, principal);
boolean changed = entity.markRead(clock.instant());
items.saveAndFlush(entity);
@@ -133,6 +137,7 @@ public final class JpaNotificationInbox implements NotificationInbox {
@Override
public InboxMutationResult archive(InboxItemId id, InboxPrincipal principal) {
CallerTransaction.require("inbox archive");
InboxItemEntity entity = require(id, principal);
boolean changed = entity.archive(clock.instant());
items.saveAndFlush(entity);
@@ -141,6 +146,7 @@ public final class JpaNotificationInbox implements NotificationInbox {
@Override
public int markAllRead(MarkAllReadCommand command) {
CallerTransaction.require("inbox markAllRead");
Objects.requireNonNull(command, "command");
// Both halves of the cursor. Passing only the timestamp made "up to here" mean something the
// caller could not predict whenever two rows shared a millisecond.
@@ -202,7 +202,14 @@ public final class DefaultCleanupService implements CleanupService {
// and the delete a writer could acquire that very lease, and the bytes removed were then the
// ones an upload was actively appending to. The claim clears the lease in the same statement
// that proves it was not held, and the session is terminal, so no later acquire can succeed.
if (sessionStore.find(uploadId).isPresent() && !sessionStore.claimForCleanup(uploadId, now)) {
// It commits before the bytes go: its own boundary, because the store refuses a modifying
// statement without one (it used to run between two, and failed every time — P30-new-1).
boolean claimed =
transactions.inWrite(
() ->
sessionStore.find(uploadId).isEmpty()
|| sessionStore.claimForCleanup(uploadId, now));
if (!claimed) {
markFailed(item, "ACTIVE_WRITER_LEASE", now);
return Outcome.of(OutcomeKind.SKIPPED_ACTIVE_LEASE, 0);
}
@@ -40,6 +40,7 @@ class CleanupServiceTest {
private final InMemoryFileMetadataStore metadata = new InMemoryFileMetadataStore();
private final InMemoryUploadSessionStore sessions = new InMemoryUploadSessionStore();
private final RecordingQuotaReclaimGateway quota = new RecordingQuotaReclaimGateway();
private final DirectTransactions transactions = new DirectTransactions();
private final CleanupService cleanup =
new DefaultCleanupService(
@@ -50,7 +51,7 @@ class CleanupServiceTest {
quota,
Duration.ofMinutes(5),
FileserverMetricsPort.noop(),
new DirectTransactions(),
transactions,
Clock.fixed(FileserverFixtures.NOW, ZoneOffset.UTC));
@Test
@@ -213,6 +214,35 @@ class CleanupServiceTest {
.isEqualTo(queue.claimSweeps().get(0));
}
/**
* The staging claim is a modifying statement, and the JPA store refuses one without a caller
* transaction (review X1-#4). It used to run between two boundaries, so against the real store
* every staging item with a session failed and was retried until abandoned (P30-new-1).
*/
@Test
void theStagingClaimRunsInsideACallerTransaction() {
// given
UploadId uploadId = UploadId.of(UUID.randomUUID());
FileId fileId = FileId.of(UUID.randomUUID());
sessions.create(
new UploadSessionDraft(
uploadId,
fileId,
UploadMode.SINGLE_SHOT,
OptionalLong.of(SIZE),
FileserverFixtures.NOW.plusSeconds(3600)));
sessions.terminate(uploadId);
content.storeStaging(uploadId);
queue.enqueue(CleanupRequest.forStaging(CleanupType.CANCELLED_STAGING, fileId, uploadId));
sessions.requireBoundaryOf(transactions);
// when
CleanupBatchResult result = cleanup.runBatch(100, 1L << 30);
// then
assertThat(result.deleted()).isEqualTo(1);
}
/**
* Settling twice reclaims once.
*
@@ -19,6 +19,12 @@ public final class DirectTransactions implements TransactionPort {
private final List<String> opened = new ArrayList<>();
private RuntimeException nextNewFailure;
private int depth;
/** True while an action runs inside one of this port's boundaries. */
public boolean active() {
return depth > 0;
}
/** Makes the next {@link #inNew(Supplier)} fail with {@code failure} instead of running. */
public void failNextNew(RuntimeException failure) {
@@ -37,19 +43,19 @@ public final class DirectTransactions implements TransactionPort {
@Override
public <T> T inWrite(Supplier<T> action) {
opened.add("write");
return action.get();
return run(action);
}
@Override
public <T> T inRootWrite(Supplier<T> action) {
opened.add("root-write");
return action.get();
return run(action);
}
@Override
public <T> T inRead(Supplier<T> action) {
opened.add("read");
return action.get();
return run(action);
}
@Override
@@ -60,6 +66,15 @@ public final class DirectTransactions implements TransactionPort {
nextNewFailure = null;
throw failure;
}
return action.get();
return run(action);
}
private <T> T run(Supplier<T> action) {
depth++;
try {
return action.get();
} finally {
depth--;
}
}
}
@@ -33,6 +33,16 @@ public final class InMemoryUploadSessionStore
implements UploadSessionPort, StagingUploadLocatorPort {
private final Map<UploadId, UploadSession> sessions = new LinkedHashMap<>();
private DirectTransactions boundary;
/**
* Refuses a claim made outside {@code transactions}, as the JPA store's {@code CallerTransaction}
* guard does. Off by default, so fixture set-up can still seed rows directly.
*/
public void requireBoundaryOf(DirectTransactions transactions) {
this.boundary = transactions;
}
private Instant now = FileserverFixtures.NOW;
public void advanceTo(Instant instant) {
@@ -192,6 +202,10 @@ public final class InMemoryUploadSessionStore
@Override
public boolean claimForCleanup(UploadId uploadId, Instant clockNow) {
if (boundary != null && !boundary.active()) {
throw new IllegalStateException(
"upload session claimForCleanup requires an active caller transaction");
}
UploadSession current = sessions.get(uploadId);
if (current == null || !current.terminal()) {
return false;
@@ -124,7 +124,10 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU
public NotificationReceipt handle(AcceptNotificationCommand command) {
Objects.requireNonNull(command, "command");
TenantId tenantId = command.tenantId().map(TenantId::new).orElseGet(tenants::currentTenant);
// Checked before the contact point is registered: that is the first write this makes.
TenantId tenantId =
WritableTenant.require(
command.tenantId().map(TenantId::new).orElseGet(tenants::currentTenant));
ContactPointValue value = parse(command.channel(), command.address());
ContactPointId contactPointId = registerOrReuse(tenantId, command.recipientRef(), value);
@@ -147,11 +147,16 @@ public final class NotificationDispatchService {
if (guard instanceof DispatchGuardOutcome.Blocked blocked) {
// Fenced like every other write this worker makes: a lease that expired while the guard ran
// belongs to another worker now, and an unfenced write would overwrite its state.
// The request's roll-up belongs to the same transaction: it used to run after this one
// closed,
// each statement committing on its own, so a crash between them left the request's status
// behind its recipient's.
transactions.inWrite(
() ->
recipients.transitionHeldBy(
work.recipient().id(), blocked.state(), blocked.nextDispatchAt(), lease));
refreshStatus(work);
() -> {
recipients.transitionHeldBy(
work.recipient().id(), blocked.state(), blocked.nextDispatchAt(), lease);
refreshStatus(work);
});
releaseLease(lease);
return;
}
@@ -94,6 +94,7 @@ public final class NotificationSubmissionService {
*/
PreparedSubmission prepare(NotificationPlan plan, Optional<Instant> scheduleAt) {
Objects.requireNonNull(plan, "plan");
WritableTenant.require(plan.tenantId());
Instant now = clock.instant();
scheduleAt.ifPresent(
at -> {
@@ -0,0 +1,38 @@
package dev.caskeleton.application.notification.platform.dispatch;
import dev.caskeleton.application.notification.platform.api.TenantId;
import dev.caskeleton.application.notification.platform.api.error.FailureCategory;
import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode;
import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor;
import dev.caskeleton.application.notification.platform.api.error.NotificationValidationException;
/**
* The tenant rule for a new write: the grammar every transport accepts.
*
* <p>{@link TenantId} itself only asks for non-blank and at most 100 characters, and it stays that
* lenient on purpose: it is also what every stored row is read back into, and rows written under
* that rule — a space, a newline, a path character — must remain readable. What changes is what may
* be written from now on: a submission or an accepted notification must name a tenant the web and
* GraphQL transports would accept ({@link dev.caskeleton.application.tenant.TenantId}), so a tenant
* no transport can ask about is never created (review P19-new-1).
*/
final class WritableTenant {
private WritableTenant() {}
/**
* Returns {@code tenant} when it matches the shared grammar.
*
* @throws NotificationValidationException when it does not
*/
static TenantId require(TenantId tenant) {
try {
new dev.caskeleton.application.tenant.TenantId(tenant.value());
return tenant;
} catch (IllegalArgumentException malformed) {
throw new NotificationValidationException(
NotificationFailureDescriptor.preDispatch(
NotificationFailureCode.VALIDATION_FAILED, FailureCategory.INVALID_PAYLOAD));
}
}
}
@@ -162,6 +162,46 @@ class AcceptNotificationApplicationUseCaseTest {
.containsExactly(1L, DEFAULT_LOCALE, Optional.of(DEFAULT_LOCALE));
}
/** Refused before the contact point is registered, its first write (review P19-new-1). */
@Test
void anAcceptanceForATenantOutsideTheTransportGrammarRegistersNothing() {
// given
InMemoryContactPoints contactPoints = new InMemoryContactPoints();
AcceptNotificationApplicationUseCase useCase =
new AcceptNotificationApplicationUseCase(
new CapturingSubmit(),
contactPoints,
protector(),
PlatformFakes.tenant("tenant-a"),
new PlatformFakes.SequentialIds(),
PlatformFakes.fingerprints(),
new PlatformFakes.RecordingTransactions(),
Clock.fixed(NOW, ZoneOffset.UTC),
DEFAULT_LOCALE);
AcceptNotificationCommand command =
new AcceptNotificationCommand(
Optional.of("tenant a/../b"),
"customer-42",
Channel.EMAIL,
"person@example.com",
"payment-receipt",
Optional.empty(),
Optional.empty(),
Map.of(),
Optional.empty(),
"billing");
// when
Throwable refused = catchThrowable(() -> useCase.handle(command));
// then
assertThat(refused)
.isInstanceOf(
dev.caskeleton.application.notification.platform.api.error
.NotificationValidationException.class)
.hasMessage("VALIDATION_FAILED");
}
@Test
void theRootLocaleIsRefusedAsTheConfiguredDefault() {
// when
@@ -227,6 +227,42 @@ class NotificationDispatchServiceTest {
assertThat(scenario.stored().nextDispatchAt()).contains(notBefore);
}
/**
* A blocked delivery's request roll-up commits with the recipient's transition. It ran after that
* boundary closed, and the JPA store now refuses a write without one (review X1-#4).
*/
@Test
void aBlockedDeliveryRollsUpItsRequestStatusInsideTheTransitionTransaction() {
// given
NotificationPlan base = PlatformFakes.plan("blocked-roll-up", Map.of());
Scenario scenario =
new Scenario(
new NotificationPlan(
base.tenantId(),
base.idempotencyKey(),
base.category(),
base.template(),
base.variables(),
base.recipients(),
base.deliveryStrategy(),
Optional.of(NOW.plusSeconds(3600)),
base.expiresAt(),
base.deduplication(),
base.collapse(),
base.correlationId(),
base.boundedMetadata()));
scenario.recipients.transition(
scenario.recipient.id(), RecipientDeliveryState.READY_TO_DISPATCH, Optional.of(NOW));
scenario.requests.observe(scenario.dispatchTransactions);
NotificationDispatchService service = scenario.service(new RecordingLeases(), renderer());
// when
service.dispatch(scenario.lease());
// then
assertThat(scenario.requests.statusWritesInTransaction).containsExactly(true);
}
@Test
@DisplayName("provider profile 이 사라진 route 는 일반 재시도 backoff 뒤에 다시 꺼낸다")
void aRouteWhoseProviderProfileIsGoneWaitsForTheRetryBackoff() {
@@ -350,6 +386,8 @@ class NotificationDispatchServiceTest {
private final PlatformFakes.RecipientStore recipients =
new PlatformFakes.RecipientStore(requests);
private final PlatformFakes.AttemptStore attempts = new PlatformFakes.AttemptStore();
private final PlatformFakes.RecordingTransactions dispatchTransactions =
new PlatformFakes.RecordingTransactions();
private final NotificationId notificationId;
private final RecipientDeliveryRecord recipient;
@@ -429,7 +467,7 @@ class NotificationDispatchServiceTest {
new ProfileOnlyGateway(),
renderer,
leases,
new PlatformFakes.RecordingTransactions(),
dispatchTransactions,
Clock.fixed(NOW, ZoneOffset.UTC),
3,
Duration.ofSeconds(5));
@@ -2,6 +2,7 @@ package dev.caskeleton.application.notification.platform.dispatch;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.notification.platform.api.CancelCommand;
import dev.caskeleton.application.notification.platform.api.NotificationId;
@@ -22,6 +23,8 @@ import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/**
* Submission: what a receipt is allowed to mean.
@@ -64,11 +67,52 @@ class NotificationSubmissionServiceTest {
.handle(new SubmitNotificationCommand(plan));
}
private static NotificationPlan forTenant(NotificationPlan base, String tenant) {
return new NotificationPlan(
new TenantId(tenant),
base.idempotencyKey(),
base.category(),
base.template(),
base.variables(),
base.recipients(),
base.deliveryStrategy(),
base.notBefore(),
base.expiresAt(),
base.deduplication(),
base.collapse(),
base.correlationId(),
base.boundedMetadata());
}
private NotificationReceipt schedule(NotificationPlan plan, Instant scheduleAt) {
return new ScheduleNotificationApplicationUseCase(service, transactions)
.handle(new ScheduleNotificationCommand(plan, scheduleAt));
}
/**
* A new request names a tenant the transports would accept (review P19-new-1). The stored-row
* type stays lenient so rows written under the old rule are still read; see the next test.
*/
@ParameterizedTest
@ValueSource(strings = {"tenant a", "tenant\nb", "../tenant", "tenant/c", "-tenant"})
void aSubmissionForATenantOutsideTheTransportGrammarIsRefused(String tenant) {
// given
NotificationPlan plan = forTenant(PlatformFakes.plan("idem-tenant", Map.of()), tenant);
// when
Throwable refused = catchThrowable(() -> submit(plan));
// then
assertThat(refused)
.isInstanceOf(NotificationValidationException.class)
.hasMessage("VALIDATION_FAILED");
}
@Test
void aTenantStoredUnderTheOldRuleIsStillReadable() {
assertThat(new TenantId("tenant with a space").value()).isEqualTo("tenant with a space");
}
@Test
void aReceiptMeansTheRequestAndItsJobsAreDurable() {
var receipt = submit(PlatformFakes.plan("idem-1", Map.of("amount", "1000")));
@@ -124,6 +124,19 @@ public final class PlatformFakes {
public final Map<String, NotificationId> byIdempotency = new HashMap<>();
public final Map<NotificationId, List<RecipientDeliveryRecord>> recipients = new HashMap<>();
/** Whether each status write ran inside {@link #observe}'s transactions, in call order. */
public final List<Boolean> statusWritesInTransaction = new ArrayList<>();
private RecordingTransactions observed;
/**
* Records, for every later status write, whether {@code transactions} had one open — what the
* JPA store's {@code CallerTransaction} guard refuses when it did not.
*/
public void observe(RecordingTransactions transactions) {
this.observed = transactions;
}
/**
* Set to make the next insert lose the race, as a concurrent claim would.
*
@@ -182,6 +195,9 @@ public final class PlatformFakes {
@Override
public NotificationRequestRecord updateStatus(
TenantId tenantId, NotificationId notificationId, RequestStatus status) {
if (observed != null) {
statusWritesInTransaction.add(observed.inTransaction());
}
NotificationRequestRecord current = byId.get(notificationId);
if (current == null || !current.tenantId().equals(tenantId)) {
throw new IllegalStateException("notification request no longer exists");
+6 -3
View File
@@ -74,7 +74,8 @@
"source_path": "src/adapter/outbound/persistence-fileserver",
"allowed_dependencies": [
"application-core",
"application-fileserver"
"application-fileserver",
"adapter-outbound-persistence-jpa"
]
},
{
@@ -83,7 +84,8 @@
"source_path": "src/adapter/outbound/persistence-notification",
"allowed_dependencies": [
"application-core",
"application-notification"
"application-notification",
"adapter-outbound-persistence-jpa"
]
},
{
@@ -121,7 +123,8 @@
"allowed_dependencies": [
"application-core",
"shared-contract",
"application-objectstorage"
"application-objectstorage",
"adapter-outbound-support"
]
},
{
+5 -3
View File
@@ -16,14 +16,16 @@ Package root: `dev.caskeleton.sample.portfolio`.
- Reference implementation for template adopters: the WorkLog domain slice, layered
exactly like a consuming project — `domain/worklog` (`WorkLog`, `WorkLogId`,
`Period`, `WorkLogRepository`), `application/` (commands, queries, use cases,
ports such as `RepoStatsPort`), and reference adapters under `adapter/web`,
`Period`, `WorkLogRepository`), `application/<feature>` — one package per
feature (`worklog`, `poster`, `posterimage`) holding its use cases, commands, queries,
exceptions, ports such as `RepoStatsPort` and event payloads; `application/event` keeps only the
contracts the features share, and reference adapters under `adapter/web`,
`adapter/persistence`, `adapter/outbound/repostats` (`RepoStatsPortClient` +
`RepoStatsAclMapper`), `adapter/identifier` (`UuidWorkLogIdFactory`).
- Contract-test fixtures the app-bootstrap verification suite analyses
(`DomainExceptionHandler`, `PortfolioErrorCode`, wire/contract tests).
- The sample's integration-event contracts: `WorkLogReservedPayload` with its contribution,
schema/digest and golden vectors, and the poster contracts in `PortfolioEventContracts`. Every
schema/digest and golden vectors, and the poster contracts in `PosterEventContracts` / `PosterImageEventContracts`. Every
outbox append goes through `PortfolioEventOutbox` → the application's encoder → the canonical
`OutboxAppendPort`. The composition registers each contract as a bean; nothing is
classpath-discovered, and payloads are not validated against their JSON Schema.
+6 -3
View File
@@ -58,7 +58,10 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{
## 계층 (adapter-mirrored)
- `domain/worklog` — WorkLog/WorkCategory/Period/RepoStats/WorkLogRepository (POJO)
- `application/worklog` — *UseCase (CommandUseCase/QueryUseCase + @UseCaseCapability)
- `application/<기능>` — 기능별 패키지(review S6-#10a): `worklog`(대표 예제), `poster`,
`posterimage`(object storage 검증용). 각 패키지가 자기 *UseCase(CommandUseCase/QueryUseCase +
@UseCaseCapability)·command·query·예외·포트·이벤트 payload를 함께 가진다. `application/event`에는
기능 사이에 공유하는 계약(`PortfolioEventContract(s)`·`PortfolioEventOutbox`)만 남는다
- `adapter/web` — controller/dto/mapper/error
- `adapter/persistence` — entity/repository/mapper
- `adapter/outbound/repostats` — B7 ACL 예시
@@ -125,7 +128,7 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{
- "WorkLog 기간이 예약됨"이라는 도메인 사실을 표현하는 이벤트입니다. **전송(transport)과
무관**합니다 — 도메인 데이터(`WorkLogId`/`WorkCategory`/`LocalDate`)만 담고 broker/wire/HTTP
타입을 일절 참조하지 않습니다. 이것을 발행 가능한 integration 이벤트로 바꾸는 일은 application
경계의 몫입니다(`application.event.WorkLogReservedPayload` 와 `PortfolioEventOutbox` 참고).
경계의 몫입니다(`application.worklog.WorkLogReservedPayload` 와 `application.event.PortfolioEventOutbox` 참고).
### 포트 — WorkLogRepository / WorkLogIdFactory / OutboxEventIdFactory
- **WorkLogRepository**: WorkLog 영속 아웃바운드 포트(구현은 adapter-persistence). `findPage` 는
@@ -223,7 +226,7 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{
않으며 매 호출 filesystem I/O도 하지 않는다.
- `CreateWorkLogUseCase`가 이 contract로 발행한다. 예전의 3-field `WorkLogReservedIntegrationEvent`와
손으로 짠 JSON 매퍼는 outbox 를 canonical 로 통일하면서 삭제했다(2026-09-28).
- 포스터 이벤트의 contract 는 `PortfolioEventContracts`(schema 는 `contracts/messaging/poster.*`)에
- 포스터 이벤트의 contract 는 기능별 `PosterEventContracts`·`PosterImageEventContracts`(schema 는 `contracts/messaging/poster.*`)에
있다. 조립(`SampleApplicationUseCaseConfig`)이 contract 마다 bean 을 등록하고, 템플릿 encoder 가 그
bean 들로 닫힌 catalog 를 만든다. classpath scanning 은 없다. encoder 는 선언한 schema hash 를 schema
파일과 대조하지만 Draft 2020-12 validator 로 payload 를 검증하지는 않는다.
+1 -1
View File
@@ -225,7 +225,7 @@ strictTestLanes {
lane('messagingSampleContractQualificationTest') {
sourceSet = 'test'
description = 'Runs exact Messaging sample contract qualification tests.'
requires('dev.caskeleton.sample.portfolio.application.event.WorkLogReservedContractContributionTest')
requires('dev.caskeleton.sample.portfolio.application.worklog.WorkLogReservedContractContributionTest')
rejectSkipped = true
jvmArgs '-Duser.timezone=UTC'
}
@@ -6,18 +6,18 @@ import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request.CreatePos
import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request.UpdatePosterRequest;
import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.PosterResponse;
import dev.caskeleton.sample.portfolio.adapter.inbound.web.mapper.PosterWebMapper;
import dev.caskeleton.sample.portfolio.application.command.ArchivePosterCommand;
import dev.caskeleton.sample.portfolio.application.command.DeletePosterCommand;
import dev.caskeleton.sample.portfolio.application.command.PublishPosterCommand;
import dev.caskeleton.sample.portfolio.application.poster.ArchivePosterCommand;
import dev.caskeleton.sample.portfolio.application.poster.ArchivePosterUseCase;
import dev.caskeleton.sample.portfolio.application.poster.CreatePosterUseCase;
import dev.caskeleton.sample.portfolio.application.poster.DeletePosterCommand;
import dev.caskeleton.sample.portfolio.application.poster.DeletePosterUseCase;
import dev.caskeleton.sample.portfolio.application.poster.GetPosterQuery;
import dev.caskeleton.sample.portfolio.application.poster.GetPosterUseCase;
import dev.caskeleton.sample.portfolio.application.poster.ListPostersQuery;
import dev.caskeleton.sample.portfolio.application.poster.ListPostersUseCase;
import dev.caskeleton.sample.portfolio.application.poster.PublishPosterCommand;
import dev.caskeleton.sample.portfolio.application.poster.PublishPosterUseCase;
import dev.caskeleton.sample.portfolio.application.poster.UpdatePosterUseCase;
import dev.caskeleton.sample.portfolio.application.query.GetPosterQuery;
import dev.caskeleton.sample.portfolio.application.query.ListPostersQuery;
import dev.caskeleton.sample.portfolio.domain.poster.PosterId;
import dev.caskeleton.sample.portfolio.domain.poster.PosterPage;
import dev.caskeleton.sample.portfolio.domain.poster.PosterSortField;
@@ -13,10 +13,10 @@ import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.PosterIm
import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.PosterImagePublicationStatusResponse;
import dev.caskeleton.sample.portfolio.adapter.inbound.web.mapper.PosterImagePublicationWebMapper;
import dev.caskeleton.sample.portfolio.adapter.inbound.web.objectstorage.MultipartObjectContentProducer;
import dev.caskeleton.sample.portfolio.application.command.PublishPosterImageCommand;
import dev.caskeleton.sample.portfolio.application.poster.GetPosterImagePublicationStatusUseCase;
import dev.caskeleton.sample.portfolio.application.poster.PublishPosterImageUseCase;
import dev.caskeleton.sample.portfolio.application.query.GetPosterImagePublicationStatusQuery;
import dev.caskeleton.sample.portfolio.application.posterimage.GetPosterImagePublicationStatusQuery;
import dev.caskeleton.sample.portfolio.application.posterimage.GetPosterImagePublicationStatusUseCase;
import dev.caskeleton.sample.portfolio.application.posterimage.PublishPosterImageCommand;
import dev.caskeleton.sample.portfolio.application.posterimage.PublishPosterImageUseCase;
import dev.caskeleton.sample.portfolio.domain.poster.PosterId;
import java.time.Duration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@@ -12,16 +12,16 @@ import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.RepoStat
import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.WorkLogResponse;
import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.WorkLogSummaryResponse;
import dev.caskeleton.sample.portfolio.adapter.inbound.web.mapper.WorkLogWebMapper;
import dev.caskeleton.sample.portfolio.application.command.BatchCreateWorkLogsCommand;
import dev.caskeleton.sample.portfolio.application.command.DeleteWorkLogCommand;
import dev.caskeleton.sample.portfolio.application.query.GetRepoStatsQuery;
import dev.caskeleton.sample.portfolio.application.query.GetWorkLogQuery;
import dev.caskeleton.sample.portfolio.application.query.ListWorkLogsQuery;
import dev.caskeleton.sample.portfolio.application.worklog.BatchCreateWorkLogsCommand;
import dev.caskeleton.sample.portfolio.application.worklog.BatchCreateWorkLogsUseCase;
import dev.caskeleton.sample.portfolio.application.worklog.CreateWorkLogUseCase;
import dev.caskeleton.sample.portfolio.application.worklog.DeleteWorkLogCommand;
import dev.caskeleton.sample.portfolio.application.worklog.DeleteWorkLogUseCase;
import dev.caskeleton.sample.portfolio.application.worklog.GetRepoStatsQuery;
import dev.caskeleton.sample.portfolio.application.worklog.GetRepoStatsUseCase;
import dev.caskeleton.sample.portfolio.application.worklog.GetWorkLogQuery;
import dev.caskeleton.sample.portfolio.application.worklog.GetWorkLogUseCase;
import dev.caskeleton.sample.portfolio.application.worklog.ListWorkLogsQuery;
import dev.caskeleton.sample.portfolio.application.worklog.ListWorkLogsUseCase;
import dev.caskeleton.sample.portfolio.application.worklog.UpdateWorkLogUseCase;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory;
@@ -1,11 +1,11 @@
package dev.caskeleton.sample.portfolio.adapter.inbound.web.error;
import dev.caskeleton.adapter.inbound.web.error.ErrorResponseFactory;
import dev.caskeleton.sample.portfolio.application.exception.PosterImageAlreadyPublishedException;
import dev.caskeleton.sample.portfolio.application.exception.PosterNotFoundException;
import dev.caskeleton.sample.portfolio.application.exception.PosterTitleAlreadyExistsException;
import dev.caskeleton.sample.portfolio.application.exception.WorkLogNotFoundException;
import dev.caskeleton.sample.portfolio.application.exception.WorkLogVersionMismatchException;
import dev.caskeleton.sample.portfolio.application.poster.PosterNotFoundException;
import dev.caskeleton.sample.portfolio.application.poster.PosterTitleAlreadyExistsException;
import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageAlreadyPublishedException;
import dev.caskeleton.sample.portfolio.application.worklog.WorkLogNotFoundException;
import dev.caskeleton.sample.portfolio.application.worklog.WorkLogVersionMismatchException;
import dev.caskeleton.sample.portfolio.domain.poster.PosterInvariantException;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogInvariantException;
import dev.caskeleton.shared.error.OperationalError;
@@ -3,8 +3,8 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.mapper;
import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request.CreatePosterRequest;
import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request.UpdatePosterRequest;
import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.PosterResponse;
import dev.caskeleton.sample.portfolio.application.command.CreatePosterCommand;
import dev.caskeleton.sample.portfolio.application.command.UpdatePosterCommand;
import dev.caskeleton.sample.portfolio.application.poster.CreatePosterCommand;
import dev.caskeleton.sample.portfolio.application.poster.UpdatePosterCommand;
import dev.caskeleton.sample.portfolio.domain.poster.Poster;
import dev.caskeleton.sample.portfolio.domain.poster.PosterId;
import dev.caskeleton.sample.portfolio.domain.poster.PosterSortField;
@@ -5,8 +5,8 @@ import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request.UpdateWor
import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.RepoStatsResponse;
import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.WorkLogResponse;
import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.WorkLogSummaryResponse;
import dev.caskeleton.sample.portfolio.application.command.CreateWorkLogCommand;
import dev.caskeleton.sample.portfolio.application.command.UpdateWorkLogCommand;
import dev.caskeleton.sample.portfolio.application.worklog.CreateWorkLogCommand;
import dev.caskeleton.sample.portfolio.application.worklog.UpdateWorkLogCommand;
import dev.caskeleton.sample.portfolio.domain.worklog.RepoStats;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId;
@@ -1,7 +1,7 @@
package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository;
import dev.caskeleton.sample.portfolio.application.port.WorkLogSummaryQueryPort;
import dev.caskeleton.sample.portfolio.application.query.WorkLogSummary;
import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummary;
import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummaryQueryPort;
import java.util.List;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
@@ -1,6 +1,6 @@
package dev.caskeleton.sample.portfolio.adapter.outbound.repostats;
import dev.caskeleton.sample.portfolio.application.port.RepoStatsPort;
import dev.caskeleton.sample.portfolio.application.worklog.RepoStatsPort;
import dev.caskeleton.sample.portfolio.domain.worklog.RepoStats;
import org.springframework.stereotype.Component;
@@ -51,7 +51,7 @@ public record PortfolioEventContract<P extends IntegrationPayload>(
Duration.ofDays(7));
/** A contract whose schema hash is given as lower-case hex. */
static <P extends IntegrationPayload> PortfolioEventContract<P> of(
public static <P extends IntegrationPayload> PortfolioEventContract<P> of(
String contractId, int payloadVersion, Class<P> payloadType, String schemaSha256Hex) {
return new PortfolioEventContract<>(
new ContractId(contractId),
@@ -1,72 +0,0 @@
package dev.caskeleton.sample.portfolio.application.event;
import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution;
import java.util.List;
/**
* Every integration event the sample publishes, one constant per contract.
*
* <p>The composition registers each as a bean, which is how the application's encoder learns the
* closed catalog. The hashes are of the schema files under {@code contracts/messaging/}; {@code
* PortfolioEventContractsTest} and the encoder at startup both hold them to those bytes.
*/
public final class PortfolioEventContracts {
public static final PortfolioEventContract<PosterCreatedPayload> POSTER_CREATED =
PortfolioEventContract.of(
"poster.created",
1,
PosterCreatedPayload.class,
"8be3a72b7b469d894d06bd30f79f565feb23fbf698674d5caee094de5a2300fb");
public static final PortfolioEventContract<PosterIdPayload> POSTER_PUBLISHED =
PortfolioEventContract.of(
"poster.published",
1,
PosterIdPayload.class,
"d89954e3074fc015a20d616bf0ec1cb46c088fa417d78e006163f1c2dc61170c");
public static final PortfolioEventContract<PosterIdPayload> POSTER_ARCHIVED =
PortfolioEventContract.of(
"poster.archived",
1,
PosterIdPayload.class,
"c71019a727f351aa26afbf6c9246b6cf1a7abcfd2b6bb3ee1185dfce6be504d8");
public static final PortfolioEventContract<PosterIdPayload> POSTER_DELETED =
PortfolioEventContract.of(
"poster.deleted",
1,
PosterIdPayload.class,
"c5310821c338be5aa916d126008a0a0f4be6c6999775018ce29cbefc44c8a942");
public static final PortfolioEventContract<PosterImageAttachmentPreparedPayload>
POSTER_IMAGE_ATTACHMENT_PREPARED =
PortfolioEventContract.of(
"poster.image-attachment-prepared",
1,
PosterImageAttachmentPreparedPayload.class,
"179160ec458b710535c7846a47a1abceab1a743a3a5f11633c47c2115e82e2c4");
public static final PortfolioEventContract<PosterImageAttachmentReadyPayload>
POSTER_IMAGE_ATTACHMENT_READY =
PortfolioEventContract.of(
"poster.image-attachment-ready",
2,
PosterImageAttachmentReadyPayload.class,
"1a256fa47c382a4900ed8f852da9256a01ef1ddb2dc5b0b75047f827ae81644e");
private PortfolioEventContracts() {}
/** The closed catalog: every contract above plus {@code portfolio.worklog.reserved} v1. */
public static List<IntegrationEventContractContribution<?>> all() {
return List.of(
POSTER_CREATED,
POSTER_PUBLISHED,
POSTER_ARCHIVED,
POSTER_DELETED,
POSTER_IMAGE_ATTACHMENT_PREPARED,
POSTER_IMAGE_ATTACHMENT_READY,
new WorkLogReservedContractContribution());
}
}
@@ -1,4 +1,4 @@
package dev.caskeleton.sample.portfolio.application.command;
package dev.caskeleton.sample.portfolio.application.poster;
import dev.caskeleton.application.command.Command;
import dev.caskeleton.sample.portfolio.domain.poster.PosterId;
@@ -7,9 +7,6 @@ import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import dev.caskeleton.sample.portfolio.application.command.ArchivePosterCommand;
import dev.caskeleton.sample.portfolio.application.event.PosterEventPublisher;
import dev.caskeleton.sample.portfolio.application.exception.PosterNotFoundException;
import dev.caskeleton.sample.portfolio.domain.poster.Poster;
import dev.caskeleton.sample.portfolio.domain.poster.PosterArchived;
import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository;
@@ -1,4 +1,4 @@
package dev.caskeleton.sample.portfolio.application.command;
package dev.caskeleton.sample.portfolio.application.poster;
import dev.caskeleton.application.command.Command;
import java.util.Objects;
@@ -7,9 +7,6 @@ import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import dev.caskeleton.sample.portfolio.application.command.CreatePosterCommand;
import dev.caskeleton.sample.portfolio.application.event.PosterEventPublisher;
import dev.caskeleton.sample.portfolio.application.exception.PosterTitleAlreadyExistsException;
import dev.caskeleton.sample.portfolio.domain.poster.Poster;
import dev.caskeleton.sample.portfolio.domain.poster.PosterCreated;
import dev.caskeleton.sample.portfolio.domain.poster.PosterIdFactory;
@@ -1,4 +1,4 @@
package dev.caskeleton.sample.portfolio.application.command;
package dev.caskeleton.sample.portfolio.application.poster;
import dev.caskeleton.application.command.Command;
import dev.caskeleton.sample.portfolio.domain.poster.PosterId;
@@ -7,9 +7,7 @@ import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import dev.caskeleton.sample.portfolio.application.command.DeletePosterCommand;
import dev.caskeleton.sample.portfolio.application.event.PosterEventPublisher;
import dev.caskeleton.sample.portfolio.application.exception.PosterNotFoundException;
import dev.caskeleton.sample.portfolio.application.posterimage.RetirePosterImageUseCase;
import dev.caskeleton.sample.portfolio.domain.poster.Poster;
import dev.caskeleton.sample.portfolio.domain.poster.PosterDeleted;
import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository;

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