fix: 3차 확인 리뷰의 Minor 19건을 고친다
문제: 3차 수정의 확인 리뷰가 새 Important 없이 Minor 19건을 남겼다. 동작에 닿는 것이 셋이다. JDK read-idle watchdog이 공용 ForkJoinPool에서 돌아 그 풀이 바쁘면 300ms timeout이 6초 가까이 늦었다. 붙여 쓴 -x<task>를 verifyStrictLaneStages가 읽지 않아 lane을 뺀 workflow가 통과했다. 사용자 전송이 중간 클래스를 거쳐 @SystemCaller bean을 부르면 ArchUnit 규칙을 지났다. 잠금 대기 검사기는 FK·trigger·REINDEX와 lock_timeout = 0을 못 봤고, 쿼터 보정 SQL은 코드와 다른 모양의 행을 넣었다. 방법: 영역별 4묶음이 맡은 Minor만 test-driven-development 절차로 고쳤다(재리뷰 README 12절). - watchdog은 전용 데몬 스레드 하나에서 돌고 스트림을 닫으면 작업을 취소한다. read당 비용은 그대로다(21–24ns). - 사용자 전송 → @SystemCaller는 직접·간접 의존 모두 거부한다. 리뷰가 권한 직접 의존 검사는 중간 클래스 하나로 다시 열려서 버렸다. - 검사기를 보강하면서 새로 걸린 이미 배포된 마이그레이션 5개는 내용을 바꾸지 않고 동결 목록에 더했다(main과 blob이 같다). - 비밀 목록 bean은 규칙보다 먼저 만들어 실제 클래스로 검사한다. 위험·한계: 회복 필요 예외 메시지 끝에 scope digest가 붙고 기동 실패 문구가 바뀌어, 문구 전체에 맞추던 로그 매처는 고쳐야 한다. 코드가 든 Redis 계정 참조의 fixture- 검사는 문서로만 막았다(코드로 막으려면 새 의존 edge가 필요하다). failure-retention ≥ replay-ttl 기동 검사는 넣지 않았다. -mx 같은 짧은 플래그 묶음과 graphql 전송 fixture는 남았다. spotbugsTestFixtures(게이트 밖)의 정규식 경고가 15건으로 늘었다. 검증: ci, 두 빌드의 verifyStrictLaneStages --dry-run, mainCheck, :integrationCheck, -p optional-platforms ci integrationCheck performanceCheck, :performanceCheck, :releaseCheck(-PgitRevision), verify-compose-profile-contracts(18 lane) 첫 실행 통과. watchdog은 공용 풀을 채운 상태에서 300ms 설정이 300ms에 끝나는 것을 쟀다. Refs: docs/reviews/2026-11-03-rereview/README.md 11·12절, round3/
This commit is contained in:
@@ -133,7 +133,8 @@ Never delete staging content to clear a backlog: an upload that is mid-flight wi
|
||||
with the bytes its files actually hold. The known cause is history: before the 2026-11 maturity
|
||||
review, `move` relocated a file without moving its quota. The bytes of every file moved before that
|
||||
fix are still booked on the namespace it left, and deleting such a file reclaims from the namespace
|
||||
it now lives in, where the reclaim stops at zero and leaves the old booking behind. A derived
|
||||
it now lives in: the reclaim draws down the bookings of that namespace's other files, newest first,
|
||||
or stops at zero, and the old booking stays behind either way. A derived
|
||||
service that moved files across namespaces before taking the fix has this drift; one that never did
|
||||
should see none.
|
||||
|
||||
@@ -169,7 +170,8 @@ fileserver's writes stopped.
|
||||
To correct a namespace, stop every fileserver write to it first — uploads, copy, move, delete, and
|
||||
the cleanup worker (`APP_FILESERVER_PLATFORM_CLEANUP_ENABLED=false`) — because the statement below
|
||||
recomputes from `fs_file` and a publish or reclaim that lands between its two steps would be lost.
|
||||
It zeroes the namespace's committed rows and books the recomputed total as one row; the per-row
|
||||
It zeroes the namespace's committed rows and books the recomputed total as one row, shaped the way a
|
||||
publish leaves one (`COMMITTED`, `reserved_bytes` 0, the bytes in `committed_bytes`); the per-row
|
||||
split has no meaning once reclaims have drawn rows down, and enforcement only ever reads the sum.
|
||||
`RESERVED` rows (uploads in progress) are left alone.
|
||||
|
||||
@@ -183,7 +185,7 @@ UPDATE fs_quota_reservation
|
||||
INSERT INTO fs_quota_reservation (
|
||||
reservation_id, scope_type, scope_value, reserved_bytes, committed_bytes,
|
||||
expires_at, status, version, created_at, updated_at)
|
||||
SELECT gen_random_uuid(), 'namespace', :'namespace', held, held,
|
||||
SELECT gen_random_uuid(), 'namespace', :'namespace', 0, held,
|
||||
now(), 'COMMITTED', 0, now(), now()
|
||||
FROM (SELECT coalesce(sum(actual_size), 0) AS held
|
||||
FROM fs_file
|
||||
|
||||
@@ -103,10 +103,12 @@ greater than zero (`TIMEOUT_NOT_POSITIVE`): both engines read zero as "wait fore
|
||||
`total-call` also bounds the setup of a streaming download — connect, send, and the wait for
|
||||
response headers. Once the stream is handed over, each gap of the body is bounded by `read-idle`
|
||||
instead, so a long download is not cut at an arbitrary total (design §15.3). This holds on both
|
||||
transports. The JDK transport keeps its exchange-wide timeout off a streamed body and bounds each
|
||||
read with its own `read-idle` timer, because the JDK client has no socket read timeout; before
|
||||
review 2026-11-03 RR-04-03 every JDK download longer than `response-header` was cut mid-body. A body
|
||||
failure after hand-over is thrown from `read` as `HttpBodyReadException` — an `IOException`, as
|
||||
transports. The JDK transport keeps its exchange-wide timeout off a streamed body, and a per-stream
|
||||
watchdog bounds each read's wait by `read-idle`, because the JDK client has no socket read timeout.
|
||||
The watchdog wakes on one daemon thread of its own (`httpclient-jdk-read-idle`), not on the common
|
||||
`ForkJoinPool`, so a service that fills that pool with blocking work does not delay it (re-review
|
||||
2026-11-04 RR3-03-01). Before review 2026-11-03 RR-04-03 every JDK download longer than
|
||||
`response-header` was cut mid-body. A body failure after hand-over is thrown from `read` as `HttpBodyReadException` — an `IOException`, as
|
||||
`InputStream` promises, so `catch (IOException)` still sees it — whose `failure()` is
|
||||
`HttpResponseTimeoutException` (a wait longer than `read-idle`) or `HttpResponseTruncatedException`
|
||||
(the connection ended early), stage `RESPONSE_BODY`, evidence `PARTIAL_RESPONSE` (re-review
|
||||
|
||||
@@ -85,7 +85,10 @@ reason those are ID references.
|
||||
bidirectional pair, on `@Entity`, `@MappedSuperclass` and `@Embeddable` types: an association that
|
||||
declares `mappedBy` (only that inverse half is reported), and two entities whose associations point
|
||||
at each other without `mappedBy` (both halves are reported — the `@JoinColumn` form above, review
|
||||
RR-03-04). That last check also refuses two entities that each hold their own foreign key to the
|
||||
RR-03-04). The message says how the pair keeps the link: one join column mapped from both ends, or
|
||||
the link stored twice — a `@OneToMany` without `@JoinColumn` in a join table beside the child's own
|
||||
`@ManyToOne` column (what a forgotten `mappedBy` produces), or two `@ManyToMany` each owning a join
|
||||
table (re-review round 3, RR3-02-05). That last check also refuses two entities that each hold their own foreign key to the
|
||||
other (`Order.@OneToOne latestInvoice` with `Invoice.@ManyToOne order`). It is not one link mapped
|
||||
twice, and the message says so; it is refused on purpose, because the two tables then reference each
|
||||
other: neither row can be inserted or deleted first, one key has to be nullable and written by a
|
||||
|
||||
+26
-13
@@ -45,20 +45,33 @@ rolls it back whole, the database stays on the version before it and the new rel
|
||||
start: a failed deploy instead of an outage. Deploy again when the transaction has ended.
|
||||
|
||||
`LOCAL`, because a plain `SET` outlives the migration on the pooled connection Flyway borrowed and
|
||||
changes every statement that later runs on it. A statement on a table the same migration created a
|
||||
moment earlier waits for nothing and needs no bound.
|
||||
changes every statement that later runs on it. The value is not zero: `lock_timeout = 0` (or
|
||||
`DEFAULT`, or a later `RESET`) is no bound at all. A migration with `executeInTransaction=false`
|
||||
cannot use it — `SET LOCAL` outside a transaction only warns — so a statement that locks a table
|
||||
goes into a migration that runs in one. A statement on a table the same migration created a moment
|
||||
earlier waits for nothing and needs no bound; `CREATE TABLE IF NOT EXISTS` does not count, because
|
||||
the table may already be there.
|
||||
|
||||
Enforced, not remembered: `LockWaitMigrationInspector` (persistence-jpa testkit) reads a script
|
||||
and names every statement that locks an existing table before the bound. `MigrationLockWaitTest`
|
||||
runs it over every tree this leaf's database runs, `SampleMigrationLockWaitTest` over the sample's
|
||||
stream; a service stream copies the latter with its own directory. The migrations released before
|
||||
the rule wait unbounded and stay that way (they are applied, and applied files are never edited);
|
||||
the test lists them and refuses any new one. `PostgreSqlMigrationLockWaitIntegrationTest`
|
||||
(`postgresqlMigrationLockWaitIntegrationTest`) and the gRPC ledger's
|
||||
`GrpcOperationLedgerMigrationLockWaitIT` show on real PostgreSQL that a bounded migration gives up
|
||||
within the bound while another transaction holds the table, and leaves the version below it. The
|
||||
rule came from V21 having the bound and V22, in the same commit, not having it (re-review
|
||||
2026-11-03 round 2, RR-02-09).
|
||||
Enforced, not remembered: `LockWaitMigrationInspector` (persistence-jpa testkit) reads a script —
|
||||
and the `.sql.conf` beside it — and names the statements from its list that lock an existing table
|
||||
with no bound in force: `ALTER TABLE`, `LOCK TABLE`, `TRUNCATE`, `DROP TABLE`; `CREATE INDEX`,
|
||||
`DROP INDEX`, `REINDEX` and `REFRESH MATERIALIZED VIEW` without `CONCURRENTLY`, `CLUSTER`, `VACUUM
|
||||
FULL`; `REFERENCES` on the table it references, in a new table as much as in an `ALTER TABLE` (a
|
||||
foreign key locks its parent against writes while it is added); `CREATE TRIGGER` and `DROP TRIGGER`
|
||||
on their table; `UPDATE` and `DELETE`. It reads text, so a statement outside the list is not
|
||||
checked. `MigrationLockWaitTest` runs it over every tree this leaf's database runs,
|
||||
`SampleMigrationLockWaitTest` over the sample's stream; a service stream copies the latter with its
|
||||
own directory. Both find the migrations the way Flyway does, decimal versions (`V22_1__`) included
|
||||
(`VersionedMigrationFiles`, testkit). The migrations released before the rule wait unbounded and
|
||||
stay that way (they are applied, and applied files are never edited); the test lists them and
|
||||
refuses any new one. `PostgreSqlMigrationLockWaitIntegrationTest`
|
||||
(`postgresqlMigrationLockWaitIntegrationTest`) shows on real PostgreSQL that a bounded migration
|
||||
gives up within the bound while another transaction holds the table, and leaves the version below
|
||||
it. The gRPC ledger's tree lives in the optional build, which cannot reach the testkit: its
|
||||
`GrpcOperationLedgerMigrationLockWaitIT` runs every ledger migration after V001, read from the tree,
|
||||
against a held ledger instead, so its next migration is checked on real PostgreSQL. The rule came
|
||||
from V21 having the bound and V22, in the same commit, not having it (re-review 2026-11-03 round 2,
|
||||
RR-02-09; round 3, RR3-02-01, RR3-02-03, RR3-02-04).
|
||||
|
||||
## Concurrent index builds
|
||||
|
||||
|
||||
@@ -128,8 +128,10 @@ capability 스트림 db/migration/jpa/<capability> 각자 histor
|
||||
(리뷰 README 13.2, 09-02).
|
||||
- 기존 데이터가 새 제약을 어기면 마이그레이션이 이유를 남기고 멈추게 쓴다(`V8_1`의 `DO $$` 블록). 조용히
|
||||
지우지 않는다.
|
||||
- 운영 중인 테이블을 잠그는 문장(`ALTER TABLE`, `CONCURRENTLY` 없는 `CREATE INDEX`, `UPDATE`·`DELETE`)이 있으면
|
||||
그 앞에 `SET LOCAL lock_timeout = '5s';`를 둔다(`V8_1`, `V22`). 상한이 없으면 그 테이블을 건드린 열린
|
||||
- 운영 중인 테이블을 잠그는 문장(`ALTER TABLE`, `CONCURRENTLY` 없는 `CREATE INDEX`, `UPDATE`·`DELETE`, 기존
|
||||
테이블을 가리키는 `REFERENCES`, trigger 만들기·지우기 등 — 전체 목록은 `docs/jpa/migration-guide.md`)이 있으면
|
||||
그 앞에 `SET LOCAL lock_timeout = '5s';`를 둔다(`V8_1`, `V22`). 값은 0이 아니어야 하고,
|
||||
`executeInTransaction=false` 마이그레이션에서는 `SET LOCAL`이 효과가 없으니 잠그는 문장을 거기 두지 않는다. 상한이 없으면 그 테이블을 건드린 열린
|
||||
트랜잭션 하나(`ALTER TABLE`이면 읽기만 한 것도) 뒤에서 마이그레이션이 끝없이 기다리고, 그동안 뒤에 온 그
|
||||
테이블의 쓰기(`ALTER TABLE`이면 읽기까지)가 모두 마이그레이션 뒤에 줄을 선다. 상한이 있으면 5초 뒤 실패·롤백되고 새 버전이 뜨지 않을 뿐이다. 자기 스트림에도
|
||||
`SampleMigrationLockWaitTest`처럼 `LockWaitMigrationInspector`(persistence-jpa testkit) 검사를 둔다
|
||||
|
||||
@@ -57,7 +57,10 @@ DB 커밋 중 연결 끊김 ─────────────────
|
||||
같은 키 재전송은 작업을 다시 돌리지 않는다. 첫 시도가 실행을 시작한 뒤 processing lease(기본 30s)가
|
||||
지나면 두 저장소 모두 그 기록을 넘겨주지 않고 500 `IDEMPOTENCY_RECOVERY_REQUIRED`로 답한다. 넘겨받는 것은
|
||||
실행 전 claim과 재시도 가능한 실패뿐이다. 기록은 lease + `replay-ttl` 동안 남고, `replay-ttl`이 lease보다
|
||||
짧으면 기동이 실패한다(`IdempotencyStoreContract`, 재리뷰 2026-11-04 RR-01-11·RR-03-11).
|
||||
짧으면 기동이 실패한다(`IdempotencyStoreContract`, 재리뷰 2026-11-04 RR-01-11·RR-03-11). 작업이 실패로
|
||||
끝나 executor가 포기나 재시도 가능으로 표시한 기록은 표시한 때부터 `failure-retention`(기본 24h) 동안
|
||||
남는다. 이 값은 검사하지 않으므로 `replay-ttl` 이상으로 둔다. 짧으면 효과 불명으로 포기한 기록이 먼저
|
||||
사라져 같은 키 재전송이 작업을 다시 돌린다(RR3-03-02).
|
||||
|
||||
409를 `retryable=true`로 바꾼 이유(리뷰 02-01 결정): 같은 키 재전송은 서버가 안전하게 판정하므로 다시
|
||||
보내는 것이 맞고, 새 키로 보내면 서버가 막지 못한다. 짝 프론트 분류기도 이 표를 따른다.
|
||||
|
||||
@@ -72,22 +72,45 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re
|
||||
|
||||
```text
|
||||
사용자 요청 ─▶ web·GraphQL·gRPC·WebSocket ──✗──▶ @SystemInvoked 유스케이스 (빌드 실패)
|
||||
사용자 요청 ─▶ web·GraphQL·gRPC·WebSocket ──✗──▶ @SystemCaller (빌드 실패, 중간 클래스를 거쳐도)
|
||||
시스템 ─▶ 스케줄러(조립 모듈이 new로 넘김) ─────▶ @SystemInvoked 유스케이스
|
||||
시스템 ─▶ 메시지 handler(@SystemCaller, 직접 new) ─▶ @SystemInvoked 유스케이스
|
||||
시스템 ─▶ 예약 작업(@SystemCaller, 직접 new) ──────▶ @SystemInvoked 유스케이스
|
||||
어디서든 ─▶ @SystemInvoked 유스케이스를 bean으로 등록 ──✗ (기동 실패)
|
||||
```
|
||||
|
||||
- 사용자 전송: 사용자가 보낸 요청이 들어오는 inbound adapter다(web·GraphQL·gRPC·WebSocket).
|
||||
- 시스템 호출자: broker 전달이나 시간(tick)이 깨우는 코드다. 사용자 요청은 여기로 들어오지 않는다.
|
||||
|
||||
시스템 호출자가 `@SystemInvoked` 유스케이스를 얻는 길은 아래 셋뿐이다. 이 표가 정본이고, 다른 문서는 이
|
||||
절을 가리킨다.
|
||||
|
||||
| 경로 | 어디에 두나 | 유스케이스는 누가 만드나 |
|
||||
| --- | --- | --- |
|
||||
| 조립 모듈의 스케줄러 | `composition:*` leaf. 예: outbox relay(`src/composition/outbox-relay`) | 조립 모듈의 `@Bean` 메서드가 `new`로 만들어 스케줄러에 넘긴다 |
|
||||
| 메시지 handler | `adapter:inbound:messaging` leaf, 또는 서비스 leaf의 `..adapter.inbound.messaging..` 패키지 | handler 생성자가 port를 받아 `new`로 만든다. handler에 `@SystemCaller`. 작업 순서는 09장 「소비」 4단계 |
|
||||
| 예약 작업 | 서비스 자기 leaf의 `..adapter.inbound.scheduler..` 패키지. 등록된 scheduler leaf는 없다 | 작업 클래스 생성자가 port를 받아 `new`로 만든다. 작업 클래스에 `@SystemCaller`. 모양은 메시지 handler와 같고, 깨우는 것이 `@Scheduled` 메서드다 |
|
||||
|
||||
예약 작업은 controller와 같은 leaf에 놓이기 쉽다. 그때 "지금 실행" endpoint가 작업 bean을 주입받아 부르면
|
||||
권한 검사 없는 쓰기를 사용자가 부르게 된다. 아래 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`가 이것을
|
||||
빌드에서 막는다. 사용자도 같은 일을 시켜야 하면 `@RequiresPermission`을 단 사용자용 유스케이스를 따로
|
||||
만든다(아래 D4 문단).
|
||||
|
||||
| 규칙 | 무엇을 막나 | 어디 |
|
||||
| --- | --- | --- |
|
||||
| bean 금지 | `@SystemInvoked` 유스케이스가 bean이면 기동 실패. 호출자가 `new`로 만들어 혼자 들고 있는 것만 허용한다 | `src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java` |
|
||||
| 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스만 예외 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) |
|
||||
| 표시 검사 | `@SystemCaller`는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·GraphQL·STOMP mapping·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) |
|
||||
| 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스와 그 안에 중첩된 클래스만 예외 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) |
|
||||
| 표시 검사 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·JAX-RS·GraphQL·STOMP mapping·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) |
|
||||
| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 클래스는 사용자 전송 패키지에 있거나 사용자 전송 타입에 의존하는 클래스다. 그래서 handler를 bean으로 등록하는 `@Configuration`은 걸리지 않는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) |
|
||||
|
||||
규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 그래서 나중에 새 전송이 생겨도 따로
|
||||
고치지 않아도 막힌다. 메시지 소비자의 작업 순서는 09장 「소비」 4단계다.
|
||||
규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 이 성질은 **패키지** 쪽에서만 온다.
|
||||
패키지는 허용 목록이라, 나중에 새 전송 패키지가 생겨도 따로 고치지 않아도 막힌다. 사용자 전송 **타입**
|
||||
쪽은 나열 목록이다(`ARE_USER_TRANSPORT_TYPES`). 시스템 패키지 안에 놓인 endpoint를 알아보는 데 쓰는
|
||||
목록이라, 목록에 없는 전송 라이브러리로 만든 endpoint는 전송으로 보이지 않는다. 새 전송 라이브러리를
|
||||
들이면 그 패키지를 이 목록에 더한다.
|
||||
|
||||
이 규칙들은 클래스 의존만 본다. 실행 중에 bean을 찾는 코드(`getBean`, `ObjectProvider`)는 의존이 아니라서
|
||||
잡지 못한다.
|
||||
|
||||
D4 실패(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`)를 끄려고 이 표시를 쓰지 않는다. 사용자가 부르는
|
||||
쓰기라면 권한을 선언하고 역할에 매핑한다. 같은 쓰기를 사용자도 시스템도 부르면 유스케이스를 둘로 나눈다
|
||||
@@ -102,7 +125,8 @@ web이 빠진 조립(gRPC 전용·배치 전용)에는 `@RequiresPermission`을
|
||||
## 지금 이해하면 되는 것
|
||||
|
||||
- 쓰기 = `@RequiresPermission` + non-final + bean + 역할 매핑.
|
||||
- 시스템만 부르는 쓰기 = `@SystemInvoked` + bean 아님 + 사용자 전송에서 안 닿음. 부르는 쪽은 스케줄러
|
||||
조립이나 `@SystemCaller` 메시지 handler뿐이다.
|
||||
- 시스템만 부르는 쓰기 = `@SystemInvoked` + bean 아님 + 사용자 전송에서 안 닿음. 부르는 쪽은 셋뿐이다:
|
||||
조립 모듈의 스케줄러, `@SystemCaller` 메시지 handler, `@SystemCaller` 예약 작업. 사용자 전송은
|
||||
`@SystemCaller`에도 닿지 못한다.
|
||||
- 객체 판정은 유스케이스 안, 남의 것은 404.
|
||||
- 역할은 자기 client 것만 읽는다.
|
||||
|
||||
@@ -1681,6 +1681,10 @@ env_keys:
|
||||
required_test: redis-idempotency-contract:processing-lease-bounded
|
||||
|
||||
- name: APP_IDEMPOTENCY_FAILURE_RETENTION
|
||||
# app.capabilities.idempotency.failure-retention: how long a record the executor marked failed
|
||||
# (abandoned with an unknown effect, or retryable without one) stays, from the marking. Not
|
||||
# compared with APP_IDEMPOTENCY_TTL at startup; keep it at least that long, or an abandoned
|
||||
# record goes first and a same-key resend runs the work again (re-review 2026-11-04 RR3-03-02).
|
||||
type: duration
|
||||
default: 24h
|
||||
allowed_values: null
|
||||
|
||||
@@ -208,3 +208,33 @@ Minor 19건 중 동작에 닿는 것:
|
||||
### 11.1 결정
|
||||
|
||||
리뷰 반복은 여기서 멈춘다. Minor 19건은 사용자 지시("남은 부분 전부 진행")에 따라 마지막 정리 라운드(r6)로 고친다. r6의 멈춤 기준: 전체 게이트 통과 + r6 diff 확인 리뷰 1회에서 Important가 나오면 그것만 고치고, Minor는 남은 것으로 기록하고 더 돌지 않는다.
|
||||
|
||||
## 12. 마지막 정리 라운드 r6 (Minor 19건, 2026-11-04)
|
||||
|
||||
11.1절 결정대로 3차 확인 리뷰의 Minor 19건을 영역 묶음 4개가 `339cf8fd`에서 `test-driven-development` 절차로 고쳤다. 맡은 Minor 밖은 고치지 않고 보고만 하게 했다.
|
||||
|
||||
| 묶음 | 발견 | 상태 | 검증 (에이전트) | 처리 내용 | 결정·남은 것 |
|
||||
|---|---|---|---|---|---|
|
||||
| r6-a core·inbound | RR3-01-01~04 | 완료 | application-core·service-runtime·inbound messaging·app-bootstrap check(systemTest 포함), architectureTest 208, architectureCheck, 실 PG16 | RR3-01-01 `@SystemCaller` 안의 중첩 클래스도 검사, 새 규칙 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(사용자 전송 → `@SystemCaller`를 직접·중간 클래스 경유 모두 거부, RED 3). RR3-01-02 전송 타입 목록에 `jakarta.ws.rs..`·`graphql..`(RED JAX-RS)와 "목록 방식" 문서. RR3-01-03 쿼터 보정 SQL이 COMMITTED 행 `reserved_bytes`를 0으로(RED 실 PG). RR3-01-04 scheduler·handler·예약 작업 세 경로를 매뉴얼 07장 표로 정본화하고 Javadoc·README·가드 문구를 맞춤 | 새 규칙은 직접 의존이 아니라 이어지는 의존 전체를 본다(중간 클래스 하나로 다시 열리지 않게, 실행 5.7초). 남음: `graphql..` 항목은 fixture 없음(graphql-java가 architectureTest classpath에 없다) |
|
||||
| r6-b persistence·messaging | RR3-02-01~05 | 완료 | persistence-jpa check 611, sample check 339, `-p optional-platforms` grpc ledger check·integrationTest 46, `postgresqlMigrationLockWaitIntegrationTest` 5/5, outbox runbook lane, documentContractTest 62, architectureCheck | RR3-02-01 검사기가 `REFERENCES`·trigger·비동시 `REINDEX`·`REFRESH MATERIALIZED VIEW`·`CLUSTER`·`VACUUM FULL`을 잡고, `lock_timeout` 0·`DEFAULT`·`RESET`과 비트랜잭션(`.sql.conf executeInTransaction=false`) `SET LOCAL`을 상한으로 치지 않음(RED 19). 새로 걸린 배포 파일 5개는 내용 그대로 동결 목록에(main과 blob 같음). RR3-02-02 원인 세션을 `pg_locks`로 찾는 runbook 조회(실 PG). RR3-02-03 버전 판정을 testkit `VersionedMigrationFiles` 하나로(RED `V22_1`·`V22.2`). RR3-02-04 grpc ledger IT가 tree 전체 검사(RED). RR3-02-05 연관 규칙 메시지(RED 2) | grpc는 optional 빌드라 testkit을 못 써 실 PG IT로 검사(버전 정규식 한 벌 더). 남음: `spotbugsTestFixtures`(게이트 밖) ReDoS 경고 8→15 |
|
||||
| r6-c outbound·멱등성 | RR3-03-01~05 | 완료 | 6개 leaf check, architectureCheck, verifyEnvKeys, redisContainerContractTest 59/59, PG 멱등성 계약 20/20, httpclient 성능 5·장애 주입 4, documentContractTest 62, repositoryContractTest 69 | RR3-03-01 watchdog을 전용 데몬 스레드(`httpclient-jdk-read-idle`)로, close 시 작업 취소(RED 공용 풀 포화 시 300ms 설정이 5,995ms → 수정 후 300ms, read당 비용 21–24ns 그대로). RR3-03-02 `failure-retention` 수명 문서. RR3-03-03 회복 필요 예외 메시지 끝에 scope digest(RED 3), runbook에 Redis·PG 기록 조회와 ABANDONED만 지우는 절차(실 Redis 7.4·PG 16). RR3-03-04 옛 표현. RR3-03-05 INSPECT가 `leaseUntil`을 돌려줌(RED 실 Redis) | `failure-retention ≥ replay-ttl` 기동 검사는 넣지 않음(지금 뜨는 설정을 깨지 않게, 문서만 — 소유자 판단). 본 것: gRPC는 carrier 실패를 로그에 남기지 않아 digest를 찾을 수 없다 |
|
||||
| r6-d bootstrap·build | RR3-04-01~05 | 완료(RR3-04-03은 문서) | `-p build-logic check`, support·redis-sdk·sample·app-bootstrap check, verifyEnvKeys, 두 빌드 verifyStrictLaneStages, systemTest 11, documentContractTest 62, `SampleDemoProfilesStartupSystemTest` 3 | RR3-04-01 규칙을 돌리기 전에 비밀 목록 bean을 만들어 실제 클래스를 검사(모든 프로필, RED). RR3-04-02 붙여 쓴 `-x<task>`·`-p<dir>`(RED). RR3-04-03 코드가 든 Redis 계정 참조는 조립하는 쪽이 `static RequiredProductionSecrets` bean을 두는 방법을 문서로. RR3-04-04 "선언된 property" 계산을 classpath 기준 하나로(RED). RR3-04-05 주석 | RR3-04-03 코드 수정은 redis-sdk에 새 의존 edge가 필요하거나 G-7c 결정을 되돌려야 해서 하지 않음. 남음: `-mx` 같은 짧은 플래그 묶음은 읽지 않음, 바뀐 기동 실패 문구에 맞추던 로그 매처 |
|
||||
|
||||
합칠 때 오케스트레이터: 업그레이드 안내 B-14·B-15(r6-d)와 B-16(r6-a)을 손으로 합쳤고, r6-c가 남긴 동작 변경 두 줄(JDK watchdog 스레드, 회복 필요 메시지의 scope digest·INSPECT `leaseUntil`)을 5절에 더했다.
|
||||
|
||||
### 12.1 게이트 (2026-11-04, 합친 메인 작업 트리, 공유 잠금)
|
||||
|
||||
첫 실행에서 모두 통과했다.
|
||||
|
||||
| 게이트 | 결과 | 시간 | 실행 직전 부하(1분) |
|
||||
|---|---|---|---|
|
||||
| `ci` | rc=0 | 6분 22초 | 2.31 |
|
||||
| `verifyStrictLaneStages --dry-run` (주 빌드 / `-p optional-platforms`) | rc=0 / rc=0 | 11초 / 3초 | 16.09 / 14.51 |
|
||||
| `mainCheck` | rc=0 | 3분 10초 | 13.90 |
|
||||
| `:integrationCheck` | rc=0 | 14분 27초 | 10.98 |
|
||||
| `-p optional-platforms ci integrationCheck performanceCheck` | rc=0 | 1분 | 2.32 |
|
||||
| `:performanceCheck` | rc=0 | 22초 | 9.95 |
|
||||
| `:releaseCheck -PgitRevision=<HEAD>` | rc=0 | 3초 | 7.81 |
|
||||
| `scripts/verify-compose-profile-contracts.sh` | rc=0, 18 lane | — | 8.31 |
|
||||
|
||||
다음: 이 커밋만 보는 확인 리뷰 1회. Important가 나오면 그것만 고치고, Minor는 남은 것으로 기록한다(11.1절).
|
||||
|
||||
@@ -4,7 +4,7 @@ category: TRANSIENT_DEPENDENCY
|
||||
error_codes: [IDEMPOTENCY_UNAVAILABLE, IDEMPOTENCY_COMPLETION_UNKNOWN, IDEMPOTENCY_RECOVERY_REQUIRED]
|
||||
severity: P2
|
||||
owner: oncall
|
||||
last_updated: 2026-11-03
|
||||
last_updated: 2026-11-04
|
||||
status: active
|
||||
---
|
||||
|
||||
@@ -18,11 +18,18 @@ status: active
|
||||
`app.idempotency` selects) did not answer. Nothing was executed: the refusal happens before the
|
||||
action, so a client retry is safe.
|
||||
- HTTP 503 `IDEMPOTENCY_COMPLETION_UNKNOWN` (`retryable=true`) is the same outage hitting after the
|
||||
action ran: the store did not answer while the result was being recorded. Effects in the action's
|
||||
own transaction rolled back; anything else it did (an outbound call, a message) may have happened.
|
||||
This is not "nothing was executed". Clients resend with the same key.
|
||||
action ran: the store did not answer while the result was being recorded. When the use case called
|
||||
the executor inside its write transaction, that transaction's database writes rolled back with the
|
||||
exception; an action that committed a transaction of its own kept its writes, and anything outside
|
||||
a transaction (an outbound call, a message) may have happened. This is not "nothing was executed".
|
||||
Clients resend with the same key.
|
||||
- HTTP 500 `IDEMPOTENCY_RECOVERY_REQUIRED` (`retryable=false`) means the opposite case: the store
|
||||
cannot tell whether an earlier attempt's external effect already happened.
|
||||
cannot tell whether an earlier attempt's effect already happened. The usual cause: an attempt
|
||||
started and its processing lease (`APP_IDEMPOTENCY_PROCESSING_LEASE`, 30s) ran out before it
|
||||
recorded a result — it crashed, or ran longer than the lease. The next request with the key marks
|
||||
the record abandoned and every later one gets this 500; the server never runs it again, and a late
|
||||
result from the first attempt is not recorded either. An action that threw, or reported its effect
|
||||
unknown, is abandoned the same way.
|
||||
|
||||
## Diagnosis
|
||||
|
||||
@@ -30,8 +37,37 @@ status: active
|
||||
JPA datasource or Redis, depending on the selected provider).
|
||||
- Look for connection-pool saturation or timeouts on that store in the same time window; the
|
||||
executor reports saturation as unavailable rather than guessing.
|
||||
- For `IDEMPOTENCY_RECOVERY_REQUIRED`, find the scope digest in the server log line of the failed
|
||||
request and inspect that record's state in the store.
|
||||
- For `IDEMPOTENCY_RECOVERY_REQUIRED`, find the scope in the server's ERROR log of the failed request
|
||||
(the web adapter logs `failure classified as IDEMPOTENCY_RECOVERY_REQUIRED` with the exception,
|
||||
under the request's `X-Request-Id`). The exception message ends with
|
||||
`<operation code>::v<digest version>::<scope digest>`, for example
|
||||
`claim requires reconciliation: CHARGE_CARD::v1::3f9a…` (64 hex characters). Then look at the
|
||||
record in the store the service uses (`APP_IDEMPOTENCY_PROVIDER`). There is no tool for this; these
|
||||
are the commands.
|
||||
- Redis. The key is
|
||||
`<APP_REDIS_NAMESPACE_ENVIRONMENT>:<APP_REDIS_NAMESPACE_SERVICE>:<APP_REDIS_NAMESPACE_DOMAIN>:idem:v1:d<digest version>:<operation code>:<scope digest>`,
|
||||
for example `prod:order:shared:idem:v1:d1:CHARGE_CARD:3f9a…`.
|
||||
|
||||
```
|
||||
HMGET <key> state attempt leaseUntil
|
||||
PTTL <key>
|
||||
```
|
||||
|
||||
`state` `ABANDONED` is the recovery-required record. `leaseUntil` is the lease end in epoch
|
||||
milliseconds (server clock); `PTTL` is how long the record still lives, in milliseconds.
|
||||
- PostgreSQL, in the application's schema:
|
||||
|
||||
```sql
|
||||
SELECT status, attempt, failure_disposition, last_transition_kind,
|
||||
processing_lease_until, expires_at, updated_at
|
||||
FROM idempotency_record
|
||||
WHERE record_version = 2
|
||||
AND scope_hash = '<scope digest>';
|
||||
```
|
||||
|
||||
`last_transition_kind` `EXPIRED_EXECUTION` means the lease ran out (the first attempt may still
|
||||
have finished its work); `FAIL_ABANDONED` means the action threw or reported its effect unknown.
|
||||
`expires_at` is when the reaper deletes the row.
|
||||
|
||||
## Action
|
||||
|
||||
@@ -40,9 +76,29 @@ status: active
|
||||
transaction for the failed requests (the ERROR log line names the code). A same-key resend replays
|
||||
a result that was in fact recorded, gets `IDEMPOTENT_IN_FLIGHT` while the attempt's lease lasts,
|
||||
and `IDEMPOTENCY_RECOVERY_REQUIRED` after it — handle that one as below.
|
||||
- `IDEMPOTENCY_RECOVERY_REQUIRED`: do not ask the client to retry blindly. Confirm whether the
|
||||
downstream effect of the earlier attempt exists, then complete or release the record so the next
|
||||
request with that key replays or re-executes deterministically.
|
||||
- `IDEMPOTENCY_RECOVERY_REQUIRED`: do not ask the client to retry blindly. Confirm from business data
|
||||
(the order, the payment, the downstream system) whether the earlier attempt's effect exists. There
|
||||
is no way to complete the record by hand — the stored response is the action's own result.
|
||||
- The effect exists: tell the client it was applied. Leave the record; a resend with the key keeps
|
||||
getting this 500 until the record expires (Redis `PTTL`, PostgreSQL `expires_at`).
|
||||
- The effect does not exist: the client sends the request again under a new key. To let the same
|
||||
key run again instead, delete the record — only while it is `ABANDONED`, because any other state
|
||||
belongs to a request in progress or a stored result:
|
||||
- Redis: check `HMGET <key> state` is `ABANDONED` and `PTTL <key>` has minutes left, then
|
||||
`DEL <key>`. A record that is about to expire needs nothing; once it is gone the key is new.
|
||||
- PostgreSQL:
|
||||
|
||||
```sql
|
||||
DELETE FROM idempotency_record
|
||||
WHERE record_version = 2
|
||||
AND scope_hash = '<scope digest>'
|
||||
AND status = 'ABANDONED';
|
||||
```
|
||||
|
||||
Without either step the key is released when the record expires. That record lives for the
|
||||
processing lease plus `APP_IDEMPOTENCY_TTL` from its claim when its lease ran out, and for
|
||||
`APP_IDEMPOTENCY_FAILURE_RETENTION` from the failure when the action failed
|
||||
(`docs/web/http-contract.md`, "서버가 기억하는 기간").
|
||||
|
||||
## Escalation
|
||||
|
||||
|
||||
@@ -44,9 +44,20 @@ status: active
|
||||
migration that locks a table already in use gives up after its own `SET LOCAL lock_timeout`
|
||||
(5 s; SQLState `55P03` `lock_not_available`) and rolls back whole, so the history ends one
|
||||
version below it. The blocker is a transaction that touched the table and is still open —
|
||||
often an idle-in-transaction session: `SELECT pid, state, xact_start, query FROM
|
||||
pg_stat_activity WHERE xact_start < now() - interval '5 seconds' ORDER BY xact_start;`. End
|
||||
it, then rerun (`docs/jpa/migration-guide.md` "Bound the lock wait");
|
||||
often an idle-in-transaction session. Find it by the lock it holds on that table (`<table>`
|
||||
is the table the failing statement locks; for a `REFERENCES`, also the table it references):
|
||||
|
||||
```sql
|
||||
SELECT DISTINCT a.pid, a.state, a.xact_start, a.query
|
||||
FROM pg_locks l JOIN pg_stat_activity a USING (pid)
|
||||
WHERE l.relation = '<table>'::regclass AND l.granted AND a.pid <> pg_backend_pid()
|
||||
ORDER BY a.xact_start;
|
||||
```
|
||||
|
||||
`query` is only that session's last statement, not the one that touched the table, so do not
|
||||
look for the table name in it. Listing every long transaction instead names unrelated ones
|
||||
(reports, batches) beside the blocker. End the blocker, then rerun
|
||||
(`docs/jpa/migration-guide.md` "Bound the lock wait");
|
||||
- SQL/data precondition: create a new forward migration that makes the precondition explicit;
|
||||
a duplicate outbox order key stopping V21 (`ux_outbox_event_aggregate_order`) is the known
|
||||
case — clean it up with `outbox-dead-letter.md` §8 and rerun, the migration stays as it is;
|
||||
|
||||
@@ -129,8 +129,17 @@ V20(`deferred_attempt_count`)과 V22(`last_failure_code`)도 같은 상한을
|
||||
둘 다 `ALTER TABLE outbox_event`라 가장 강한 잠금(ACCESS EXCLUSIVE)을 건다. 이 잠금은 읽기와도 충돌하므로,
|
||||
`outbox_event`를 읽기만 한 트랜잭션 하나(운영자가 `BEGIN` 안에서 조회하고 둔 psql 세션 포함)가 열려 있어도
|
||||
기다린다. 5초 안에 못 잡으면 그 마이그레이션이 실패·롤백되고 DB는 한 버전 아래(V19 또는 V21)에 남으며 새 버전은
|
||||
기동하지 않는다(`MIGRATION_FAILED`, exit 70). 열린 트랜잭션을 찾아 끝낸 뒤 다시 배포한다 —
|
||||
`SELECT pid, state, xact_start, query FROM pg_stat_activity WHERE xact_start < now() - interval '5 seconds' ORDER BY xact_start;`
|
||||
기동하지 않는다(`MIGRATION_FAILED`, exit 70). `outbox_event`에 잠금을 쥔 열린 트랜잭션을 찾아 끝낸 뒤 다시 배포한다.
|
||||
|
||||
```sql
|
||||
SELECT DISTINCT a.pid, a.state, a.xact_start, a.query
|
||||
FROM pg_locks l JOIN pg_stat_activity a USING (pid)
|
||||
WHERE l.relation = 'outbox_event'::regclass AND l.granted AND a.pid <> pg_backend_pid()
|
||||
ORDER BY a.xact_start;
|
||||
```
|
||||
|
||||
`query`는 그 세션의 마지막 문장일 뿐이다. `outbox_event`를 읽은 뒤 다른 문장을 실행한 세션이면 표 이름이 보이지
|
||||
않으니 `query`로 원인을 고르지 않는다. 오래 열린 트랜잭션을 모두 보는 조회는 보고·배치 같은 무관한 트랜잭션까지 낸다.
|
||||
|
||||
rolling 배포 중 아직 옛 버전인 인스턴스가 벽시계 번호로 쓴 행은 floor보다 크다. 새 버전의 counter는
|
||||
그 aggregate의 가장 큰 행 번호보다 작아지지 않으므로 그 행 뒤에 번호를 준다. 서로 커밋되지 않은 채
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
| 1 | JWT 모드면 `APP_SECURITY_JWT_AUDIENCE`에 이 서비스의 client id를 쉼표로 넣는다 | 기동 실패 `APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required` | JWT 모드(기본값) 전부 |
|
||||
| 2 | dev·prod 환경 변수의 `APP_FLYWAY_ENABLED` 값을 확인한다 | `false`가 남아 있으면 이제 정말로 마이그레이션이 안 돈다 | persistence-jpa 선택 |
|
||||
| 3 | prod 비밀값(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/<VAR>`이 가리키는 변수)이 `fixture-`로 시작하지 않게 한다 | prod 기동 실패(exit 78) | prod 배포 전부 |
|
||||
| 4 | 직접 만든 `StartupRule`·`RequiredProductionSecrets` bean을 `static @Bean`, 의존성 없이 바꾸고, 그 클래스에서 `@Value`·`@Autowired` 멤버와 `@ConfigurationProperties`를 뺀다 | 기동 실패 `startup rule '<이름>' created [...]` 또는 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one`(exit 78) | 자기 rule이 있는 서비스 |
|
||||
| 4 | 직접 만든 `StartupRule`·`RequiredProductionSecrets` bean을 `static @Bean`, 의존성 없이 바꾸고, 그 클래스에서 `@Value`·`@Autowired` 멤버와 `@ConfigurationProperties`를 뺀다 | 기동 실패 `startup rule or secret list '<이름>' created [...]` 또는 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one`(exit 78) | 자기 rule이 있는 서비스 |
|
||||
| 5 | 직접 구현한 outbox·발행·알림·파일 서버 포트를 새 시그니처로 고친다(3.1절) | 컴파일 오류 | 해당 포트를 구현·호출하는 서비스 |
|
||||
| 6 | `dev.caskeleton.application.outbound.*` import를 `application.secret.*`·`application.objectstorage.content.CallBudget`으로 바꾼다 | 컴파일 오류 | 해당 타입을 쓰는 서비스 |
|
||||
| 7 | 이벤트 id를 소문자 UUIDv7로 만들고 `IntegrationEventDraft`는 `IntegrationEventDrafts.draft(...)`로만 만든다 | 쓰기 요청이 `IllegalArgumentException`으로 실패, architectureTest 실패 | 통합 이벤트를 내는 서비스 |
|
||||
@@ -66,9 +66,9 @@
|
||||
|---|---|---|---|---|
|
||||
| B-12 | JWT 모드에서 `APP_SECURITY_JWT_AUDIENCE` 필수(빈 값 거부, `${...}`가 안 풀린 값도 없는 값으로 봄). 토큰 `aud`가 목록 중 하나를 담아야 통과. `resource_access` role은 audience에 적은 client 것만 읽는다(realm role은 그대로) | 기동 실패 `APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required`(exit 코드 확인 못 함). `.env.example`이 `APP_SECURITY_JWT_AUDIENCE=`(빈 값)를 싣고 있다. 다른 client의 role에 기대던 권한이 사라짐 | client id를 쉼표로 넣는다. 다른 client role로 권한을 받던 사용자가 있는지 IdP에서 확인 | `34565130`(필수·role), `1400dc15`(안 풀린 `${...}`) · `src/adapter/inbound/web/.../auth/JwtDecoderConfig.java`, `.../JwtToAuthenticatedPrincipalConverter.java`, `.../settings/SecuritySettings.java` |
|
||||
| B-13 | `app.security.*` strict 바인딩: 접두어 아래 오타 키, 또는 설정·placeholder 어디에도 쓰이지 않는 `APP_SECURITY_*` 환경 변수가 기동을 막는다 | 기동 실패(메시지는 `StrictSettingsBinder`가 키 이름을 담아 냄, 정확한 문구 확인 못 함) | 쓰지 않는 `APP_SECURITY_*` 변수를 지운다 | `5786126c` · `SecuritySettings.bind`, `src/adapter/outbound/support/.../StrictSettingsBinder.java` |
|
||||
| B-14 | prod 프로필에서 `fixture-`로 시작하는 비밀값을 거부(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/<VAR>` 참조 대상. `HOSTNAME`·앱 이름 같은 비밀 아닌 값은 보지 않는다 — RR2-04-01). Redis ACL fixture 파일 이름 변경: `infra/redis-sdk/acl/all-accounts.acl` → `lane-fixture-accounts.acl` | prod 기동 실패, 요약 `prod secret/config-source contract is invalid`(exit 78). 옛 ACL 경로를 mount하던 compose는 파일 없음 | prod 값을 진짜 비밀로 바꾼다. compose의 ACL 경로를 새 이름으로 | `bbe944bd` · `src/app-bootstrap/.../runtime/SecretSourceValidator.java`, `docs/registries/secrets-classification.yaml` |
|
||||
| B-15 | 기동 rule이 모든 singleton보다 먼저 돈다(`StartupRuleRunner`가 `BeanFactoryPostProcessor`). `StartupRule`과 `RequiredProductionSecrets` bean은 `static @Bean`이고 `Environment`, bean factory, static 무인자 `RequiredProductionSecrets`의 `ObjectProvider`만 받아야 한다. 두 타입의 클래스는 `@Value`·`@Autowired`·`@Inject`·`@Resource` 멤버, `@PostConstruct`·`@PreDestroy`, `@ConfigurationProperties`를 가질 수 없다(post-processor보다 먼저 만들어져 비어 있게 된다, RR2-04-03) | non-static `@Bean`이거나 다른 bean을 받으면 기동 실패 `startup rule '<이름>' created [<bean>] while creating it ... Declare the rule with a static @Bean method ...`, 위 멤버가 있으면 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one: [...]`(둘 다 exit 78, 후자는 모든 프로필) | rule 선언을 `static`으로, 인자를 위 셋으로 줄인다. 값은 `violations(Environment)`가 받는 `Environment`에서 읽는다. 다른 bean이 필요한 검사는 rule이 아니라 일반 bean으로 둔다 | `34565130`, `bbe944bd` · `src/adapter/outbound/support/.../startup/StartupRule.java`, `StartupRuleRunner.java` |
|
||||
| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS` 추가, 새 표시 `@SystemCaller` | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). `@SystemCaller`가 아닌 inbound adapter가 그 유스케이스를 부르면 architectureTest 실패 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 호출자(scheduler 등)에 넘기거나, 메시지 handler면 handler에 `@SystemCaller`를 달고 생성자에서 `new`로 만든다(매뉴얼 09장 「소비」 4단계). `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd` · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java`, `SystemCaller.java` |
|
||||
| B-14 | prod 프로필에서 `fixture-`로 시작하는 비밀값을 거부(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/<VAR>` 참조 대상. `HOSTNAME`·앱 이름 같은 비밀 아닌 값은 보지 않는다 — RR2-04-01). Redis ACL fixture 파일 이름 변경: `infra/redis-sdk/acl/all-accounts.acl` → `lane-fixture-accounts.acl` | prod 기동 실패, 요약 `prod secret/config-source contract is invalid`(exit 78). 옛 ACL 경로를 mount하던 compose는 파일 없음 | prod 값을 진짜 비밀로 바꾼다. compose의 ACL 경로를 새 이름으로. Redis SDK admin 계정(`RedisAccountContribution`)을 조립했다면 그 변수를 `static` `RequiredProductionSecrets` bean으로도 낸다(코드에 든 참조는 검사가 보지 않는다, RR3-04-03, `src/adapter/outbound/redis-sdk/README.md`) | `bbe944bd` · `src/app-bootstrap/.../runtime/SecretSourceValidator.java`, `docs/registries/secrets-classification.yaml` |
|
||||
| B-15 | 기동 rule이 모든 singleton보다 먼저 돈다(`StartupRuleRunner`가 `BeanFactoryPostProcessor`). `StartupRule`과 `RequiredProductionSecrets` bean은 `static @Bean`이고 `Environment`, bean factory, static 무인자 `RequiredProductionSecrets`의 `ObjectProvider`만 받아야 한다. 두 타입의 클래스는 `@Value`·`@Autowired`·`@Inject`·`@Resource` 멤버, `@PostConstruct`·`@PreDestroy`, `@ConfigurationProperties`를 가질 수 없다(post-processor보다 먼저 만들어져 비어 있게 된다, RR2-04-03) | non-static `@Bean`이거나 다른 bean을 받으면 기동 실패 `startup rule or secret list '<이름>' created [<bean>] while creating it ... Declare the rule with a static @Bean method ...`, 위 멤버가 있으면 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one: [...]`(둘 다 exit 78, 둘 다 모든 프로필. runner가 rule과 비밀 목록을 프로필과 무관하게 먼저 만들어, 인터페이스 타입 `@Bean`이 돌려준 실제 클래스까지 본다, RR3-04-01) | rule 선언을 `static`으로, 인자를 위 셋으로 줄인다. 값은 `violations(Environment)`가 받는 `Environment`에서 읽는다. 다른 bean이 필요한 검사는 rule이 아니라 일반 bean으로 둔다 | `34565130`, `bbe944bd` · `src/adapter/outbound/support/.../startup/StartupRule.java`, `StartupRuleRunner.java` |
|
||||
| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`, `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS` 추가, 새 표시 `@SystemCaller` | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). `@SystemCaller`가 아닌 inbound adapter가 그 유스케이스를 부르거나, 사용자 전송(controller 등)이 `@SystemCaller` bean을 직접·중간 클래스를 거쳐 부르면 architectureTest 실패 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 스케줄러에 넘기거나, 메시지 handler·예약 작업이면 그 클래스에 `@SystemCaller`를 달고 생성자에서 `new`로 만든다. 예약 작업은 서비스 leaf의 `..adapter.inbound.scheduler..` 패키지에 둔다. 세 경로와 두는 곳은 매뉴얼 07장 「시스템이 부르는 쓰기」(handler 작업 순서는 09장 「소비」 4단계). "지금 실행" endpoint가 필요하면 `@RequiresPermission` 유스케이스를 따로 만든다. `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd` · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java`, `SystemCaller.java` |
|
||||
| B-17 | `IntegrationEventDraft`: `eventId`·`causationId`는 소문자 UUIDv7만. ArchUnit `INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`: `new IntegrationEventDraft<>(...)` 금지, `IntegrationEventDrafts.draft(...)`만 | 이벤트를 만드는 쓰기 요청이 `IllegalArgumentException: eventId must be a canonical lower-case UUIDv7...`로 실패. architectureTest 실패 | event id를 UUIDv7로 만든다(예: sample `UuidOutboxEventIdFactory`가 `UuidCreator.getTimeOrderedEpochPlus1()`). draft는 헬퍼로 만든다. tenant가 없는 이벤트는 `IntegrationEventDrafts.SINGLE_TENANT_SCOPE`(`global`) | `1400dc15`, `bbe944bd` · `src/application-core/.../messaging/event/IntegrationEventDraft.java`, `IntegrationEventDrafts.java` |
|
||||
| B-18 | `MessageHandler.schemaVersions()`(vendored `messaging-core-api`, default `{v1}`): 소비자 decode 목록을 handler 선언으로 만든다. 같은 (메시지 타입, 버전)에 다른 payload class를 선언하면 실패 | 컴파일은 된다. v1이 아닌 메시지는 `SCHEMA_VERSION_NOT_REGISTERED`로 거부. 발행 등록(`MessageContracts`)과 class가 다르면 기동 실패 `MESSAGING_CONTRACT_CONFLICT` | v2 이상을 읽는 handler는 `schemaVersions()`를 override한다. 소비 타입을 `MessageContracts`에 따로 등록하던 코드는 지운다 | `5786126c` · `src/messaging/messaging-core-api/.../delivery/MessageHandler.java`, `messaging-spring-boot-starter/.../MessageContracts.java` |
|
||||
| B-19 | `APP_FLYWAY_ENABLED`가 모든 프로필에서 읽힌다. dev·prod 프로필 파일의 `spring.flyway.enabled: true`·`app.persistence.vendor` 고정값을 지우고 persistence-jpa `config/module-defaults`가 `${APP_FLYWAY_ENABLED:true}`를 싣는다 | dev·prod 환경에 `APP_FLYWAY_ENABLED=false`가 있으면 전에는 무시됐지만 이제 기동 때 마이그레이션이 안 돈다 | dev·prod 환경 값을 확인한다. 자기 `application-dev.yml`·`application-prod.yml`에 같은 고정값을 다시 넣지 않는다 | `5786126c` · `src/app-bootstrap/src/main/resources/application-{dev,prod}.yml`, `src/adapter/outbound/persistence-jpa/.../module-defaults/persistence-jpa.yml` |
|
||||
@@ -100,7 +100,7 @@
|
||||
|---|---|---|---|---|
|
||||
| B-34 | 템플릿 패키지 규칙(ArchUnit): `FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`, `TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`. 템플릿 이름: application `usecase command query capability transaction security tenant observability secret messaging outbox idempotency operation lease lock cache realtime notification fileserver objectstorage`, domain `identifier stereotype` | 기능 패키지 이름이 이 목록과 겹치거나(예: `domain.lock`), 업무 코드를 템플릿 패키지(예: `application.usecase.*`)에 두고 기능 패키지를 import하면 `:app-bootstrap:architectureTest` 실패 | 기능 패키지 이름을 바꾸고, 업무 코드를 `dev.caskeleton.application.<feature>`로 옮긴다. 규칙 정본은 `src/application-core/CLAUDE.md` "Package ownership" | `5786126c` · `src/app-bootstrap/src/architectureTest/.../TemplatePackageOwnership.java` |
|
||||
| B-35 | JPA 규칙: 양방향 연관은 한쪽에서만 매핑(`mappedBy`), notification·fileserver 저장소 엔티티는 그 leaf 안에서만, `@Version` 엔티티의 bulk update는 version을 올려야 함 | 위반 엔티티·쿼리가 있으면 architectureTest 실패 | 매핑·쿼리를 고친다 | `34565130`, `1400dc15`, `bbe944bd` · `src/app-bootstrap/src/architectureTest/.../JpaProductionArchitectureTest.java` |
|
||||
| B-36 | 빌드 검사 강화: `modules.json`에 없는 `build.gradle`이 있으면 `verifyCleanArchitectureDependencies` 실패. `verifyStrictLaneStages --dry-run`은 모든 strict lane이 workflow가 실행하는 단계(`:ci` `:sample-portfolio:check` `:mainCheck` `:integrationCheck` `:performanceCheck` `:releaseCheck`)에 속해야 하고 `.github/workflows`를 읽는다. 명령의 빌드는 `working-directory`(단계·job·workflow `defaults`)와 `-p`를 합친 디렉터리로 정하고, `workflow_dispatch`로만 시작하는 workflow의 명령은 세지 않으며, 축약한 `-x`도 Gradle처럼 맞춰 본다(RR2-04-04). `verifyEnvKeys`: lane 계약 json의 `APP_` 밖 키는 `SPRING_`·`MANAGEMENT_`·`SERVER_`이거나 `secret://…/<VAR>`가 가리키는 변수여야 하고, 레지스트리 `property:` 행은 그 property가 설정 metadata에 있어야 읽히는 것으로 친다(`@ConditionalOnProperty`로만 읽는 스위치는 `META-INF/additional-spring-configuration-metadata.json`에 선언, RR2-04-05). SpotBugs 신뢰도 HIGH → MEDIUM | 등록 안 한 leaf, 단계에 안 걸린 자기 lane, 자기 코드의 MEDIUM 발견이 `ci`·`qualityCheck`를 막는다. `working-directory: src` 없이 `./gradlew`를 부르는 자기 workflow 단계는 실행으로 세지 않는다 | leaf를 등록하거나 지운다. 자기 lane은 단계에 건다. 단계를 부르는 workflow 명령에 `working-directory`를 둔다. SpotBugs 발견은 고치거나 이유를 단 제외로 | `1400dc15`, `34565130`, `bbe944bd`, `5786126c` · `src/build-logic/.../ModuleRegistry.java`, `.../strictlane/StrictLaneStagesPlugin.java`, `.../quality/QualityConventionsPlugin.java`, `src/build.gradle` |
|
||||
| B-36 | 빌드 검사 강화: `modules.json`에 없는 `build.gradle`이 있으면 `verifyCleanArchitectureDependencies` 실패. `verifyStrictLaneStages --dry-run`은 모든 strict lane이 workflow가 실행하는 단계(`:ci` `:sample-portfolio:check` `:mainCheck` `:integrationCheck` `:performanceCheck` `:releaseCheck`)에 속해야 하고 `.github/workflows`를 읽는다. 명령의 빌드는 `working-directory`(단계·job·workflow `defaults`)와 `-p`를 합친 디렉터리로 정하고, `workflow_dispatch`로만 시작하는 workflow의 명령은 세지 않으며, 축약한 `-x`도 Gradle처럼 맞춰 본다(RR2-04-04). 붙여 쓴 `-x<task>`·`-p<dir>`도 Gradle처럼 읽는다(RR3-04-02). `verifyEnvKeys`: lane 계약 json의 `APP_` 밖 키는 `SPRING_`·`MANAGEMENT_`·`SERVER_`이거나 `secret://…/<VAR>`가 가리키는 변수여야 하고, 레지스트리 `property:` 행은 그 property가 설정 metadata에 있어야 읽히는 것으로 친다(`@ConditionalOnProperty`로만 읽는 스위치는 `META-INF/additional-spring-configuration-metadata.json`에 선언, RR2-04-05). SpotBugs 신뢰도 HIGH → MEDIUM | 등록 안 한 leaf, 단계에 안 걸린 자기 lane, 자기 코드의 MEDIUM 발견이 `ci`·`qualityCheck`를 막는다. `working-directory: src` 없이 `./gradlew`를 부르는 자기 workflow 단계는 실행으로 세지 않는다 | leaf를 등록하거나 지운다. 자기 lane은 단계에 건다. 단계를 부르는 workflow 명령에 `working-directory`를 둔다. SpotBugs 발견은 고치거나 이유를 단 제외로 | `1400dc15`, `34565130`, `bbe944bd`, `5786126c` · `src/build-logic/.../ModuleRegistry.java`, `.../strictlane/StrictLaneStagesPlugin.java`, `.../quality/QualityConventionsPlugin.java`, `src/build.gradle` |
|
||||
| B-37 | app-bootstrap 테스트 lane 분리: 저장소 파일을 읽는 테스트는 태그 `document-contract`(main 단계) 또는 `repository-contract`(`check`)여야 하고, 일반 `test` lane에는 `ca.repository.root`가 없다 | app-bootstrap에 둔 자기 테스트가 저장소 파일을 읽으면 `test`에서 실패 | 태그를 단다 | `1400dc15` · `src/app-bootstrap/build.gradle` |
|
||||
|
||||
### 3.5 모듈 registry·새 leaf
|
||||
@@ -132,6 +132,11 @@
|
||||
`SET LOCAL lock_timeout = '5s'`를 둔다. 실패하면 SQLState `55P03`이고, 열린 트랜잭션을 끝낸 뒤 다시 배포한다
|
||||
(`docs/runbooks/migration-failed.md` "Classify the failure"). 자기 스트림에도 같은 규칙과 검사
|
||||
(`LockWaitMigrationInspector`, 예: `SampleMigrationLockWaitTest`)를 둔다(`docs/jpa/migration-guide.md` "Bound the lock wait").
|
||||
검사기는 3차 확인 리뷰(RR3-02-01) 뒤로 기존 테이블을 가리키는 `REFERENCES`, trigger 만들기·지우기, `REINDEX` 등을 더 잡고,
|
||||
`CREATE TABLE IF NOT EXISTS`를 "이 마이그레이션이 만든 테이블"로 세지 않으며, 0인 `lock_timeout`과 `executeInTransaction=false`
|
||||
파일의 `SET LOCAL`을 상한으로 세지 않는다. 자기 스트림의 이미 배포된 파일이 새로 걸리면 그 파일은 고치지 않고 규칙 이전
|
||||
목록에 더한다(템플릿은 idempotency V1, notification V3, messaging V1003, postgresql V11·V12를 더했다). 파일 경로를 넘기는
|
||||
`unboundedLockingStatements(Path)`가 옆의 `.sql.conf`까지 읽으니, 복사한 검사는 문자열 대신 경로를 넘긴다.
|
||||
- **번호 충돌**: 템플릿이 이제 postgresql V20~V22, notification V11~V13, sample V8_1, grpc V002·V003을 쓴다. 파생 서비스가 같은
|
||||
위치에 같은 번호를 두었다면 Flyway가 같은 버전 두 개로 실패한다. 자기 마이그레이션은 템플릿과 떨어진 번호대로 옮긴다
|
||||
(이미 적용된 파일 이름을 바꾸면 checksum·history가 어긋나므로 운영 DB에 적용된 것이면 DB 담당과 정한다).
|
||||
@@ -212,6 +217,8 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur
|
||||
| 로그 설정 | logback이 `APP_LOG_*` 대신 `app.logging.*`을 읽는다(환경 변수 이름은 그대로 매핑) | 프로필 yml의 `app.logging.*`이 이제 먹힌다 | `1400dc15` · `logback-spring.xml` |
|
||||
| local 프로필 | `server.port`가 `${APP_SERVER_PORT:8080}`을 읽는다. Flyway·`ddl-auto validate`·PostgreSQL vendor를 module-defaults에서 받는다 | local에서 `APP_SERVER_PORT`가 다른 값이면 포트가 바뀐다 | `1400dc15`, `5786126c` · `application-local.yml` |
|
||||
| deprecated | `APP_CACHE_REDIS_TTL_JITTER`는 아무것도 바인딩하지 않음(`removal_deadline: 2027-02-28`) | 값이 아무 효과 없다 | `1400dc15` · `env-keys.yaml` |
|
||||
| HTTP client(JDK transport) | 스트리밍 응답의 read-idle 감시가 전용 데몬 스레드 하나(`httpclient-jdk-read-idle`)에서 돈다. 스트림마다 감시 작업 하나, 스트림을 닫으면 작업을 바로 취소 | 스레드 덤프에 그 스레드가 하나 보인다. 공용 `ForkJoinPool`이 바빠도 timeout이 설정값에 난다(전에는 늦게 났다). Apache transport(기본)는 영향 없음 | 3차 확인 리뷰 RR3-03-01 · `src/adapter/outbound/httpclient/.../jdk/ReadIdleInputStream.java` |
|
||||
| 멱등성 | `IDEMPOTENCY_RECOVERY_REQUIRED`를 내는 예외 메시지 끝에 scope digest가 붙는다. Redis 기록 조회(INSPECT 스크립트)가 `leaseUntil`을 돌려줘 `processingLeaseUntil`이 실제 lease 끝이다(전에는 key TTL 끝, 즉 lease + replay TTL) | 예외 메시지 전체에 맞추던 로그 매처는 고친다. 회복 절차는 `docs/runbooks/idempotency-unavailable.md`(digest로 기록을 찾는다) | 3차 확인 리뷰 RR3-03-03·05 · `src/application-core/.../idempotency/IdempotencyRecoveryRequiredException.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java` |
|
||||
| sample-portfolio | 익명 쓰기 401, 포스터 제목 대소문자 무시 유일(409 `POSTER_ALREADY_EXISTS`), 관리자도 남의 work log 수정 불가, 샘플 이벤트 tenant `global` | sample을 남긴 서비스만 | `34565130`, `1400dc15` |
|
||||
|
||||
## 6. 따라오는 순서
|
||||
|
||||
@@ -122,9 +122,19 @@ status는 코드 표(`HttpStatusErrorCodes`)에 있는 것만 그대로 나간
|
||||
요청이 만나면 두 저장소(PostgreSQL·Redis) 모두 넘겨주지 않고 포기(abandoned)로 표시한다 — 그 뒤 첫 시도가
|
||||
늦게 끝나도 결과는 기록되지 않고 그 요청도 500을 받는다. 새 키로 보내면 서버는 다른 요청으로 보고 막지 못한다
|
||||
(재리뷰 2026-11-03 README 4절 결정 RR-02-03, 2026-11-04 9.1절 결정 RR-01-11).
|
||||
- **서버가 기억하는 기간.** 완료된 응답은 완료부터 `replay-ttl`(기본 24h), 끝나지 않은 시도의 기록은
|
||||
claim부터 processing lease + `replay-ttl` 동안 남는다. 그 뒤 같은 키는 새 요청으로 실행된다.
|
||||
- **서버가 기억하는 기간.** 위 판정은 기록이 남아 있는 동안만 선다. 기록이 사라지면 같은 키는 새
|
||||
요청으로 실행된다. 기록의 수명은 시도가 어떻게 끝났는지로 갈린다.
|
||||
- 완료된 응답: 완료부터 `replay-ttl`(`APP_IDEMPOTENCY_TTL`, 기본 24h).
|
||||
- 끝나지 않은 시도: claim부터 processing lease + `replay-ttl`. lease가 지나 다음 요청이 포기로 표시한
|
||||
기록도 이 수명을 그대로 쓴다.
|
||||
- 실패로 표시된 시도: 작업이 예외를 던졌거나 효과 불명으로 끝나 포기(abandoned)된 시도, 효과 없이
|
||||
재시도 가능으로 끝난 시도. 표시한 때부터 `failure-retention`(`APP_IDEMPOTENCY_FAILURE_RETENTION`,
|
||||
기본 24h).
|
||||
|
||||
`replay-ttl`이 `processing-lease`보다 짧으면 기동이 실패한다(재리뷰 2026-11-04 RR-03-11).
|
||||
`failure-retention`은 `replay-ttl`과 비교하지 않는다. 더 짧게 두면 효과 불명으로 포기한 기록이 그만큼
|
||||
먼저 사라지고, 그 뒤 같은 키 재전송은 작업을 다시 돌린다. 그래서 `replay-ttl` 이상으로 둔다
|
||||
(재리뷰 2026-11-04 RR3-03-02).
|
||||
|
||||
## 3. 헤더
|
||||
|
||||
|
||||
@@ -9,8 +9,12 @@ control of it (`CONFIG`, `MODULE`, every key). A deployment writes its own ACL f
|
||||
shape: the application accounts it actually uses, passwords from its secret store, and none of the
|
||||
lane-only accounts (review 2026-11-03 RR-07-04). The application enforces its half of that: under
|
||||
the `prod` runtime profile it refuses to start while a secret holds a value beginning with
|
||||
`fixture-` (`SecretSourceValidator`): a key the secrets registry classifies `secret`, or the
|
||||
variable a `secret://…/<VAR>` credential reference names. A deployment that copied a lane's
|
||||
`fixture-` (`SecretSourceValidator`): a key the secrets registry classifies `secret`, a variable a
|
||||
module's `RequiredProductionSecrets` bean names, or the variable a `secret://…/<VAR>` credential
|
||||
reference in the environment names. A reference held in code — the typed SDK's admin account,
|
||||
contributed as a `RedisAccountContribution` bean — is none of those: the composer names its variable
|
||||
in a `RequiredProductionSecrets` bean too (`src/adapter/outbound/redis-sdk/README.md`), or the
|
||||
`fixture-admin` password passes. A deployment that copied a lane's
|
||||
`APP_REDIS_AUTHENTICATION_*_REFERENCE` and `REDIS_LANE_*` values stops before it connects. Values
|
||||
that are not secrets — a pod's `HOSTNAME`, an application name — are not read, because `fixture-`
|
||||
is an ordinary word as well.
|
||||
|
||||
@@ -128,6 +128,7 @@ APP_IDEMPOTENCY_TTL=24h
|
||||
APP_IDEMPOTENCY_PROVIDER=disabled
|
||||
APP_IDEMPOTENCY_REDIS_NAMESPACE_ENVIRONMENT=local
|
||||
APP_IDEMPOTENCY_PROCESSING_LEASE=30s
|
||||
# Failure retention: at most 30d. Not checked against APP_IDEMPOTENCY_TTL; keep it at least that long.
|
||||
APP_IDEMPOTENCY_FAILURE_RETENTION=24h
|
||||
APP_LEASE_PROVIDER=disabled
|
||||
APP_LEASE_REDIS_NAMESPACE_ENVIRONMENT=local
|
||||
|
||||
@@ -11,8 +11,10 @@
|
||||
- Boundaries: no business rule in a handler (HARD-STOP 4); no persistence entity or repository; no
|
||||
broker SDK type. Allowed edges come only from the registry entry.
|
||||
- A handler that calls a write use case is `@SystemCaller(reason = ...)` and constructs the
|
||||
`@SystemInvoked` use case itself; the use case is never a bean (manual 09 「소비」 step 4,
|
||||
`ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`).
|
||||
`@SystemInvoked` use case itself; the use case is never a bean, and no user transport calls the
|
||||
handler (manual 09 「소비」 step 4, manual 07 「시스템이 부르는 쓰기」,
|
||||
`ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`,
|
||||
`USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`).
|
||||
- Tests: focused auto-configuration and inbox behavior tests; `./gradlew :adapter:inbound:messaging:check`.
|
||||
The real Kafka + PostgreSQL redelivery lane is `messagingInboxRedeliveryIntegrationTest`
|
||||
(`:integrationCheck`).
|
||||
|
||||
@@ -103,8 +103,10 @@ PostgreSQL에서 같은 모양은 `InboxRedeliveryIntegrationTest`의 `Projectio
|
||||
`messaging-core-api`만 보는 anti-corruption 경계이고, 소비는 inbound 방향이다.
|
||||
- 고름(RR-01-12): handler가 `@SystemCaller`를 달고 `@SystemInvoked` use case를 직접 `new`로 만든다. 사용자
|
||||
요청이 들어오는 전송(web·GraphQL·gRPC·WebSocket)만 그 use case에 닿지 못하고, 표시는 ArchUnit이 검사한다
|
||||
(`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`: messaging·scheduler inbound 패키지에만, 사용자 전송
|
||||
타입에 의존하지 않음). 기동 가드는 바꾸지 않는다: `@SystemInvoked` bean은 예외 없이 실패다.
|
||||
(`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`: 표시한 클래스와 그 안에 중첩된 클래스는 messaging·
|
||||
scheduler inbound 패키지에만, 사용자 전송 타입에 의존하지 않음). 사용자 전송이 handler bean을 주입받아
|
||||
부르는 길은 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`가 막는다(RR3-01-01). 기동 가드는 바꾸지 않는다:
|
||||
`@SystemInvoked` bean은 예외 없이 실패다. 규칙 전체는 매뉴얼 07장 「시스템이 부르는 쓰기」.
|
||||
- 버림: use case를 bean으로 두고 가드에 "handler만 주입받으면 허용" 예외 — 누가 주입받는지는 기동 때
|
||||
확정되지 않는다(`ObjectProvider`, `getBean`, 나중에 추가된 bean). 예외 조건이 곧 우회 경로가 된다.
|
||||
- 버림: handler는 `CommandUseCase` 인터페이스만 받고 조립 모듈이 `new`로 넣기 — 소비자마다 composition
|
||||
@@ -113,7 +115,9 @@ PostgreSQL에서 같은 모양은 `InboxRedeliveryIntegrationTest`의 `Projectio
|
||||
- 버림: ArchUnit 대상에서 messaging 패키지를 통째로 빼기 — 클래스에 표시가 없어 의도가 안 보이고, 그
|
||||
패키지의 아무 클래스(HTTP endpoint 포함)나 닿는다.
|
||||
- 버림: 사용자 전송 패키지만 나열해 금지 — 나중에 새 전송이 생기면 조용히 열린다. 규칙은 "닿아도 되는
|
||||
쪽"을 적는다.
|
||||
쪽"을 적는다. 이 성질은 패키지 쪽에만 있다: 시스템 패키지 안에 놓인 endpoint를 알아보는 사용자 전송
|
||||
**타입**은 나열 목록이다(`ARE_USER_TRANSPORT_TYPES`, JAX-RS·graphql-java 포함). 새 전송 라이브러리를
|
||||
들이면 그 목록에 더한다(RR3-01-02).
|
||||
- 버림: application-core에 소비 포트를 새로 만들어 platform `MessageHandler`로 감싸는 범용 bridge —
|
||||
payload 타입 매핑과 결과 매핑 규칙을 먼저 정해야 해서 이번 범위보다 크다. 지금은 handler가 직접
|
||||
use case를 부른다.
|
||||
|
||||
+10
-2
@@ -243,7 +243,14 @@ public final class IdempotencyScripts {
|
||||
return {'APPLIED', attempt, rev, owner, '', ''}
|
||||
""";
|
||||
|
||||
/** Inspect: read the record without touching it. */
|
||||
/**
|
||||
* Inspect: read the record without touching it.
|
||||
*
|
||||
* <p>The detail is {@code ownership|key PTTL|leaseUntil}. A completed record's replay deadline is
|
||||
* its key's TTL; an in-progress record's lease is not, because its key lives for the lease plus
|
||||
* {@code afterLease} — reading the lease off the TTL reported it a replay TTL too late (re-review
|
||||
* 2026-11-04 RR3-03-05).
|
||||
*/
|
||||
private static final String INSPECT =
|
||||
"""
|
||||
local state = redis.call('HGET', KEYS[1], 'state')
|
||||
@@ -268,7 +275,8 @@ public final class IdempotencyScripts {
|
||||
end
|
||||
return {state, attempt, rev, owner,
|
||||
redis.call('HGET', KEYS[1], 'resp') or '',
|
||||
mine .. '|' .. tostring(redis.call('PTTL', KEYS[1]))}
|
||||
mine .. '|' .. tostring(redis.call('PTTL', KEYS[1])) .. '|'
|
||||
.. (redis.call('HGET', KEYS[1], 'leaseUntil') or '')}
|
||||
""";
|
||||
|
||||
private final RegisteredLuaScript claim = new RegisteredLuaScript(CLAIM);
|
||||
|
||||
+10
-3
@@ -361,9 +361,16 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort
|
||||
if (reply.status() == ScriptStatus.FINGERPRINT_MISMATCH) {
|
||||
return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.FINGERPRINT_MISMATCH);
|
||||
}
|
||||
String[] detail = reply.detail().split("\\|", 2);
|
||||
String[] detail = reply.detail().split("\\|", 3);
|
||||
String ownership = detail[0];
|
||||
long ttlMillis = detail.length > 1 ? parseLong(detail[1]) : 0;
|
||||
// The lease the record carries, in server time as the claim reported it — not the key's TTL,
|
||||
// which runs a replay TTL past the lease (RR3-03-05).
|
||||
long leaseUntilMillis = detail.length > 2 ? parseLong(detail[2]) : 0;
|
||||
Optional<Instant> leaseUntil =
|
||||
leaseUntilMillis > 0
|
||||
? Optional.of(Instant.ofEpochMilli(leaseUntilMillis))
|
||||
: Optional.empty();
|
||||
if ("OPERATION_CONFLICT".equals(ownership)) {
|
||||
return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.OPERATION_CONFLICT);
|
||||
}
|
||||
@@ -390,7 +397,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort
|
||||
? new IdempotencyInspection(
|
||||
IdempotencyInspectionOutcome.CLAIMED_SAME_OPERATION,
|
||||
Optional.of(handle),
|
||||
Optional.of(now.plusMillis(Math.max(1, ttlMillis))),
|
||||
leaseUntil,
|
||||
Optional.empty(),
|
||||
Optional.empty())
|
||||
: IdempotencyInspection.outcome(IdempotencyInspectionOutcome.IN_PROGRESS_OTHER);
|
||||
@@ -399,7 +406,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort
|
||||
? new IdempotencyInspection(
|
||||
IdempotencyInspectionOutcome.EXECUTING_SAME_OPERATION,
|
||||
Optional.of(handle),
|
||||
Optional.of(now.plusMillis(Math.max(1, ttlMillis))),
|
||||
leaseUntil,
|
||||
Optional.empty(),
|
||||
Optional.empty())
|
||||
: IdempotencyInspection.outcome(IdempotencyInspectionOutcome.IN_PROGRESS_OTHER);
|
||||
|
||||
@@ -42,11 +42,12 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d
|
||||
left, the experimental Jetty HTTP/3 transport aborts the request, and the caller gets
|
||||
`HttpDeadlineExceededException`. A streaming download's setup (up to the response headers) runs
|
||||
inside the same deadline; after hand-over each body gap is bounded by `read-idle` and nothing else,
|
||||
on both transports — the JDK transport arms its own per-read timer for this, because the JDK client
|
||||
has no socket read timeout. A body that fails after hand-over throws `HttpBodyReadException`, an
|
||||
`IOException` as `InputStream.read` promises, whose `failure()` is the same stable exception a
|
||||
buffered call throws (`HttpResponseTimeoutException` for a stalled body,
|
||||
`HttpResponseTruncatedException` for a cut one).
|
||||
on both transports — on the JDK transport, which has no socket read timeout, a per-stream watchdog
|
||||
on its own daemon thread (`httpclient-jdk-read-idle`) bounds each read's wait. A body that fails
|
||||
after hand-over throws `HttpBodyReadException`, an `IOException` as `InputStream.read` promises,
|
||||
whose `failure()` is the same stable exception a buffered call throws
|
||||
(`HttpResponseTimeoutException` for a stalled body, `HttpResponseTruncatedException` for a cut
|
||||
one).
|
||||
- **Evidence.** Each attempt reports `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, or
|
||||
`PARTIAL_RESPONSE`. `NOT_SENT` is only claimed when a stage failure proves it.
|
||||
- **Retry.** Never from the HTTP method alone. Idempotency, body replayability, evidence, deadline,
|
||||
|
||||
+64
-2
@@ -6,7 +6,9 @@ import java.io.InputStream;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.time.Duration;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
@@ -31,6 +33,20 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
* it moves the queue off the shared scheduler but keeps a queue insertion and removal on every
|
||||
* read.
|
||||
*
|
||||
* <p>The watchdog wakes on a thread of its own: one daemon thread, {@code
|
||||
* httpclient-jdk-read-idle}, shared by every JDK stream and started with the first (re-review
|
||||
* 2026-11-04 RR3-03-01). It used to wake through {@code CompletableFuture.delayedExecutor}, whose
|
||||
* task runs on the common {@code ForkJoinPool}; a service that filled that pool with blocking work
|
||||
* — {@code supplyAsync(blockingCall)} without an executor — held every timeout until a pool thread
|
||||
* came free, and a 300 ms {@code read-idle} ended after 2.7 s. The wake is O(1), and the close it
|
||||
* may do waits on no I/O — the JDK body marks itself closed, cancels its subscription and wakes the
|
||||
* read — so both run on this thread, as the per-read timer before RR-03-13 closed on the JDK's
|
||||
* delay thread. Rejected: {@code delayedExecutor(delay, unit, Runnable::run)}, which judges on the
|
||||
* JDK's own delay thread — that thread fires every {@code CompletableFuture} timeout in the
|
||||
* process, so a slow close there would delay them all, and it returns no handle to take a closed
|
||||
* stream's wake off the queue. Closing the stream cancels its pending wake, so a closed stream is
|
||||
* not kept reachable until its {@code read-idle} passes.
|
||||
*
|
||||
* <p>{@link #skip} reads through this stream rather than delegating: the JDK body does not override
|
||||
* {@code skip}, so {@code InputStream.skip} ran many reads inside one guarded call and a long skip
|
||||
* over a steady body timed out as one long wait (re-review 2026-11-04 RR-03-12).
|
||||
@@ -53,10 +69,35 @@ final class ReadIdleInputStream extends FilterInputStream {
|
||||
private final AtomicBoolean idled = new AtomicBoolean();
|
||||
private volatile long readStartedAt = NOT_READING;
|
||||
private volatile boolean closed;
|
||||
private volatile ScheduledFuture<?> pendingWake;
|
||||
private final ScheduledExecutorService watchdogs;
|
||||
|
||||
ReadIdleInputStream(InputStream delegate, Duration readIdle) {
|
||||
this(delegate, readIdle, SharedWatchdogs.INSTANCE);
|
||||
}
|
||||
|
||||
/** The scheduler is a parameter so a test can see what a stream leaves queued on it. */
|
||||
ReadIdleInputStream(InputStream delegate, Duration readIdle, ScheduledExecutorService watchdogs) {
|
||||
super(Objects.requireNonNull(delegate, "body stream"));
|
||||
this.readIdleNanos = Objects.requireNonNull(readIdle, "read idle timeout").toNanos();
|
||||
this.watchdogs = Objects.requireNonNull(watchdogs, "watchdog scheduler");
|
||||
}
|
||||
|
||||
/**
|
||||
* A watchdog scheduler as every stream gets it: one daemon thread, and a cancelled wake leaves
|
||||
* the queue at once instead of when it would have fired.
|
||||
*/
|
||||
static ScheduledThreadPoolExecutor newWatchdogs() {
|
||||
ScheduledThreadPoolExecutor scheduler =
|
||||
new ScheduledThreadPoolExecutor(
|
||||
1,
|
||||
runnable -> {
|
||||
Thread thread = new Thread(runnable, "httpclient-jdk-read-idle");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
scheduler.setRemoveOnCancelPolicy(true);
|
||||
return scheduler;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -89,6 +130,7 @@ final class ReadIdleInputStream extends FilterInputStream {
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
closed = true;
|
||||
cancelPendingWake();
|
||||
super.close();
|
||||
}
|
||||
|
||||
@@ -113,7 +155,19 @@ final class ReadIdleInputStream extends FilterInputStream {
|
||||
/** Wakes the watchdog when a read that started at {@code started} reaches read-idle. */
|
||||
private void watchFrom(long started) {
|
||||
long left = Math.max(0, readIdleNanos - (System.nanoTime() - started));
|
||||
CompletableFuture.delayedExecutor(left, TimeUnit.NANOSECONDS).execute(this::watch);
|
||||
pendingWake = watchdogs.schedule(this::watch, left, TimeUnit.NANOSECONDS);
|
||||
// A close between the watchdog's check and this schedule did not see the new wake; take it
|
||||
// off here. Both sides write their own volatile before reading the other's.
|
||||
if (closed) {
|
||||
cancelPendingWake();
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelPendingWake() {
|
||||
ScheduledFuture<?> wake = pendingWake;
|
||||
if (wake != null) {
|
||||
wake.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void watch() {
|
||||
@@ -158,4 +212,12 @@ final class ReadIdleInputStream extends FilterInputStream {
|
||||
throw new SocketTimeoutException("no response body bytes within the read-idle timeout");
|
||||
}
|
||||
}
|
||||
|
||||
/** The scheduler every stream shares, started with the first stream that is read. */
|
||||
private static final class SharedWatchdogs {
|
||||
|
||||
static final ScheduledExecutorService INSTANCE = newWatchdogs();
|
||||
|
||||
private SharedWatchdogs() {}
|
||||
}
|
||||
}
|
||||
|
||||
+86
-1
@@ -8,6 +8,8 @@ import java.io.InputStream;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -15,12 +17,14 @@ import org.junit.jupiter.api.Test;
|
||||
/**
|
||||
* What the JDK transport's read-idle bound promises: each read that waits longer than {@code
|
||||
* read-idle} for the server ends the body, and nothing else does (re-review 2026-11-04 RR-03-12,
|
||||
* RR-03-13).
|
||||
* RR-03-13); the watchdog keeps that time whatever the common pool is doing, and leaves nothing
|
||||
* scheduled for a stream that is closed or timed out (RR3-03-01).
|
||||
*/
|
||||
class ReadIdleInputStreamTest {
|
||||
|
||||
private static final Duration READ_IDLE = Duration.ofMillis(300);
|
||||
private static final Duration GAP = Duration.ofMillis(20);
|
||||
private static final Duration COMMON_POOL_HOLD = Duration.ofSeconds(3);
|
||||
|
||||
@Test
|
||||
@DisplayName("데이터가 read-idle보다 짧은 간격으로 오면 read-idle보다 오래 걸리는 skip도 끝까지 건너뛴다")
|
||||
@@ -67,6 +71,79 @@ class ReadIdleInputStreamTest {
|
||||
assertThat(waited).isGreaterThanOrEqualTo(READ_IDLE).isLessThan(READ_IDLE.multipliedBy(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("공용 ForkJoinPool이 블로킹 작업으로 차 있어도 멈춘 read는 read-idle 무렵에 끝난다")
|
||||
void aStalledReadTimesOutOnTimeWhileTheCommonPoolIsBlocked() throws Exception {
|
||||
// given
|
||||
// Every common-pool worker parks on a latch, which does not make the pool add a spare thread —
|
||||
// what a service's supplyAsync(blockingCall) without an executor does. The hold is bounded so
|
||||
// a watchdog that needs a pool worker still ends the read, late (re-review 2026-11-04
|
||||
// RR3-03-01: 300 ms read-idle timed out after 2,699 ms).
|
||||
int workers = Math.max(1, ForkJoinPool.getCommonPoolParallelism());
|
||||
CountDownLatch occupied = new CountDownLatch(workers);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
for (int task = 0; task < workers * 2; task++) {
|
||||
ForkJoinPool.commonPool()
|
||||
.execute(
|
||||
() -> {
|
||||
occupied.countDown();
|
||||
awaitQuietly(release, COMMON_POOL_HOLD);
|
||||
});
|
||||
}
|
||||
assertThat(occupied.await(5, TimeUnit.SECONDS)).as("every common-pool worker is held").isTrue();
|
||||
InputStream body = new ReadIdleInputStream(new StalledStream(), READ_IDLE);
|
||||
long started = System.nanoTime();
|
||||
try {
|
||||
// when
|
||||
Throwable failure = catchThrowable(body::read);
|
||||
|
||||
// then
|
||||
Duration waited = Duration.ofNanos(System.nanoTime() - started);
|
||||
assertThat(failure).isInstanceOf(SocketTimeoutException.class);
|
||||
assertThat(waited).isGreaterThanOrEqualTo(READ_IDLE).isLessThan(READ_IDLE.multipliedBy(3));
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("스트림을 닫으면 그 스트림의 watchdog 예약이 스케줄러에서 바로 빠진다")
|
||||
void closingTheStreamTakesItsWatchdogOffTheScheduler() throws IOException {
|
||||
// given
|
||||
ScheduledThreadPoolExecutor watchdogs = ReadIdleInputStream.newWatchdogs();
|
||||
try {
|
||||
InputStream body = new ReadIdleInputStream(new DrippingStream(1, GAP), READ_IDLE, watchdogs);
|
||||
body.read();
|
||||
|
||||
// when
|
||||
body.close();
|
||||
|
||||
// then
|
||||
assertThat(watchdogs.getQueue()).isEmpty();
|
||||
} finally {
|
||||
watchdogs.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("read-idle로 끝난 스트림은 닫지 않아도 watchdog을 더 예약하지 않는다")
|
||||
void aStreamThatTimedOutLeavesNoWatchdogBehind() {
|
||||
// given
|
||||
ScheduledThreadPoolExecutor watchdogs = ReadIdleInputStream.newWatchdogs();
|
||||
try {
|
||||
InputStream body = new ReadIdleInputStream(new StalledStream(), READ_IDLE, watchdogs);
|
||||
|
||||
// when
|
||||
Throwable failure = catchThrowable(body::read);
|
||||
|
||||
// then
|
||||
assertThat(failure).isInstanceOf(SocketTimeoutException.class);
|
||||
assertThat(watchdogs.getQueue()).isEmpty();
|
||||
} finally {
|
||||
watchdogs.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("호출자가 read 사이에 오래 머문 시간은 read-idle로 세지 않는다")
|
||||
void timeTheCallerSpendsBetweenReadsIsNotIdle() throws Exception {
|
||||
@@ -83,6 +160,14 @@ class ReadIdleInputStreamTest {
|
||||
}
|
||||
}
|
||||
|
||||
private static void awaitQuietly(CountDownLatch latch, Duration atMost) {
|
||||
try {
|
||||
latch.await(atMost.toNanos(), TimeUnit.NANOSECONDS);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
/** Gives one byte per read, each after {@code gap}. */
|
||||
private static final class DrippingStream extends InputStream {
|
||||
|
||||
|
||||
@@ -95,7 +95,8 @@ not grow by wiring accident.
|
||||
- OSIV is false in every runtime profile; Flyway owns schema change and Hibernate only validates.
|
||||
- A migration that locks a table already in use starts with `SET LOCAL lock_timeout = '5s';`
|
||||
(`docs/jpa/migration-guide.md` "Bound the lock wait"). `MigrationLockWaitTest` refuses one
|
||||
without it; its list of migrations released before the rule only ever shrinks.
|
||||
without it. Its list of migrations released before the rule never takes a new migration; it
|
||||
grows only when the inspector learns a statement and finds it in a file already on `main`.
|
||||
- Metric tags, exception messages, and logs carry no SQL parameters, entity ids, tenant ids, or PII.
|
||||
- Contracts run against real PostgreSQL. H2 never satisfies one.
|
||||
|
||||
|
||||
+12
-4
@@ -4,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.migration.LockWaitMigrationInspector;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -26,21 +25,30 @@ class MigrationLockWaitTest {
|
||||
* Migrations released before the rule, which wait without a bound and stay that way: they are
|
||||
* applied (on {@code main} when the rule came in), and an applied migration is never edited
|
||||
* ({@link AppliedMigrationImmutabilityTest}). Their waits are behind every database that ran
|
||||
* them. Nothing is added here — a new migration bounds its wait.
|
||||
* them. A new migration is never added here — it bounds its wait. The list grows only when the
|
||||
* inspector learns a statement it did not know and finds it in a file released before the rule:
|
||||
* {@code REFERENCES} on an existing table, and a {@code CREATE TABLE IF NOT EXISTS} that no
|
||||
* longer exempts the statements after it (re-review 2026-11-03 round 3, RR3-02-01), added {@code
|
||||
* jpa/idempotency/V1}, notification {@code V3}, {@code messaging/V1003} and {@code
|
||||
* postgresql/V11} and {@code V12} — all five on {@code main} ({@code 01a8a2a7}), unchanged since.
|
||||
*/
|
||||
private static final Set<String> RELEASED_BEFORE_THE_RULE =
|
||||
Set.of(
|
||||
"jpa/core/V2__widen_capability_schema_stream.sql",
|
||||
"jpa/idempotency/V1__expand_owner_safe_v2.sql",
|
||||
"jpa/idempotency/V2__request_hash_varchar.sql",
|
||||
"postgresql/V5__int_lock_expired_after.sql",
|
||||
"postgresql/V9__widen_capability_schema_stream.sql",
|
||||
"postgresql/V10__idempotency_request_hash_varchar.sql",
|
||||
"postgresql/V11__durable_operation.sql",
|
||||
"postgresql/V12__live_event_log.sql",
|
||||
"postgresql/V13__outbox_canonical_transport_compatibility.sql",
|
||||
"postgresql/V14__validate_outbox_canonical_constraints.sql",
|
||||
"postgresql/V16__outbox_canonical_hash_columns_varchar.sql",
|
||||
"postgresql/V17__outbox_event_lease_fencing.sql",
|
||||
"postgresql/V18__outbox_event_unpublished_aggregate_order.sql",
|
||||
"postgresql/V19__outbox_event_canonical_only.sql",
|
||||
"jpa/notification-platform/V3__notification_platform_inbox_admin.sql",
|
||||
"jpa/notification-platform/V4__notification_platform_alignment_and_activation.sql",
|
||||
"jpa/notification-platform/V5__notification_recipient_expiry.sql",
|
||||
"jpa/notification-platform/V6__notification_projection_facts.sql",
|
||||
@@ -52,6 +60,7 @@ class MigrationLockWaitTest {
|
||||
"jpa/fileserver/V4__fileserver_upload_terminal_state.sql",
|
||||
"jpa/fileserver/V5__fileserver_file_owner.sql",
|
||||
"messaging/V1002__messaging_outbox_lease_fencing.sql",
|
||||
"messaging/V1003__messaging_admin_operation_journal.sql",
|
||||
"messaging/V1004__messaging_outbox_canonical_metadata.sql",
|
||||
"messaging/V1005__messaging_outbox_ordering_key_index.sql");
|
||||
|
||||
@@ -94,8 +103,7 @@ class MigrationLockWaitTest {
|
||||
throws IOException {
|
||||
Map<String, List<String>> unbounded = new TreeMap<>();
|
||||
for (Map.Entry<String, Path> migration : migrations.entrySet()) {
|
||||
List<String> statements =
|
||||
inspector.unboundedLockingStatements(Files.readString(migration.getValue()));
|
||||
List<String> statements = inspector.unboundedLockingStatements(migration.getValue());
|
||||
if (!statements.isEmpty()) {
|
||||
unbounded.put(migration.getKey(), statements);
|
||||
}
|
||||
|
||||
+9
-14
@@ -1,12 +1,11 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.migration;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.migration.VersionedMigrationFiles;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* The migration trees that run against the database this leaf owns, read the one way every
|
||||
@@ -46,22 +45,18 @@ final class MigrationTrees {
|
||||
private MigrationTrees() {}
|
||||
|
||||
/**
|
||||
* Every versioned migration, keyed by its path below its tree ({@code postgresql/V22__...sql}),
|
||||
* the key {@code applied-migrations.sha256} uses.
|
||||
* Every versioned migration ({@link VersionedMigrationFiles}, the definition the sample's check
|
||||
* uses too), keyed by its path below its tree ({@code postgresql/V22__...sql}), the key {@code
|
||||
* applied-migrations.sha256} uses.
|
||||
*/
|
||||
static Map<String, Path> versionedMigrations() throws IOException {
|
||||
Map<String, Path> migrations = new TreeMap<>();
|
||||
for (Path root : ROOTS) {
|
||||
try (Stream<Path> files = Files.walk(root)) {
|
||||
for (Path file :
|
||||
files
|
||||
.filter(path -> path.getFileName().toString().matches("V\\d+__.+\\.sql"))
|
||||
.toList()) {
|
||||
String key = root.relativize(file).toString().replace('\\', '/');
|
||||
if (migrations.put(key, file) != null) {
|
||||
throw new IllegalStateException(
|
||||
key + " exists in two migration trees; the classpath would load one at random");
|
||||
}
|
||||
for (Map.Entry<String, Path> migration : VersionedMigrationFiles.under(root).entrySet()) {
|
||||
if (migrations.put(migration.getKey(), migration.getValue()) != null) {
|
||||
throw new IllegalStateException(
|
||||
migration.getKey()
|
||||
+ " exists in two migration trees; the classpath would load one at random");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+49
@@ -12,6 +12,8 @@ import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseMa
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseOneToOneEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinColumnChildEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinColumnParentEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinTableChildEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinTableParentEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.MutualForeignKeyInvoiceEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.MutualForeignKeyOrderEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.NoDefaultConstructorEntity;
|
||||
@@ -19,6 +21,8 @@ import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OrderEnti
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningChildEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningManyToManyEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningOneToOneEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.TwoOwnerCourseEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.TwoOwnerStudentEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.UnidirectionalCollectionEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.BadOrderController;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.GoodOrderController;
|
||||
@@ -230,6 +234,51 @@ class JpaArchitectureRulesTest {
|
||||
.hasMessageNotContaining("two fields map one link");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("mappedBy를 잊어 컬렉션은 조인 테이블에, 반대쪽은 자기 외래 키 열에 링크를 두면 한 링크가 아니라 따로 저장된 두 사본으로 거부된다")
|
||||
void aCollectionInAJoinTableAndAToOneInItsOwnColumnAreRefusedAsTwoStoredCopies() {
|
||||
// given
|
||||
var classes =
|
||||
new ClassFileImporter()
|
||||
.importClasses(JoinTableParentEntity.class, JoinTableChildEntity.class);
|
||||
|
||||
// when
|
||||
Throwable failure =
|
||||
catchThrowable(
|
||||
() -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes));
|
||||
|
||||
// then
|
||||
assertThat(failure)
|
||||
.isInstanceOf(AssertionError.class)
|
||||
.hasMessageContaining("JoinTableParentEntity.children")
|
||||
.hasMessageContaining("JoinTableChildEntity.parent")
|
||||
.hasMessageContaining("the link is stored twice")
|
||||
.hasMessageContaining("column parent_id")
|
||||
.hasMessageNotContaining("two fields map one link");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("mappedBy 없는 두 @ManyToMany는 한 링크가 아니라 양쪽이 따로 저장하는 두 사본으로 거부된다")
|
||||
void twoManyToManyCollectionsWithoutMappedByAreRefusedAsTwoStoredCopies() {
|
||||
// given
|
||||
var classes =
|
||||
new ClassFileImporter()
|
||||
.importClasses(TwoOwnerStudentEntity.class, TwoOwnerCourseEntity.class);
|
||||
|
||||
// when
|
||||
Throwable failure =
|
||||
catchThrowable(
|
||||
() -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes));
|
||||
|
||||
// then
|
||||
assertThat(failure)
|
||||
.isInstanceOf(AssertionError.class)
|
||||
.hasMessageContaining("TwoOwnerStudentEntity.courses")
|
||||
.hasMessageContaining("TwoOwnerCourseEntity.students")
|
||||
.hasMessageContaining("the link is stored twice")
|
||||
.hasMessageNotContaining("two fields map one link");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("단방향 연관관계는 통과한다")
|
||||
void unidirectionalAssociationsPass() {
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
|
||||
/** Refused by the association rule: the other half of {@link JoinTableParentEntity}'s pair. */
|
||||
@Entity
|
||||
public class JoinTableChildEntity {
|
||||
|
||||
@Id private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "parent_id")
|
||||
private JoinTableParentEntity parent;
|
||||
|
||||
protected JoinTableChildEntity() {}
|
||||
|
||||
/** The identifier. */
|
||||
public Long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/** The reference kept in this table's own column. */
|
||||
public JoinTableParentEntity parent() {
|
||||
return parent;
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Refused by the association rule: a pair without {@code mappedBy} that stores the link twice.
|
||||
*
|
||||
* <p>A {@code @OneToMany} without {@code @JoinColumn} keeps its links in a join table, and {@link
|
||||
* JoinTableChildEntity#parent} keeps the same link in its own {@code parent_id} column — the shape
|
||||
* forgetting {@code mappedBy} produces. Two copies stored apart, not one mapped twice (re-review
|
||||
* round 3, RR3-02-05).
|
||||
*/
|
||||
@Entity
|
||||
public class JoinTableParentEntity {
|
||||
|
||||
@Id private Long id;
|
||||
|
||||
@OneToMany private List<JoinTableChildEntity> children = new ArrayList<>();
|
||||
|
||||
protected JoinTableParentEntity() {}
|
||||
|
||||
/** The identifier. */
|
||||
public Long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/** The collection kept in the join table. */
|
||||
public List<JoinTableChildEntity> children() {
|
||||
return List.copyOf(children);
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.ManyToMany;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/** Refused by the association rule: the other half of {@link TwoOwnerStudentEntity}'s pair. */
|
||||
@Entity
|
||||
public class TwoOwnerCourseEntity {
|
||||
|
||||
@Id private Long id;
|
||||
|
||||
@ManyToMany private Set<TwoOwnerStudentEntity> students = new HashSet<>();
|
||||
|
||||
protected TwoOwnerCourseEntity() {}
|
||||
|
||||
/** The identifier. */
|
||||
public Long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/** The students, kept in this side's join table. */
|
||||
public Set<TwoOwnerStudentEntity> students() {
|
||||
return Set.copyOf(students);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.ManyToMany;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Refused by the association rule: two {@code @ManyToMany} collections without {@code mappedBy}.
|
||||
*
|
||||
* <p>Both this collection and {@link TwoOwnerCourseEntity#students} own the link, each in its own
|
||||
* join table by default. Two copies stored apart, not one mapped twice (re-review round 3,
|
||||
* RR3-02-05).
|
||||
*/
|
||||
@Entity
|
||||
public class TwoOwnerStudentEntity {
|
||||
|
||||
@Id private Long id;
|
||||
|
||||
@ManyToMany private Set<TwoOwnerCourseEntity> courses = new HashSet<>();
|
||||
|
||||
protected TwoOwnerStudentEntity() {}
|
||||
|
||||
/** The identifier. */
|
||||
public Long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/** The courses, kept in this side's join table. */
|
||||
public Set<TwoOwnerCourseEntity> courses() {
|
||||
return Set.copyOf(courses);
|
||||
}
|
||||
}
|
||||
+84
-2
@@ -2,9 +2,15 @@ package dev.caskeleton.adapter.outbound.persistence.testkit.migration;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
import static org.assertj.core.api.InstanceOfAssertFactories.STRING;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
@@ -14,6 +20,9 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
*/
|
||||
class LockWaitMigrationInspectorTest {
|
||||
|
||||
private static final String BOUNDED_ALTER =
|
||||
"SET LOCAL lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;";
|
||||
|
||||
private final LockWaitMigrationInspector inspector = new LockWaitMigrationInspector();
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -26,7 +35,20 @@ class LockWaitMigrationInspectorTest {
|
||||
"UPDATE outbox_event SET status = 'FAILED';",
|
||||
"LOCK TABLE outbox_event IN SHARE MODE;",
|
||||
"ALTER TABLE outbox_event ADD COLUMN c INT;\nSET LOCAL lock_timeout = '5s';",
|
||||
"SET lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;"
|
||||
"SET lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;",
|
||||
"CREATE TABLE outbox_note (id BIGINT, event_id UUID REFERENCES outbox_event (event_id));",
|
||||
"CREATE TABLE poster_note (id BIGINT);\n"
|
||||
+ "ALTER TABLE poster_note ADD CONSTRAINT fk FOREIGN KEY (id) REFERENCES poster (id);",
|
||||
"CREATE TRIGGER trg_outbox BEFORE UPDATE ON outbox_event FOR EACH ROW EXECUTE FUNCTION f();",
|
||||
"CREATE OR REPLACE TRIGGER trg_outbox AFTER INSERT ON public.outbox_event"
|
||||
+ " FOR EACH ROW EXECUTE FUNCTION f();",
|
||||
"DROP TRIGGER IF EXISTS trg_outbox ON outbox_event;",
|
||||
"REINDEX TABLE outbox_event;",
|
||||
"REINDEX INDEX ux_outbox_event_aggregate_order;",
|
||||
"REFRESH MATERIALIZED VIEW outbox_summary;",
|
||||
"CLUSTER outbox_event USING ix_outbox_event_status;",
|
||||
"VACUUM FULL outbox_event;",
|
||||
"CREATE TABLE IF NOT EXISTS ledger (id BIGINT);\nALTER TABLE ledger ADD c INT;"
|
||||
})
|
||||
@DisplayName("이미 있는 테이블에 잠금을 거는 문장 앞에 SET LOCAL lock_timeout이 없으면 거부된다")
|
||||
void aLockOnAnExistingTableWithoutABoundBeforeItIsRefused(String sql) {
|
||||
@@ -50,8 +72,12 @@ class LockWaitMigrationInspectorTest {
|
||||
"-- bound first\nset local lock_timeout = '5s';\ndelete from notification_suppression;",
|
||||
"CREATE TABLE ledger (id BIGINT);\nCREATE INDEX ix_ledger ON ledger (id);\n"
|
||||
+ "ALTER TABLE ledger ADD COLUMN c INT;",
|
||||
"CREATE TABLE IF NOT EXISTS public.ledger (id BIGINT);\nALTER TABLE ledger ADD c INT;",
|
||||
"CREATE INDEX CONCURRENTLY ix_outbox ON outbox_event (status);",
|
||||
"REINDEX TABLE CONCURRENTLY outbox_event;",
|
||||
"CREATE TABLE parent (id BIGINT PRIMARY KEY);\n"
|
||||
+ "CREATE TABLE child (id BIGINT, parent_id BIGINT REFERENCES parent (id));",
|
||||
"CREATE TABLE node (id BIGINT PRIMARY KEY, parent_id BIGINT REFERENCES node (id));",
|
||||
"SET LOCAL lock_timeout TO 5000;\nDROP TRIGGER trg_outbox ON outbox_event;",
|
||||
"-- ALTER TABLE outbox_event ADD COLUMN c INT;\n/* DELETE FROM outbox_event; */\n"
|
||||
+ "COMMENT ON TABLE outbox_event IS 'update outbox_event set status';",
|
||||
"CREATE TABLE poster_copy AS SELECT * FROM poster;"
|
||||
@@ -68,6 +94,62 @@ class LockWaitMigrationInspectorTest {
|
||||
assertThat(refused).isNull();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(
|
||||
strings = {
|
||||
"SET LOCAL lock_timeout = 0;\nALTER TABLE outbox_event ADD COLUMN c INT;",
|
||||
"SET LOCAL lock_timeout = '0s';\nALTER TABLE outbox_event ADD COLUMN c INT;",
|
||||
"SET LOCAL lock_timeout TO DEFAULT;\nALTER TABLE outbox_event ADD COLUMN c INT;",
|
||||
"SET LOCAL lock_timeout = '5s';\nSET LOCAL lock_timeout = 0;\n"
|
||||
+ "ALTER TABLE outbox_event ADD COLUMN c INT;",
|
||||
"SET LOCAL lock_timeout = '5s';\nRESET lock_timeout;\n"
|
||||
+ "ALTER TABLE outbox_event ADD COLUMN c INT;"
|
||||
})
|
||||
@DisplayName("lock_timeout을 0이나 기본값으로 두거나 되돌린 뒤의 잠금은 상한이 없는 것으로 거부된다")
|
||||
void aLockAfterATimeoutOfZeroOrALiftedBoundIsRefused(String sql) {
|
||||
// given
|
||||
MigrationResource migration = new MigrationResource("V99__change.sql", sql);
|
||||
|
||||
// when
|
||||
Throwable refused = catchThrowable(() -> inspector.requireBoundedLockWait(migration));
|
||||
|
||||
// then
|
||||
assertThat(refused)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("alter table outbox_event");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("executeInTransaction=false인 마이그레이션의 SET LOCAL lock_timeout은 상한으로 세지 않는다")
|
||||
void setLocalInANonTransactionalMigrationIsNotABound(@TempDir Path stream) throws IOException {
|
||||
// given
|
||||
Path script = Files.writeString(stream.resolve("V99__change.sql"), BOUNDED_ALTER);
|
||||
Files.writeString(stream.resolve("V99__change.sql.conf"), "executeInTransaction=false\n");
|
||||
|
||||
// when
|
||||
List<String> unbounded = inspector.unboundedLockingStatements(script);
|
||||
|
||||
// then
|
||||
assertThat(unbounded)
|
||||
.singleElement(STRING)
|
||||
.contains("alter table outbox_event")
|
||||
.contains("executeInTransaction=false");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("설정 파일이 없는 마이그레이션 파일은 트랜잭션 안에서 돌아 SET LOCAL lock_timeout이 상한이 된다")
|
||||
void setLocalInAMigrationFileWithoutConfigurationIsABound(@TempDir Path stream)
|
||||
throws IOException {
|
||||
// given
|
||||
Path script = Files.writeString(stream.resolve("V99__change.sql"), BOUNDED_ALTER);
|
||||
|
||||
// when
|
||||
List<String> unbounded = inspector.unboundedLockingStatements(script);
|
||||
|
||||
// then
|
||||
assertThat(unbounded).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("거부 메시지는 상한 없이 잠금을 기다리는 문장과 대상 테이블을 모두 말한다")
|
||||
void theRefusalNamesEveryUnboundedStatementAndItsTable() {
|
||||
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.testkit.migration;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* One definition of a versioned migration for every check that walks a tree (re-review 2026-11-03
|
||||
* round 3, RR3-02-03): the operating trees' checks once skipped {@code V22_1__} while the sample's
|
||||
* counted it.
|
||||
*/
|
||||
class VersionedMigrationFilesTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("소수 버전을 포함한 버전 마이그레이션만 하위 디렉터리까지 찾고 다른 파일은 뺀다")
|
||||
void everyVersionedMigrationIncludingADecimalVersionIsFoundAndNothingElse(@TempDir Path tree)
|
||||
throws IOException {
|
||||
// given
|
||||
Files.createDirectories(tree.resolve("postgresql"));
|
||||
for (String file :
|
||||
Set.of(
|
||||
"postgresql/V22__outbox.sql",
|
||||
"postgresql/V22_1__outbox_fix.sql",
|
||||
"postgresql/V22.2__outbox_index.sql",
|
||||
"postgresql/V22__outbox.sql.conf",
|
||||
"postgresql/R__view.sql",
|
||||
"postgresql/U22__undo.sql",
|
||||
"README.md")) {
|
||||
Files.writeString(tree.resolve(file), "SELECT 1;");
|
||||
}
|
||||
|
||||
// when
|
||||
Set<String> found = VersionedMigrationFiles.under(tree).keySet();
|
||||
|
||||
// then
|
||||
assertThat(found)
|
||||
.containsExactlyInAnyOrder(
|
||||
"postgresql/V22__outbox.sql",
|
||||
"postgresql/V22_1__outbox_fix.sql",
|
||||
"postgresql/V22.2__outbox_index.sql");
|
||||
}
|
||||
}
|
||||
+79
-13
@@ -10,6 +10,8 @@ import com.tngtech.archunit.core.domain.JavaType;
|
||||
import com.tngtech.archunit.lang.ArchCondition;
|
||||
import com.tngtech.archunit.lang.ConditionEvents;
|
||||
import com.tngtech.archunit.lang.SimpleConditionEvent;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.JoinTable;
|
||||
import jakarta.persistence.ManyToMany;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.OneToMany;
|
||||
@@ -30,10 +32,12 @@ import java.util.stream.Stream;
|
||||
* <ul>
|
||||
* <li>With {@code mappedBy}: the inverse half says so. Only that half is reported, because the
|
||||
* foreign key belongs to the owning {@code @ManyToOne} either way.
|
||||
* <li>Without it: both halves map the same join column, one of them usually {@code insertable =
|
||||
* false, updatable = false} (Hibernate's {@code @JoinColumn} form). Neither half says it is
|
||||
* the copy, so both are reported (review RR-03-04). Reading the attribute alone let this form
|
||||
* pass.
|
||||
* <li>Without it: neither half says it is the copy, so both are reported (review RR-03-04).
|
||||
* Reading the attribute alone let this form pass. Either both halves map the same join
|
||||
* column, one of them usually {@code insertable = false, updatable = false} (Hibernate's
|
||||
* {@code @JoinColumn} form), or each stores the link on its own — a {@code @OneToMany}
|
||||
* without {@code @JoinColumn} in a join table beside the to-one's column, two
|
||||
* {@code @ManyToMany} in a join table each — and the report says which (RR3-02-05).
|
||||
* </ul>
|
||||
*
|
||||
* <p>Two to-one links the other way round — {@code Order.@OneToOne latestInvoice} and {@code
|
||||
@@ -116,25 +120,48 @@ public final class SingleSidedAssociationCondition extends ArchCondition<JavaCla
|
||||
+ " (@"
|
||||
+ back.get().annotation()
|
||||
+ ") point at each other without mappedBy: "
|
||||
+ why(own.annotation(), back.get().annotation())
|
||||
+ why(mappedType, member, own, target, counterpart, back.get())
|
||||
+ ALTERNATIVE));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a pair without {@code mappedBy} is refused. A collection and the to-one that points back,
|
||||
* or two many-to-many collections, map one link from both ends; two to-one links are two foreign
|
||||
* keys that reference each other's table.
|
||||
* Why a pair without {@code mappedBy} is refused, from where each half keeps the link.
|
||||
*
|
||||
* <ul>
|
||||
* <li>Two to-one links are two foreign keys that reference each other's table.
|
||||
* <li>A collection with {@code @JoinColumn} and a to-one on that same column (or one that does
|
||||
* not name its column) map one link from both ends — Hibernate's {@code @JoinColumn} form.
|
||||
* <li>Anything else stores the link twice: a {@code @OneToMany} without {@code @JoinColumn}
|
||||
* keeps it in a join table while the to-one keeps it in its own column (the shape a
|
||||
* forgotten {@code mappedBy} produces), two {@code @ManyToMany} each own a join table, and
|
||||
* two differently named columns are two columns (re-review 2026-11-03 round 3, RR3-02-05).
|
||||
* </ul>
|
||||
*/
|
||||
private static String why(String own, String back) {
|
||||
if (own.equals(inverseOf(back)) && !own.equals("OneToOne")) {
|
||||
private static String why(
|
||||
JavaClass ownType,
|
||||
JavaMember ownMember,
|
||||
Association own,
|
||||
JavaClass backType,
|
||||
JavaMember backMember,
|
||||
Association back) {
|
||||
if (!own.toMany() && !back.toMany()) {
|
||||
return "each holds a foreign key to the other, so the two tables reference each other: neither"
|
||||
+ " row can be inserted or deleted first, and one key has to be nullable and written by a"
|
||||
+ " second UPDATE.";
|
||||
}
|
||||
Storage ownStorage = Storage.of(ownType, ownMember, own);
|
||||
Storage backStorage = Storage.of(backType, backMember, back);
|
||||
if (ownStorage.sameColumnAs(backStorage)) {
|
||||
return "two fields map one link, and the read-only one does not follow a change made through"
|
||||
+ " the other.";
|
||||
}
|
||||
return "each holds a foreign key to the other, so the two tables reference each other: neither"
|
||||
+ " row can be inserted or deleted first, and one key has to be nullable and written by a"
|
||||
+ " second UPDATE.";
|
||||
return "the link is stored twice — in "
|
||||
+ ownStorage.where()
|
||||
+ " and in "
|
||||
+ backStorage.where()
|
||||
+ " — and each copy is written on its own, so the two drift apart.";
|
||||
}
|
||||
|
||||
/** The annotation the other half of a pair carries. */
|
||||
@@ -154,9 +181,48 @@ public final class SingleSidedAssociationCondition extends ArchCondition<JavaCla
|
||||
return owner.getSimpleName() + "." + member.getName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Where one half keeps the link: a foreign-key column ({@code column} is its name, empty when the
|
||||
* mapping leaves it to the default) or a join table.
|
||||
*
|
||||
* @param where how the message names it
|
||||
*/
|
||||
private record Storage(boolean joinTable, String column, String where) {
|
||||
|
||||
static Storage of(JavaClass owner, JavaMember member, Association association) {
|
||||
Optional<String> joinColumn =
|
||||
member
|
||||
.tryGetAnnotationOfType(JoinColumn.class.getName())
|
||||
.map(annotation -> String.valueOf(annotation.get("name").orElse("")));
|
||||
boolean joinTable =
|
||||
association.annotation().equals("ManyToMany")
|
||||
|| member.isAnnotatedWith(JoinTable.class)
|
||||
|| (association.annotation().equals("OneToMany") && joinColumn.isEmpty());
|
||||
if (joinTable) {
|
||||
return new Storage(true, "", name(owner, member) + "'s join table");
|
||||
}
|
||||
String column = joinColumn.orElse("");
|
||||
return new Storage(
|
||||
false,
|
||||
column,
|
||||
column.isEmpty() ? name(owner, member) + "'s foreign-key column" : "column " + column);
|
||||
}
|
||||
|
||||
/** Whether both halves name, or may default to, one foreign-key column. */
|
||||
boolean sameColumnAs(Storage other) {
|
||||
return !joinTable
|
||||
&& !other.joinTable
|
||||
&& (column.isEmpty() || other.column.isEmpty() || column.equalsIgnoreCase(other.column));
|
||||
}
|
||||
}
|
||||
|
||||
/** One association member: its annotation, its {@code mappedBy}, and the entity it points at. */
|
||||
private record Association(String annotation, String mappedBy, JavaClass target) {
|
||||
|
||||
boolean toMany() {
|
||||
return annotation.equals("OneToMany") || annotation.equals("ManyToMany");
|
||||
}
|
||||
|
||||
static Optional<Association> of(JavaMember member) {
|
||||
for (Class<? extends Annotation> type : ASSOCIATIONS) {
|
||||
if (!member.isAnnotatedWith(type)) {
|
||||
|
||||
+129
-18
@@ -1,11 +1,16 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.testkit.migration;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.NavigableMap;
|
||||
import java.util.Objects;
|
||||
import java.util.TreeMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -22,21 +27,44 @@ import java.util.regex.Pattern;
|
||||
* version before it — a failed deploy, not an outage. {@code LOCAL}, because a plain {@code SET}
|
||||
* outlives the migration on the pooled connection Flyway borrowed.
|
||||
*
|
||||
* <p>What counts as waiting for a lock: {@code ALTER TABLE}, {@code CREATE [UNIQUE] INDEX} and
|
||||
* {@code DROP INDEX} without {@code CONCURRENTLY}, {@code LOCK TABLE}, {@code TRUNCATE}, {@code
|
||||
* DROP TABLE}, and {@code UPDATE}/{@code DELETE} (they wait on the rows other transactions hold). A
|
||||
* statement on a table this same migration created earlier waits for nothing and is left out.
|
||||
* Comments and quoted literals are not read as statements. The check reads text, not a parse tree:
|
||||
* it is a guard against the forgotten line, not a proof.
|
||||
* <p>The statements it looks for, each on the table named in it:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code ALTER TABLE}, {@code LOCK TABLE}, {@code TRUNCATE}, {@code DROP TABLE};
|
||||
* <li>{@code CREATE [UNIQUE] INDEX}, {@code DROP INDEX} and {@code REINDEX} without {@code
|
||||
* CONCURRENTLY}, {@code REFRESH MATERIALIZED VIEW} without it, {@code CLUSTER}, {@code VACUUM
|
||||
* FULL};
|
||||
* <li>{@code REFERENCES} — in a new table as much as in an {@code ALTER TABLE} — on the table it
|
||||
* references: a foreign key locks its parent against writes while it is added;
|
||||
* <li>{@code CREATE TRIGGER} and {@code DROP TRIGGER} on the table the trigger is on;
|
||||
* <li>{@code UPDATE} and {@code DELETE}, which wait on the rows other transactions hold.
|
||||
* </ul>
|
||||
*
|
||||
* <p>A statement on a table this same migration created earlier waits for nothing and is left out;
|
||||
* {@code CREATE TABLE IF NOT EXISTS} does not count as creating it, because the table may already
|
||||
* be there. The bound in force at a statement is the last {@code lock_timeout} setting before it,
|
||||
* and it counts only as {@code SET LOCAL} with a value that is not zero: {@code 0}, {@code DEFAULT}
|
||||
* and {@code RESET} wait without end, a plain {@code SET} outlives the migration. A migration
|
||||
* Flyway runs outside a transaction ({@code executeInTransaction=false} in its {@code .sql.conf},
|
||||
* read by {@link #unboundedLockingStatements(Path)}) has no bound at all: {@code SET LOCAL} there
|
||||
* only warns. Comments and quoted literals are not read as statements. The check reads text, not a
|
||||
* parse tree: it is a guard against the forgotten line for the statements above, not a proof that
|
||||
* no other statement waits (re-review 2026-11-03 round 3, RR3-02-01).
|
||||
*/
|
||||
public final class LockWaitMigrationInspector {
|
||||
|
||||
private static final String NAME =
|
||||
"((?:\"[^\"]+\"|[a-z_][a-z0-9_$]*)(?:\\.(?:\"[^\"]+\"|[a-z_][a-z0-9_$]*))?)";
|
||||
private static final String IDENTIFIER = "(?:\"[^\"]+\"|[a-z_][a-z0-9_$]*)";
|
||||
|
||||
/** A possibly qualified name the pattern does not capture: a trigger's own name. */
|
||||
private static final String OTHER_NAME = IDENTIFIER + "(?:\\." + IDENTIFIER + ")?";
|
||||
|
||||
/** A possibly qualified name, captured as group 1: the table the statement locks. */
|
||||
private static final String NAME = "(" + OTHER_NAME + ")";
|
||||
|
||||
private static final Pattern CREATED_TABLE =
|
||||
Pattern.compile(
|
||||
"\\bcreate\\s+(?:(?:temp|temporary|unlogged)\\s+)?table\\s+(?:if\\s+not\\s+exists\\s+)?"
|
||||
"\\bcreate\\s+(?:(?:temp|temporary|unlogged)\\s+)?(?:table|materialized\\s+view)\\s+"
|
||||
+ "(?!if\\s+not\\s+exists\\b)"
|
||||
+ NAME);
|
||||
|
||||
/** Each pattern's group 1, when it has one, is the table the statement locks. */
|
||||
@@ -48,6 +76,28 @@ public final class LockWaitMigrationInspector {
|
||||
+ "(?:[a-z0-9_$\"]+\\s+)??on\\s+(?:only\\s+)?"
|
||||
+ NAME),
|
||||
Pattern.compile("\\bdrop\\s+index\\s+(?!concurrently\\b)"),
|
||||
Pattern.compile(
|
||||
"\\breindex\\s+(?:\\([^)]*\\)\\s+)?(?:(?:index|table)\\s+(?!concurrently\\b)"
|
||||
+ NAME
|
||||
+ "|(?:schema|database|system)\\b(?!\\s+concurrently\\b))"),
|
||||
Pattern.compile("\\brefresh\\s+materialized\\s+view\\s+(?!concurrently\\b)" + NAME),
|
||||
Pattern.compile(
|
||||
"(?<!without )\\bcluster(?:\\s+verbose)?(?:\\s+(?!using\\b|on\\b)"
|
||||
+ NAME
|
||||
+ ")?(?=\\s*(?:;|$|using\\b))"),
|
||||
Pattern.compile(
|
||||
"\\bvacuum\\s+(?:\\([^)]*\\bfull\\b[^)]*\\)|full\\b)"
|
||||
+ "(?:\\s+(?:freeze|verbose|analyze)\\b)*(?:\\s+"
|
||||
+ NAME
|
||||
+ ")?"),
|
||||
Pattern.compile("\\breferences\\s+" + NAME),
|
||||
Pattern.compile(
|
||||
"\\bcreate\\s+(?:or\\s+replace\\s+)?(?:constraint\\s+)?trigger\\s+"
|
||||
+ OTHER_NAME
|
||||
+ "\\s+(?:before|after|instead\\s+of)\\s+[^;]*?\\bon\\s+(?:only\\s+)?"
|
||||
+ NAME),
|
||||
Pattern.compile(
|
||||
"\\bdrop\\s+trigger\\s+(?:if\\s+exists\\s+)?" + OTHER_NAME + "\\s+on\\s+" + NAME),
|
||||
Pattern.compile("\\block\\s+(?:table\\s+)?(?:only\\s+)?" + NAME),
|
||||
Pattern.compile("\\btruncate\\s+(?:table\\s+)?(?:only\\s+)?" + NAME),
|
||||
Pattern.compile("\\bdrop\\s+table\\s+(?:if\\s+exists\\s+)?" + NAME),
|
||||
@@ -55,7 +105,22 @@ public final class LockWaitMigrationInspector {
|
||||
Pattern.compile(
|
||||
"\\bupdate\\s+(?:only\\s+)?" + NAME + "(?:\\s+(?:as\\s+)?[a-z_]\\w*)?\\s+set\\b"));
|
||||
|
||||
private static final Pattern BOUND = Pattern.compile("\\bset\\s+local\\s+lock_timeout\\b");
|
||||
/**
|
||||
* A {@code lock_timeout} setting: group 1 is {@code local} for {@code SET LOCAL}, group 2 the
|
||||
* value. {@code RESET lock_timeout} matches with neither.
|
||||
*/
|
||||
private static final Pattern LOCK_TIMEOUT_SETTING =
|
||||
Pattern.compile(
|
||||
"\\bset\\s+(?:(local)\\s+|session\\s+)?lock_timeout(?:\\s*=\\s*|\\s+to\\s+)"
|
||||
+ "('[^']*'|[^\\s;]+)|\\breset\\s+lock_timeout\\b");
|
||||
|
||||
/** A literal kept as written so a setting's value can be read: a number and an optional unit. */
|
||||
private static final Pattern DURATION =
|
||||
Pattern.compile("[0-9.]+\\s*[a-z]*", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
/** The line in a migration's {@code .sql.conf} that makes Flyway run it outside a transaction. */
|
||||
private static final Pattern OUTSIDE_A_TRANSACTION =
|
||||
Pattern.compile("(?m)^\\s*executeInTransaction\\s*=\\s*false\\s*$");
|
||||
|
||||
/**
|
||||
* Fails when the migration locks a table it did not create before it bounds the wait.
|
||||
@@ -78,10 +143,27 @@ public final class LockWaitMigrationInspector {
|
||||
}
|
||||
|
||||
/**
|
||||
* The statements that wait for a lock on an existing table before any {@code SET LOCAL
|
||||
* lock_timeout}, each as its leading words and table; empty when there are none.
|
||||
* The statements that wait for a lock on an existing table without a {@code SET LOCAL
|
||||
* lock_timeout} in force, each as its leading words and table; empty when there are none. The
|
||||
* script is taken to run in a transaction, as Flyway runs a migration by default.
|
||||
*/
|
||||
public List<String> unboundedLockingStatements(String sql) {
|
||||
return unboundedLockingStatements(sql, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* The same, for a migration file on disk: a {@code <script>.conf} beside it that sets {@code
|
||||
* executeInTransaction=false} makes every statement found unbounded, each named with the reason.
|
||||
*/
|
||||
public List<String> unboundedLockingStatements(Path script) throws IOException {
|
||||
Path configuration = script.resolveSibling(script.getFileName() + ".conf");
|
||||
boolean inTransaction =
|
||||
!Files.exists(configuration)
|
||||
|| !OUTSIDE_A_TRANSACTION.matcher(Files.readString(configuration)).find();
|
||||
return unboundedLockingStatements(Files.readString(script), inTransaction);
|
||||
}
|
||||
|
||||
private List<String> unboundedLockingStatements(String sql, boolean inTransaction) {
|
||||
if (sql == null) {
|
||||
return List.of();
|
||||
}
|
||||
@@ -91,14 +173,23 @@ public final class LockWaitMigrationInspector {
|
||||
while (created.find()) {
|
||||
createdAt.putIfAbsent(table(created.group(1)), created.start());
|
||||
}
|
||||
Matcher bound = BOUND.matcher(text);
|
||||
int boundAt = bound.find() ? bound.start() : Integer.MAX_VALUE;
|
||||
NavigableMap<Integer, Boolean> bounds = inTransaction ? bounds(text) : new TreeMap<>();
|
||||
List<Located> found = new ArrayList<>();
|
||||
for (Pattern pattern : LOCKING) {
|
||||
Matcher statement = pattern.matcher(text);
|
||||
while (statement.find()) {
|
||||
if (statement.start() < boundAt && !createdEarlier(statement, createdAt)) {
|
||||
found.add(new Located(statement.start(), statement.group().trim()));
|
||||
Map.Entry<Integer, Boolean> setting = bounds.lowerEntry(statement.start());
|
||||
boolean bounded = setting != null && setting.getValue();
|
||||
if (!bounded && !createdEarlier(statement, createdAt)) {
|
||||
String named = statement.group().trim();
|
||||
found.add(
|
||||
new Located(
|
||||
statement.start(),
|
||||
inTransaction
|
||||
? named
|
||||
: named
|
||||
+ " (executeInTransaction=false: SET LOCAL does nothing outside a"
|
||||
+ " transaction; move it to a migration that runs in one)"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -108,6 +199,18 @@ public final class LockWaitMigrationInspector {
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** Each {@code lock_timeout} setting by position: whether it bounds the statements after it. */
|
||||
private static NavigableMap<Integer, Boolean> bounds(String text) {
|
||||
NavigableMap<Integer, Boolean> bounds = new TreeMap<>();
|
||||
Matcher setting = LOCK_TIMEOUT_SETTING.matcher(text);
|
||||
while (setting.find()) {
|
||||
boolean local = setting.group(1) != null;
|
||||
String value = setting.group(2) == null ? "" : setting.group(2);
|
||||
bounds.put(setting.start(), local && value.matches(".*[1-9].*"));
|
||||
}
|
||||
return bounds;
|
||||
}
|
||||
|
||||
private static boolean createdEarlier(Matcher statement, Map<String, Integer> createdAt) {
|
||||
if (statement.groupCount() < 1 || statement.group(1) == null) {
|
||||
return false;
|
||||
@@ -124,7 +227,9 @@ public final class LockWaitMigrationInspector {
|
||||
|
||||
/**
|
||||
* Blanks out comments and single-quoted literals, keeping every other character in place, so a
|
||||
* word in a {@code COMMENT ON ... IS '...'} or a {@code -- } line is not read as a statement.
|
||||
* word in a {@code COMMENT ON ... IS '...'} or a {@code -- } line is not read as a statement. A
|
||||
* literal that is a number with an optional unit ({@code '5s'}) is kept: it holds no statement,
|
||||
* and the {@code lock_timeout} value is read from it.
|
||||
*/
|
||||
private static String withoutCommentsAndLiterals(String sql) {
|
||||
StringBuilder kept = new StringBuilder(sql.length());
|
||||
@@ -140,6 +245,7 @@ public final class LockWaitMigrationInspector {
|
||||
i = end < 0 ? sql.length() : end + 2;
|
||||
kept.append(' ');
|
||||
} else if (c == '\'') {
|
||||
int start = i;
|
||||
i++;
|
||||
while (i < sql.length()) {
|
||||
if (sql.charAt(i) == '\'' && i + 1 < sql.length() && sql.charAt(i + 1) == '\'') {
|
||||
@@ -151,7 +257,12 @@ public final class LockWaitMigrationInspector {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
kept.append("''");
|
||||
String literal = sql.substring(start, i);
|
||||
boolean duration =
|
||||
literal.length() >= 2
|
||||
&& literal.endsWith("'")
|
||||
&& DURATION.matcher(literal.substring(1, literal.length() - 1)).matches();
|
||||
kept.append(duration ? literal : "''");
|
||||
} else {
|
||||
kept.append(c);
|
||||
i++;
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.testkit.migration;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import java.util.SortedMap;
|
||||
import java.util.TreeMap;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* The versioned migrations of one tree, found the way Flyway finds them: {@code V}, a version whose
|
||||
* parts are separated by {@code _} or {@code .} ({@code V22}, {@code V22_1}, {@code V22.1}), two
|
||||
* underscores, a description, {@code .sql}. Repeatable ({@code R__}) and undo ({@code U}) scripts
|
||||
* and {@code .sql.conf} files are not versioned migrations.
|
||||
*
|
||||
* <p>One definition for every check that walks a tree — the operating trees' lock-wait and checksum
|
||||
* checks and the sample stream's. Two copies had drifted: the operating trees' skipped {@code
|
||||
* V22_1__} while the sample's counted it, so a decimal version in an operating tree was neither
|
||||
* pinned nor held to the lock-wait rule (re-review 2026-11-03 round 3, RR3-02-03).
|
||||
*/
|
||||
public final class VersionedMigrationFiles {
|
||||
|
||||
private static final Pattern VERSIONED = Pattern.compile("V\\d+(?:[._]\\d+)*__.+\\.sql");
|
||||
|
||||
private VersionedMigrationFiles() {}
|
||||
|
||||
/**
|
||||
* Every versioned migration below {@code root}, keyed by its path relative to {@code root} with
|
||||
* {@code /} separators ({@code postgresql/V22__...sql}).
|
||||
*/
|
||||
public static SortedMap<String, Path> under(Path root) throws IOException {
|
||||
Objects.requireNonNull(root, "root");
|
||||
SortedMap<String, Path> migrations = new TreeMap<>();
|
||||
try (Stream<Path> files = Files.walk(root)) {
|
||||
for (Path file : files.filter(VersionedMigrationFiles::isVersioned).toList()) {
|
||||
migrations.put(root.relativize(file).toString().replace('\\', '/'), file);
|
||||
}
|
||||
}
|
||||
return migrations;
|
||||
}
|
||||
|
||||
private static boolean isVersioned(Path file) {
|
||||
return VERSIONED.matcher(file.getFileName().toString()).matches();
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -371,7 +371,14 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
|
||||
mine = operationId.equals(field(rendered, "op")) ? "MINE" : "OPERATION_CONFLICT";
|
||||
}
|
||||
String stored = field(rendered, "resp");
|
||||
return reply(state, attempt, rev, owner, stored == null ? "" : stored, mine + "|60000");
|
||||
String leaseUntil = field(rendered, "leaseUntil");
|
||||
return reply(
|
||||
state,
|
||||
attempt,
|
||||
rev,
|
||||
owner,
|
||||
stored == null ? "" : stored,
|
||||
mine + "|60000|" + (leaseUntil == null ? "" : leaseUntil));
|
||||
}
|
||||
|
||||
private static List<Object> reply(
|
||||
|
||||
@@ -38,9 +38,20 @@ service contributes them to the runtime as beans, one per lane it uses, through
|
||||
@Bean RedisAccountContribution redisAdminAccount() {
|
||||
return RedisSdkComposition.adminAccount("secret://ca-skeleton-admin-readonly@environment/APP_REDIS_ADMIN");
|
||||
}
|
||||
// The admin reference is code, not an environment value, so the prod secret guard only sees the
|
||||
// variable it names when the composer names it too (adapter:outbound:support).
|
||||
@Bean static RequiredProductionSecrets redisAdminSecret() {
|
||||
return environment -> List.of("APP_REDIS_ADMIN");
|
||||
}
|
||||
```
|
||||
|
||||
— and builds `LettuceRedisCommandGateway.over(lease.driver())` over a borrowed lease. The service's
|
||||
— and builds `LettuceRedisCommandGateway.over(lease.driver())` over a borrowed lease. The last bean
|
||||
matters only with an admin account: under `prod`, `SecretSourceValidator` refuses a secret that holds
|
||||
a lane fixture password (`fixture-admin` is in `infra/redis-sdk/acl`), but it learns which variables
|
||||
are secrets from the registry, from `secret://` references in the environment and from
|
||||
`RequiredProductionSecrets` beans — not from a reference held in code. Without the bean the admin
|
||||
account could run in production on the public lane password (review 2026-11-04 RR3-04-03). The SDK
|
||||
cannot contribute it itself: it depends on `redis-runtime` and `shared-contract` only. The service's
|
||||
adapter composes the SDK objects it uses on top of that; `LiveRedisOperationsFixture` in this leaf's
|
||||
tests is a complete worked composition (catalog, permit verifier, guard, executor, operations).
|
||||
|
||||
|
||||
+13
-1
@@ -17,10 +17,22 @@ import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisAccou
|
||||
* @Bean RedisLaneContribution redisTransactionLane() { return RedisSdkComposition.transactionLane(16); }
|
||||
* @Bean RedisLaneContribution redisAdminLane() { return RedisSdkComposition.adminLane(); }
|
||||
* @Bean RedisAccountContribution redisAdminAccount() {
|
||||
* return RedisSdkComposition.adminAccount("secret://ca-skeleton-admin@environment/APP_REDIS_ADMIN");
|
||||
* return RedisSdkComposition.adminAccount(
|
||||
* "secret://ca-skeleton-admin-readonly@environment/APP_REDIS_ADMIN");
|
||||
* }
|
||||
* @Bean static RequiredProductionSecrets redisAdminSecret() {
|
||||
* return environment -> List.of("APP_REDIS_ADMIN");
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* <p>The last bean names the admin account's variable to the {@code prod} secret guard, which
|
||||
* refuses a secret holding a lane fixture password. The guard finds secrets in the registry, in
|
||||
* {@code secret://} references among the environment's values, and in {@code
|
||||
* RequiredProductionSecrets} beans; a reference held in code is none of those, so without it the
|
||||
* admin account could run in production on the public {@code fixture-admin} password (review
|
||||
* 2026-11-04 RR3-04-03). The SDK cannot declare it: it does not depend on {@code
|
||||
* adapter:outbound:support}.
|
||||
*
|
||||
* <p>Like the SDK's other knobs (operation limits, enabled policies, raw approvals) these are code,
|
||||
* not {@code app.redis.*} settings: the runtime's settings describe the runtime, and a lane nobody
|
||||
* composed has no setting to be wrong about. An admin lane without an admin account runs on the
|
||||
|
||||
+5
@@ -10,6 +10,11 @@ import org.springframework.core.env.Environment;
|
||||
* secret-source guard, which checks each named secret resolves under the {@code prod} profile. The
|
||||
* guard does not know which roles a module has or which secret each one needs; before this it
|
||||
* spelled out every Redis role's selector and secret prefix itself.
|
||||
*
|
||||
* <p>Declare it with a {@code static} {@code @Bean} method without parameters. The guard reads it
|
||||
* before any bean post-processor exists, so {@link StartupRuleRunner} creates every one in every
|
||||
* profile before any rule runs, and fails the boot when one pulls another bean forward or its
|
||||
* runtime class needs a post-processor — not only on the first {@code prod} boot.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface RequiredProductionSecrets {
|
||||
|
||||
+21
-8
@@ -60,8 +60,11 @@ import org.springframework.util.ReflectionUtils;
|
||||
* binding on the class or its {@code @Bean} method. Each of those stays unset or uncalled for the
|
||||
* whole run, silently: a rule then reads {@code null} and its check is off, and a settings class
|
||||
* that doubles as a secret list keeps its defaults in {@code prod}, where the secret guard reads it
|
||||
* early, and only there (review 2026-11-04 RR2-04-03). The runner refuses such a bean by name
|
||||
* before any rule runs, in every profile, and again by its runtime class when it is created.
|
||||
* early, and only there (review 2026-11-04 RR2-04-03). The runner refuses such a bean before any
|
||||
* rule runs, in every profile: first by the type its definition declares, then by its runtime
|
||||
* class, because it creates every rule and every secret list then — the declared type of a {@code
|
||||
* static} method that returns an interface hides the class behind it (RR3-04-01). A secret list
|
||||
* that pulls another bean forward fails the same way in every profile, not only in {@code prod}.
|
||||
*
|
||||
* <p>Checked by what the bean needs rather than by how it is declared. Requiring a {@code static}
|
||||
* factory method was the other way, and it checks the wrong thing: it refuses a rule registered
|
||||
@@ -109,6 +112,16 @@ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordere
|
||||
refuseUnprocessedMembers(beanFactory, name, beanFactory.getType(name, false));
|
||||
}
|
||||
}
|
||||
// The declared type of a @Bean method can hide the class it returns (an interface-typed static
|
||||
// method returning a class with an @Value field), and only creating the bean shows it. Rules
|
||||
// are created below in every profile; secret lists are created here, so their runtime class is
|
||||
// checked in every profile too, not only when prod's secret guard reads them (RR3-04-01).
|
||||
for (String name :
|
||||
beanFactory.getBeanNamesForType(RequiredProductionSecrets.class, true, false)) {
|
||||
Set<String> before = singletons(beanFactory);
|
||||
beanFactory.getBean(name, RequiredProductionSecrets.class);
|
||||
refusePulledForward(beanFactory, name, "creating it", before);
|
||||
}
|
||||
IdentityHashMap<StartupRule, String> names = new IdentityHashMap<>();
|
||||
List<StartupRule> rules = new ArrayList<>();
|
||||
for (String name : beanFactory.getBeanNamesForType(StartupRule.class, true, false)) {
|
||||
@@ -139,11 +152,11 @@ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordere
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails when creating or running the rule {@code ruleName} brought a singleton into existence
|
||||
* other than a rule or a {@link RequiredProductionSecrets}: that bean was built before the bean
|
||||
* post-processors, so its settings are unbound and it is not proxied, for the rest of the run. A
|
||||
* rule or secret list it created is held to {@link #refuseUnprocessedMembers} by its runtime
|
||||
* class, which a {@code @Bean} method's declared return type may hide.
|
||||
* Fails when creating or running the rule or secret list {@code ruleName} brought a singleton
|
||||
* into existence other than a rule or a {@link RequiredProductionSecrets}: that bean was built
|
||||
* before the bean post-processors, so its settings are unbound and it is not proxied, for the
|
||||
* rest of the run. A rule or secret list it created is held to {@link #refuseUnprocessedMembers}
|
||||
* by its runtime class, which a {@code @Bean} method's declared return type may hide.
|
||||
*/
|
||||
private static void refusePulledForward(
|
||||
ConfigurableListableBeanFactory beanFactory,
|
||||
@@ -170,7 +183,7 @@ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordere
|
||||
// A configuration error of the composition, so the configuration exit code (78): no
|
||||
// environment fixes it, but neither does a retry, and it must not look like a crash.
|
||||
throw StartupFailures.envValidation(
|
||||
"startup rule '"
|
||||
"startup rule or secret list '"
|
||||
+ ruleName
|
||||
+ "' created "
|
||||
+ pulled
|
||||
|
||||
+65
-2
@@ -133,8 +133,11 @@ class StartupRuleRunnerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("규칙이 실행 중에 꺼내는 RequiredProductionSecrets가 다른 bean을 앞당기면 기동이 실패한다")
|
||||
@DisplayName("규칙이 읽는 RequiredProductionSecrets가 다른 bean을 앞당기면 규칙이 돌기 전에 기동이 실패한다")
|
||||
void aProductionSecretsBeanThatPullsItsConfigurationForwardFailsTheBoot() {
|
||||
// given
|
||||
SecretReadingRuleConfig.SEEN.clear();
|
||||
|
||||
// when
|
||||
runner
|
||||
.withUserConfiguration(SecretReadingRuleConfig.class, NonStaticSecretsConfig.class)
|
||||
@@ -143,8 +146,9 @@ class StartupRuleRunnerTest {
|
||||
// then
|
||||
assertThat(context.getStartupFailure())
|
||||
.isInstanceOf(StartupFailureException.class)
|
||||
.hasMessageContaining("secretReadingRule")
|
||||
.hasMessageContaining("probeSecrets")
|
||||
.hasMessageContaining("NonStaticSecretsConfig");
|
||||
assertThat(SecretReadingRuleConfig.SEEN).isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -240,6 +244,43 @@ class StartupRuleRunnerTest {
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("인터페이스 타입 static @Bean이 돌려준 비밀 목록의 @Value 필드는 그것을 읽는 규칙이 없는 프로필에서도 기동을 실패시킨다")
|
||||
void aSecretsListHiddenBehindAnInterfaceTypedBeanFailsTheBootWithoutAReadingRule() {
|
||||
// given
|
||||
ValueFieldSecrets.SEEN.clear();
|
||||
|
||||
// when
|
||||
runner
|
||||
.withPropertyValues("probe4.secret=bound")
|
||||
.withUserConfiguration(InterfaceTypedSecretsConfig.class)
|
||||
.run(
|
||||
context -> {
|
||||
// then
|
||||
assertThat(context.getStartupFailure())
|
||||
.isInstanceOf(StartupFailureException.class)
|
||||
.hasMessageContaining("hiddenSecrets")
|
||||
.hasMessageContaining("secret (@Value)");
|
||||
assertThat(ValueFieldSecrets.SEEN).isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("다른 bean을 앞당기는 RequiredProductionSecrets는 그것을 읽는 규칙이 없는 프로필에서도 기동을 실패시킨다")
|
||||
void aProductionSecretsBeanThatPullsItsConfigurationForwardFailsTheBootWithoutAReadingRule() {
|
||||
// when
|
||||
runner
|
||||
.withUserConfiguration(NonStaticSecretsConfig.class)
|
||||
.run(
|
||||
context -> {
|
||||
// then
|
||||
assertThat(context.getStartupFailure())
|
||||
.isInstanceOf(StartupFailureException.class)
|
||||
.hasMessageContaining("probeSecrets")
|
||||
.hasMessageContaining("NonStaticSecretsConfig");
|
||||
});
|
||||
}
|
||||
|
||||
private static StartupRule rule(StartupPhase phase, String summary, List<String> violations) {
|
||||
return new StartupRule() {
|
||||
@Override
|
||||
@@ -395,6 +436,28 @@ class StartupRuleRunnerTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** RR3-04-01: a secret list whose @Value field the declared interface return type hides. */
|
||||
public static class ValueFieldSecrets implements RequiredProductionSecrets {
|
||||
static final List<String> SEEN = new ArrayList<>();
|
||||
|
||||
@Value("${probe4.secret}")
|
||||
private String secret;
|
||||
|
||||
@Override
|
||||
public List<String> requiredSecrets(Environment environment) {
|
||||
SEEN.add(secret);
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
static class InterfaceTypedSecretsConfig {
|
||||
@Bean
|
||||
static RequiredProductionSecrets hiddenSecrets() {
|
||||
return new ValueFieldSecrets();
|
||||
}
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
static class NonStaticSecretsConfig {
|
||||
@Bean
|
||||
|
||||
@@ -88,8 +88,9 @@ configurations, Redis as one 376-line class.
|
||||
- **An environment-only guard is a `StartupRule` bean** (`support.startup`): it returns violations,
|
||||
and the one `StartupRuleRunner` raises them before any other singleton exists (declare it with a
|
||||
`static` `@Bean` method that takes only the `Environment`, the bean factory or an `ObjectProvider`
|
||||
of static `RequiredProductionSecrets`; the runner fails the boot naming any other bean a rule
|
||||
creates, and naming any rule or `RequiredProductionSecrets` that has an `@Value`/`@Autowired`/
|
||||
of static `RequiredProductionSecrets`; in every profile the runner creates each rule and each
|
||||
`RequiredProductionSecrets` before any rule runs, and fails the boot naming any other bean one of
|
||||
them creates, and naming any whose runtime class has an `@Value`/`@Autowired`/
|
||||
`@Inject`/`@Resource` member, a `@PostConstruct`/`@PreDestroy` callback or a
|
||||
`@ConfigurationProperties` binding — those are created before the post-processors and would stay
|
||||
unset). A guard that needs another bean stays a bean. A
|
||||
|
||||
@@ -133,8 +133,10 @@ README의 "startup" 절에 있다.
|
||||
lane용으로 적어 둔 공개 비밀번호(`infra/redis-sdk/acl`의 Redis ACL fixture, compose lane의
|
||||
`REDIS_LANE_*`)라서, lane 환경이나 lane ACL 파일을 베낀 배포가 그대로 운영에 뜨는 것을 막는다
|
||||
(review 2026-11-03 RR-07-04). 이 검사는 비밀값만 본다 — 레지스트리의 `secret` 행
|
||||
(`CLASSIFIED_SECRETS`), 모듈이 기여한 비밀, `secret://…/<VAR>` 참조가 가리키는 변수
|
||||
(review 2026-11-04 RR2-04-01). `fixture-`는 평범한 단어라서 `fixture-api` Deployment의 pod 이름
|
||||
(`CLASSIFIED_SECRETS`), 모듈이 기여한 비밀, 환경 값에 든 `secret://…/<VAR>` 참조가 가리키는 변수
|
||||
(review 2026-11-04 RR2-04-01). 코드에 든 참조(Redis SDK admin 계정의 `RedisAccountContribution`)는 보지
|
||||
못하므로, 그 계정을 조립하는 쪽이 변수를 `RequiredProductionSecrets` bean으로도 낸다(RR3-04-03,
|
||||
`src/adapter/outbound/redis-sdk/README.md`). `fixture-`는 평범한 단어라서 `fixture-api` Deployment의 pod 이름
|
||||
(`HOSTNAME`)이나 앱 이름까지 거부하면 운영에서만 기동이 막혔다. `__LOCAL_DEV_` 표시는 정당한 값이 가질
|
||||
일이 없으니 모든 값을 본다. 실패 메시지는 변수 이름만 적고 값은 적지 않는다. (2) 레지스트리에서 `secret` +
|
||||
`prod_default: null`로 분류된 모든 키는 prod 에서 비어 있지 않게 주입돼야 한다 — 빈 시크릿으로
|
||||
|
||||
+59
-9
@@ -462,6 +462,10 @@ class ApplicationBoundaryArchitectureTest {
|
||||
* framework types an endpoint is built from. {@code org.springframework.messaging} is named only
|
||||
* for STOMP ({@code simp}, {@code @MessageMapping}): a broker listener's {@code @Payload} and
|
||||
* {@code @Header} live beside them and are a system consumer's, not a user's.
|
||||
*
|
||||
* <p>The framework half is a list, unlike the package allowlist above: a transport library
|
||||
* missing from it is not recognised as one. A service that brings in a new transport library adds
|
||||
* its packages here (review 2026-11-04 RR3-01-02).
|
||||
*/
|
||||
private static final DescribedPredicate<JavaClass> ARE_USER_TRANSPORT_TYPES =
|
||||
JavaClass.Predicates.resideInAnyPackage(
|
||||
@@ -474,14 +478,33 @@ class ApplicationBoundaryArchitectureTest {
|
||||
"org.springframework.messaging.simp..",
|
||||
"io.grpc..",
|
||||
"jakarta.servlet..",
|
||||
"jakarta.websocket..")
|
||||
"jakarta.websocket..",
|
||||
"jakarta.ws.rs..",
|
||||
"graphql..")
|
||||
.or(
|
||||
com.tngtech.archunit.core.domain.properties.HasName.Predicates.name(
|
||||
"org.springframework.stereotype.Controller"))
|
||||
.or(
|
||||
com.tngtech.archunit.core.domain.properties.HasName.Predicates.name(
|
||||
"org.springframework.messaging.handler.annotation.MessageMapping"))
|
||||
.as("user-transport types (web, GraphQL, gRPC, WebSocket/STOMP endpoints)");
|
||||
.as("user-transport types (web, JAX-RS, GraphQL, gRPC, WebSocket/STOMP endpoints)");
|
||||
|
||||
/**
|
||||
* A class a user request comes in through: it lives in a user-transport package or is built from
|
||||
* a user-transport type. A configuration that only registers a system caller is neither, which is
|
||||
* why the rule below names these rather than every inbound class.
|
||||
*/
|
||||
private static final DescribedPredicate<JavaClass> ARE_USER_TRANSPORTS =
|
||||
new DescribedPredicate<>(
|
||||
"are user transports (in a user-transport package or built from one)") {
|
||||
@Override
|
||||
public boolean test(JavaClass candidate) {
|
||||
return ARE_USER_TRANSPORT_TYPES.test(candidate)
|
||||
|| candidate.getDirectDependenciesFromSelf().stream()
|
||||
.anyMatch(
|
||||
dependency -> ARE_USER_TRANSPORT_TYPES.test(dependency.getTargetClass()));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A class marked {@link SystemCaller}, or nested in one: a handler's anonymous or inner helper
|
||||
@@ -533,13 +556,14 @@ class ApplicationBoundaryArchitectureTest {
|
||||
* {@link SystemCaller} is a claim, so it is checked: the marked class lives in a system-driven
|
||||
* inbound package and is no endpoint a user can call — a controller, a GraphQL or STOMP mapping,
|
||||
* a gRPC service. Without this the mark would be the next way to silence the rule above (review
|
||||
* 2026-11-03 RR-01-12).
|
||||
* 2026-11-03 RR-01-12). The claim covers the classes nested in the marked one, because the rule
|
||||
* above exempts exactly those: an endpoint nested in a job is checked as the job is (review
|
||||
* 2026-11-04 RR3-01-01).
|
||||
*/
|
||||
@ArchTest
|
||||
static final ArchRule SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS =
|
||||
classes()
|
||||
.that()
|
||||
.areAnnotatedWith(SystemCaller.class)
|
||||
.that(ARE_SYSTEM_CALLERS)
|
||||
.should()
|
||||
.resideInAnyPackage(SYSTEM_DRIVEN_INBOUND_PACKAGES)
|
||||
.andShould(
|
||||
@@ -547,10 +571,36 @@ class ApplicationBoundaryArchitectureTest {
|
||||
com.tngtech.archunit.lang.conditions.ArchConditions.dependOnClassesThat(
|
||||
ARE_USER_TRANSPORT_TYPES)))
|
||||
.as(
|
||||
"SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS: a @SystemCaller lives in a "
|
||||
+ "system-driven inbound package (..adapter.inbound.messaging.., "
|
||||
+ "..adapter.inbound.scheduler..) and depends on no user-transport type — the mark "
|
||||
+ "says no user request reaches the class, so a user transport cannot carry it")
|
||||
"SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS: a @SystemCaller, and every class "
|
||||
+ "nested in one, lives in a system-driven inbound package "
|
||||
+ "(..adapter.inbound.messaging.., ..adapter.inbound.scheduler..) and depends on "
|
||||
+ "no user-transport type — the mark says no user request reaches the class, so a "
|
||||
+ "user transport cannot carry it")
|
||||
.allowEmptyShould(true);
|
||||
|
||||
/**
|
||||
* The other way round: a user transport does not reach a {@link SystemCaller}, directly or
|
||||
* through classes in between. A "run now" endpoint handed the job bean never names the {@link
|
||||
* SystemInvoked} use case, so the rules above do not see it, yet a user request then runs a write
|
||||
* no permission guards (review 2026-11-04 RR3-01-01). The configuration that registers the
|
||||
* handler is no transport and may depend on it.
|
||||
*
|
||||
* <p>Like every rule here it reads class dependencies. A lookup at run time ({@code getBean},
|
||||
* {@code ObjectProvider}) is not a dependency and is not seen.
|
||||
*/
|
||||
@ArchTest
|
||||
static final ArchRule USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS =
|
||||
noClasses()
|
||||
.that(ARE_USER_TRANSPORTS)
|
||||
.should()
|
||||
.transitivelyDependOnClassesThat(ARE_SYSTEM_CALLERS)
|
||||
.as(
|
||||
"USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS: a class a user request comes in "
|
||||
+ "through (a user-transport package, or built from a web, JAX-RS, GraphQL, gRPC "
|
||||
+ "or WebSocket type) does not reach a @SystemCaller, directly or through other "
|
||||
+ "classes — the system caller runs a @SystemInvoked write with no permission "
|
||||
+ "check. A user-triggered run of the same work is its own use case with "
|
||||
+ "@RequiresPermission (manual 07 「시스템이 부르는 쓰기」)")
|
||||
.allowEmptyShould(true);
|
||||
|
||||
/**
|
||||
|
||||
+1
@@ -168,6 +168,7 @@ class ArchRuleDiscoveryContractTest {
|
||||
"SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION",
|
||||
"TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES",
|
||||
"THROWABLES_ARE_NAMED_EXCEPTION",
|
||||
"USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS",
|
||||
"USE_CASE_CAPABILITY_MATCHES_TRANSACTION_PORT_BOUNDARY",
|
||||
"USE_CASE_PORTS_CARRY_ONE_OPERATION",
|
||||
"VALIDATION_CONSTRAINTS_STAY_AT_WEB_BOUNDARY",
|
||||
|
||||
+91
@@ -7,11 +7,16 @@ import com.tngtech.archunit.core.importer.ClassFileImporter;
|
||||
import com.tngtech.archunit.lang.EvaluationResult;
|
||||
import dev.caskeleton.application.architecture.violations.ApplicationDiagnosticFrameworkViolation;
|
||||
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerRegistrationFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.allowed.application.CleanProjectionQueryPort;
|
||||
import dev.caskeleton.bootstrap.architecture.fixtures.application.RootWriteTransactionBoundaryUseCase;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.SystemCallerRestControllerFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.UnmarkedSystemInvokedHandlerFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.SystemCallerWithNestedEndpointFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.SystemJobLauncherFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerControllerFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerInvokingControllerFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerRelayingControllerFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemInvokedCallingControllerFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.outbound.RawExternalResponseFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.outbound.messaging.GenericTypeLeakingAdapterFixture;
|
||||
@@ -188,6 +193,47 @@ class ArchitectureViolationFixtureTest {
|
||||
private static final JavaClasses SYSTEM_CALLER_THAT_IS_AN_HTTP_ENDPOINT_FIXTURE_ONLY =
|
||||
new ClassFileImporter().importClasses(SystemCallerRestControllerFixture.class);
|
||||
|
||||
// Review 2026-11-04 RR3-01-01: a user transport that never names the use case but calls the
|
||||
// system caller holding it — directly, and through one unmarked class in between.
|
||||
private static final JavaClasses CONTROLLER_CALLING_A_SYSTEM_CALLER_FIXTURE_ONLY =
|
||||
new ClassFileImporter()
|
||||
.importClasses(
|
||||
SystemCallerInvokingControllerFixture.class,
|
||||
SystemCallerHandlerFixture.class,
|
||||
SystemInvokedFixtureUseCase.class);
|
||||
|
||||
private static final JavaClasses CONTROLLER_RELAYING_TO_A_SYSTEM_CALLER_FIXTURE_ONLY =
|
||||
new ClassFileImporter()
|
||||
.importClasses(
|
||||
SystemCallerRelayingControllerFixture.class,
|
||||
SystemJobLauncherFixture.class,
|
||||
SystemCallerHandlerFixture.class,
|
||||
SystemInvokedFixtureUseCase.class);
|
||||
|
||||
// The configuration that registers the handler: it depends on a system caller and is no
|
||||
// transport, so the rule above must leave it alone.
|
||||
private static final JavaClasses SYSTEM_CALLER_REGISTRATION_FIXTURE_ONLY =
|
||||
new ClassFileImporter()
|
||||
.importClasses(
|
||||
SystemCallerHandlerRegistrationFixture.class,
|
||||
SystemCallerHandlerFixture.class,
|
||||
SystemInvokedFixtureUseCase.class);
|
||||
|
||||
// An endpoint nested in a marked job: the mark exempts nested classes, so they carry its claim.
|
||||
private static final JavaClasses ENDPOINT_NESTED_IN_A_SYSTEM_CALLER_FIXTURE_ONLY =
|
||||
new ClassFileImporter()
|
||||
.importClasses(
|
||||
SystemCallerWithNestedEndpointFixture.class,
|
||||
SystemCallerWithNestedEndpointFixture.RunNowEndpoint.class,
|
||||
SystemInvokedFixtureUseCase.class);
|
||||
|
||||
// RR3-01-02: a JAX-RS endpoint carrying the mark. importPackages, so the compile-only
|
||||
// jakarta.ws.rs types are read from bytecode and never linked.
|
||||
private static final JavaClasses JAXRS_SYSTEM_CALLER_FIXTURE_ONLY =
|
||||
new ClassFileImporter()
|
||||
.importPackages(
|
||||
"dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.jaxrs");
|
||||
|
||||
// Review 2026-11-03 RR-01-03: one class that builds the draft by hand.
|
||||
private static final JavaClasses HAND_BUILT_DRAFT_FIXTURE_ONLY =
|
||||
new ClassFileImporter().importClasses(HandBuiltIntegrationEventDraftFixture.class);
|
||||
@@ -246,6 +292,51 @@ class ArchitectureViolationFixtureTest {
|
||||
assertThat(result.hasViolation()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aControllerThatCallsASystemCallerBeanIsCaught() {
|
||||
EvaluationResult result =
|
||||
ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate(
|
||||
CONTROLLER_CALLING_A_SYSTEM_CALLER_FIXTURE_ONLY);
|
||||
|
||||
assertThat(result.hasViolation()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aControllerThatReachesASystemCallerThroughAnotherClassIsCaught() {
|
||||
EvaluationResult result =
|
||||
ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate(
|
||||
CONTROLLER_RELAYING_TO_A_SYSTEM_CALLER_FIXTURE_ONLY);
|
||||
|
||||
assertThat(result.hasViolation()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConfigurationThatRegistersASystemCallerMayDependOnIt() {
|
||||
EvaluationResult result =
|
||||
ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate(
|
||||
SYSTEM_CALLER_REGISTRATION_FIXTURE_ONLY);
|
||||
|
||||
assertThat(result.getFailureReport().getDetails()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEndpointNestedInASystemCallerIsCaught() {
|
||||
EvaluationResult result =
|
||||
ApplicationBoundaryArchitectureTest.SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS
|
||||
.evaluate(ENDPOINT_NESTED_IN_A_SYSTEM_CALLER_FIXTURE_ONLY);
|
||||
|
||||
assertThat(result.hasViolation()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aJaxRsEndpointMarkedAsASystemCallerIsCaught() {
|
||||
EvaluationResult result =
|
||||
ApplicationBoundaryArchitectureTest.SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS
|
||||
.evaluate(JAXRS_SYSTEM_CALLER_FIXTURE_ONLY);
|
||||
|
||||
assertThat(result.hasViolation()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFeatureThatBuildsAnIntegrationEventDraftByHandIsCaught() {
|
||||
EvaluationResult result =
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* The configuration that registers a system caller as a bean. It depends on the handler and is no
|
||||
* user transport, so {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS} must not flag it — that is
|
||||
* why the rule names user transports rather than every inbound class (review 2026-11-04 RR3-01-01).
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class SystemCallerHandlerRegistrationFixture {
|
||||
|
||||
@Bean
|
||||
SystemCallerHandlerFixture systemCallerHandler() {
|
||||
return new SystemCallerHandlerFixture();
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -4,6 +4,8 @@
|
||||
* {@code @SystemInvoked} use case it constructed itself. {@code
|
||||
* ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES} and {@code
|
||||
* SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS} must NOT flag it — it is the one legitimate
|
||||
* way a consumer reaches a system write (manual 09 「소비」 step 4).
|
||||
* way a consumer reaches a system write (manual 09 「소비」 step 4). The configuration that registers
|
||||
* that handler as a bean is here too: {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS} must not
|
||||
* flag it either (review 2026-11-04 RR3-01-01).
|
||||
*/
|
||||
package dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging;
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.jaxrs;
|
||||
|
||||
import dev.caskeleton.application.security.SystemCaller;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
|
||||
/**
|
||||
* Negative fixture for {@code SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS}: a JAX-RS endpoint
|
||||
* in a system-driven package carrying the mark. The transport-type half of the rule is a list, so a
|
||||
* transport missing from it passes (review 2026-11-04 RR3-01-02). Loaded with {@code
|
||||
* importPackages}: {@code jakarta.ws.rs-api} is compile-only here, so JUnit must never link it.
|
||||
*/
|
||||
@SystemCaller(reason = "fixture: a JAX-RS endpoint hiding in the messaging package")
|
||||
@Path("/fixture/jaxrs-system-write")
|
||||
public class JaxRsSystemCallerFixture {
|
||||
|
||||
private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase();
|
||||
|
||||
@POST
|
||||
public void trigger() {
|
||||
useCase.handle();
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler;
|
||||
|
||||
import dev.caskeleton.application.security.SystemCaller;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* Negative fixture for {@code SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS}: a scheduled job
|
||||
* that carries the mark, with an HTTP endpoint nested inside it. The mark exempts nested classes
|
||||
* from {@code ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES}, so the claim has to be checked
|
||||
* on them too (review 2026-11-04 RR3-01-01).
|
||||
*/
|
||||
@SystemCaller(reason = "fixture: the scheduler ticks it")
|
||||
public final class SystemCallerWithNestedEndpointFixture {
|
||||
|
||||
private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase();
|
||||
|
||||
public void run() {
|
||||
useCase.handle();
|
||||
}
|
||||
|
||||
/** A user transport living under the job's mark. */
|
||||
@RestController
|
||||
public static class RunNowEndpoint {
|
||||
|
||||
private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase();
|
||||
|
||||
@PostMapping("/fixture/nested-run-now")
|
||||
public void runNow() {
|
||||
useCase.handle();
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler;
|
||||
|
||||
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture;
|
||||
|
||||
/**
|
||||
* The class in between for {@code SystemCallerRelayingControllerFixture}: unmarked, no transport
|
||||
* type, and it calls the system caller it is given.
|
||||
*/
|
||||
public class SystemJobLauncherFixture {
|
||||
|
||||
private final SystemCallerHandlerFixture handler;
|
||||
|
||||
public SystemJobLauncherFixture(SystemCallerHandlerFixture handler) {
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
public void launch() {
|
||||
handler.handle();
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller;
|
||||
|
||||
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a "run now" endpoint
|
||||
* that is handed the system caller bean and calls it. It never names the {@code @SystemInvoked} use
|
||||
* case, so the rule on that dependency does not see it, yet a user request now runs a write no
|
||||
* permission guards (review 2026-11-04 RR3-01-01).
|
||||
*/
|
||||
@RestController
|
||||
public class SystemCallerInvokingControllerFixture {
|
||||
|
||||
private final SystemCallerHandlerFixture handler;
|
||||
|
||||
public SystemCallerInvokingControllerFixture(SystemCallerHandlerFixture handler) {
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
@PostMapping("/fixture/run-now")
|
||||
public void runNow() {
|
||||
handler.handle();
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller;
|
||||
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.SystemJobLauncherFixture;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: the same "run now"
|
||||
* endpoint with one more class in between. The launcher is neither a transport nor a system caller,
|
||||
* so only a rule that follows the chain sees that a user request still reaches the system write
|
||||
* (review 2026-11-04 RR3-01-01).
|
||||
*/
|
||||
@RestController
|
||||
public class SystemCallerRelayingControllerFixture {
|
||||
|
||||
private final SystemJobLauncherFixture launcher;
|
||||
|
||||
public SystemCallerRelayingControllerFixture(SystemJobLauncherFixture launcher) {
|
||||
this.launcher = launcher;
|
||||
}
|
||||
|
||||
@PostMapping("/fixture/run-now-via-launcher")
|
||||
public void runNow() {
|
||||
launcher.launch();
|
||||
}
|
||||
}
|
||||
+8
-3
@@ -163,9 +163,14 @@ public final class SecretSourceValidator implements StartupRule {
|
||||
|
||||
/**
|
||||
* Names every secret that holds a lane fixture password: the keys the registry classifies {@code
|
||||
* secret}, the ones a module contributed, and every variable a credential reference names. Read
|
||||
* through the same backend the application resolves them with. The value is never put in the
|
||||
* message.
|
||||
* secret}, the ones a module contributed, and every variable a credential reference among the
|
||||
* environment's values names. Read through the same backend the application resolves them with.
|
||||
* The value is never put in the message.
|
||||
*
|
||||
* <p>A reference held in code is not seen — the typed Redis SDK's admin account is a {@code
|
||||
* RedisAccountContribution} bean, which this rule cannot read without creating it early. Its
|
||||
* composer names the variable in a {@link RequiredProductionSecrets} bean as well (review
|
||||
* 2026-11-04 RR3-04-03, {@code RedisSdkComposition}).
|
||||
*/
|
||||
private static void collectFixturePasswordViolations(
|
||||
Environment environment,
|
||||
|
||||
@@ -202,12 +202,15 @@ subclass a final class (`RequiresPermissionProxyabilityTest`). It is registered
|
||||
same reason — a use case built with `new` is never checked. A use case only the system calls (a
|
||||
scheduler, a relay, a message consumer) carries `@SystemInvoked(reason = ...)` instead of a
|
||||
permission and is not a bean: it is a write with no permission check, so no user request may reach
|
||||
it. Its system caller constructs it — a composition module for a scheduler, or a
|
||||
`@SystemCaller(reason = ...)` message handler in `..adapter.inbound.messaging..` (manual 09
|
||||
「소비」 step 4). Both halves are enforced — a `@SystemInvoked` bean fails startup, and an inbound
|
||||
adapter that depends on one without being a `@SystemCaller` fails
|
||||
`ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES` (`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`
|
||||
keeps the mark off user transports). A composition with `@RequiresPermission`
|
||||
it. Its system caller constructs it — a composition module for a scheduler, a
|
||||
`@SystemCaller(reason = ...)` message handler in `..adapter.inbound.messaging..`, or a
|
||||
`@SystemCaller` scheduled job in the service's own `..adapter.inbound.scheduler..` package. Manual
|
||||
07 「시스템이 부르는 쓰기」 is the canonical list of the three and where each lives. All of it is
|
||||
enforced — a `@SystemInvoked` bean fails startup, an inbound adapter that depends on one without
|
||||
being a `@SystemCaller` fails `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`,
|
||||
`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS` keeps the mark (and classes nested in a marked
|
||||
one) off user transports, and `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS` keeps a user transport
|
||||
from calling a system caller. A composition with `@RequiresPermission`
|
||||
beans but no enforcing advisor fails startup too (`composition:service-runtime`
|
||||
`PermissionEnforcementGuard`, both checks).
|
||||
|
||||
@@ -268,8 +271,9 @@ generation; the V1 `IdempotencyScope`/`tryBegin` API is gone.
|
||||
could not prove the outcome, so do not blindly retry.
|
||||
- Every store answers an execution whose processing lease ran out with `RecoveryRequired` and never
|
||||
takes it over; only a claim that never started or a retryable failure is taken over. A record lives
|
||||
for the lease plus the replay TTL. `IdempotencyStoreContract` holds the fake, Redis and PostgreSQL
|
||||
to both on real servers (re-review 2026-11-04 RR-01-11, RR-03-11).
|
||||
for the lease plus the replay TTL. `IdempotencyStoreContract` holds Redis and PostgreSQL to both on
|
||||
real servers; the in-memory fake models no time, so it runs only the contract's time-free cases
|
||||
(re-review 2026-11-04 RR-01-11, RR-03-11, RR3-03-04).
|
||||
|
||||
The former ArchUnit freeze rule `inbound_port_implementations_do_not_declare_keyed_idempotency`
|
||||
and its fixture were removed when this branch merged.
|
||||
|
||||
@@ -458,7 +458,8 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장.
|
||||
`PermissionEnforcementGuard`가 기동을 실패시키고, `@SystemCaller`가 아닌 inbound adapter가 그 클래스에
|
||||
의존하면 `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`가 빌드를 실패시킨다(review 2026-11-03
|
||||
RR-01-02, RR-01-12). 메시지 소비자는 `@SystemCaller` handler가 use case를 직접 만든다(매뉴얼 09장
|
||||
「소비」 4단계).
|
||||
「소비」 4단계). 시스템 호출자 세 가지(조립 모듈의 스케줄러, `@SystemCaller` 메시지 handler,
|
||||
`@SystemCaller` 예약 작업)와 각각 두는 곳은 매뉴얼 07장 「시스템이 부르는 쓰기」가 정본이다.
|
||||
|
||||
### OutboxBackoffPolicy
|
||||
|
||||
|
||||
+44
-23
@@ -121,9 +121,9 @@ public final class IdempotencyExecutor {
|
||||
case IdempotencyClaimOutcome.InProgress ignored ->
|
||||
throw IdempotencyInFlightException.forScopeDigest(diagnostic(scope));
|
||||
case IdempotencyClaimOutcome.RecoveryRequired ignored ->
|
||||
throw recovery("claim requires reconciliation");
|
||||
throw recovery(scope, "claim requires reconciliation");
|
||||
case IdempotencyClaimOutcome.OwnerOperationConflict ignored ->
|
||||
throw recovery("claim requires reconciliation");
|
||||
throw recovery(scope, "claim requires reconciliation");
|
||||
case IdempotencyClaimOutcome.Unavailable ignored ->
|
||||
throw new IdempotencyUnavailableException();
|
||||
// The response was lost, not the attempt. The retained attempt is what makes the record
|
||||
@@ -148,9 +148,11 @@ public final class IdempotencyExecutor {
|
||||
IdempotencyInspection inspection = inspect(request);
|
||||
return switch (inspection.outcome()) {
|
||||
case CLAIMED_SAME_OPERATION ->
|
||||
startAndRun(request, requireOwner(inspection), action, codec, false);
|
||||
case EXECUTING_SAME_OPERATION -> runStarted(request, requireOwner(inspection), action, codec);
|
||||
case COMPLETED_REPLAY -> codec.deserialize(requireResponse(inspection).payload());
|
||||
startAndRun(request, requireOwner(request.scope(), inspection), action, codec, false);
|
||||
case EXECUTING_SAME_OPERATION ->
|
||||
runStarted(request, requireOwner(request.scope(), inspection), action, codec);
|
||||
case COMPLETED_REPLAY ->
|
||||
codec.deserialize(requireResponse(request.scope(), inspection).payload());
|
||||
case FINGERPRINT_MISMATCH ->
|
||||
throw IdempotencyRequestMismatchException.forScopeDigest(diagnostic(request.scope()));
|
||||
case IN_PROGRESS_OTHER ->
|
||||
@@ -159,7 +161,8 @@ public final class IdempotencyExecutor {
|
||||
// ABSENT, FAILED_RETRYABLE, ABANDONED and OPERATION_CONFLICT all mean the same thing here:
|
||||
// this caller cannot prove what happened to its own attempt, and guessing is the one thing an
|
||||
// owner-safe store exists to prevent.
|
||||
default -> throw recovery("an indeterminate claim could not be resumed safely");
|
||||
default ->
|
||||
throw recovery(request.scope(), "an indeterminate claim could not be resumed safely");
|
||||
};
|
||||
}
|
||||
|
||||
@@ -179,11 +182,14 @@ public final class IdempotencyExecutor {
|
||||
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
|
||||
case INDETERMINATE -> {
|
||||
if (alreadyRetried) {
|
||||
throw recovery("execution start stayed indeterminate after reconciliation");
|
||||
throw recovery(
|
||||
request.scope(), "execution start stayed indeterminate after reconciliation");
|
||||
}
|
||||
yield resumeAfterIndeterminateStart(request, action, codec);
|
||||
}
|
||||
default -> throw recovery("execution start was not confirmed for this exact operation");
|
||||
default ->
|
||||
throw recovery(
|
||||
request.scope(), "execution start was not confirmed for this exact operation");
|
||||
};
|
||||
}
|
||||
|
||||
@@ -194,11 +200,13 @@ public final class IdempotencyExecutor {
|
||||
IdempotencyInspection inspection = inspect(request);
|
||||
return switch (inspection.outcome()) {
|
||||
case CLAIMED_SAME_OPERATION ->
|
||||
startAndRun(request, requireOwner(inspection), action, codec, true);
|
||||
case EXECUTING_SAME_OPERATION -> runStarted(request, requireOwner(inspection), action, codec);
|
||||
case COMPLETED_REPLAY -> codec.deserialize(requireResponse(inspection).payload());
|
||||
startAndRun(request, requireOwner(request.scope(), inspection), action, codec, true);
|
||||
case EXECUTING_SAME_OPERATION ->
|
||||
runStarted(request, requireOwner(request.scope(), inspection), action, codec);
|
||||
case COMPLETED_REPLAY ->
|
||||
codec.deserialize(requireResponse(request.scope(), inspection).payload());
|
||||
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
|
||||
default -> throw recovery("execution start is indeterminate");
|
||||
default -> throw recovery(request.scope(), "execution start is indeterminate");
|
||||
};
|
||||
}
|
||||
|
||||
@@ -253,7 +261,7 @@ public final class IdempotencyExecutor {
|
||||
// The action has run. Reporting "unavailable" here would tell the client it did not.
|
||||
case UNAVAILABLE -> throw new IdempotencyCompletionUnknownException();
|
||||
case INDETERMINATE -> reconcileCompletion(request, result, codec, alreadyRetried);
|
||||
default -> throw recovery("completion was not confirmed");
|
||||
default -> throw recovery(request.scope(), "completion was not confirmed");
|
||||
};
|
||||
}
|
||||
|
||||
@@ -272,22 +280,25 @@ public final class IdempotencyExecutor {
|
||||
IdempotencyInspection inspection = inspect(request);
|
||||
return switch (inspection.outcome()) {
|
||||
case COMPLETED_REPLAY -> {
|
||||
StoredResponse stored = requireResponse(inspection);
|
||||
StoredResponse stored = requireResponse(request.scope(), inspection);
|
||||
if (stored.payload().equals(codec.serialize(result))) {
|
||||
yield result;
|
||||
}
|
||||
// The stored response is somebody else's answer to this scope. Returning either one would
|
||||
// be asserting a fact this caller cannot establish.
|
||||
throw recovery("the completed response conflicts with the one this caller produced");
|
||||
throw recovery(
|
||||
request.scope(), "the completed response conflicts with the one this caller produced");
|
||||
}
|
||||
case EXECUTING_SAME_OPERATION -> {
|
||||
if (alreadyRetried) {
|
||||
throw recovery("completion stayed indeterminate after reconciliation");
|
||||
throw recovery(request.scope(), "completion stayed indeterminate after reconciliation");
|
||||
}
|
||||
yield complete(request, requireOwner(inspection), result, codec, true);
|
||||
yield complete(request, requireOwner(request.scope(), inspection), result, codec, true);
|
||||
}
|
||||
case UNAVAILABLE -> throw new IdempotencyCompletionUnknownException();
|
||||
default -> throw recovery("the completion response is indeterminate and was not reconciled");
|
||||
default ->
|
||||
throw recovery(
|
||||
request.scope(), "the completion response is indeterminate and was not reconciled");
|
||||
};
|
||||
}
|
||||
|
||||
@@ -320,20 +331,24 @@ public final class IdempotencyExecutor {
|
||||
return transition.owner().orElse(fallback);
|
||||
}
|
||||
|
||||
private static IdempotencyOwner requireOwner(IdempotencyInspection inspection) {
|
||||
private static IdempotencyOwner requireOwner(
|
||||
IdempotencyScopeDigest scope, IdempotencyInspection inspection) {
|
||||
Optional<IdempotencyOwner> owner = inspection.owner();
|
||||
return owner.orElseThrow(
|
||||
() ->
|
||||
recovery(
|
||||
scope,
|
||||
"the store reported "
|
||||
+ inspection.outcome()
|
||||
+ " without the owner handle it needs"));
|
||||
}
|
||||
|
||||
private static StoredResponse requireResponse(IdempotencyInspection inspection) {
|
||||
private static StoredResponse requireResponse(
|
||||
IdempotencyScopeDigest scope, IdempotencyInspection inspection) {
|
||||
return inspection
|
||||
.response()
|
||||
.orElseThrow(() -> recovery("the store reported a completed replay with no response"));
|
||||
.orElseThrow(
|
||||
() -> recovery(scope, "the store reported a completed replay with no response"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -345,7 +360,13 @@ public final class IdempotencyExecutor {
|
||||
return scope.operationCode() + "::v" + scope.keyDigestVersion() + "::" + scope.digest();
|
||||
}
|
||||
|
||||
private static IdempotencyRecoveryRequiredException recovery(String message) {
|
||||
return new IdempotencyRecoveryRequiredException(message);
|
||||
/**
|
||||
* A recovery-required failure that names its scope, as the in-flight and mismatch failures do:
|
||||
* the runbook's first step is to find this record, and the scope digest is the only identity this
|
||||
* lifecycle holds (re-review 2026-11-04 RR3-03-03).
|
||||
*/
|
||||
private static IdempotencyRecoveryRequiredException recovery(
|
||||
IdempotencyScopeDigest scope, String message) {
|
||||
return new IdempotencyRecoveryRequiredException(message + ": " + diagnostic(scope));
|
||||
}
|
||||
}
|
||||
|
||||
+5
-1
@@ -4,7 +4,11 @@ import dev.caskeleton.shared.error.ApiErrorCarrier;
|
||||
import dev.caskeleton.shared.error.ApiErrorCode;
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
|
||||
/** Raised when request replay cannot safely decide whether an external effect already occurred. */
|
||||
/**
|
||||
* Raised when request replay cannot safely decide whether an external effect already occurred. The
|
||||
* executor's message ends with the opaque scope digest, for logs only — the record an operator
|
||||
* looks up (re-review 2026-11-04 RR3-03-03); transports answer with the code's fixed message.
|
||||
*/
|
||||
public final class IdempotencyRecoveryRequiredException extends RuntimeException
|
||||
implements ApiErrorCarrier {
|
||||
|
||||
|
||||
+9
-5
@@ -15,14 +15,18 @@ import java.lang.annotation.Target;
|
||||
* system reaches it through a delivery or a tick. This marker is how an inbound adapter of the
|
||||
* second kind says so, in code, next to the reason. Without it an inbound adapter that depends on a
|
||||
* {@code @SystemInvoked} use case fails {@code ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES};
|
||||
* with it, {@code SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS} checks the claim: the class
|
||||
* lives in a system-driven inbound package ({@code ..adapter.inbound.messaging..}, {@code
|
||||
* ..adapter.inbound.scheduler..}) and depends on no user-transport type. A controller cannot carry
|
||||
* it.
|
||||
* with it, {@code SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS} checks the claim on the class
|
||||
* and on every class nested in it: they live in a system-driven inbound package ({@code
|
||||
* ..adapter.inbound.messaging..}, {@code ..adapter.inbound.scheduler..}) and depend on no
|
||||
* user-transport type. A controller cannot carry it.
|
||||
*
|
||||
* <p>The marked adapter constructs the use case it calls with {@code new} from the ports it is
|
||||
* given and keeps it to itself: the use case is never a bean ({@code PermissionEnforcementGuard}
|
||||
* refuses one), so nothing but this adapter holds it. Review 2026-11-03 RR-01-12, decision 9.1.
|
||||
* refuses one), and no user transport depends on the adapter, directly or through other classes
|
||||
* ({@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}). The rules read class dependencies; a bean
|
||||
* looked up at run time ({@code getBean}, {@code ObjectProvider}) is not seen. The three system
|
||||
* callers and where each lives are listed in manual 07 「시스템이 부르는 쓰기」. Review 2026-11-03 RR-01-12,
|
||||
* decision 9.1; review 2026-11-04 RR3-01-01.
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
|
||||
+9
-7
@@ -19,13 +19,15 @@ import java.lang.annotation.Target;
|
||||
* <p>A use case marked this way is a write with no permission check, so no user request may reach
|
||||
* it. Its system caller constructs it directly and keeps it: a composition module hands it to a
|
||||
* scheduler (the outbox relay), or a {@link SystemCaller} inbound adapter — a message handler, a
|
||||
* scheduled job — constructs it from the ports its bean method receives (manual 09 「소비」 step 4).
|
||||
* Both ways a user could reach it are refused: a bean of it fails startup ({@code
|
||||
* composition:service-runtime} {@code PermissionEnforcementGuard}), and an inbound adapter that
|
||||
* depends on it without being a {@link SystemCaller} fails the architecture rule {@code
|
||||
* ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES} (review 2026-11-03 RR-01-02, RR-01-12). It is
|
||||
* not a way to silence the rule that a mutating use case declares a permission: a write a user
|
||||
* triggers declares one, and a write both a user and the system trigger is two use cases.
|
||||
* scheduled job — constructs it from the ports its bean method receives (manual 07 「시스템이 부르는 쓰기」
|
||||
* lists the three). The ways a user could reach it are refused: a bean of it fails startup ({@code
|
||||
* composition:service-runtime} {@code PermissionEnforcementGuard}), an inbound adapter that depends
|
||||
* on it without being a {@link SystemCaller} fails the architecture rule {@code
|
||||
* ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES}, and a user transport that depends on the
|
||||
* system caller fails {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS} (review 2026-11-03
|
||||
* RR-01-02, RR-01-12; review 2026-11-04 RR3-01-01). It is not a way to silence the rule that a
|
||||
* mutating use case declares a permission: a write a user triggers declares one, and a write both a
|
||||
* user and the system trigger is two use cases.
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
|
||||
+50
@@ -185,6 +185,56 @@ class IdempotencyExecutorTest {
|
||||
assertThat(ran).isFalse();
|
||||
}
|
||||
|
||||
/**
|
||||
* The runbook's first step for a recovery-required answer is to find the record, and the scope
|
||||
* digest is the only identity the lifecycle holds; the ERROR line of a 5xx carrier prints the
|
||||
* message (re-review 2026-11-04 RR3-03-03).
|
||||
*/
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@MethodSource("recoveryRequiredStores")
|
||||
@DisplayName("회복 필요로 끝나면 운영자가 기록을 찾도록 예외 메시지에 scope digest를 남긴다")
|
||||
void aRecoveryRequiredFailureNamesTheScopeDigest(String path, FakeStore store) {
|
||||
// when
|
||||
Throwable thrown =
|
||||
catchThrowable(
|
||||
() ->
|
||||
executor(store)
|
||||
.execute(
|
||||
SCOPE,
|
||||
FINGERPRINT,
|
||||
ATTEMPT,
|
||||
() -> new IdempotentAction.Outcome.Success<>("created"),
|
||||
codec()));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(IdempotencyRecoveryRequiredException.class)
|
||||
.hasMessageContaining(SCOPE.operationCode())
|
||||
.hasMessageContaining(SCOPE.digest());
|
||||
}
|
||||
|
||||
static Stream<Arguments> recoveryRequiredStores() {
|
||||
FakeStore expiredExecution = new FakeStore();
|
||||
expiredExecution.claim = new IdempotencyClaimOutcome.RecoveryRequired(1);
|
||||
FakeStore abandonedAfterLostClaim = new FakeStore();
|
||||
abandonedAfterLostClaim.claim = new IdempotencyClaimOutcome.Indeterminate(OPERATION);
|
||||
abandonedAfterLostClaim.inspection =
|
||||
IdempotencyInspection.outcome(IdempotencyInspectionOutcome.ABANDONED);
|
||||
FakeStore conflictingReplay = startedStore();
|
||||
conflictingReplay.complete = IdempotencyCompleteOutcome.INDETERMINATE;
|
||||
conflictingReplay.inspectionAfterComplete =
|
||||
new IdempotencyInspection(
|
||||
IdempotencyInspectionOutcome.COMPLETED_REPLAY,
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.of(new StoredResponse("somebody-elses-answer")),
|
||||
Optional.of(Instant.parse("2026-07-29T13:00:00Z")));
|
||||
return Stream.of(
|
||||
Arguments.of("claim answered recovery required", expiredExecution),
|
||||
Arguments.of("lost claim found abandoned", abandonedAfterLostClaim),
|
||||
Arguments.of("lost completion found someone else's", conflictingReplay));
|
||||
}
|
||||
|
||||
/**
|
||||
* The action already ran when completion fails, so "refused before the action" would be false.
|
||||
* Effects in the action's own transaction roll back with the exception; anything else it did has
|
||||
|
||||
+23
@@ -9,6 +9,7 @@ import dev.caskeleton.application.idempotency.IdempotencyCompleteOutcome;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyFailOutcome;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyFailureDisposition;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyInspection;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyInspectionOutcome;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyInspectionRequest;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyMutationResult;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyOwner;
|
||||
@@ -378,6 +379,28 @@ public abstract class IdempotencyStoreContract {
|
||||
.isGreaterThan(claimed.stateRevision());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("실행 중인 자기 기록을 inspect하면 기록 수명이 아니라 claim이 받은 처리 lease 만료 시각이 나온다")
|
||||
void inspectingAnOwnExecutionReportsItsProcessingLeaseNotTheRecordLifetime() {
|
||||
// given
|
||||
// A record now outlives its lease by the replay TTL, so a store that reports when the record
|
||||
// goes away reports a lease hours past the real one (re-review 2026-11-04 RR3-03-05).
|
||||
IdempotencyStorePort store = subject();
|
||||
IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION);
|
||||
IdempotencyClaimOutcome.Acquired acquired =
|
||||
(IdempotencyClaimOutcome.Acquired) store.claim(claim(attempt, FINGERPRINT));
|
||||
store.markExecutionStarted(acquired.owner(), OPERATION);
|
||||
|
||||
// when
|
||||
IdempotencyInspection inspection =
|
||||
store.inspect(new IdempotencyInspectionRequest(SCOPE, FINGERPRINT, attempt));
|
||||
|
||||
// then
|
||||
assertThat(inspection.outcome())
|
||||
.isEqualTo(IdempotencyInspectionOutcome.EXECUTING_SAME_OPERATION);
|
||||
assertThat(inspection.processingLeaseUntil()).contains(acquired.processingLeaseUntil());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("renew한 처리 lease는 처음 만료 시각이 지나도 다른 요청에 넘어가지 않는다")
|
||||
void aRenewedLeaseOutlivesItsFirstExpiry() {
|
||||
|
||||
+27
-87
@@ -14,9 +14,6 @@ import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import tools.jackson.databind.DeserializationFeature;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Repository policy for the operator-facing environment contract. No Gradle API. */
|
||||
public final class EnvContractVerifier {
|
||||
@@ -59,28 +56,9 @@ public final class EnvContractVerifier {
|
||||
* manifest test and strict binder), not as a row here.
|
||||
*/
|
||||
private static final Pattern INDEXED_KEY = Pattern.compile(".*_[0-9]+(_.*)?");
|
||||
private static final ObjectMapper JSON =
|
||||
JsonMapper.builder().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).build();
|
||||
|
||||
private EnvContractVerifier() {}
|
||||
|
||||
public static EnvContractResult verify(
|
||||
File envFile,
|
||||
Collection<File> configurationFiles,
|
||||
File registryFile,
|
||||
Collection<File> productionSources,
|
||||
Collection<MetadataScope> metadataScopes,
|
||||
Collection<String> enforcedPrefixes) {
|
||||
return verify(
|
||||
envFile,
|
||||
configurationFiles,
|
||||
registryFile,
|
||||
productionSources,
|
||||
metadataScopes,
|
||||
enforcedPrefixes,
|
||||
List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies the contract, and also every {@code APP_*} name the operator-facing files set.
|
||||
*
|
||||
@@ -93,38 +71,6 @@ public final class EnvContractVerifier {
|
||||
* in a Compose file that nothing reads is a setting the operator believes is in force and is not
|
||||
* ({@code APP_LOG_JSON_ENABLED} in the prod-smoke file, 07-10).
|
||||
*
|
||||
* @param operatorFiles the operator-facing files whose {@code APP_*} names are checked
|
||||
*/
|
||||
public static EnvContractResult verify(
|
||||
File envFile,
|
||||
Collection<File> configurationFiles,
|
||||
File registryFile,
|
||||
Collection<File> productionSources,
|
||||
Collection<MetadataScope> metadataScopes,
|
||||
Collection<String> enforcedPrefixes,
|
||||
Collection<File> operatorFiles) {
|
||||
Set<String> declared = new TreeSet<>();
|
||||
for (MetadataScope scope : metadataScopes) {
|
||||
if (scope.metadataFile().exists()) {
|
||||
parseMetadata(scope.metadataFile()).properties().stream()
|
||||
.map(SpringConfigurationProperty::name)
|
||||
.forEach(declared::add);
|
||||
}
|
||||
}
|
||||
return verify(
|
||||
envFile,
|
||||
configurationFiles,
|
||||
registryFile,
|
||||
productionSources,
|
||||
metadataScopes,
|
||||
enforcedPrefixes,
|
||||
operatorFiles,
|
||||
declared);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies the contract, with every configuration property the composition declares.
|
||||
*
|
||||
* <p>An operator-file key whose registry row names a {@code property:} counts as read only when
|
||||
* that property is declared — a registry row alone is what the operator file was already trusted
|
||||
* for (review 2026-11-04 RR2-04-05). A non-{@code APP_} key of a JSON object counts as read only
|
||||
@@ -132,17 +78,26 @@ public final class EnvContractVerifier {
|
||||
* the {@code CASKELETON_GRPC_ENABLED} switch that started RR-06-07 was neither, and nothing read
|
||||
* it.
|
||||
*
|
||||
* @param declaredProperties every property name the composition's configuration metadata declares
|
||||
* <p>The typed properties under {@code typedPrefixes} and the declared properties an operator key
|
||||
* may name are read once, from the same classpath, by {@link ConfigurationMetadataClasspath}. They
|
||||
* used to be two computations — the task read the classpath, the tests a scope file — so the unit
|
||||
* tests did not see the path the build runs (review 2026-11-04 RR3-04-04).
|
||||
*
|
||||
* @param metadataClasspath the composition's classpath with every capability a service can
|
||||
* select, whose configuration metadata declares the properties
|
||||
* @param typedPrefixes the property trees whose every typed property needs a registry row
|
||||
* @param enforcedPrefixes the {@code APP_*} prefixes whose every registered key must be read
|
||||
* @param operatorFiles the operator-facing files whose {@code APP_*} names are checked
|
||||
*/
|
||||
public static EnvContractResult verify(
|
||||
File envFile,
|
||||
Collection<File> configurationFiles,
|
||||
File registryFile,
|
||||
Collection<File> productionSources,
|
||||
Collection<MetadataScope> metadataScopes,
|
||||
Collection<File> metadataClasspath,
|
||||
Collection<String> typedPrefixes,
|
||||
Collection<String> enforcedPrefixes,
|
||||
Collection<File> operatorFiles,
|
||||
Collection<String> declaredProperties) {
|
||||
Collection<File> operatorFiles) {
|
||||
requireFile(
|
||||
envFile,
|
||||
"missing "
|
||||
@@ -218,25 +173,23 @@ public final class EnvContractVerifier {
|
||||
"shipped configuration references APP_ keys absent from docs/registries/env-keys.yaml "
|
||||
+ "(optional defaults and environment secret references are included): ");
|
||||
|
||||
Set<String> declared = ConfigurationMetadataClasspath.propertiesUnder(metadataClasspath, "");
|
||||
Set<String> typedProperties = new TreeSet<>();
|
||||
Set<String> missingMetadata = new TreeSet<>();
|
||||
for (MetadataScope scope : metadataScopes) {
|
||||
if (!scope.metadataFile().exists()) {
|
||||
missingMetadata.add(scope.propertyPrefix() + " (" + scope.metadataFile() + ")");
|
||||
continue;
|
||||
Set<String> undeclaredPrefixes = new TreeSet<>();
|
||||
for (String prefix : typedPrefixes) {
|
||||
List<String> underPrefix = declared.stream().filter(name -> name.startsWith(prefix)).toList();
|
||||
if (underPrefix.isEmpty()) {
|
||||
undeclaredPrefixes.add(prefix);
|
||||
}
|
||||
SpringConfigurationMetadata metadata = parseMetadata(scope.metadataFile());
|
||||
metadata.properties().stream()
|
||||
.map(SpringConfigurationProperty::name)
|
||||
.filter(name -> name.startsWith(scope.propertyPrefix()))
|
||||
.forEach(typedProperties::add);
|
||||
typedProperties.addAll(underPrefix);
|
||||
}
|
||||
if (!missingMetadata.isEmpty()) {
|
||||
if (!undeclaredPrefixes.isEmpty()) {
|
||||
throw new IllegalStateException(
|
||||
"verifyEnvKeys: configuration metadata is missing for "
|
||||
+ missingMetadata
|
||||
+ " — run the owning module's compileJava first (the annotation processor writes it), "
|
||||
+ "or the typed-property check silently covers nothing.");
|
||||
"verifyEnvKeys: no configuration metadata on the classpath declares a property under "
|
||||
+ undeclaredPrefixes
|
||||
+ " — put the owning module on the metadata classpath and run its compileJava (the"
|
||||
+ " annotation processor writes the metadata), or the typed-property check silently"
|
||||
+ " covers nothing.");
|
||||
}
|
||||
|
||||
failUnlessEmpty(
|
||||
@@ -247,7 +200,7 @@ public final class EnvContractVerifier {
|
||||
|
||||
Set<String> scopedRegistryProperties = new TreeSet<>();
|
||||
for (String property : registryProperties) {
|
||||
if (metadataScopes.stream().anyMatch(scope -> property.startsWith(scope.propertyPrefix()))) {
|
||||
if (typedPrefixes.stream().anyMatch(property::startsWith)) {
|
||||
scopedRegistryProperties.add(property);
|
||||
}
|
||||
}
|
||||
@@ -279,7 +232,6 @@ public final class EnvContractVerifier {
|
||||
"operator files (Compose, logback-spring.xml, the Compose lane contract, the smoke wrapper)"
|
||||
+ " set APP_ keys absent from docs/registries/env-keys.yaml: ");
|
||||
Set<String> typedRows = new TreeSet<>();
|
||||
Set<String> declared = new HashSet<>(declaredProperties);
|
||||
registryRows.stream()
|
||||
.filter(row -> row.property().filter(declared::contains).isPresent())
|
||||
.forEach(row -> typedRows.add(row.name()));
|
||||
@@ -374,14 +326,6 @@ public final class EnvContractVerifier {
|
||||
return COMPOSE_ENVIRONMENT_KEY;
|
||||
}
|
||||
|
||||
private static SpringConfigurationMetadata parseMetadata(File file) {
|
||||
SpringConfigurationMetadata metadata =
|
||||
JSON.readValue(file, SpringConfigurationMetadata.class);
|
||||
return metadata.properties() == null
|
||||
? new SpringConfigurationMetadata(List.of())
|
||||
: metadata;
|
||||
}
|
||||
|
||||
private static List<EnvRegistryRow> parseRegistryRows(File registryFile) {
|
||||
List<EnvRegistryRow> rows = new ArrayList<>();
|
||||
RowBuilder current = null;
|
||||
@@ -469,10 +413,6 @@ public final class EnvContractVerifier {
|
||||
}
|
||||
}
|
||||
|
||||
private record SpringConfigurationMetadata(List<SpringConfigurationProperty> properties) {}
|
||||
|
||||
private record SpringConfigurationProperty(String name) {}
|
||||
|
||||
private static final class RowBuilder {
|
||||
private final String name;
|
||||
private String property;
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
package dev.caskeleton.buildlogic.config;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Objects;
|
||||
|
||||
public record MetadataScope(String propertyPrefix, File metadataFile) {
|
||||
public MetadataScope {
|
||||
Objects.requireNonNull(propertyPrefix, "propertyPrefix");
|
||||
Objects.requireNonNull(metadataFile, "metadataFile");
|
||||
}
|
||||
}
|
||||
+3
-34
@@ -1,13 +1,6 @@
|
||||
package dev.caskeleton.buildlogic.config;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.gradle.api.DefaultTask;
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.file.ConfigurableFileCollection;
|
||||
@@ -71,20 +64,16 @@ public abstract class VerifyEnvKeysTask extends DefaultTask {
|
||||
}
|
||||
EnvContractResult result;
|
||||
try {
|
||||
List<MetadataScope> scopes = new ArrayList<>();
|
||||
for (String prefix : TYPED_PREFIXES) {
|
||||
scopes.add(new MetadataScope(prefix, metadataOf(prefix)));
|
||||
}
|
||||
result =
|
||||
EnvContractVerifier.verify(
|
||||
getEnvFile().get().getAsFile(),
|
||||
getConfigurationFiles().getFiles(),
|
||||
getRegistryFile().get().getAsFile(),
|
||||
getProductionSources().getFiles(),
|
||||
scopes,
|
||||
getMetadataClasspath().getFiles(),
|
||||
TYPED_PREFIXES,
|
||||
ENFORCED_PREFIXES,
|
||||
getOperatorFiles().getFiles(),
|
||||
ConfigurationMetadataClasspath.propertiesUnder(getMetadataClasspath().getFiles(), ""));
|
||||
getOperatorFiles().getFiles());
|
||||
} catch (IllegalStateException invalidContract) {
|
||||
throw new GradleException(invalidContract.getMessage(), invalidContract);
|
||||
}
|
||||
@@ -99,24 +88,4 @@ public abstract class VerifyEnvKeysTask extends DefaultTask {
|
||||
result.typedPropertyCount(),
|
||||
result.consumedOrDeprecatedRegistryRowCount());
|
||||
}
|
||||
|
||||
/** The typed properties under {@code prefix}, as one metadata file the verifier reads. */
|
||||
private File metadataOf(String prefix) {
|
||||
Set<String> properties =
|
||||
ConfigurationMetadataClasspath.propertiesUnder(getMetadataClasspath().getFiles(), prefix);
|
||||
StringBuilder json = new StringBuilder("{\"properties\":[");
|
||||
String separator = "";
|
||||
for (String property : properties) {
|
||||
json.append(separator).append("{\"name\":\"").append(property).append("\"}");
|
||||
separator = ",";
|
||||
}
|
||||
json.append("]}");
|
||||
File file = new File(getTemporaryDir(), prefix + "metadata.json");
|
||||
try {
|
||||
Files.writeString(file.toPath(), json, StandardCharsets.UTF_8);
|
||||
} catch (IOException failure) {
|
||||
throw new UncheckedIOException("failed to write " + file, failure);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
}
|
||||
|
||||
+16
-8
@@ -20,16 +20,18 @@ import java.util.regex.Pattern;
|
||||
* dropped before anything is matched, so a task named only in a comment is not "run".
|
||||
*
|
||||
* <p>A command is read with what decides whether it gates anything (review 2026-11-03 RR-06-04):
|
||||
* its {@code -x} exclusions, and the {@code continue-on-error} and {@code if:} of its step and its
|
||||
* job. A command whose failure cannot fail the run, or that runs only under a condition other than
|
||||
* a status function, is still returned, with the reason it does not count. So is a command of a
|
||||
* workflow that starts only on {@code workflow_dispatch}: nothing runs it unless someone asks, the
|
||||
* same reason an {@code if:} on the event name does not count (review 2026-11-04 RR2-04-04).
|
||||
* its {@code -x} exclusions (spelled {@code -x task}, {@code -xtask}, {@code --exclude-task task}
|
||||
* or {@code --exclude-task=task}, as Gradle reads them), and the {@code continue-on-error} and
|
||||
* {@code if:} of its step and its job. A command whose failure cannot fail the run, or that runs
|
||||
* only under a condition other than a status function, is still returned, with the reason it does
|
||||
* not count. So is a command of a workflow that starts only on {@code workflow_dispatch}: nothing
|
||||
* runs it unless someone asks, the same reason an {@code if:} on the event name does not count
|
||||
* (review 2026-11-04 RR2-04-04).
|
||||
*
|
||||
* <p>Which build a command starts is where it starts: the step's {@code working-directory} (or the
|
||||
* job's or the workflow's {@code defaults.run.working-directory}) joined with its {@code -p}, as a
|
||||
* path from the repository root. A {@code run:} that is an input of a {@code uses:} step ({@code
|
||||
* with: run:}) is not a shell command and is not read.
|
||||
* job's or the workflow's {@code defaults.run.working-directory}) joined with its {@code -p} (also
|
||||
* {@code -pdir} and {@code --project-dir}), as a path from the repository root. A {@code run:} that
|
||||
* is an input of a {@code uses:} step ({@code with: run:}) is not a shell command and is not read.
|
||||
*/
|
||||
public final class WorkflowGradleInvocations {
|
||||
private static final Pattern RUN_KEY = Pattern.compile("^(\\s*)(?:-\\s+)?run:(.*)$");
|
||||
@@ -614,6 +616,12 @@ public final class WorkflowGradleInvocations {
|
||||
index++;
|
||||
} else if (token.startsWith("--exclude-task=")) {
|
||||
excluded.add(token.substring("--exclude-task=".length()));
|
||||
} else if (token.startsWith("-x") && token.length() > 2) {
|
||||
// Gradle takes a short option's value attached, the way it takes -Dkey=value:
|
||||
// -xgrpcPerformanceTest excludes that task (review 2026-11-04 RR3-04-02).
|
||||
excluded.add(token.substring(2));
|
||||
} else if (token.startsWith("-p") && token.length() > 2) {
|
||||
projectDir = token.substring(2);
|
||||
} else if (OPTIONS_WITH_VALUE.contains(token)) {
|
||||
index++;
|
||||
} else if (!token.startsWith("-")) {
|
||||
|
||||
+108
-22
@@ -4,8 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -23,8 +25,10 @@ class EnvContractVerifierTest {
|
||||
List.of(fixture.applicationYaml().toFile()),
|
||||
fixture.registry().toFile(),
|
||||
List.of(),
|
||||
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
|
||||
List.of("APP_REDIS_"));
|
||||
fixture.metadataClasspath(),
|
||||
List.of("app.redis."),
|
||||
List.of("APP_REDIS_"),
|
||||
List.of());
|
||||
|
||||
assertEquals(2, result.envKeyCount());
|
||||
assertEquals(1, result.requiredPlaceholderCount());
|
||||
@@ -50,13 +54,43 @@ class EnvContractVerifierTest {
|
||||
List.of(fixture.applicationYaml().toFile()),
|
||||
fixture.registry().toFile(),
|
||||
List.of(),
|
||||
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
|
||||
List.of("APP_REDIS_")));
|
||||
fixture.metadataClasspath(),
|
||||
List.of("app.redis."),
|
||||
List.of("APP_REDIS_"),
|
||||
List.of()));
|
||||
|
||||
assertTrue(failure.getMessage().contains("typed configuration properties absent"));
|
||||
assertTrue(failure.getMessage().contains("app.redis.port"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("typed prefix 아래 property를 선언한 metadata가 classpath에 없으면 검사가 빈 채로 통과하지 않고 실패한다")
|
||||
void aTypedPrefixNothingOnTheClasspathDeclaresFails(@TempDir Path temp) throws Exception {
|
||||
// given
|
||||
Fixture fixture = fixture(temp);
|
||||
Path unrelatedClasses = fixture.repositoryRoot().resolve("adapter/other/build/classes/java/main");
|
||||
Files.createDirectories(unrelatedClasses);
|
||||
|
||||
// when
|
||||
IllegalStateException failure =
|
||||
assertThrows(
|
||||
IllegalStateException.class,
|
||||
() ->
|
||||
EnvContractVerifier.verify(
|
||||
fixture.envFile().toFile(),
|
||||
List.of(fixture.applicationYaml().toFile()),
|
||||
fixture.registry().toFile(),
|
||||
List.of(),
|
||||
List.of(unrelatedClasses.toFile()),
|
||||
List.of("app.redis."),
|
||||
List.of("APP_REDIS_"),
|
||||
List.of()));
|
||||
|
||||
// then
|
||||
assertTrue(failure.getMessage().contains("no configuration metadata"), failure.getMessage());
|
||||
assertTrue(failure.getMessage().contains("app.redis."), failure.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void envExamplePresenceDoesNotCountAsRuntimeConsumption(@TempDir Path temp) throws Exception {
|
||||
Fixture fixture = fixture(temp);
|
||||
@@ -79,8 +113,10 @@ class EnvContractVerifierTest {
|
||||
List.of(fixture.applicationYaml().toFile()),
|
||||
fixture.registry().toFile(),
|
||||
List.of(),
|
||||
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
|
||||
List.of("APP_REDIS_")));
|
||||
fixture.metadataClasspath(),
|
||||
List.of("app.redis."),
|
||||
List.of("APP_REDIS_"),
|
||||
List.of()));
|
||||
|
||||
assertTrue(failure.getMessage().contains("registered Redis keys that nothing reads"));
|
||||
assertTrue(failure.getMessage().contains("APP_REDIS_UNUSED"));
|
||||
@@ -101,8 +137,10 @@ class EnvContractVerifierTest {
|
||||
List.of(fixture.applicationYaml().toFile(), secondary.toFile()),
|
||||
fixture.registry().toFile(),
|
||||
List.of(),
|
||||
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
|
||||
List.of("APP_REDIS_")));
|
||||
fixture.metadataClasspath(),
|
||||
List.of("app.redis."),
|
||||
List.of("APP_REDIS_"),
|
||||
List.of()));
|
||||
|
||||
assertTrue(failure.getMessage().contains("shipped configuration references APP_ keys"));
|
||||
assertTrue(failure.getMessage().contains("APP_SECONDARY_ONLY"));
|
||||
@@ -124,8 +162,10 @@ class EnvContractVerifierTest {
|
||||
List.of(fixture.applicationYaml().toFile(), secondary.toFile()),
|
||||
fixture.registry().toFile(),
|
||||
List.of(),
|
||||
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
|
||||
List.of("APP_REDIS_")));
|
||||
fixture.metadataClasspath(),
|
||||
List.of("app.redis."),
|
||||
List.of("APP_REDIS_"),
|
||||
List.of()));
|
||||
|
||||
assertTrue(failure.getMessage().contains("required env absent from src/.env.example"));
|
||||
assertTrue(failure.getMessage().contains("APP_REQUIRED_SECONDARY"));
|
||||
@@ -145,8 +185,10 @@ class EnvContractVerifierTest {
|
||||
List.of(fixture.applicationYaml().toFile()),
|
||||
fixture.registry().toFile(),
|
||||
List.of(),
|
||||
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
|
||||
List.of("APP_REDIS_")));
|
||||
fixture.metadataClasspath(),
|
||||
List.of("app.redis."),
|
||||
List.of("APP_REDIS_"),
|
||||
List.of()));
|
||||
|
||||
assertTrue(failure.getMessage().contains("required env absent from src/.env.example"));
|
||||
assertTrue(failure.getMessage().contains("APP_REQUIRED"));
|
||||
@@ -175,7 +217,8 @@ class EnvContractVerifierTest {
|
||||
List.of(fixture.applicationYaml().toFile()),
|
||||
fixture.registry().toFile(),
|
||||
List.of(),
|
||||
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
|
||||
fixture.metadataClasspath(),
|
||||
List.of("app.redis."),
|
||||
List.of("APP_REDIS_"),
|
||||
List.of(compose.toFile())));
|
||||
|
||||
@@ -201,7 +244,8 @@ class EnvContractVerifierTest {
|
||||
List.of(fixture.applicationYaml().toFile()),
|
||||
fixture.registry().toFile(),
|
||||
List.of(),
|
||||
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
|
||||
fixture.metadataClasspath(),
|
||||
List.of("app.redis."),
|
||||
List.of("APP_REDIS_"),
|
||||
List.of(compose.toFile())));
|
||||
|
||||
@@ -223,7 +267,8 @@ class EnvContractVerifierTest {
|
||||
List.of(fixture.applicationYaml().toFile()),
|
||||
fixture.registry().toFile(),
|
||||
List.of(),
|
||||
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
|
||||
fixture.metadataClasspath(),
|
||||
List.of("app.redis."),
|
||||
List.of("APP_REDIS_"),
|
||||
List.of(compose.toFile()));
|
||||
|
||||
@@ -325,13 +370,47 @@ class EnvContractVerifierTest {
|
||||
assertTrue(failure.getMessage().contains("APP_GHOST_ENABLED"), failure.getMessage());
|
||||
}
|
||||
|
||||
private static EnvContractResult verifyWithOperatorFiles(Fixture fixture, Path operatorFile) {
|
||||
@Test
|
||||
@DisplayName("레지스트리 행의 property를 classpath의 다른 모듈 metadata가 선언하면 그 키는 읽히는 것으로 친다")
|
||||
void anOperatorKeyWhoseRegisteredPropertyAnotherModuleDeclaresPasses(@TempDir Path temp)
|
||||
throws Exception {
|
||||
// given
|
||||
Fixture fixture = fixture(temp);
|
||||
Files.writeString(
|
||||
fixture.envFile(), Files.readString(fixture.envFile()) + "APP_GHOST_ENABLED=true\n");
|
||||
Files.writeString(
|
||||
fixture.registry(),
|
||||
Files.readString(fixture.registry())
|
||||
+ "- name: APP_GHOST_ENABLED\n property: app.ghost.enabled\n type: boolean\n");
|
||||
Path ghostClasses = fixture.repositoryRoot().resolve("adapter/ghost/build/classes/java/main");
|
||||
Files.createDirectories(ghostClasses.resolve("META-INF"));
|
||||
Files.writeString(
|
||||
ghostClasses.resolve(ConfigurationMetadataClasspath.METADATA),
|
||||
"{\"properties\":[{\"name\":\"app.ghost.enabled\"}]}");
|
||||
Path compose = fixture.repositoryRoot().resolve("docker-compose.yml");
|
||||
Files.writeString(
|
||||
compose, "services:\n app:\n environment:\n APP_GHOST_ENABLED: \"true\"\n");
|
||||
|
||||
// when
|
||||
EnvContractResult result = verifyWithOperatorFiles(fixture, compose, ghostClasses);
|
||||
|
||||
// then
|
||||
assertEquals(3, result.envKeyCount());
|
||||
}
|
||||
|
||||
private static EnvContractResult verifyWithOperatorFiles(
|
||||
Fixture fixture, Path operatorFile, Path... otherModuleClasses) {
|
||||
List<File> classpath = new ArrayList<>(fixture.metadataClasspath());
|
||||
for (Path classes : otherModuleClasses) {
|
||||
classpath.add(classes.toFile());
|
||||
}
|
||||
return EnvContractVerifier.verify(
|
||||
fixture.envFile().toFile(),
|
||||
List.of(fixture.applicationYaml().toFile()),
|
||||
fixture.registry().toFile(),
|
||||
List.of(),
|
||||
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
|
||||
classpath,
|
||||
List.of("app.redis."),
|
||||
List.of("APP_REDIS_"),
|
||||
List.of(operatorFile.toFile()));
|
||||
}
|
||||
@@ -347,9 +426,9 @@ class EnvContractVerifierTest {
|
||||
Path envFile = repositoryRoot.resolve(".env.example");
|
||||
Path applicationYaml = repositoryRoot.resolve("app-bootstrap/src/main/resources/application.yml");
|
||||
Path registry = docsRoot.resolve("env-keys.yaml");
|
||||
Path metadata =
|
||||
repositoryRoot.resolve(
|
||||
"adapter/outbound/redis-runtime/build/classes/java/main/META-INF/spring-configuration-metadata.json");
|
||||
Path redisClasses =
|
||||
repositoryRoot.resolve("adapter/outbound/redis-runtime/build/classes/java/main");
|
||||
Path metadata = redisClasses.resolve(ConfigurationMetadataClasspath.METADATA);
|
||||
|
||||
Files.writeString(envFile, "APP_REQUIRED=required\nAPP_REDIS_HOST=localhost\n");
|
||||
Files.writeString(
|
||||
@@ -359,7 +438,7 @@ class EnvContractVerifierTest {
|
||||
"- name: APP_REQUIRED\n type: string\n default: none\n"
|
||||
+ "- name: APP_REDIS_HOST\n property: app.redis.host\n type: string\n default: localhost\n");
|
||||
Files.writeString(metadata, "{\"properties\":[{\"name\":\"app.redis.host\"}]}");
|
||||
return new Fixture(repositoryRoot, envFile, applicationYaml, registry, metadata);
|
||||
return new Fixture(repositoryRoot, envFile, applicationYaml, registry, redisClasses, metadata);
|
||||
}
|
||||
|
||||
private record Fixture(
|
||||
@@ -367,5 +446,12 @@ class EnvContractVerifierTest {
|
||||
Path envFile,
|
||||
Path applicationYaml,
|
||||
Path registry,
|
||||
Path redisMetadata) {}
|
||||
Path redisClasses,
|
||||
Path redisMetadata) {
|
||||
|
||||
/** The redis-runtime classes directory, as the composition's metadata classpath holds it. */
|
||||
List<File> metadataClasspath() {
|
||||
return List.of(redisClasses.toFile());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+34
@@ -226,6 +226,40 @@ class WorkflowGradleInvocationsTest {
|
||||
assertThat(invocation.executes(":integrationCheck", ".")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("-x에 태스크를 붙여 쓴 토큰은 Gradle처럼 그 태스크를 뺀 것으로 읽는다")
|
||||
void anExcludedTaskAttachedToDashXIsReadAsAnExclusion() {
|
||||
// given
|
||||
String workflow =
|
||||
"""
|
||||
- run: ./gradlew performanceCheck -xgrpcPerformanceTest --exclude-task=:leaf:test
|
||||
""";
|
||||
|
||||
// when
|
||||
Invocation invocation = WorkflowGradleInvocations.read(workflow).get(0);
|
||||
|
||||
// then
|
||||
assertThat(invocation.excludedTasks()).containsExactly("grpcPerformanceTest", ":leaf:test");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("-p에 디렉터리를 붙여 쓴 명령은 Gradle처럼 그 디렉터리의 빌드를 실행한다")
|
||||
void aProjectDirectoryAttachedToDashPIsTheBuildTheCommandStarts() {
|
||||
// given
|
||||
String workflow =
|
||||
"""
|
||||
- run: ./gradlew -poptional-platforms integrationCheck --stacktrace
|
||||
""";
|
||||
|
||||
// when
|
||||
Invocation invocation = WorkflowGradleInvocations.read(workflow).get(0);
|
||||
|
||||
// then
|
||||
assertThat(invocation.projectDir()).isEqualTo("optional-platforms");
|
||||
assertThat(invocation.executes(":integrationCheck", ".")).isFalse();
|
||||
assertThat(invocation.executes(":integrationCheck", "optional-platforms")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("job의 continue-on-error와 단계의 if 조건은 명령을 실행으로 세지 않는 이유로 남는다")
|
||||
void jobAndStepGatingIsKeptAsTheReasonACommandDoesNotCount() {
|
||||
|
||||
@@ -45,7 +45,7 @@ executor, 설정 기본값이 함께 빠진다(그때 KEYED use case는 executor
|
||||
| 언제 | 키 |
|
||||
| --- | --- |
|
||||
| 켤 때 | `APP_IDEMPOTENCY_PROVIDER` (`redis` 또는 `postgresql`), 그리고 그 provider 모듈의 줄과 env |
|
||||
| 조정할 때 | `APP_IDEMPOTENCY_PROCESSING_LEASE`(≤1h), `APP_IDEMPOTENCY_TTL`(≤72h, processing lease 이상), `APP_IDEMPOTENCY_FAILURE_RETENTION`(≤30d) |
|
||||
| 조정할 때 | `APP_IDEMPOTENCY_PROCESSING_LEASE`(≤1h), `APP_IDEMPOTENCY_TTL`(≤72h, processing lease 이상), `APP_IDEMPOTENCY_FAILURE_RETENTION`(≤30d, `APP_IDEMPOTENCY_TTL` 이상으로 — 기동 검사는 없다) |
|
||||
|
||||
## 설계 결정 참조 (app-bootstrap에서 옮김)
|
||||
|
||||
@@ -74,7 +74,7 @@ executor, 설정 기본값이 함께 빠진다(그때 KEYED use case는 executor
|
||||
| `provider` | `APP_IDEMPOTENCY_PROVIDER` | `disabled` | `disabled` \| `redis` \| `postgresql` |
|
||||
| `processing-lease` | `APP_IDEMPOTENCY_PROCESSING_LEASE` | 30s | 1h |
|
||||
| `replay-ttl` | `APP_IDEMPOTENCY_TTL` | 24h | 72h, 그리고 `processing-lease` 이상 |
|
||||
| `failure-retention` | `APP_IDEMPOTENCY_FAILURE_RETENTION` | 24h | 30d |
|
||||
| `failure-retention` | `APP_IDEMPOTENCY_FAILURE_RETENTION` | 24h | 30d. `replay-ttl`과 비교하지 않는다(아래) |
|
||||
| `response-codec-id` | — | `json-v2` | 1–64자 |
|
||||
| `policy-revision` | — | 2 | 양수 |
|
||||
| `reaper-interval` | — | 10m | 양수 |
|
||||
@@ -87,6 +87,10 @@ executor, 설정 기본값이 함께 빠진다(그때 KEYED use case는 executor
|
||||
둔다 — 이 검사는 store 를 지키는 것이 아니라 재생을 무력하게 만드는 정책을 막는다.
|
||||
`IdempotencyClaimRequest` 에는 두지 않았다: 포트는 어떤 값 쌍으로도 쓸 수 있고, store 가 모든 쌍에서
|
||||
안전한지는 공유 계약이 본다.
|
||||
- **`failure-retention` 은 `replay-ttl` 과 비교하지 않는다.** 실패로 표시된 기록(포기·재시도 가능)은 표시부터
|
||||
이 기간만 남는다. `replay-ttl` 보다 짧으면 효과 불명으로 포기한 기록이 먼저 사라져 같은 키 재전송이 작업을
|
||||
다시 돌리므로 운영 값은 `replay-ttl` 이상으로 둔다. 기동 검사로 막지 않은 이유: 지금 기동하는 설정을 이
|
||||
라운드에서 실패로 바꾸지 않는다 — 검사 추가는 소유자 결정으로 남겼다(재리뷰 2026-11-04 RR3-03-02).
|
||||
- **상한 검사는 컴팩트 생성자에서 fail-fast 로 던진다.** `Duration`의 상한은 JSR-303(`@Valid`)
|
||||
애너테이션으로 표현할 수 없어 생성자에서 직접 검증한다. 검증을 느슨하게 두면 과도하게 긴 TTL 이
|
||||
저장소를 조용히 부풀리고 멱등성 키 추측 공격의 유효 시간 창을 넓히기 때문에, 부팅 시점에 즉시
|
||||
|
||||
@@ -32,7 +32,8 @@ composition:service-runtime
|
||||
유스케이스가 빈으로 등록돼 있으면 같은 가드가 기동을 멈춘다 — 권한 검사가 없는 쓰기를 전송 계층이
|
||||
닿는 곳에 두는 조립이기 때문이다(review 2026-11-03 RR-01-02). 가드가 허용하는 경우는 하나다: 시스템
|
||||
호출자의 bean이 자기가 `new`로 만든 use case를 필드로 든다(스케줄러에 넘기는 조립 모듈, 또는
|
||||
`@SystemCaller` 메시지 handler — RR-01-12). 가드는 bean 타입만 보므로 둘 다 기동한다.
|
||||
`@SystemCaller` 메시지 handler·예약 작업 — RR-01-12, 목록의 정본은 매뉴얼 07장 「시스템이 부르는 쓰기」).
|
||||
가드는 bean 타입만 보므로 모두 기동한다.
|
||||
|
||||
- 모두 이 모듈의 `AutoConfiguration.imports`로 등록된다(설정 브리지와 tracing 스위치는
|
||||
`spring.factories`의 `EnvironmentPostProcessor`·`AutoConfigurationImportFilter`). 구성 루트의
|
||||
|
||||
+8
-7
@@ -32,12 +32,13 @@ import org.springframework.util.ClassUtils;
|
||||
* reach with no check, whatever advisor the context holds, so its presence fails startup (review
|
||||
* 2026-11-03 RR-01-02), with no exception. The system caller that runs it holds it instead, and
|
||||
* that is the one condition this guard allows: the use case is a field of a bean, never a bean.
|
||||
* There are two such callers (decision 9.1, RR-01-12): a scheduler, to which a composition module
|
||||
* hands the use case it constructed (the outbox relay), and a {@code @SystemCaller} message
|
||||
* handler, which constructs the use case from the ports its own bean method receives. The guard
|
||||
* looks at bean types only, so both start. {@code
|
||||
* ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES} closes the static path, a user transport that
|
||||
* constructs one itself.
|
||||
* There are two shapes of such a caller (decision 9.1, RR-01-12): a scheduler, to which a
|
||||
* composition module hands the use case it constructed (the outbox relay), and a
|
||||
* {@code @SystemCaller} message handler or scheduled job, which constructs the use case from the
|
||||
* ports its own bean method receives (manual 07 「시스템이 부르는 쓰기」 lists them). The guard looks at bean
|
||||
* types only, so all of them start. The static paths are the architecture rules': {@code
|
||||
* ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES} refuses a user transport that constructs one
|
||||
* itself, and {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS} one that calls the system caller.
|
||||
*/
|
||||
final class PermissionEnforcementGuard implements SmartInitializingSingleton, BeanFactoryAware {
|
||||
|
||||
@@ -71,7 +72,7 @@ final class PermissionEnforcementGuard implements SmartInitializingSingleton, Be
|
||||
"@SystemInvoked use cases are registered as beans, where a transport can reach a write"
|
||||
+ " that has no permission check — a system-invoked use case is constructed by the"
|
||||
+ " system caller that runs it (a scheduler's composition, a @SystemCaller message"
|
||||
+ " handler) and never registered as a bean: "
|
||||
+ " handler or scheduled job) and never registered as a bean: "
|
||||
+ String.join(", ", systemInvoked));
|
||||
}
|
||||
if (!unenforced.isEmpty()) {
|
||||
|
||||
+20
-6
@@ -3,6 +3,7 @@ package dev.caskeleton.grpc.ledger;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
@@ -13,9 +14,10 @@ import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.postgresql.ds.PGSimpleDataSource;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
@@ -31,6 +33,13 @@ import org.testcontainers.postgresql.PostgreSQLContainer;
|
||||
* Flyway runs it, in one transaction. Unbounded it waits until the writer leaves, with every claim
|
||||
* queued behind it, and then applies; bounded it fails with {@code lock_not_available} first and
|
||||
* its rollback leaves the ledger as it was.
|
||||
*
|
||||
* <p>Every migration after V001 is held to this, read from the tree itself ({@link
|
||||
* GrpcOperationLedgerMigrations#inOrder()}), so a V004 is checked without anyone naming it here.
|
||||
* This is the ledger tree's lock-wait rule: the optional build cannot reach the persistence-jpa
|
||||
* testkit whose text check the other trees run, and a copy of that check would drift (re-review
|
||||
* 2026-11-03 round 3, RR3-02-04). A later migration that does not touch the ledger at all fails
|
||||
* here too, on purpose: say so in this test rather than let the rule pass it unseen.
|
||||
*/
|
||||
@Testcontainers(disabledWithoutDocker = true)
|
||||
class GrpcOperationLedgerMigrationLockWaitIT {
|
||||
@@ -47,12 +56,13 @@ class GrpcOperationLedgerMigrationLockWaitIT {
|
||||
.withUsername("grpc")
|
||||
.withPassword("grpc");
|
||||
|
||||
/** Every ledger migration after V001, the one that creates the ledger. */
|
||||
static Stream<String> migrationsAfterTheFirst() throws IOException {
|
||||
return GrpcOperationLedgerMigrations.inOrder().stream().skip(1);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(
|
||||
strings = {
|
||||
"V002__index_grpc_operation_ledger_finished_rows.sql",
|
||||
"V003__add_grpc_operation_ledger_claim_attempt.sql"
|
||||
})
|
||||
@MethodSource("migrationsAfterTheFirst")
|
||||
@DisplayName("ledger에 쓴 트랜잭션이 열려 있으면 ledger를 잠그는 마이그레이션은 상한 안에 실패하고 아무것도 바꾸지 않는다")
|
||||
void aLedgerMigrationGivesUpOnAnOpenWriterAndChangesNothing(String migration) throws Exception {
|
||||
PGSimpleDataSource dataSource = dataSource();
|
||||
@@ -73,6 +83,10 @@ class GrpcOperationLedgerMigrationLockWaitIT {
|
||||
String.valueOf(attempt.sqlState()),
|
||||
attempt.took().compareTo(GIVES_UP_WITHIN) < 0,
|
||||
schema(statement)))
|
||||
.as(
|
||||
"%s must put SET LOCAL lock_timeout = '5s'; before it locks the ledger"
|
||||
+ " (docs/jpa/migration-guide.md, \"Bound the lock wait\")",
|
||||
migration)
|
||||
.containsExactly(LOCK_NOT_AVAILABLE, true, schemaBefore);
|
||||
}
|
||||
}
|
||||
|
||||
+41
-16
@@ -3,24 +3,44 @@ package dev.caskeleton.grpc.ledger;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* The ledger's Flyway scripts in version order, as one SQL text for a test database.
|
||||
*
|
||||
* <p>One list for every PostgreSQL lane, so a new migration is applied by all of them or by none;
|
||||
* two copies of the list drift the first time someone adds a V003 to one of them.
|
||||
* <p>One list for every PostgreSQL lane, so a new migration is applied by all of them or by none.
|
||||
* The list is the tree on disk, not a copy of it: a hand-kept list let a V004 that nobody added to
|
||||
* it go unapplied and unchecked by every lane (re-review 2026-11-03 round 3, RR3-02-04).
|
||||
*/
|
||||
final class GrpcOperationLedgerMigrations {
|
||||
|
||||
private static final List<String> IN_ORDER =
|
||||
List.of(
|
||||
"db/migration/grpc/V001__create_grpc_operation_ledger.sql",
|
||||
"db/migration/grpc/V002__index_grpc_operation_ledger_finished_rows.sql",
|
||||
"db/migration/grpc/V003__add_grpc_operation_ledger_claim_attempt.sql");
|
||||
/** The ledger's tree from this leaf's directory, where the lanes run. */
|
||||
private static final Path TREE = Path.of("src/main/resources/db/migration/grpc");
|
||||
|
||||
/** The same tree on the classpath, where the scripts are read from. */
|
||||
private static final String LOCATION = "db/migration/grpc/";
|
||||
|
||||
private GrpcOperationLedgerMigrations() {}
|
||||
|
||||
/**
|
||||
* The file name of every versioned migration in the tree ({@code V<version>__<name>.sql}), in
|
||||
* Flyway's order: by version, its parts compared as numbers.
|
||||
*/
|
||||
static List<String> inOrder() throws IOException {
|
||||
try (Stream<Path> files = Files.list(TREE)) {
|
||||
return files
|
||||
.map(file -> file.getFileName().toString())
|
||||
.filter(name -> name.matches("V\\d+(?:[._]\\d+)*__.+\\.sql"))
|
||||
.sorted(Comparator.comparing(GrpcOperationLedgerMigrations::version, Arrays::compare))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
/** Every migration's SQL, concatenated in version order. */
|
||||
static String all() throws IOException {
|
||||
return before(null);
|
||||
@@ -29,26 +49,31 @@ final class GrpcOperationLedgerMigrations {
|
||||
/** The SQL of every migration before the one named, concatenated in version order. */
|
||||
static String before(String fileName) throws IOException {
|
||||
StringBuilder sql = new StringBuilder();
|
||||
for (String path : IN_ORDER) {
|
||||
if (path.endsWith("/" + fileName)) {
|
||||
for (String name : inOrder()) {
|
||||
if (name.equals(fileName)) {
|
||||
break;
|
||||
}
|
||||
sql.append(read(path)).append('\n');
|
||||
sql.append(read(name)).append('\n');
|
||||
}
|
||||
return sql.toString();
|
||||
}
|
||||
|
||||
/** One migration's SQL, by its file name. */
|
||||
static String named(String fileName) throws IOException {
|
||||
for (String path : IN_ORDER) {
|
||||
if (path.endsWith("/" + fileName)) {
|
||||
return read(path);
|
||||
}
|
||||
if (!inOrder().contains(fileName)) {
|
||||
throw new IOException("no gRPC operation-ledger migration is named " + fileName);
|
||||
}
|
||||
throw new IOException("no gRPC operation-ledger migration is named " + fileName);
|
||||
return read(fileName);
|
||||
}
|
||||
|
||||
private static String read(String path) throws IOException {
|
||||
private static int[] version(String fileName) {
|
||||
return Arrays.stream(fileName.substring(1, fileName.indexOf("__")).split("[._]"))
|
||||
.mapToInt(Integer::parseInt)
|
||||
.toArray();
|
||||
}
|
||||
|
||||
private static String read(String fileName) throws IOException {
|
||||
String path = LOCATION + fileName;
|
||||
try (InputStream stream =
|
||||
GrpcOperationLedgerMigrations.class.getClassLoader().getResourceAsStream(path)) {
|
||||
if (stream == null) {
|
||||
|
||||
@@ -217,7 +217,9 @@ app:
|
||||
# profile the guard lets the sample start under must also start it. This document used to name
|
||||
# `local` alone, so `test` and `demo` were allowed and stopped on an object-storage binding with no
|
||||
# destination (review 2026-11-04 RR2-04-02). SampleDemoProfilesStartupSystemTest starts the sample
|
||||
# under each listed profile with nothing but this file and a database address.
|
||||
# under each listed profile, given a database address and free ports: `demo` and `local` with the
|
||||
# shipped configuration alone, `test` with the system-test source set's application-test.yml loaded
|
||||
# as well.
|
||||
spring:
|
||||
config:
|
||||
activate:
|
||||
|
||||
+3
-15
@@ -3,14 +3,13 @@ package dev.caskeleton.sample.portfolio.bootstrap.persistence;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.migration.LockWaitMigrationInspector;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.migration.VersionedMigrationFiles;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -33,13 +32,12 @@ class SampleMigrationLockWaitTest {
|
||||
@DisplayName("샘플 스트림의 규칙 이후 마이그레이션은 기존 테이블 잠금 앞에 SET LOCAL lock_timeout을 둔다")
|
||||
void everySampleMigrationAfterTheRuleBoundsItsLockWait() throws IOException {
|
||||
// given
|
||||
Map<String, Path> migrations = versionedMigrations();
|
||||
Map<String, Path> migrations = VersionedMigrationFiles.under(STREAM);
|
||||
|
||||
// when
|
||||
Map<String, List<String>> unbounded = new TreeMap<>();
|
||||
for (Map.Entry<String, Path> migration : migrations.entrySet()) {
|
||||
List<String> statements =
|
||||
inspector.unboundedLockingStatements(Files.readString(migration.getValue()));
|
||||
List<String> statements = inspector.unboundedLockingStatements(migration.getValue());
|
||||
if (!statements.isEmpty()) {
|
||||
unbounded.put(migration.getKey(), statements);
|
||||
}
|
||||
@@ -50,14 +48,4 @@ class SampleMigrationLockWaitTest {
|
||||
.as("these wait for a table lock without a bound: %s", unbounded)
|
||||
.isEqualTo(RELEASED_BEFORE_THE_RULE);
|
||||
}
|
||||
|
||||
private static Map<String, Path> versionedMigrations() throws IOException {
|
||||
Map<String, Path> migrations = new TreeMap<>();
|
||||
try (Stream<Path> files = Files.list(STREAM)) {
|
||||
files
|
||||
.filter(path -> path.getFileName().toString().matches("V[0-9_]+__.+\\.sql"))
|
||||
.forEach(path -> migrations.put(path.getFileName().toString(), path));
|
||||
}
|
||||
return migrations;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +47,8 @@ public enum OperationalError implements ApiErrorCode {
|
||||
IDEMPOTENT_IN_FLIGHT(Category.CONFLICT, 409, true),
|
||||
IDEMPOTENT_REQUEST_MISMATCH(Category.VALIDATION, 422, false),
|
||||
IDEMPOTENCY_UNAVAILABLE(Category.TRANSIENT_DEPENDENCY, 503, true),
|
||||
// the action ran and recording its result failed; a resend with the same key never runs it again
|
||||
// the action ran and recording its result failed; while the server still holds the record, a
|
||||
// resend with the same key never runs it again (docs/web/http-contract.md, "서버가 기억하는 기간")
|
||||
IDEMPOTENCY_COMPLETION_UNKNOWN(Category.TRANSIENT_DEPENDENCY, 503, true),
|
||||
IDEMPOTENCY_RECOVERY_REQUIRED(Category.DATA_INTEGRITY, 500, false),
|
||||
// adapter runtime lifecycle
|
||||
|
||||
Reference in New Issue
Block a user