feat!: 남은 리뷰 발견을 고치고 개발 매뉴얼과 기능 생성 명령을 더한다
문제: High·P1을 고친 뒤에도 P2·P3 약 90건이 남았다. 연결·구독·메시지 크기 상한이 없는 전송(WebSocket·gRPC·GraphQL deadline), 낙관적 충돌의 500, upsert 경쟁, Mongo 무제한 timeout, 샘플 목록 N+1, 갈라진 복사본 (TenantId 3벌, 이벤트 ID 문법 5곳, SQLState 표 2벌), 문서를 읽는 PR 테스트와 캐시를 막는 lane 설정 등이다. 새 기능을 어디에 어떤 순서로 만드는지 알려 주는 문서와 도구가 없었다. MinIO 공식 이미지가 사라져 객체 저장소 lane이 돌지 않았다. 방법: 영역별 묶음으로 실패 테스트를 먼저 쓰고 고쳤다. 고치는 중에 찾은 결함도 함께 고쳤다(durable operation id가 UUIDv4라 이벤트가 전부 DEAD, S3 어댑터 생성·작은 chunk 읽기 실패, Redis 조건부 기록의 EVALSHA 권한). MinIO는 pgsty/minio를 digest로 고정했다(Chainguard는 태그·실행 사용자· mc 이미지 문제로 버림). docs/manual/에 작업 순서와 판단 지점을 쓰고, scripts/new-feature.sh가 5개 leaf에 뼈대를 만든다. 생성→빌드→통과 왕복을 verifyFeatureScaffold가 mainCheck에서 본다. 묶음별 결과와 결정은 리뷰 README 14절에 있다. 위험·한계: 파생 서비스 동작이 바뀐다. JDBC batch 50 기본, 운영 jar에서 H2 제거, 트랜잭션 30초 제한, 격리 수준을 Hikari에서 고정, gRPC· WebSocket·GraphQL 새 한도, correlation ID 규칙 밖이면 서버가 교체, 샘플 키 오류 코드 IDEMPOTENCY_KEY_INVALID. 새 leaf 두 개 (composition:durable-operation, adapter:inbound:messaging)와 새 마이그레이션(postgresql V20·V21, notification V11·V12, sample V8_1, grpc-ledger V002)이 생긴다. V21 유일 인덱스는 기존 중복이 있으면 실패한다(runbook에 확인 쿼리). 검증: ci, mainCheck(생성 명령 왕복 포함), integrationCheck(MinIO 포함 전 컨테이너 lane), -p optional-platforms ci integrationCheck 통과. Refs: docs/reviews/2026-11-01-maturity-review/README.md 14절 BREAKING CHANGE: JDBC batch 기본 켜짐, H2 운영 의존 제거, 트랜잭션 기본 제한 30초, gRPC·WebSocket·GraphQL 서버 한도 기본값 추가, 샘플 Idempotency-Key 오류 코드 변경.
This commit is contained in:
@@ -32,7 +32,6 @@ jobs:
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:outbound:fileserver:test --tests '*NfsAmbiguityIntegrationTest'
|
||||
|
||||
--stacktrace
|
||||
- name: Tear down the NFS environment
|
||||
if: always()
|
||||
@@ -51,7 +50,6 @@ jobs:
|
||||
:adapter:outbound:fileserver:test --tests '*CrashRecoveryMatrixTest'
|
||||
:application-fileserver:test --tests '*FileReconciliationServiceTest'
|
||||
--rerun-tasks
|
||||
|
||||
--stacktrace
|
||||
|
||||
fileserver-large-file-performance:
|
||||
@@ -69,7 +67,6 @@ jobs:
|
||||
:adapter:outbound:fileserver:test --tests '*LargeFileBoundedMemoryTest'
|
||||
:adapter:outbound:fileserver:test --tests '*LocalAppendMemoryTest'
|
||||
--rerun-tasks
|
||||
|
||||
--stacktrace
|
||||
|
||||
fileserver-multi-instance-lease:
|
||||
@@ -84,5 +81,4 @@ jobs:
|
||||
./gradlew
|
||||
:application-fileserver:test --tests '*MultiInstanceWriterLeaseTest'
|
||||
--rerun-tasks
|
||||
|
||||
--stacktrace
|
||||
|
||||
@@ -56,7 +56,6 @@ jobs:
|
||||
./gradlew
|
||||
:application-fileserver:test
|
||||
:composition:fileserver-platform:test
|
||||
|
||||
--stacktrace
|
||||
|
||||
fileserver-local-ext4-contract:
|
||||
@@ -70,7 +69,6 @@ jobs:
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:outbound:fileserver:test
|
||||
|
||||
--stacktrace
|
||||
|
||||
fileserver-http-contract:
|
||||
@@ -84,7 +82,6 @@ jobs:
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:inbound:web-fileserver:test
|
||||
|
||||
--stacktrace
|
||||
|
||||
fileserver-security-suite:
|
||||
@@ -99,7 +96,6 @@ jobs:
|
||||
./gradlew
|
||||
:adapter:inbound:web-fileserver:test --tests '*FileserverHardeningContractTest'
|
||||
:adapter:outbound:fileserver:test --tests '*PhysicalPathResolverTest'
|
||||
|
||||
--stacktrace
|
||||
|
||||
fileserver-bounded-memory:
|
||||
@@ -113,5 +109,4 @@ jobs:
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:outbound:fileserver:test --tests '*LargeFileBoundedMemoryTest'
|
||||
|
||||
--stacktrace
|
||||
|
||||
@@ -152,6 +152,16 @@ jobs:
|
||||
# The container lanes take the build-wide `exclusiveRealServerLane` slot one at a time, so the
|
||||
# job's length is the sum of the lanes. Split the aggregate across jobs when it outgrows its
|
||||
# timeout rather than going back to naming lanes.
|
||||
#
|
||||
# Measured length (one local run of `:integrationCheck`, 2026-11-01, 37 lanes, images already
|
||||
# pulled, machine load 24): 794 s for the command, of which the lanes' test JVMs took about 624 s
|
||||
# in sum — mongoSecurityIntegrationTest 89, jpaPlatformContractTest 104, messagingCertificationTest
|
||||
# 70, mongoCompatibilityTest 69, jpaPlatformMigrationTest 66, mongoFailoverTest 59, the eleven JPA
|
||||
# readiness lanes 57 together, httpClientFailureInjectionTest 27, sample integrationTest 23,
|
||||
# messaging starter integrationTest 21, the rest under 10 each — and the remainder was compilation
|
||||
# and container start-up between lanes. A hosted runner adds cold image pulls (about 5 GB
|
||||
# uncompressed across the PostgreSQL, MongoDB, Kafka, nginx, httpbin and Toxiproxy images) and a
|
||||
# cold Gradle cache; expect 25 to 40 minutes (an estimate, not a measured hosted run). The 240-minute timeout is a ceiling for a hung container, not a budget.
|
||||
integration-check:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 240
|
||||
|
||||
@@ -37,7 +37,6 @@ jobs:
|
||||
./gradlew
|
||||
:adapter:outbound:persistence-jpa:jpaPlatformContractTest
|
||||
-Pjpa.matrix.versions=${{ matrix.postgresql }}
|
||||
|
||||
--stacktrace
|
||||
|
||||
jpa-failure-injection:
|
||||
@@ -51,7 +50,6 @@ jobs:
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:outbound:persistence-jpa:jpaPlatformFailureTest
|
||||
|
||||
--stacktrace
|
||||
|
||||
jpa-query-plan-and-security:
|
||||
@@ -66,7 +64,6 @@ jobs:
|
||||
./gradlew
|
||||
:adapter:outbound:persistence-jpa:jpaPlatformQueryPlanTest
|
||||
:adapter:outbound:persistence-jpa:jpaPlatformSecurityTest
|
||||
|
||||
--stacktrace
|
||||
|
||||
jpa-pool-pressure:
|
||||
@@ -86,5 +83,4 @@ jobs:
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:outbound:persistence-jpa:jpaPlatformPoolContractTest
|
||||
|
||||
--stacktrace
|
||||
|
||||
@@ -142,7 +142,6 @@ jobs:
|
||||
./gradlew
|
||||
:adapter:inbound:web:systemTest
|
||||
:adapter:inbound:web:webJettyCompatTest
|
||||
|
||||
--stacktrace
|
||||
- name: Publish the test reports
|
||||
if: always()
|
||||
@@ -165,7 +164,6 @@ jobs:
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:inbound:websocket:websocketJettyTest
|
||||
|
||||
--stacktrace
|
||||
|
||||
# Docker-gated, and the lane fails rather than skipping. Upgrade handling is the single most
|
||||
@@ -183,7 +181,6 @@ jobs:
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:inbound:websocket:websocketNginxTest
|
||||
|
||||
--stacktrace
|
||||
|
||||
# One transport per job, so a transport that stops satisfying the shared contract fails on its own
|
||||
@@ -206,7 +203,6 @@ jobs:
|
||||
./gradlew
|
||||
:adapter:outbound:httpclient:httpClientStableContractTest
|
||||
-Phttpclient.contract.transports=${{ matrix.transport }}
|
||||
|
||||
--stacktrace
|
||||
|
||||
# Only the Spring 7.0 lane. httpClientSecurityTest and spring62ApiSurfaceScan used to run here
|
||||
@@ -226,7 +222,6 @@ jobs:
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:outbound:httpclient:spring70CompatibilityTest
|
||||
|
||||
--stacktrace
|
||||
|
||||
# 16 and 18 — the ends of the Stable matrix. 17 runs in the integration stage. What this does not
|
||||
@@ -250,7 +245,6 @@ jobs:
|
||||
./gradlew
|
||||
:adapter:outbound:persistence-jpa:jpaPlatformContractTest
|
||||
-Pjpa.matrix.versions=${{ matrix.postgresql }}
|
||||
|
||||
--stacktrace
|
||||
|
||||
jpa-migration-smoke:
|
||||
@@ -266,5 +260,4 @@ jobs:
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:outbound:persistence-jpa:jpaPlatformMigrationTest
|
||||
|
||||
--stacktrace
|
||||
|
||||
@@ -73,7 +73,6 @@ jobs:
|
||||
:adapter:inbound:web:systemTest
|
||||
:adapter:inbound:web:webJettyCompatTest
|
||||
:adapter:inbound:web-advanced:webAdvancedTest
|
||||
|
||||
--stacktrace
|
||||
- name: Publish the release evidence
|
||||
if: always()
|
||||
@@ -100,7 +99,6 @@ jobs:
|
||||
:adapter:inbound:websocket:websocketJettyTest
|
||||
:adapter:inbound:websocket:websocketNginxTest
|
||||
:adapter:inbound:websocket:websocketTransportQualificationTest
|
||||
|
||||
--stacktrace
|
||||
- name: Publish the release evidence
|
||||
if: always()
|
||||
|
||||
@@ -65,11 +65,22 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어
|
||||
`ca.architecture`가 아키텍처 검증 태스크를 소유한다. 기능별 검사(notification·mongo·messaging·
|
||||
graphql·JPA readiness 등)는 build-logic이 아니라 소유 leaf의 테스트다. 테스트가 저장소 파일을 읽으면
|
||||
그 파일을 그 leaf의 test task `inputs`로 선언한다. 저장소 문서와 대조하는 테스트는 `mainStage()`
|
||||
레인(`document-contract` 태그)으로 leaf `mainCheck`에서 돈다.
|
||||
레인(`document-contract` 태그)으로 leaf `mainCheck`에서 돈다. 문서가 아닌 저장소 파일(빌드 스크립트,
|
||||
workflow, Compose, 다른 leaf 소스)을 읽어야 merge 전에 막을 수 있는 계약은 그 파일만 입력으로 둔
|
||||
별도 레인(app-bootstrap `repository-contract`)에 둔다. 저장소 루트(`ca.repository.root`)는 이 두
|
||||
레인에만 주므로 태그 없이 저장소를 읽는 테스트는 `test`에서 실패한다.
|
||||
- strict lane 캐시: `TEST`·`ARCHITECTURE` lane은 입력이 같으면 up-to-date·build cache를 쓴다.
|
||||
`INTEGRATION`·`SYSTEM`·`PERFORMANCE` lane과 `mainStage()` lane은 이미지·네트워크·시간·문서처럼
|
||||
입력으로 잡히지 않는 것에 기대므로 매번 다시 돈다. hermetic lane이 저장소 파일을 읽으면 그 파일을
|
||||
입력으로 선언해야 캐시가 거짓 통과를 내지 않는다.
|
||||
- `verifyEnvKeys`는 app-bootstrap 태스크로 유지한다(소유자 결정 4). 구현은 build-logic의
|
||||
`ca.config-contract`다. `src/build-tools/` included build는 비워서 삭제했다.
|
||||
- `src/build.gradle`: 루트 라이프사이클(`ci`, `mainCheck`, `releaseCheck`, `qualityCheck`,
|
||||
`configContractCheck`, `integrationCheck`)과 버전/리비전
|
||||
- `src/build.gradle`: 루트 라이프사이클(`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`,
|
||||
`releaseCheck`, `qualityCheck`, `configContractCheck`)과 버전/리비전. `verifyStrictLaneStages
|
||||
--dry-run`(PR 게이트)은 `explicitOnly`가 아닌 모든 strict lane이 workflow가 실제로 실행하는 단계
|
||||
(`ci`·`sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`)
|
||||
중 하나에 들어 있는지, 그리고 workflow의 접힌(`>`) run 블록이 빈 줄 때문에 옵션을 별개 명령으로
|
||||
떼어 내지 않는지 검사한다.
|
||||
|
||||
작업 파일의 소유 leaf는 registry의 `source_path`로 판단하고 가장 가까운 `src/**/CLAUDE.md`를
|
||||
함께 읽는다. focused test는 registry의 `gradle_path`에서
|
||||
@@ -140,6 +151,10 @@ Gradle 의존성 검증도 같은 registry를 읽는다. root 문서나 기억
|
||||
9. endpoint는 마지막에 해당 `adapter:inbound:*` leaf에서 얇게 연결한다.
|
||||
10. focused test를 먼저 돌리고, 가능한 경우 전체 Gradle test를 돌린다.
|
||||
|
||||
단계별 판단 지점(배치·저장 포트·트랜잭션·멱등성·오류·권한)은 `docs/manual/`, 뼈대는
|
||||
`scripts/new-feature.sh <FeatureName>`이 계층 leaf에 만든다. `sample-portfolio`는 모든 계층을 한 leaf에
|
||||
두는 지울 수 있는 샘플이라 배치 예시가 아니다. 실제 기능은 계층 leaf별로 나눈다.
|
||||
|
||||
## 테스트 전략
|
||||
|
||||
계층별 테스트 기준:
|
||||
@@ -154,8 +169,8 @@ Gradle 의존성 검증도 같은 registry를 읽는다. root 문서나 기억
|
||||
테스트 작성 규칙 (새로 쓰거나 고치는 테스트에 적용):
|
||||
|
||||
1. 이름은 lowerCamelCase 행동 문장(`<상황/주체><결과>`)이다. 이름에 적은 성질은 반드시 단언한다.
|
||||
2. `@DisplayName`은 메서드 이름으로 못 쓰는 내용(숫자, 기호, 이유)이 있을 때만 쓰고, 언어는 영어로
|
||||
통일한다.
|
||||
2. `@DisplayName`은 메서드 이름으로 못 쓰는 내용(숫자, 기호, 이유)이 있을 때만 쓰고, 한국어로
|
||||
쓴다(소유자 결정 5). 기존 영어 `@DisplayName`은 그 테스트를 고칠 때 한국어로 바꾼다.
|
||||
3. 본문 문장이 3개 이상이면 `// given` `// when` `// then` 주석과 구역 사이 빈 줄을 둔다. 준비할
|
||||
것이 없으면 `// given`은 생략한다. `// when`은 정확히 하나다. 두 번 필요하면 테스트를 나눈다.
|
||||
예외 테스트는 `catchThrowable`로 when을 분리한다(기존 `assertThatThrownBy`는 손댈 때
|
||||
@@ -188,6 +203,9 @@ cd src
|
||||
./gradlew qualityCheck # SpotBugs + FindSecBugs (leaf check에는 없다)
|
||||
./gradlew ci # PR 게이트 = leaf check + architecture + quality
|
||||
./gradlew mainCheck # main 단계 = env 계약·전체 기동·public path·전송/메시징 레인·leaf 문서 대조 레인
|
||||
./gradlew integrationCheck # 실제 컨테이너 integration 레인 전체(main·nightly, Docker 필요)
|
||||
./gradlew performanceCheck # 부하·종료·자원 한계 레인(main·nightly)
|
||||
./gradlew verifyStrictLaneStages --dry-run # 모든 strict lane이 workflow가 실행하는 단계에 속하는지
|
||||
./gradlew verifyPublicPathSnapshot
|
||||
./gradlew :app-bootstrap:verifyEnvKeys
|
||||
```
|
||||
|
||||
@@ -30,11 +30,16 @@ If this summary drifts from `AGENTS.md`, `AGENTS.md` wins and this summary must
|
||||
and one test-lane mechanism (`strictTestLanes`). Feature-specific checks are the owning leaf's
|
||||
tests; a test that reads repository files declares them as that leaf's test `inputs`, and a test
|
||||
that compares a leaf with repository documents is a `mainStage()` lane (tag `document-contract`)
|
||||
in that leaf's `mainCheck`.
|
||||
in that leaf's `mainCheck`; a merge-blocking contract over non-document repository files is a
|
||||
pull-request lane whose inputs are exactly those files (app-bootstrap `repository-contract`).
|
||||
`TEST`/`ARCHITECTURE` lanes are cacheable; `INTEGRATION`/`SYSTEM`/`PERFORMANCE` and main-stage
|
||||
lanes rerun every time.
|
||||
- `verifyEnvKeys` stays an app-bootstrap task (owner decision 4); its implementation is build-logic's
|
||||
`ca.config-contract`. The `src/build-tools/` included build was emptied and removed.
|
||||
- `src/build.gradle`: the root lifecycle (`ci`, `mainCheck`, `releaseCheck` and the named
|
||||
repository-wide gates).
|
||||
- `src/build.gradle`: the root lifecycle (`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`,
|
||||
`releaseCheck` and the named repository-wide gates). `verifyStrictLaneStages --dry-run` (pull
|
||||
request) fails when a non-`explicitOnly` strict lane is in no stage a workflow executes, or a
|
||||
folded workflow `run:` block splits an option off its command.
|
||||
|
||||
Commit policy is `human-only`: agents do not stage, commit, amend, or push implementation changes.
|
||||
|
||||
@@ -124,15 +129,17 @@ Repository-wide questions have their own names: `architectureCheck` (dependency
|
||||
of domain-core/shared-contract/application-*, Git-carryable sources, ArchUnit), `qualityCheck`
|
||||
(SpotBugs, FindSecBugs), `configContractCheck` (the environment contract), `integrationCheck` (the
|
||||
declared strict integration lanes; a lane that needs an input the build was not given is left out
|
||||
and named). `ci` (pull request) is leaf checks (API surfaces included, owner decision 20) +
|
||||
architectureCheck + qualityCheck; `mainCheck` (main branch) is configContractCheck +
|
||||
and named), `performanceCheck` (the declared performance lanes; main and nightly). `ci` (pull
|
||||
request) is leaf checks (API surfaces included, owner decision 20) + architectureCheck +
|
||||
qualityCheck, and the workflow also runs `verifyStrictLaneStages --dry-run`; `mainCheck` (main branch) is configContractCheck +
|
||||
qualificationCheck + the sample web contract + the public-path snapshot + the transport and
|
||||
messaging qualification lanes + every leaf's `mainCheck` (document-contract lanes, MinIO lanes);
|
||||
`releaseCheck` is the tag-only checks: release provenance and the public-path snapshot.
|
||||
|
||||
Test-writing rules (behavior-sentence names that assert what they promise, given/when/then comments,
|
||||
one `// when`, one fake per port in the port owner's testFixtures, fake and adapter sharing one
|
||||
abstract contract test) are canonical in `AGENTS.md`.
|
||||
Test-writing rules (behavior-sentence names that assert what they promise, `@DisplayName` in Korean
|
||||
only when the name cannot say it (owner decision 5), given/when/then comments, one `// when`, one
|
||||
fake per port in the port owner's testFixtures, fake and adapter sharing one abstract contract test)
|
||||
are canonical in `AGENTS.md`.
|
||||
|
||||
Use public-path and env-key checks only when their surfaces changed. Full `test`, `check` or `ci`
|
||||
requires the controller's workflow authorization.
|
||||
|
||||
@@ -64,7 +64,7 @@ services:
|
||||
-Djava.rmi.server.hostname=127.0.0.1
|
||||
ports:
|
||||
- "8080:8080"
|
||||
- "9001:9001"
|
||||
- "127.0.0.1:9001:9001" # management — localhost only (07-13)
|
||||
- "127.0.0.1:9999:9999" # JMX — localhost only
|
||||
# No health check constraint in dev; let the app start at its own pace.
|
||||
healthcheck:
|
||||
|
||||
+13
-11
@@ -13,16 +13,16 @@
|
||||
|
||||
# The local MinIO runtime, used by the server and by the object-storage smoke client below.
|
||||
#
|
||||
# It is deliberately not the image the MinIO qualification lanes run. Those read their image from
|
||||
# src/adapter/outbound/objectstorage/src/test/resources/object-storage/minio-provider-evidence.json,
|
||||
# whose digest is the release the recorded findings (status UNSUPPORTED, the excluded create-only
|
||||
# profiles) were measured on. This one is a later release because the healthcheck runs `mc ready`
|
||||
# and the smoke script runs the bundled mc, and moving it onto the evidence release is unverified.
|
||||
# A local runtime is not evidence, so the two may differ; they must not be mistaken for each other.
|
||||
# It is the image the MinIO qualification lanes measured, by the same digest:
|
||||
# src/adapter/outbound/objectstorage/src/test/resources/object-storage/minio-provider-evidence.json
|
||||
# records it with the conditional-write findings, and ComposeMinioImageMatchesEvidenceTest in that
|
||||
# leaf fails when this default and the evidence disagree. Change both together.
|
||||
#
|
||||
# Both come from Docker Hub's minio/minio, which stopped serving it (review 05-09). LOCAL_MINIO_IMAGE
|
||||
# points this runtime at a mirror; the lanes take OBJECT_STORAGE_MINIO_IMAGE, digest-checked.
|
||||
x-local-minio-image: &local-minio-image "${LOCAL_MINIO_IMAGE:-minio/minio:RELEASE.2024-09-13T20-26-02Z}"
|
||||
# Source: pgsty/minio, a community fork on Docker Hub, after Docker Hub's minio/minio and quay.io
|
||||
# stopped serving MinIO images (review 05-09). cgr.dev/chainguard/minio measured the same but was
|
||||
# not chosen; the evidence file's rejectedCandidates says why. LOCAL_MINIO_IMAGE points this runtime
|
||||
# at a mirror; the lanes take OBJECT_STORAGE_MINIO_IMAGE, digest-checked.
|
||||
x-local-minio-image: &local-minio-image "${LOCAL_MINIO_IMAGE:-pgsty/minio@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372}"
|
||||
|
||||
services:
|
||||
# ---- PostgreSQL --------------------------------------------------------------
|
||||
@@ -217,7 +217,9 @@ services:
|
||||
profiles:
|
||||
- shared-infra
|
||||
- prod-smoke
|
||||
image: minio/mc:RELEASE.2024-09-16T17-43-14Z
|
||||
# The client from the same supplier as the server. cgr.dev/chainguard/minio-client was not used:
|
||||
# it has no shell, and the bootstrap below is a shell script.
|
||||
image: "${LOCAL_MINIO_MC_IMAGE:-pgsty/mc@sha256:ce62c9053c69ce12a527a322345b5ad9f44b5f8a7b8189f82e516f2e3f30f1d8}"
|
||||
depends_on:
|
||||
minio:
|
||||
condition: service_healthy
|
||||
@@ -428,7 +430,7 @@ services:
|
||||
- caskeleton-infra
|
||||
restart: "no"
|
||||
|
||||
# The server image, not the mc client image: minio/mc ships no sed, grep or cmp, and the round-trip
|
||||
# The server image, not the mc client image: the mc image ships no sed, grep or cmp, and the round-trip
|
||||
# client needs a digest tool. See infra/minio/smoke/object-storage-smoke.sh for how that went
|
||||
# unnoticed. The lane already pulls this image for the server itself.
|
||||
object-storage-smoke:
|
||||
|
||||
@@ -34,7 +34,7 @@ services:
|
||||
TZ: "UTC"
|
||||
LANG: "C.UTF-8"
|
||||
LC_ALL: "C.UTF-8"
|
||||
# fallback matches env-keys.yaml SSOT default (30s); base compose grace is 40s.
|
||||
# fallback matches env-keys.yaml SSOT default (30s); base compose grace is 60s.
|
||||
APP_SERVER_SHUTDOWN_TIMEOUT: "${APP_SERVER_SHUTDOWN_TIMEOUT:-30s}"
|
||||
APP_SERVER_SHUTDOWN: "graceful"
|
||||
# Database connection — points to the local `db` service below.
|
||||
|
||||
@@ -26,7 +26,6 @@ services:
|
||||
# generated file and injected an empty string — which the prod env validator then refused, for
|
||||
# the right reason, about a value the lane had actually supplied.
|
||||
APP_DATASOURCE_DDL_AUTO: "validate"
|
||||
APP_LOG_JSON_ENABLED: "true"
|
||||
APP_SECURITY_JWT_ISSUER: "http://keycloak:8080/realms/ca-skeleton"
|
||||
APP_SECURITY_JWT_AUDIENCE: "ca-skeleton-api"
|
||||
networks:
|
||||
|
||||
+15
-5
@@ -9,11 +9,17 @@
|
||||
# Graceful-shutdown sync table (feature-container-runtime-contract D5):
|
||||
# App shutdown timeout : 30s (APP_SERVER_SHUTDOWN_TIMEOUT — SSOT: docs/registries/
|
||||
# env-keys.yaml, owner feature-env-driven-runtime-configuration)
|
||||
# Async executor wait : 19s (AsyncExecutorConfig.AWAIT_TERMINATION_SECONDS)
|
||||
# Container preStop : 5s (handled by the orchestrator / stop_grace_period offset)
|
||||
# stop_grace_period : 40s (30s app drain + 5s preStop + 5s safety margin)
|
||||
# stop_grace_period : 60s (30s app drain + 19s async + 5s preStop + 6s safety margin)
|
||||
#
|
||||
# The drain and the async wait are consecutive, not concurrent: Spring finishes the lifecycle
|
||||
# phase (the web server's graceful drain) before it destroys the executor, which then waits for
|
||||
# its queue. A 40s grace let the container be killed 9s into that wait (07-07).
|
||||
# DeveloperExperienceContractTest fails when this value is below the sum.
|
||||
#
|
||||
# Ownership: env-driven-config owns the app shutdown *value* (30s); this contract owns the
|
||||
# *relationship* (stop_grace_period >= app timeout + preStop + margin). The grace is therefore
|
||||
# *relationship* (stop_grace_period >= app timeout + async wait + preStop + margin). The grace is therefore
|
||||
# sized UP to the env-keys SSOT value (30s) — you do not shrink the app drain window to fit an
|
||||
# arbitrary grace. This resolves the earlier 20s/35s drift, which had assumed an app-timeout
|
||||
# value this branch does not own (env-keys.yaml is the SSOT and sets 30s).
|
||||
@@ -49,7 +55,10 @@ services:
|
||||
required: false
|
||||
ports:
|
||||
- "${APP_SERVER_PORT:-8080}:8080"
|
||||
- "9001:9001"
|
||||
# Management (health, info, prometheus — answered without authentication) on loopback only:
|
||||
# published on every interface it reaches the whole LAN (07-13). The smoke lanes read it from
|
||||
# inside the container, so they need no host port at all.
|
||||
- "127.0.0.1:9001:9001"
|
||||
environment:
|
||||
TZ: "UTC"
|
||||
LANG: "C.UTF-8"
|
||||
@@ -85,8 +94,9 @@ services:
|
||||
mem_limit: 512m
|
||||
memswap_limit: 512m
|
||||
# ---- Graceful shutdown (D5) ---------------------------------------------
|
||||
# stop_grace_period = app drain (30s, env-keys SSOT) + preStop (5s) + margin (5s) = 40s.
|
||||
stop_grace_period: 40s
|
||||
# stop_grace_period = app drain (30s, env-keys SSOT) + async wait (19s) + preStop (5s)
|
||||
# + margin (6s) = 60s.
|
||||
stop_grace_period: 60s
|
||||
# ---- Health check -------------------------------------------------------
|
||||
# Targets the actuator readiness probe on the management port (9001).
|
||||
# The warning that used to stand here — that this probe would report UNHEALTHY until two
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
| --- | --- |
|
||||
| `adr/` | 아키텍처 결정 기록 |
|
||||
| `architecture/` | 공개 API 표면 스냅숏 |
|
||||
| `manual/` | 개발 매뉴얼: 새 기능을 만드는 순서와 판단 지점, 생성 명령(`scripts/new-feature.sh`) |
|
||||
| `evidence/` | 작업 단계별 증거·체크포인트 |
|
||||
| `registries/` | env 키·에러 코드·메트릭·헤더 등 레지스트리 SSOT |
|
||||
| `reviews/` | 모듈 코드 리뷰 결과 |
|
||||
|
||||
@@ -53,8 +53,10 @@ request takes it over with `GrpcOperationLedger.reclaimStale` — one conditiona
|
||||
`UPDATE … WHERE state = 'IN_PROGRESS' AND claimed_at < :cutoff`, so of two concurrent takeovers exactly
|
||||
one wins, the same shape as `reclaimFailed`. The TTL is the `claimTtl` argument of
|
||||
`GrpcIdempotencyInterceptor`, refused at construction when it is not longer than every keyed method's
|
||||
deadline. It is not a configuration key: the starter does not assemble the interceptor yet (03-11), so
|
||||
there is nothing for a key to configure.
|
||||
deadline. Since the 03-11 follow-up the starter assembles the interceptor when
|
||||
`app.grpc.platform.operation-ledger-enabled=true` and takes the TTL from
|
||||
`app.grpc.platform.operation-ledger-claim-ttl` (default 5m); a TTL the constructor refuses fails startup
|
||||
naming that key, and an enabled flag without a `GrpcOperationLedger` bean fails startup too.
|
||||
|
||||
The takeover is safe only because the commit is recorded in the mutation's own transaction: then a
|
||||
claim still `IN_PROGRESS` means the mutation never committed. An adopter that commits them separately
|
||||
@@ -65,7 +67,18 @@ method and not just its deadline.
|
||||
Rejected: an owner token with a heartbeat lease (the outbox lease model) — needed only when a keyed
|
||||
method can run longer than any fixed TTL; revisit when one exists. A sweeper job that deletes stale
|
||||
rows — it needs a scheduler this family does not have, and deleting a claim makes the next retry a
|
||||
fresh claim with no record that an attempt was abandoned. Retention of terminal rows is still open.
|
||||
fresh claim with no record that an attempt was abandoned.
|
||||
|
||||
**Finished rows are purged after a retention; in-progress rows never are** (03-10 follow-up).
|
||||
`GrpcOperationLedger.purgeCompletedBefore(cutoff, limit)` deletes at most `limit` `COMMITTED` or
|
||||
`FAILED_TERMINAL` rows that completed before the cutoff, oldest first — on PostgreSQL one bounded
|
||||
`DELETE … WHERE storage_key IN (SELECT … LIMIT … FOR UPDATE SKIP LOCKED)` served by the partial index
|
||||
of migration V002. `GrpcOperationLedgerRetention.purgeExpired(now)` applies
|
||||
`app.grpc.platform.operation-ledger-retention` (default 24h, the HTTP idempotency replay TTL) in
|
||||
batches. A retry after its record was purged is a fresh claim and runs again, so the retention must
|
||||
exceed the callers' retry window. The adopter schedules the purge; the starter assembles the policy
|
||||
only, because a scheduled bean would force a scheduler onto every deployment and the starter cannot
|
||||
know which replica should run it.
|
||||
|
||||
**A key reused for a different request is a caller error, not a duplicate.** The stored request
|
||||
fingerprint turns that into `FAILED_PRECONDITION` rather than silently returning the first request's
|
||||
|
||||
@@ -52,7 +52,6 @@ dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException
|
||||
dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchValue
|
||||
dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderFactory
|
||||
dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName
|
||||
dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderRequestRegistry
|
||||
dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException
|
||||
dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyPolicy
|
||||
dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCategory
|
||||
@@ -75,7 +74,6 @@ dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCacheKey
|
||||
dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCacheMetrics
|
||||
dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCachePolicy
|
||||
dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException
|
||||
dev.caskeleton.adapter.inbound.graphql.execution.GraphQlTimeoutPolicy
|
||||
dev.caskeleton.adapter.inbound.graphql.fetch.GraphQlFetchProfile
|
||||
dev.caskeleton.adapter.inbound.graphql.fetch.GraphQlFetchProfileClassifier
|
||||
dev.caskeleton.adapter.inbound.graphql.fetch.GraphQlFetchProfileName
|
||||
@@ -132,12 +130,14 @@ dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBatchLoaderRegistrar
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlCostBudgetHandler
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDataFetcherExceptionResolver
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDeadlineInstrumentation
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDocumentAuthorizationHandler
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionChain
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionContext
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionHandler
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionRequest
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlOperationSelectionHandler
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPerParentFetchInstrumentation
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformInstrumentation
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformWebInterceptor
|
||||
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPreparsedDocumentAdapter
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
# root yet.
|
||||
# Update only after review with:
|
||||
# ./gradlew :adapter:outbound:persistence-jpa:updateJpaApiSurface -PapproveJpaApiSurfaceChange
|
||||
# types: 166
|
||||
# types: 165
|
||||
dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName
|
||||
dev.caskeleton.adapter.outbound.persistence.api.capability.CapabilitySupport
|
||||
dev.caskeleton.adapter.outbound.persistence.api.capability.JpaCapability
|
||||
@@ -74,7 +74,6 @@ dev.caskeleton.adapter.outbound.persistence.experimental.schema.SchemaTenantRegi
|
||||
dev.caskeleton.adapter.outbound.persistence.experimental.schema.TenantMigrationStatus
|
||||
dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantAwareRepositoryGuard
|
||||
dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantContext
|
||||
dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId
|
||||
dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator
|
||||
dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping
|
||||
dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping
|
||||
|
||||
@@ -82,8 +82,6 @@ materialise a nameless client in every deployment, which the aggregate validatio
|
||||
| `max-idle-time` | `30s` | Idle eviction |
|
||||
| `max-life-time` | `5m` | Picks up DNS, load-balancer, and certificate changes |
|
||||
| `validate-after-inactivity` | `5s` | Stale and half-open detection |
|
||||
| `eviction-interval` | `15s` | Background cleanup |
|
||||
| `shutdown-timeout` | `5s` | Drain deadline before forced close |
|
||||
| `requires-route-pool` | `false` | Set when route-scoped limits are mandatory; the JDK transport then refuses the profile |
|
||||
| `requires-bounded-pending-queue` | `false` | Same, for a bounded pending queue |
|
||||
|
||||
@@ -94,14 +92,49 @@ materialise a nameless client in every deployment, which the aggregate validatio
|
||||
| `dns` | `300ms` | Hostname resolution |
|
||||
| `connect` | `500ms` | Socket connect |
|
||||
| `tls-handshake` | `1s` | TLS and ALPN |
|
||||
| `proxy-connect` | `500ms` | Proxy socket or CONNECT |
|
||||
| `request-write-idle` | `1s` | No progress writing the request |
|
||||
| `response-header` | `2s` | Until final response headers |
|
||||
| `read-idle` | `3s` | Between response chunks |
|
||||
| `total-call` | `4s` | The whole logical call, including retry backoff |
|
||||
|
||||
`total-call` must not be shorter than `connect` or `response-header`; the validator emits
|
||||
`INVALID_TIMEOUT_BUDGET` otherwise.
|
||||
`INVALID_TIMEOUT_BUDGET` otherwise. Every timeout above, and `pool.pending-acquire-timeout`, must be
|
||||
greater than zero (`TIMEOUT_NOT_POSITIVE`): both engines read zero as "wait forever".
|
||||
|
||||
`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).
|
||||
|
||||
### Removed settings
|
||||
|
||||
Six keys were removed because they were bound and reached no transport (review 2026-11-01 05-15).
|
||||
Setting one now fails startup with `HTTPCLIENT_UNKNOWN_SETTING` naming the key, instead of being
|
||||
accepted and ignored.
|
||||
|
||||
| Removed key | Why |
|
||||
|---|---|
|
||||
| `timeout.request-write-idle` | Neither engine can bound a blocking socket write |
|
||||
| `timeout.proxy-connect`, `proxy.connect-timeout` | The TCP connect to a proxy is governed by `timeout.connect` |
|
||||
| `pool.eviction-interval` | Apache's idle evictor runs at `max-idle-time` |
|
||||
| `pool.shutdown-timeout` | A retired runtime drains for `app.httpclient.rotation-drain-timeout` |
|
||||
| `observability.operation-name-required` | An operation name is mandatory in the API; the switch could only be true |
|
||||
|
||||
### `circuit-breaker`
|
||||
|
||||
What counts as a failure is fixed: a 5xx, 408 or 429 response — whether the call throws or returns
|
||||
it as a result — and every transport failure. Every other 4xx is a healthy answer. These settings
|
||||
only say how many failures, out of how many calls, open the circuit. Defaults are Resilience4j's own,
|
||||
which every profile ran with before the keys existed.
|
||||
|
||||
| Property | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `failure-rate-threshold` | `50` | Percent of failed calls in the window that opens the circuit, 1–100 |
|
||||
| `minimum-number-of-calls` | `100` | Calls recorded before the rate is evaluated; at most `sliding-window-size` |
|
||||
| `sliding-window-size` | `100` | The last N calls the rate is computed over (count-based) |
|
||||
| `wait-duration-in-open-state` | `60s` | How long an open circuit rejects before trial calls; positive |
|
||||
| `permitted-calls-in-half-open-state` | `10` | Trial calls while half-open; at least 1 |
|
||||
|
||||
An out-of-range value fails startup with `CIRCUIT_BREAKER_SETTING_INVALID`. The breaker belongs to
|
||||
the profile, not to a runtime generation, so a certificate rotation keeps its state.
|
||||
|
||||
### `redirect`, `request`, `response`
|
||||
|
||||
@@ -132,12 +165,12 @@ materialise a nameless client in every deployment, which the aggregate validatio
|
||||
| Property | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `policy` | `none` | Named policy for reporting |
|
||||
| `max-attempts` | `1` | Attempts, not retries |
|
||||
| `max-attempts` | `1` | Attempts, not retries; at most 5 (`RETRY_MAX_ATTEMPTS_EXCEEDED`) |
|
||||
| `base-backoff` | `50ms` | |
|
||||
| `max-backoff` | `200ms` | |
|
||||
| `jitter` | `FULL` | `NONE` \| `FULL` \| `DECORRELATED` |
|
||||
| `retry-after` | `HONOR` | `HONOR` \| `IGNORE` \| `CAP` |
|
||||
| `budget` | — | Shared token bucket name |
|
||||
| `budget` | — | Shared token bucket name. A retrying profile that names none gets its own bucket, with the same pool-derived capacity (`max-total-connections / 10`, at least 1, refilled each minute) |
|
||||
|
||||
### `tls`
|
||||
|
||||
@@ -158,9 +191,7 @@ materialise a nameless client in every deployment, which the aggregate validatio
|
||||
| `proxy.enabled` | `false` | |
|
||||
| `proxy.host` / `proxy.port` / `proxy.type` | — / `0` / `HTTP` | |
|
||||
| `proxy.credential-provider` | — | Proxy authentication is separate from target authentication |
|
||||
| `proxy.connect-timeout` | `500ms` | Recorded as its own metric |
|
||||
| `proxy.import-ambient-no-proxy` | `false` | Ambient `NO_PROXY` never widens a validated profile |
|
||||
| `observability.operation-name-required` | `true` | |
|
||||
| `observability.full-url-recording` | `false` | |
|
||||
| `observability.body-logging` | `false` | |
|
||||
|
||||
@@ -193,9 +224,16 @@ materialise a nameless client in every deployment, which the aggregate validatio
|
||||
`HTTP2_REQUIRED_TRANSPORT_UNSUPPORTED`, `POOL_ROUTE_EXCEEDS_TOTAL`,
|
||||
`TLS_PROTOCOL_SET_REQUIRED`,
|
||||
`RETRY_POLICY_CONTRADICTS_ATTEMPTS`, `FULL_URL_RECORDING_FORBIDDEN`, `BODY_LOGGING_FORBIDDEN`,
|
||||
`DNS_TIMEOUT_UNSUPPORTED`, `PROXY_CREDENTIAL_UNSUPPORTED`, `PROXY_AMBIENT_NO_PROXY_UNSUPPORTED`.
|
||||
`DNS_TIMEOUT_UNSUPPORTED`, `PROXY_CREDENTIAL_UNSUPPORTED`, `PROXY_AMBIENT_NO_PROXY_UNSUPPORTED`,
|
||||
`TIMEOUT_NOT_POSITIVE`, `RETRY_MAX_ATTEMPTS_EXCEEDED`, `CIRCUIT_BREAKER_SETTING_INVALID`,
|
||||
`HTTPCLIENT_UNKNOWN_SETTING`.
|
||||
|
||||
The last three name settings the platform binds but cannot yet honour. Neither the Apache classic
|
||||
`HTTPCLIENT_UNKNOWN_SETTING` covers a gap in the shared strict binder: Spring's unbound-key check
|
||||
stops at the first level under a list element, so `clients[0].timeout.<typo>` used to bind nothing
|
||||
and fail nothing. The platform now checks every key under `clients[N]` and `dynamic-targets[N]`
|
||||
against the settings records.
|
||||
|
||||
`DNS_TIMEOUT_UNSUPPORTED`, `PROXY_CREDENTIAL_UNSUPPORTED` and `PROXY_AMBIENT_NO_PROXY_UNSUPPORTED` name settings the platform binds but cannot yet honour. Neither the Apache classic
|
||||
client nor the JDK client exposes a DNS-resolution timeout, and no proxy-credential path exists, so
|
||||
a non-default value is refused rather than accepted and ignored. Leaving the defaults alone is
|
||||
unaffected — only a deliberate, unmet request fails.
|
||||
|
||||
@@ -57,10 +57,6 @@ fields:
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_POOL_MAX_LIFE_TIME
|
||||
- field: clients[N].pool.validate-after-inactivity
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_POOL_VALIDATE_AFTER_INACTIVITY
|
||||
- field: clients[N].pool.eviction-interval
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_POOL_EVICTION_INTERVAL
|
||||
- field: clients[N].pool.shutdown-timeout
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_POOL_SHUTDOWN_TIMEOUT
|
||||
- field: clients[N].pool.requires-route-pool
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_POOL_REQUIRES_ROUTE_POOL
|
||||
- field: clients[N].pool.requires-bounded-pending-queue
|
||||
@@ -71,10 +67,6 @@ fields:
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_TIMEOUT_CONNECT
|
||||
- field: clients[N].timeout.tls-handshake
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_TIMEOUT_TLS_HANDSHAKE
|
||||
- field: clients[N].timeout.proxy-connect
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_TIMEOUT_PROXY_CONNECT
|
||||
- field: clients[N].timeout.request-write-idle
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_TIMEOUT_REQUEST_WRITE_IDLE
|
||||
- field: clients[N].timeout.response-header
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_TIMEOUT_RESPONSE_HEADER
|
||||
- field: clients[N].timeout.read-idle
|
||||
@@ -123,8 +115,6 @@ fields:
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_RETRY_RETRY_AFTER
|
||||
- field: clients[N].retry.budget
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_RETRY_BUDGET
|
||||
- field: clients[N].observability.operation-name-required
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_OBSERVABILITY_OPERATION_NAME_REQUIRED
|
||||
- field: clients[N].observability.full-url-recording
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_OBSERVABILITY_FULL_URL_RECORDING
|
||||
- field: clients[N].observability.body-logging
|
||||
@@ -153,12 +143,20 @@ fields:
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_PROXY_TYPE
|
||||
- field: clients[N].proxy.credential-provider
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_PROXY_CREDENTIAL_PROVIDER
|
||||
- field: clients[N].proxy.connect-timeout
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_PROXY_CONNECT_TIMEOUT
|
||||
- field: clients[N].proxy.import-ambient-no-proxy
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_PROXY_IMPORT_AMBIENT_NO_PROXY
|
||||
- field: clients[N].experimental-acknowledgement
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_EXPERIMENTAL_ACKNOWLEDGEMENT
|
||||
- field: clients[N].circuit-breaker.failure-rate-threshold
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_CIRCUIT_BREAKER_FAILURE_RATE_THRESHOLD
|
||||
- field: clients[N].circuit-breaker.minimum-number-of-calls
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_CIRCUIT_BREAKER_MINIMUM_NUMBER_OF_CALLS
|
||||
- field: clients[N].circuit-breaker.sliding-window-size
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_CIRCUIT_BREAKER_SLIDING_WINDOW_SIZE
|
||||
- field: clients[N].circuit-breaker.wait-duration-in-open-state
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_CIRCUIT_BREAKER_WAIT_DURATION_IN_OPEN_STATE
|
||||
- field: clients[N].circuit-breaker.permitted-calls-in-half-open-state
|
||||
env: APP_HTTPCLIENT_CLIENTS_N_CIRCUIT_BREAKER_PERMITTED_CALLS_IN_HALF_OPEN_STATE
|
||||
- field: dynamic-targets[N].name
|
||||
env: APP_HTTPCLIENT_DYNAMIC_TARGETS_N_NAME
|
||||
- field: dynamic-targets[N].allowed-schemes[M]
|
||||
|
||||
@@ -33,15 +33,20 @@ upgraded to `NOT_SENT`, because that is exactly how a timeout becomes a duplicat
|
||||
`DefaultRetryEligibilityEngine` evaluates in this order, and a later rule can never re-enable
|
||||
something an earlier one forbade:
|
||||
|
||||
1. attempts exhausted → `RetryDenied.maxAttempts()`
|
||||
2. retry budget empty → `RetryDenied.budgetExhausted()`
|
||||
3. body not replayable → `RetryDenied.bodyNotReplayable()`
|
||||
4. first byte already delivered → `RetryDenied.responseAlreadyDelivered()`
|
||||
5. runtime draining → `RetryDenied.runtimeDraining()`
|
||||
6. remaining deadline below the minimum attempt budget → `RetryDenied.deadline()`
|
||||
7. permanent failure category → `RetryDenied.permanentFailure(...)`
|
||||
8. `SENT_NO_RESPONSE` on an operation that is not safely idempotent → `AmbiguousFailure`
|
||||
9. status- and failure-specific rules
|
||||
1. `SENT_NO_RESPONSE` on an operation that is not safely idempotent → `AmbiguousFailure`
|
||||
2. attempts exhausted → `RetryDenied.maxAttempts()`
|
||||
3. retry budget empty → `RetryDenied.budgetExhausted()`
|
||||
4. body not replayable → `RetryDenied.bodyNotReplayable()`
|
||||
5. first byte already delivered → `RetryDenied.responseAlreadyDelivered()`
|
||||
6. runtime draining → `RetryDenied.runtimeDraining()`
|
||||
7. remaining deadline below the minimum attempt budget → `RetryDenied.deadline()`
|
||||
8. permanent failure category → `RetryDenied.permanentFailure(...)`
|
||||
9. `PARTIAL_RESPONSE` on an operation that is not safely idempotent → `AmbiguousFailure`
|
||||
10. status- and failure-specific rules
|
||||
|
||||
Ambiguity comes first because it describes the outcome, not whether another attempt is allowed. It
|
||||
used to sit below the attempt check, so with the default `max-attempts: 1` a POST that timed out
|
||||
after it was sent reached the caller as an ordinary timeout (review 2026-11-01 05-14).
|
||||
|
||||
## Status rules
|
||||
|
||||
@@ -50,7 +55,7 @@ something an earlier one forbade:
|
||||
| 408 | retry inside deadline and budget |
|
||||
| 425 | at most one retry, first attempt only |
|
||||
| 429 | retry inside `Retry-After`, deadline, and budget |
|
||||
| 401 | one refresh-and-replay, safe replayable operations only |
|
||||
| 401 | one refresh-and-replay, safe replayable operations only. The credential is refreshed only once the retry is granted; a 401 that will not be replayed (one attempt, no budget, no deadline) leaves the token cache alone |
|
||||
| 500 | denied unless the upstream registered it as transient **and** the operation is safely idempotent |
|
||||
| 502, 503, 504 | retry for safely idempotent operations; ambiguous otherwise |
|
||||
| other 4xx | denied |
|
||||
@@ -63,6 +68,17 @@ effect, and reporting a plain failure would tell the caller the request did not
|
||||
be false. The caller reconciles, usually by querying the upstream or replaying with an idempotency
|
||||
key.
|
||||
|
||||
### Where the evidence comes from
|
||||
|
||||
Whether a failed request was sent is read from the stage the attempt reached and the engine's
|
||||
exception type. Apache reports the moment it starts writing the request onto an established
|
||||
connection (`RequestWriteSignal`), so a failure while leasing, resolving, connecting or completing
|
||||
the TLS handshake is `NOT_SENT` even when the engine throws a generic exception. Transports that
|
||||
cannot report that moment (JDK, Jetty) are treated as writing from the moment the engine is called,
|
||||
because guessing "not sent" is what turns a timeout into a duplicate payment. An HTTP/2
|
||||
`REFUSED_STREAM` frame is proof the peer processed nothing and is kept as `NOT_SENT` through
|
||||
exception mapping.
|
||||
|
||||
## Budget and backoff
|
||||
|
||||
Retry tokens come from a per-upstream token bucket sized as a fraction of real traffic, so a failing
|
||||
|
||||
@@ -7,7 +7,18 @@ Design §15-§20. What owns a transaction, what may be retried, and what must ne
|
||||
Repository adapters do not open transactions. The use case does, through `TransactionPort`,
|
||||
because the unit of work is a business decision and only the use case knows where it starts and
|
||||
ends. `SpringTransaction` is the only implementation: one pre-built `TransactionTemplate` per
|
||||
mode over Spring's `PlatformTransactionManager`, every mode pinned to `READ_COMMITTED`.
|
||||
mode over Spring's `PlatformTransactionManager`, every mode running at `READ_COMMITTED` and
|
||||
bounded in time.
|
||||
|
||||
- **Isolation** is pinned on the pool, not per transaction: the module defaults set
|
||||
`spring.datasource.hikari.transaction-isolation: TRANSACTION_READ_COMMITTED` and
|
||||
`HikariPoolConstraintValidator` refuses any other level. A template that names the level makes
|
||||
pgjdbc ask the server for it (`SHOW TRANSACTION ISOLATION LEVEL`) at every begin.
|
||||
- **Time bound**: `app.persistence-jpa.transaction.write-timeout` (`inWrite`, `inRootWrite`) and
|
||||
`read-timeout` (`inRead`), 30 s each by default; `inNew` is fixed at 30 s. Spring hands the
|
||||
remaining time to each statement, so the server cancels a slow statement or lock wait
|
||||
(`DB_QUERY_CANCELED`) and the connection returns to the pool. A unit of work that needs longer
|
||||
is usually a batch job that should be split, not a reason to raise the bound.
|
||||
|
||||
| Call | Propagation | When |
|
||||
|---|---|---|
|
||||
@@ -29,7 +40,8 @@ maximumPoolSize >= (concurrent_threads x (1 + max_requires_new_depth)) + 1
|
||||
## Nothing is retried by the port
|
||||
|
||||
`SpringTransaction` runs the action once. A failure rolls back and propagates, translated to
|
||||
the shared persistence error codes where the SQLSTATE is known. A caller that decides to retry must
|
||||
the shared persistence error codes where the SQLSTATE is known; a lost `@Version` race has no
|
||||
SQLSTATE and is reported as `DB_OPTIMISTIC_CONFLICT` (409). A caller that decides to retry must
|
||||
re-run the whole use case in a new transaction — never re-issue one statement — because an
|
||||
optimistic conflict or a serialization failure means the state the attempt computed against is no
|
||||
longer the committed state.
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
# 01. 생성 명령 — 새 기능 뼈대
|
||||
|
||||
## 핵심
|
||||
|
||||
`scripts/new-feature.sh <FeatureName>` 한 번으로 새 업무 기능의 뼈대가 계층 leaf 다섯 곳에 생긴다.
|
||||
만든 직후 그대로 PR 게이트(`ci`의 해당 leaf check)와 `architectureCheck`를 통과한다. 이 성질은
|
||||
`scripts/verify-feature-scaffold.sh`가 main 단계(`mainCheck`)에서 매번 확인한다.
|
||||
|
||||
```text
|
||||
scripts/new-feature.sh Invoice
|
||||
-> domain-core Invoice, InvoiceId, InvoiceIdFactory, InvoiceRepository, InvoiceInvariantException
|
||||
+ testFixtures: InMemoryInvoiceRepository, SequentialInvoiceIdFactory, InvoiceRepositoryContract
|
||||
-> application-core CreateInvoiceUseCase, GetInvoiceUseCase, command·query·view, InvoiceErrorCode, 예외 2개
|
||||
-> outbound:identifier UuidInvoiceIdFactory
|
||||
-> inbound:web InvoiceController (POST /invoices, GET /invoices/{id}), 요청·응답 DTO
|
||||
-> app-bootstrap InvoiceConfig + AutoConfiguration.imports 한 줄
|
||||
-> 각 leaf 테스트 불변식, id 문법, 유스케이스, 공유 계약, HTTP 계약, 조립 조건
|
||||
-> spotlessApply (이름 길이에 따라 Javadoc 줄바꿈이 달라져서)
|
||||
```
|
||||
|
||||
## 사용법
|
||||
|
||||
```bash
|
||||
scripts/new-feature.sh Invoice # /invoices, 권한 invoice:create
|
||||
scripts/new-feature.sh PurchaseOrder # /purchaseOrders, 권한 purchase-order:create
|
||||
scripts/new-feature.sh Person --path people # 복수형이 규칙대로 안 될 때
|
||||
scripts/new-feature.sh Invoice --no-format # Gradle 없이 파일만 (뒤에 spotlessApply 직접)
|
||||
```
|
||||
|
||||
| 입력 | 규칙 | 어디서 막나 |
|
||||
| --- | --- | --- |
|
||||
| 이름 | PascalCase, 영숫자 | 스크립트 |
|
||||
| 패키지 이름 | 이름을 소문자로(`purchaseorder`). Java 예약어·플랫폼 패키지(`operation`, `lock`, `cache`…)와 겹치면 거절 | 스크립트 |
|
||||
| HTTP 경로 | lowerCamel 복수형. AIP-122 모양 | 스크립트, `ForbiddenApiArchitectureTest.CONTROLLER_REQUEST_MAPPINGS_FOLLOW_AIP122` |
|
||||
| 이미 있는 파일·패키지 | 덮어쓰지 않고 멈춘다 | 스크립트 |
|
||||
|
||||
생성 뒤 확인:
|
||||
|
||||
```bash
|
||||
cd src
|
||||
./gradlew :domain-core:check :application-core:check :adapter:outbound:identifier:check \
|
||||
:adapter:inbound:web:check :app-bootstrap:check architectureCheck --console=plain
|
||||
```
|
||||
|
||||
## 만드는 것과 만들지 않는 것
|
||||
|
||||
| 만든다 | 만들지 않는다 | 이유 |
|
||||
| --- | --- | --- |
|
||||
| 도메인 모델·포트·불변식, 유스케이스 두 개(쓰기·읽기), id adapter, 컨트롤러, 조립, 테스트 | **저장 adapter**(JPA 엔티티·Spring Data·마이그레이션) | 저장소 종류(JPA/Mongo), 마이그레이션 위치·번호대, 실 DB 계약 lane은 서비스가 정한다(04장). 템플릿이 정하면 upstream과 병합 충돌이 나는 자리다 |
|
||||
| 권한 선언 `@RequiresPermission("<f>:create")` | 역할 → 권한 매핑 | 어떤 역할이 쓸 수 있는지는 서비스의 결정이다(07장). 매핑 전에는 쓰기가 모두 403 — 안전한 쪽 |
|
||||
| `<F>ErrorCode` enum | `docs/registries/error-codes.yaml` 행 | 그 registry는 템플릿 운영 코드 전용이다. 서비스 코드는 서비스 registry에(06장) |
|
||||
| 읽기 유스케이스 | 목록·수정·삭제 | 목록은 페이지·정렬·N+1 판단이, 수정은 동시성(버전) 판단이 필요하다(04장) |
|
||||
|
||||
저장 adapter가 없으면 `<F>Config`의 `@ConditionalOnBean(<F>Repository)`가 꺼져 있어 엔드포인트가
|
||||
**없다**. 반쯤 켜진 상태(엔드포인트는 있는데 저장이 안 됨)가 생기지 않는다.
|
||||
|
||||
생성 결과는 placeholder 필드 `name` 하나를 가진다. 기능의 실제 상태로 바꾸는 것이 첫 작업이다.
|
||||
|
||||
## 왕복 검사
|
||||
|
||||
```text
|
||||
verify-feature-scaffold.sh
|
||||
-> 작업 트리를 임시 디렉터리로 복사(추적 + 무시되지 않은 새 파일), git init
|
||||
-> new-feature.sh Invoice, new-feature.sh PurchaseOrder (한 단어 / 여러 단어)
|
||||
-> 생성 파일이 있는지 확인
|
||||
-> ./gradlew 5 leaf check + architectureCheck
|
||||
-> 각 leaf 테스트 결과에 생성된 테스트 클래스가 실행·통과로 남았는지 확인
|
||||
-> 임시 디렉터리 삭제
|
||||
```
|
||||
|
||||
- 루트 태스크 `verifyFeatureScaffold`(`src/build.gradle`)가 이 스크립트를 부르고 `mainCheck`에 들어
|
||||
있다. 중첩 Gradle 빌드라 PR 단계가 아니라 main 단계다.
|
||||
- 템플릿이나 템플릿이 기대는 규칙(ArchUnit, Error Prone, 포맷)이 바뀌어 생성물이 깨지면 여기서 빨강이 된다.
|
||||
- 생성된 테스트가 실행되지 않고 지나가는 일(빈 녹색)을 막으려고 결과 XML을 확인한다.
|
||||
|
||||
## 고른 형태와 버린 대안
|
||||
|
||||
| 형태 | 결정 | 이유 |
|
||||
| --- | --- | --- |
|
||||
| `scripts/`의 bash + 텍스트 템플릿(`scripts/feature-scaffold/templates/**/*.tmpl`) | **채택** | 개발자 도구는 `scripts/`에 둔다는 repo 관례(`ca.developer-bootstrap` 플러그인을 지우고 `scripts/bootstrap-local.sh`로 옮긴 것, `src/build-logic/README.md`). 템플릿이 실제 Java 파일 모양이라 리뷰가 쉽다. Gradle 설정 단계를 거치지 않아 빠르다 |
|
||||
| build-logic의 Gradle 태스크(`./gradlew newFeature -Pname=…`) | 버림 | build-logic은 빌드 규약·아키텍처 검사만 둔다(`CLAUDE.md` Gradle policy). 소스를 쓰는 태스크는 configuration cache·up-to-date와 맞지 않는다 |
|
||||
| 생성 대신 예시 기능을 커밋해 두고 복사 | 버림 | 복사본이 하나 더 생겨 규칙과 갈라진다. 이름 바꾸기를 사람이 손으로 한다 |
|
||||
| 왕복 검사를 JUnit 안에서 javac로 컴파일 | 버림 | Spotless·Error Prone·ArchUnit 전체를 다시 구현해야 하고, 실제 게이트와 다른 것을 검사하게 된다. 실제 Gradle 게이트를 그대로 돌리는 쪽을 골랐다 |
|
||||
| 생성 뒤 자동 `spotlessApply` | 채택(끄려면 `--no-format`) | google-java-format이 Javadoc을 이름 길이에 따라 다시 접는다. 템플릿만으로는 모든 이름에서 포맷 검사를 통과시킬 수 없다 |
|
||||
|
||||
## 생성 결과가 기대는 빌드 설정
|
||||
|
||||
생성물이 컴파일되려고 다음 의존이 미리 들어 있다(모두 registry가 허용한 edge).
|
||||
|
||||
| 파일 | 설정 | 왜 |
|
||||
| --- | --- | --- |
|
||||
| `src/domain-core/build.gradle` | `java-test-fixtures` | domain 소유 포트의 fake·계약이 포트 소유자 testFixtures에 있어야 한다(AGENTS.md 테스트 규칙 6) |
|
||||
| `src/application-core/build.gradle`, `src/adapter/inbound/web/build.gradle`, `src/app-bootstrap/build.gradle` | `testImplementation testFixtures(project(':domain-core'))` | 유스케이스·HTTP·조립 테스트가 그 fake를 쓴다 |
|
||||
| `src/adapter/inbound/web/build.gradle` | `implementation project(':domain-core')` | 컨트롤러가 경로 문자열을 도메인 id로 바꾼다 |
|
||||
| `src/adapter/outbound/identifier/build.gradle` | `implementation project(':domain-core')` | id adapter가 도메인 `IdFactory` 포트를 구현한다 |
|
||||
@@ -0,0 +1,143 @@
|
||||
# 02. 새 도메인·유스케이스 추가
|
||||
|
||||
## 핵심
|
||||
|
||||
안쪽 계층부터 바깥으로 만든다. 각 단계는 그 단계의 테스트까지 끝내고 다음으로 간다.
|
||||
생성 명령(01장)이 1~5단계의 뼈대를 만들고, 이 장은 각 단계에서 사람이 정할 것을 적는다.
|
||||
|
||||
```text
|
||||
1 domain-core ─▶ 2 application-core ─▶ 3 outbound adapter ─▶ 4 inbound adapter ─▶ 5 app-bootstrap
|
||||
모델·불변식 유스케이스·포트 저장·외부 연동 전송·DTO·오류 bean·조건·권한
|
||||
(Java만) (Java + 계약 타입) (Spring·JPA 등) (HTTP 등) (조립)
|
||||
```
|
||||
|
||||
바깥 계층은 안쪽을 알지만 안쪽은 바깥을 모른다. 그래서 안쪽부터 만들면 각 단계가 앞 단계만 보고
|
||||
컴파일된다. 한 단계가 다른 leaf나 계층을 고쳐야 하면 거기서 멈추고 설계를 다시 본다(`CLAUDE.md`
|
||||
Layer workflow).
|
||||
|
||||
## 0단계 — 배치를 정한다
|
||||
|
||||
먼저 03장으로 이 기능을 어디 둘지 정한다. 기본은 계층 leaf 안 `<feature>` 패키지다. 생성 명령은 이
|
||||
기본값만 만든다.
|
||||
|
||||
## 1단계 — domain-core: 모델과 불변식
|
||||
|
||||
만드는 것: aggregate(`@AggregateRoot`), id(`@ValueObject` record, `ResourceId`), id 생성 포트
|
||||
(`IdFactory` 상속), 저장 포트(`*Repository`), 불변식 예외(`Reason` enum).
|
||||
예: 생성 결과 `src/domain-core/src/main/java/dev/caskeleton/domain/<f>/`.
|
||||
|
||||
검사: `DomainPurityArchitectureTest`(Spring·JPA·전송 타입 금지, setter 비공개, 감사 필드 금지),
|
||||
`ForbiddenApiArchitectureTest.NO_LONG_ID_PK`.
|
||||
|
||||
### 판단: id를 누가 만드나
|
||||
|
||||
- **고르는 기준**: 클라이언트가 같은 요청을 다시 보낼 때 같은 리소스를 가리켜야 하는가.
|
||||
- **기본값**: 서버가 만든다. domain `XIdFactory extends IdFactory<XId>` + `adapter:outbound:identifier`
|
||||
구현. 문법은 id 값 객체 생성자에서 검사한다.
|
||||
- **예외**: 클라이언트가 자연 키(주문번호 등)를 주는 기능은 그 키를 id로 쓴다. 이때 중복은 DB 유일성
|
||||
제약이 막는다(04장). UUIDv7이 필요하면 `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/UuidWorkLogIdFactory.java`처럼 바꾼다.
|
||||
|
||||
### 판단: 불변식을 어디 두나
|
||||
|
||||
- **고르는 기준**: 규칙이 aggregate 하나의 상태만 보고 판정되는가.
|
||||
- **기본값**: aggregate 메서드·팩토리 안. 위반은 `XInvariantException(Reason)`.
|
||||
- **예외**: 둘 이상의 aggregate나 저장된 다른 행을 봐야 하는 규칙(중복 금지 등)은 유스케이스 + DB 제약.
|
||||
조회 후 insert만으로는 동시 요청에서 깨진다(04장).
|
||||
|
||||
### 판단: 저장 포트를 누가 소유하나
|
||||
|
||||
- **고르는 기준**: 포트가 aggregate 단위로 말하는가, 기술적 저장·조회인가.
|
||||
- **기본값**: aggregate를 통째로 저장·로드하면 domain 소유 `XRepository`.
|
||||
- **예외**: 읽기 모양이 aggregate와 다르면 application 소유 `XQueryPort` + projection(record).
|
||||
`QUERY_PORTS_DO_NOT_LEAK_DOMAIN_JPA_OR_WEB_TYPES`가 반환 타입을 검사한다. lease·claim 같은 기술
|
||||
저장은 application 소유 `*StorePort`. 이름 규칙의 정본은 `src/application-core/CLAUDE.md`.
|
||||
|
||||
## 2단계 — application-core: 유스케이스와 포트
|
||||
|
||||
만드는 것: command/query record, 유스케이스(쓰기 `CommandUseCase`, 읽기 `QueryUseCase`), 반환용 view
|
||||
record, 오류 코드 enum과 carrier 예외. 예: `src/application-core/src/main/java/dev/caskeleton/application/<f>/`.
|
||||
|
||||
필수 선언(ArchUnit이 강제, `ApplicationBoundaryArchitectureTest`):
|
||||
|
||||
- 모든 유스케이스에 `@UseCaseCapability(transactionMode, idempotency, repositoryAccess)`. 선언과
|
||||
실제 `TransactionPort` 호출이 맞아야 한다(`USE_CASE_CAPABILITY_MATCHES_TRANSACTION_PORT_BOUNDARY`).
|
||||
- 쓰기 유스케이스에 `@RequiresPermission("<resource>:<action>")`(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`).
|
||||
- 유스케이스 클래스는 `final`이 아니다. 권한 프록시가 하위 클래스를 만든다
|
||||
(`src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/authz/RequiresPermissionProxyabilityTest.java`).
|
||||
|
||||
### 판단: 트랜잭션 모양
|
||||
|
||||
- **고르는 기준**: 결과를 커밋 뒤에 내보내야 하는가, 호출자와 독립적으로 커밋해야 하는가.
|
||||
- **기본값**: 쓰기 `tx.inWrite`, 읽기 `tx.inRead`.
|
||||
- **예외**: 커밋 확인 뒤 결과를 노출해야 하면 `inRootWrite`(바깥 트랜잭션이 있으면 거부). 감사·보상만
|
||||
`inNew`(루프 안 금지). 외부 HTTP·메시지 발행은 트랜잭션 밖. 표: `src/application-core/CLAUDE.md`
|
||||
「Allowed transactional shapes」.
|
||||
|
||||
### 판단: 무엇을 반환하나
|
||||
|
||||
- **기본값**: application view record(`XView`). 전송 계층이 aggregate를 받지 않는다
|
||||
(`TypeBoundaryArchitectureTest.CONTROLLERS_DO_NOT_RETURN_DOMAIN_OR_ENTITY_TYPES`).
|
||||
- **예외**: 같은 leaf 안 다른 유스케이스가 aggregate를 이어 받아야 하면 aggregate를 반환해도 된다.
|
||||
컨트롤러는 그때도 응답 DTO로 바꾼다.
|
||||
|
||||
### 판단: 멱등성 선언
|
||||
|
||||
05장. 기본값 `NOT_IDEMPOTENT`(쓰기), `IDEMPOTENT`(읽기). 클라이언트가 재전송할 수 있는 결제·주문류
|
||||
쓰기는 `KEYED`.
|
||||
|
||||
## 3단계 — outbound adapter
|
||||
|
||||
만드는 것: 포트 구현. 생성 명령은 id adapter(`adapter:outbound:identifier/<f>/Uuid<F>IdFactory`)만
|
||||
만든다. 저장 adapter는 04장 순서로 직접 만든다.
|
||||
|
||||
필수: adapter는 포트 소유자 testFixtures의 `XRepositoryContract`를 실제 저장소로 상속하는 테스트를
|
||||
가진다(08장). 실 DB가 필요하면 strict lane(`integrationTest` 등)에 둔다.
|
||||
|
||||
## 4단계 — inbound adapter (HTTP)
|
||||
|
||||
만드는 것: 컨트롤러, 요청·응답 DTO. 예: `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/<f>/`.
|
||||
|
||||
- 컨트롤러는 변환만 한다: 요청 → command/query → 유스케이스 → `Envelope.ok(응답 DTO, ResponseMetaFactory.fromMdc())`.
|
||||
repository·엔티티 직접 사용 금지(`CONTROLLERS_DO_NOT_ACCESS_REPOSITORIES_OR_JPA_ENTITIES`).
|
||||
- 생성 201은 `Location` 헤더를 준다. 비동기 수락은 202(`DurableOperationController`).
|
||||
- 경로는 lowerCamel 복수형(AIP-122).
|
||||
- 실패는 던지기만 한다. `ApiErrorCarrier`를 전역 핸들러가 매핑한다(06장). 기능 전용 핸들러를 만들지 않는다.
|
||||
|
||||
### 판단: 입력 검증을 어디서 하나
|
||||
|
||||
- **고르는 기준**: 규칙이 도메인 규칙인가, wire 모양(형식·필수 키)인가.
|
||||
- **기본값**: 도메인 규칙은 aggregate가 한 번만 검사한다. DTO에 같은 규칙을 bean validation으로 또 쓰지
|
||||
않는다(두 벌이 갈라진다).
|
||||
- **예외**: 도메인이 볼 수 없는 wire 모양 — 크기 상한, 형식 패턴, 필수 키 — 은 DTO에
|
||||
`@NotNull`·`@Size`·`@Pattern`으로 둔다(`SubmitOperationHttpRequest`). 이것은 400 `VALIDATION_FAILED`로 나간다.
|
||||
|
||||
## 5단계 — app-bootstrap 조립
|
||||
|
||||
만드는 것: `@AutoConfiguration` 클래스 하나 + `AutoConfiguration.imports` 한 줄.
|
||||
예: `src/composition/durable-operation/src/main/java/dev/caskeleton/composition/operation/DurableOperationAutoConfiguration.java`.
|
||||
|
||||
- `@ConditionalOnBean(필요한 포트들)`: 포트 구현이 없으면 기능 전체가 없다.
|
||||
- 유스케이스는 `@Bean`으로 만든다. 직접 `new` 하면 권한 프록시가 없어 `@RequiresPermission`이 조용히
|
||||
빠진다.
|
||||
- 컨트롤러는 component scan이 아니라 `@Import`로 등록한다. scan은 `dev.caskeleton.bootstrap`만 본다
|
||||
(`CaSkeletonApplication`).
|
||||
- 포트 구현이 다른 자동 설정에서 오면 `afterName`으로 순서를 적는다. 안 적으면 조건이 그 bean을 못 본다.
|
||||
- 이벤트를 내면 계약 contribution도 `@Bean`으로 등록한다(09장).
|
||||
- 역할 → 권한 매핑을 `app.authz.role-permissions`에 더한다(07장).
|
||||
|
||||
## 6단계 — 공개 계약이 바뀌었으면 함께 고친다
|
||||
|
||||
| 바뀐 것 | 같이 할 것 |
|
||||
| --- | --- |
|
||||
| 새 공개 경로(인증 없이 열림) | `docs/security/public-paths-snapshot.txt`, `./gradlew verifyPublicPathSnapshot` |
|
||||
| 새 env 키 | `docs/registries/env-keys.yaml`, `./gradlew :app-bootstrap:verifyEnvKeys` |
|
||||
| 새 의존성 | lockfile 갱신(`./gradlew :<leaf>:resolveAndLockAll --write-locks`), `verifyDependencyLocks` |
|
||||
| 새 마이그레이션 | 04장 번호 규칙 |
|
||||
| 새 이벤트 계약 | 09장 |
|
||||
|
||||
## 지금 이해하면 되는 것
|
||||
|
||||
- 안쪽부터: domain → application → outbound → inbound → bootstrap.
|
||||
- 쓰기 유스케이스는 non-final + `@RequiresPermission` + bean. 셋 중 하나라도 빠지면 권한 검사가 없다.
|
||||
- 조립은 포트가 있을 때만 켜진다. 저장 adapter가 생기기 전 기능은 없는 상태다.
|
||||
- 같은 규칙을 두 곳에 쓰지 않는다. 도메인 규칙은 aggregate, wire 모양은 DTO.
|
||||
@@ -0,0 +1,73 @@
|
||||
# 03. 새 기능을 둘 곳 고르기
|
||||
|
||||
## 핵심
|
||||
|
||||
새 기능을 두는 모양은 셋이다. **업무 기능의 기본은 ① 계층 leaf 안 `<feature>` 패키지**다.
|
||||
선택해서 켜고 끄는 플랫폼 기능만 ② 별도 `application-*` leaf로 만든다. ③ 한 leaf 수직 슬라이스는
|
||||
지울 수 있는 샘플 전용이다. 생성 명령은 ①만 만든다.
|
||||
|
||||
```text
|
||||
① 계층 leaf 안 패키지 (기본)
|
||||
domain-core/.../domain/<f> -> application-core/.../application/<f> -> adapter:*/.../<f> -> app-bootstrap/.../autoconfigure/<f>
|
||||
|
||||
② 기능 전용 leaf (capability)
|
||||
application-<f> -> persistence-<f>, adapter:outbound:<f>, adapter:inbound:web-<f> -> composition:<f>-platform
|
||||
app-bootstrap/build.gradle 에 runtimeOnly 한 줄
|
||||
|
||||
③ 한 leaf 수직 슬라이스 (샘플 전용)
|
||||
sample-portfolio = domain + application + adapter + bootstrap 패키지
|
||||
```
|
||||
|
||||
## 기준표
|
||||
|
||||
| 질문 | ① 계층 leaf 패키지 | ② 기능 leaf | ③ 수직 슬라이스 |
|
||||
| --- | --- | --- | --- |
|
||||
| 서비스마다 켜고 끌 수 있어야 하나 | 아니오 | **예** | — |
|
||||
| 다른 서비스가 같은 기능을 라이브러리로 받나 | 아니오 | **예** | 아니오 |
|
||||
| 한 줄 지워 기능을 통째로 빼야 하나 | 아니오(패키지 삭제) | **예**(`runtimeOnly` 한 줄) | 예(leaf 삭제) |
|
||||
| leaf 단위 의존 방향 검사가 기능 안에도 걸리나 | 예(계층이 leaf) | 예 | **아니오**(ArchUnit 패키지 규칙에만 기댐) |
|
||||
| 고칠 공용 파일 | 없음(+ imports 한 줄) | `modules.json`, `settings.gradle` 매핑, `app-bootstrap/build.gradle`, lockfile | `modules.json` |
|
||||
| 예시 | 생성 명령 출력, `application-core/.../operation` | `application-notification`, `application-fileserver`, `application-objectstorage` | `sample-portfolio` |
|
||||
|
||||
### 판단: ①과 ② 중 무엇인가
|
||||
|
||||
- **고르는 기준**: 이 기능을 쓰지 않는 서비스(또는 같은 서비스의 다른 배포)가 있는가.
|
||||
- **기본값**: ①. 업무 기능은 그 서비스의 존재 이유라 끌 일이 없다. 파일 추가만으로 끝나고, leaf 경계
|
||||
검사가 계층마다 걸린다.
|
||||
- **예외**: ② — 여러 서비스가 쓰는 플랫폼 기능, 배포마다 켜고 끄는 기능, 자기 설정 prefix와 자기
|
||||
저장소를 가진 기능. 이때는 capability 완료 기준 7개를 모두 지킨다(`AGENTS.md`, 10장).
|
||||
- **다시 볼 조건**: 파생 서비스가 둘 이상 생겨 같은 업무 기능을 공유하거나, application-core 컴파일·테스트
|
||||
시간이 문제가 되면 ①을 ②로 옮긴다(리뷰 01 영역 5.2절).
|
||||
|
||||
### 판단: ③을 써도 되나
|
||||
|
||||
- **기본값**: 쓰지 않는다. ③은 leaf 하나가 모든 계층에 의존해서 leaf 단위 방향 검사가 기능 안에서는
|
||||
아무것도 막지 못한다.
|
||||
- **예외**: 통째로 지울 수 있어야 하는 샘플·데모. `sample-portfolio`가 그 예다. 샘플을 계층 leaf로 쪼개지
|
||||
않는 이유는 "leaf 하나 지우면 끝"이라는 성질을 지키려는 것이다.
|
||||
|
||||
## ① 안의 패키지 규칙
|
||||
|
||||
| 계층 | 패키지 | 하위 패키지 |
|
||||
| --- | --- | --- |
|
||||
| domain | `dev.caskeleton.domain.<f>` | fake·계약은 testFixtures `dev.caskeleton.domain.<f>.testkit` |
|
||||
| application | `dev.caskeleton.application.<f>` | 종류별 하위 패키지(`command`, `usecase`, `port`)를 만들지 않는다. 기능별 한 패키지(sample P30 결정과 같다) |
|
||||
| outbound | `dev.caskeleton.adapter.outbound.<leaf>.<f>` | |
|
||||
| inbound | `dev.caskeleton.adapter.inbound.web.<f>` | |
|
||||
| bootstrap | `dev.caskeleton.bootstrap.autoconfigure.<f>` | `@AutoConfiguration`만(`BOOTSTRAP_AUTOCONFIGURE_STEREOTYPES_ARE_AUTO_CONFIGURATIONS`) |
|
||||
|
||||
- `<f>`는 템플릿 플랫폼 패키지(`operation`, `outbox`, `lock`, `cache`, `idempotency`, `security`,
|
||||
`tenant`, `transaction`…)와 겹치지 않는다. 생성 명령이 막는다. 겹치면 upstream 템플릿을 받을 때 같은
|
||||
패키지 트리에서 병합 충돌이 난다.
|
||||
- 이름 규칙은 `src/application-core/CLAUDE.md` 「Naming convention」이 정본이다.
|
||||
|
||||
## 저장 adapter는 어디에
|
||||
|
||||
① 기능의 저장 adapter 위치는 04장 「판단: 저장 adapter를 둘 leaf」. 요약: persistence-jpa에 업무 코드를
|
||||
넣지 않는다(그 leaf는 capability라 "모듈을 아는 곳은 모듈 자신뿐" 규칙이 걸린다).
|
||||
|
||||
## 지금 이해하면 되는 것
|
||||
|
||||
- 업무 기능 = ① 계층 leaf 패키지. 생성 명령이 이 모양을 만든다.
|
||||
- 켜고 끄는 플랫폼 기능 = ② 별도 leaf, capability 기준 7개.
|
||||
- sample-portfolio는 기법 참고용이지 배치 예시가 아니다.
|
||||
@@ -0,0 +1,126 @@
|
||||
# 04. 영속성
|
||||
|
||||
## 핵심
|
||||
|
||||
저장 adapter는 생성 명령이 만들지 않는다. 이 장의 순서로 만든다. 세 가지를 지킨다.
|
||||
|
||||
1. 엔티티 연관관계는 한쪽에서만 맵핑한다. 빌드가 막는다.
|
||||
2. 중복·경쟁은 코드 순서가 아니라 **DB 제약**이 막고, 위반은 기능의 오류로 바꾼다.
|
||||
3. 마이그레이션은 템플릿 운영 스트림과 **번호가 겹치지 않는 자기 스트림**에 둔다.
|
||||
|
||||
```text
|
||||
use case ── tx.inWrite ──▶ XRepository (domain 포트)
|
||||
│
|
||||
▼
|
||||
JpaXRepository (adapter) ── CallerTransaction.require
|
||||
│ 엔티티 ↔ aggregate 변환(mapper)
|
||||
▼
|
||||
Spring Data / EntityManager ──▶ PostgreSQL (제약·인덱스)
|
||||
│
|
||||
위반·장애 ──▶ PersistenceExceptionTranslator ──▶ OperationalError 또는 기능 예외
|
||||
```
|
||||
|
||||
## 순서
|
||||
|
||||
1. 계약 테스트부터: 생성된 `XRepositoryContract`(domain-core testFixtures)에 필요한 동작을 더한다.
|
||||
in-memory fake가 먼저 통과해야 한다.
|
||||
2. 마이그레이션을 쓴다(아래 번호 규칙).
|
||||
3. 엔티티·Spring Data repository·mapper·adapter를 쓴다. adapter는 aggregate만 주고받는다
|
||||
(`OUTBOUND_ADAPTER_METHOD_RETURNS_ONLY_DOMAIN_OR_PRIMITIVES`).
|
||||
4. `JpaXRepositoryContractTest extends XRepositoryContract`를 실 PostgreSQL lane에 둔다(08장 lane).
|
||||
예: `src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterContractTest.java`.
|
||||
5. adapter를 bean으로 등록하는 자동 설정을 쓰고, 기능의 `XConfig`에 `afterName`으로 그 순서를 적는다.
|
||||
|
||||
## 판단: 저장 adapter를 둘 leaf
|
||||
|
||||
- **고르는 기준**: upstream 템플릿 leaf에 서비스 코드가 섞이는가.
|
||||
- **기본값**: 서비스 전용 persistence leaf 하나(`adapter:outbound:persistence-<service>`)를 registry에
|
||||
등록하고 업무 기능의 adapter를 모두 거기 둔다. 모양은 `src/adapter/outbound/persistence-notification`
|
||||
(`persistence-jpa`에 의존, 자기 엔티티 scan·자기 Flyway 스트림·자기 자동 설정).
|
||||
- **예외**: 하나도 없다고 보는 편이 낫다. `persistence-jpa`에 업무 패키지를 넣으면 ① capability 규칙 7
|
||||
("모듈을 아는 곳은 모듈 자신뿐")을 어기고, ② 그 leaf의 공개 API 기준선
|
||||
(`docs/architecture/jpa-api-surface.txt`)과 엔티티 scan 목록(`PersistenceJpaConfig`,
|
||||
`PersistenceEntityScanCoverageTest`)을 고쳐야 하며, ③ upstream 병합 충돌 면이 넓어진다.
|
||||
sample은 자기 leaf 안에 adapter를 둔다(③ 수직 슬라이스라서).
|
||||
- 새 leaf는 `modules.json` 등록, lockfile 생성, `app-bootstrap/build.gradle` 한 줄이 필요하다(10장).
|
||||
|
||||
## 엔티티 매핑
|
||||
|
||||
정본: `docs/jpa/entity-mapping-guide.md`.
|
||||
|
||||
| 규칙 | 막는 곳 |
|
||||
| --- | --- |
|
||||
| 연관관계는 한쪽만. aggregate 사이는 id 참조, 같은 aggregate 안은 단방향 `@ManyToOne(LAZY)`, 컬렉션은 쿼리 | `JpaArchitectureRules.associationsAreMappedFromOneSideOnly()`(`src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRules.java`) — `JpaProductionArchitectureTest`가 운영 그래프 전체에 건다 |
|
||||
| 엔티티는 adapter 밖으로 나가지 않는다 | `PERSISTENCE_ENTITIES_STAY_INSIDE_A_PERSISTENCE_ADAPTER`, `noEntityFromWeb` |
|
||||
| `Long` id 금지, id 컬럼 `varchar(255)` 금지 | `NO_LONG_ID_PK`, `NO_VARCHAR_255_FOR_ID_COLUMN` |
|
||||
| 벤더 전용 `columnDefinition` 금지 | `PERSISTENCE_RDBMS_ENTITIES_DO_NOT_PIN_VENDOR_COLUMN_DEFINITIONS` |
|
||||
| 감사 필드는 엔티티에만, 도메인에는 없다 | `DOMAIN_ENTITIES_DO_NOT_CARRY_AUDIT_FIELDS` |
|
||||
|
||||
### 판단: 단방향 `@OneToMany(@JoinColumn)`을 써도 되나
|
||||
|
||||
- **기본값**: 쓰지 않는다. 자식 목록은 repository 쿼리(`findByParentId`, 페이지는 SQL에서).
|
||||
- **예외**: 루트만 바꾸는 자식(루트를 통해서만 생기고 지워짐). 규칙은 `mappedBy`만 막으므로 허용되지만
|
||||
nullable join column이면 자식마다 UPDATE가 한 번 더 나간다(가이드 「Associations」).
|
||||
|
||||
## 트랜잭션 안에서만 쓴다
|
||||
|
||||
store는 자기 트랜잭션을 열지 않는다. 유스케이스가 연 트랜잭션에 합류해야 하는 쓰기는 시작 전에
|
||||
`CallerTransaction.require("<무엇>")`
|
||||
(`src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CallerTransaction.java`)를
|
||||
부른다. 없으면 트랜잭션 밖 호출이 문장마다 따로 커밋되어, 같이 커밋돼야 할 행(업무 행 + outbox 행)이
|
||||
갈라진다.
|
||||
|
||||
## 중복·경쟁은 DB가 막는다
|
||||
|
||||
- **고르는 기준**: "같은 X가 둘 있으면 안 된다", "한 작업을 두 인스턴스가 집으면 안 된다" 같은 규칙인가.
|
||||
- **기본값**: DB 제약.
|
||||
- 중복 금지 → 유일성 제약/인덱스. 유스케이스의 사전 조회(`existsBy…`)는 빠른 거절일 뿐이다.
|
||||
READ COMMITTED에서 두 요청이 모두 "없음"을 보고 둘 다 insert한다.
|
||||
- adapter가 그 **이름 붙은 제약**의 위반만 잡아 기능 예외로 바꾼다. 다른 제약 위반은 그대로 둔다.
|
||||
예: `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapter.java`
|
||||
(`DataIntegrityViolationException` → 제약 이름 확인 → `PosterTitleAlreadyExistsException` 409),
|
||||
제약은 `src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql`.
|
||||
- 여러 인스턴스가 집는 작업 → `FOR UPDATE SKIP LOCKED`는 **트랜잭션 안에서**, 그리고 lease(만료 시각)와
|
||||
fence 값을 함께 저장한다. 예: `ReconciliationJobStorePort.claimDue`(application-notification),
|
||||
gRPC operation ledger의 claim.
|
||||
- 수정 충돌 → 버전 열(낙관적 잠금). 예: `UpdateWorkLogUseCase`의 version 비교와 `@Version`.
|
||||
- **예외**: DB가 볼 수 없는 규칙(외부 시스템 상태)은 분산 락(`DistributedLockPort`)이나 멱등성 키(05장).
|
||||
- 동시성 테스트는 실 DB lane에서 동시 요청 N개 → 행 1개를 단언한다(sample `integrationTest` 참고).
|
||||
|
||||
## 기술 실패는 공통 코드로 나간다
|
||||
|
||||
어떤 기능 예외로도 바꾸지 않은 DB 실패는 `PersistenceExceptionTranslator`
|
||||
(`src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java`)가
|
||||
SQLState로 `OperationalError`를 고른다. `DB_UNIQUE_VIOLATION` 409, `DB_SERIALIZATION_FAILURE`·`DB_DEADLOCK`
|
||||
409(retryable), 커밋 중 연결 끊김은 `DB_COMPLETION_UNKNOWN` 500(05장). 분류표는 이 한 곳이다. adapter가
|
||||
SQLState 표를 복사하지 않는다.
|
||||
|
||||
## 마이그레이션 번호
|
||||
|
||||
```text
|
||||
템플릿 운영 스트림 classpath:db/migration/postgresql V1 … V19 … (upstream이 계속 늘린다)
|
||||
capability 스트림 db/migration/jpa/<capability> 각자 history table
|
||||
샘플 스트림 db/sample-migration flyway_sample_schema_history
|
||||
서비스 스트림(권장) db/migration/<service> flyway_<service>_schema_history
|
||||
```
|
||||
|
||||
- **고르는 기준**: upstream 템플릿을 계속 받을 것인가.
|
||||
- **기본값**: 서비스 마이그레이션은 **자기 위치 + 자기 history table** 스트림에 둔다. 모양은
|
||||
`SamplePostgreSqlPersistenceConfig.sampleMigrationStrategy`
|
||||
(`src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SamplePostgreSqlPersistenceConfig.java`)와
|
||||
`NotificationSchemaStream`(persistence-notification). 그러면 번호가 템플릿 스트림과 독립이라 V1부터 쓴다.
|
||||
- **예외**: 템플릿 운영 스트림(`db/migration/postgresql`)에 직접 넣으면 upstream이 다음에 쓸 번호와
|
||||
겹친다. 어쩔 수 없으면 upstream이 쓰지 않을 큰 번호대를 정해 문서에 적는다.
|
||||
- 이미 적용된 파일은 고치지 않는다. 고치면 체크섬 불일치로 기동이 멈추고, `repair`는 쓰지 않는다
|
||||
(`docs/jpa/migration-guide.md`).
|
||||
- 같은 스트림 안에서 기존 두 버전 사이에 끼워야 하면 소수 버전(`V8_1`)을 쓴다. 샘플 테스트 일부가 운영
|
||||
스트림과 샘플 스트림을 한 목록으로 합치는데, 정수 V9 이상은 운영이 이미 쓰고 있어서 `V8_1`을 골랐다
|
||||
(리뷰 README 13.2, 09-02).
|
||||
- 기존 데이터가 새 제약을 어기면 마이그레이션이 이유를 남기고 멈추게 쓴다(`V8_1`의 `DO $$` 블록). 조용히
|
||||
지우지 않는다.
|
||||
|
||||
## 지금 이해하면 되는 것
|
||||
|
||||
- 저장 adapter는 서비스 전용 persistence leaf에. persistence-jpa에 업무 코드를 넣지 않는다.
|
||||
- 중복은 유일성 제약, 경쟁은 트랜잭션 안 claim + lease, 수정 충돌은 버전 열.
|
||||
- 마이그레이션은 자기 스트림(자기 history table). 적용된 파일은 고치지 않는다.
|
||||
@@ -0,0 +1,79 @@
|
||||
# 05. 멱등성·결과 불명 처리
|
||||
|
||||
## 핵심
|
||||
|
||||
쓰기 요청의 결과는 세 가지다: 됐다, 안 됐다, **모른다**. "모른다"를 "안 됐다(다시 해도 됨)"로 적으면
|
||||
같은 작업이 두 번 적용된다. 그래서 결과를 증명할 수 없을 때는 항상 "모른다"로 답하고, 클라이언트가
|
||||
안전하게 다시 물을 방법(같은 멱등성 키)을 준다.
|
||||
|
||||
```text
|
||||
클라이언트 ── POST + Idempotency-Key ──▶ 컨트롤러 ──▶ KEYED 유스케이스
|
||||
│ IdempotencyExecutor
|
||||
├─ 처음 본 키 → 실행 → 결과 저장 → 응답
|
||||
├─ 끝난 키 → 저장된 결과 재생
|
||||
├─ 실행 중 키 → 409 IDEMPOTENT_IN_FLIGHT (retryable, Retry-After 2)
|
||||
└─ 다른 본문 → 422 IDEMPOTENT_REQUEST_MISMATCH
|
||||
DB 커밋 중 연결 끊김 ─────────────────────────────────────▶ 500 DB_COMPLETION_UNKNOWN (retryable=false)
|
||||
```
|
||||
|
||||
정본: `docs/web/http-contract.md` 2절(wire 응답), `src/application-core/CLAUDE.md` 「Idempotency (KEYED)」
|
||||
(executor 구조), `docs/adr/ADR-JPA-003-completion-unknown.md`(커밋 결과 불명).
|
||||
|
||||
## 판단: 이 쓰기를 KEYED로 만드나
|
||||
|
||||
- **고르는 기준**: 클라이언트가 응답을 못 받았을 때 다시 보내는가, 그리고 두 번 적용되면 피해가 있는가.
|
||||
- **기본값**: 생성·결제·주문·발송처럼 "두 번 = 피해"인 쓰기는 `KEYED`. 같은 입력이면 같은 결과인
|
||||
쓰기(상태를 X로 설정)는 `IDEMPOTENT`. 그 밖은 `NOT_IDEMPOTENT`(생성 명령의 기본값 — 바꿀지 여기서
|
||||
정한다).
|
||||
- **예외**: 자연 키가 있어 DB 유일성 제약이 중복을 막으면(04장) 키 없이도 두 번째 요청이 409로 끝난다.
|
||||
다만 그 409는 "이미 있음"이지 "첫 요청의 결과"가 아니다. 클라이언트가 첫 결과를 받아야 하면 KEYED.
|
||||
|
||||
### KEYED로 만드는 순서
|
||||
|
||||
1. `@UseCaseCapability(idempotency = Idempotency.KEYED)`.
|
||||
2. 유스케이스 본문을 `IdempotencyExecutor`로 감싼다. executor를 유스케이스가 만들지 않는다 —
|
||||
`composition:idempotency`가 한 번 만든다.
|
||||
3. scope digest(주체 + 키 + operation 코드의 HMAC)와 요청 fingerprint(SHA-256)를 유스케이스 밖(전송)에서
|
||||
만든다. 원본 키는 저장소에 닿지 않는다.
|
||||
4. 작업 결과를 `IdempotentAction.Outcome`(`Success` / `RetryableNoEffect` / `EffectUnknown`)으로 돌려준다.
|
||||
예외를 던지면 effect-unknown으로 센다.
|
||||
5. 저장소 provider를 고른다: `app.capabilities.idempotency.provider` = `postgresql` 또는 `redis`
|
||||
(기본 `disabled`). 운영에서 in-memory 금지.
|
||||
|
||||
예: `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/` 의
|
||||
`PosterImagePublicationController`(키 헤더 검증), 유스케이스 쪽은 sample `application/posterimage`.
|
||||
|
||||
## 클라이언트에게 무엇을 약속하나
|
||||
|
||||
| 응답 | 의미 | 클라이언트 행동 |
|
||||
| --- | --- | --- |
|
||||
| 409 `IDEMPOTENT_IN_FLIGHT`, `retryable=true`, `Retry-After: 2` | 같은 키가 아직 실행 중. 결과 불명 | **같은 키로** 기다렸다 재전송. 새 키 금지 |
|
||||
| 422 `IDEMPOTENT_REQUEST_MISMATCH` | 같은 키에 다른 본문 | 클라이언트 버그. 재전송 안 함 |
|
||||
| 503 `IDEMPOTENCY_UNAVAILABLE` | 실행 전 거부 | 같은 키로 나중에 |
|
||||
| 500 `IDEMPOTENCY_RECOVERY_REQUIRED` | 이전 시도 효과를 증명 못함 | 재전송·재실행 모두 위험. 업무 데이터로 확인 |
|
||||
| 500 `DB_COMPLETION_UNKNOWN`, `retryable=false` | DB 커밋 중 연결 끊김. 커밋됐을 수도 있음 | 키 없이 재시도 금지. KEYED면 같은 키로 재전송하면 서버가 판정 |
|
||||
|
||||
409를 `retryable=true`로 바꾼 이유(리뷰 02-01 결정): 같은 키 재전송은 서버가 안전하게 판정하므로 다시
|
||||
보내는 것이 맞고, 새 키로 보내면 서버가 막지 못한다. 짝 프론트 분류기도 이 표를 따른다.
|
||||
|
||||
## 결과 불명을 만드는 곳마다 같은 규칙
|
||||
|
||||
리뷰가 찾은 반복 원인 1번이 "결과 불명을 확실함으로 기록"이었다(05-01, 04-01, 06-01). 새 경계를
|
||||
만들 때 아래 질문에 답한다.
|
||||
|
||||
- **고르는 기준**: 실패한 호출이 **상대편에서 이미 효과를 냈을 수 있는가**.
|
||||
- **기본값**: 그럴 수 있으면 "결과 불명"으로 분류한다. 재시도 가능(`retryable=true`)으로 분류하지
|
||||
않는다. 근거 코드:
|
||||
- DB 커밋 중 끊김 → `DB_COMPLETION_UNKNOWN`
|
||||
(`src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java`)
|
||||
- 메시지 발행 응답 없음 → `OutboxPublishAmbiguousException`(application-core `outbox`)
|
||||
- 알림 발송 시작 뒤 crash → 재발송하지 않고 reconcile(application-notification evidence 모델)
|
||||
- **예외**: 요청이 상대에게 **도달하기 전**에 실패한 것이 증명되면(연결 수립 실패, 실행 전 거부)
|
||||
재시도 가능이다. 반대 방향 실수(확실히 안 간 것을 불명으로)도 결함이다(리뷰 05-17).
|
||||
- 불명 상태를 푸는 방법(reconcile, 키 재전송, 운영자 확인)을 runbook에 적는다(`docs/runbooks/`).
|
||||
|
||||
## 지금 이해하면 되는 것
|
||||
|
||||
- "두 번 = 피해"인 쓰기는 KEYED. executor는 composition이 만든다.
|
||||
- 409 in-flight는 같은 키로 다시, 422는 버그, 500 completion-unknown은 키 없이 재시도 금지.
|
||||
- 상대편에 효과가 났을 수 있으면 "모른다"로 분류한다.
|
||||
@@ -0,0 +1,67 @@
|
||||
# 06. 오류 모델
|
||||
|
||||
## 핵심
|
||||
|
||||
실패마다 먼저 **클라이언트 탓인가 서버 탓인가**를 정한다. 클라이언트 탓이면 안정된 오류 코드를 가진
|
||||
예외를 던지고, 서버 탓이면 코드 없이 던진다. 어느 쪽이든 기능 코드는 던지기만 하고, 전송별 핸들러
|
||||
하나가 wire 모양으로 바꾼다.
|
||||
|
||||
```text
|
||||
domain XInvariantException(Reason) ← 코드 없음. domain-core는 shared-contract를 못 본다
|
||||
│ 유스케이스가 잡아서 감싼다
|
||||
application XRejectedException implements ApiErrorCarrier → XErrorCode.X_INVALID (VALIDATION, 400)
|
||||
XNotFoundException implements ApiErrorCarrier → XErrorCode.X_NOT_FOUND (NOT_FOUND, 404)
|
||||
│ 던진다
|
||||
web GlobalExceptionHandler: ApiErrorCarrier → errorCode() → status + Envelope{error{code, category, retryable}}
|
||||
gRPC/GraphQL/WebSocket: 같은 ApiErrorCarrier를 자기 status 모양으로
|
||||
```
|
||||
|
||||
정본: `src/shared-contract/src/main/java/dev/caskeleton/shared/error/ApiErrorCarrier.java`,
|
||||
`ApiErrorCode.java`, `OperationalError.java`, `docs/registries/error-codes.yaml`, wire 모양은
|
||||
`docs/web/http-contract.md` 1절(null 필드는 내보내지 않는다).
|
||||
|
||||
## 판단: 오류 코드를 어디에 두나
|
||||
|
||||
- **고르는 기준**: 같은 유스케이스를 여는 전송이 둘 이상이 될 수 있는가.
|
||||
- **기본값**: application 기능 패키지의 `XErrorCode implements ApiErrorCode` enum + 예외가
|
||||
`ApiErrorCarrier` 구현. 전송마다 핸들러를 만들 필요가 없다. 생성 명령 출력이 이 모양이다
|
||||
(`<F>ErrorCode`, `<F>NotFoundException`, `<F>RejectedException`).
|
||||
- **예외**: 한 전송에서만 의미가 있는 실패(HTTP 헤더 형식 등)는 그 전송 adapter에 둔다. sample은 기능
|
||||
코드를 web 패키지(`PortfolioErrorCode`, `DomainExceptionHandler`)에 두는데, 한 leaf 수직 샘플이라
|
||||
가능한 모양이다. 따라 하지 않는다.
|
||||
|
||||
## 판단: 어떤 예외 타입으로 던지나
|
||||
|
||||
| 상황 | 던질 것 | 결과 |
|
||||
| --- | --- | --- |
|
||||
| 도메인 불변식 위반 | domain `XInvariantException(Reason)` → 유스케이스가 `XRejectedException`으로 감쌈 | 400 기능 코드 |
|
||||
| 찾는 것이 없음 / 남의 것 | `XNotFoundException`(carrier) | 404. 남의 것도 404로 존재를 숨긴다(07장) |
|
||||
| 상태 충돌(이미 있음, 버전 불일치) | 기능 carrier(Category.CONFLICT, 409) | 409 |
|
||||
| 요청 파라미터 형식 오류(경로 id 문법 등) | `IllegalArgumentException` | 400 `BAD_PARAMETER` |
|
||||
| 서버 조립·설정 오류, 있을 수 없는 상태 | `IllegalStateException` | 500, 로그 남음 |
|
||||
| DB·외부 의존 실패 | adapter가 shared-contract carrier(`PersistenceFailureException`, `DependencyFailureException`)로 | 분류표대로(04·05장) |
|
||||
|
||||
- `IllegalArgumentException`을 "서버 조립이 틀렸다"에 쓰지 않는다. web은 그것을 로그 없이 400으로
|
||||
바꿔서 서버 결함이 클라이언트 오류로 숨는다(리뷰 01-04).
|
||||
- 메시지는 로그용이다. 클라이언트에는 코드와 category별 고정 문구(`ClientErrorMessages`)만 간다.
|
||||
메시지에 SQLState·내부 경로·토큰을 넣어도 클라이언트에 새지 않지만, 로그 정책은 지킨다.
|
||||
|
||||
## 판단: `retryable`을 무엇으로
|
||||
|
||||
- **기본값**: `false`. 기능 오류 대부분은 같은 요청을 다시 보내도 결과가 같다.
|
||||
- **예외**: 시간이 지나면 성공할 수 있고 **다시 보내도 안전한** 경우만 `true`(일시적 의존 실패,
|
||||
`IDEMPOTENT_IN_FLIGHT`). `true`인 코드는 runbook 링크가 필요하다(registry 규칙).
|
||||
|
||||
## 코드 등록
|
||||
|
||||
- 템플릿 운영 코드: `OperationalError` + `docs/registries/error-codes.yaml`을 같은 변경에서 고친다.
|
||||
`ErrorCodeRegistryMappingTest`(app-bootstrap)가 status 일치를 검사한다.
|
||||
- 서비스 기능 코드: 그 registry에 넣지 않는다(registry 머리말 "Product/fork ApiErrorCode enums own local
|
||||
registries"). 서비스 자기 registry를 만들고 같은 모양의 대조 테스트를 둔다. 예:
|
||||
`src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCodeRegistryMappingTest.java`.
|
||||
|
||||
## 지금 이해하면 되는 것
|
||||
|
||||
- 클라이언트 탓 = carrier 예외 + 기능 코드. 서버 탓 = `IllegalStateException`.
|
||||
- 기능 코드는 application에 두고, 전송 핸들러는 기능을 모른다.
|
||||
- `retryable=true`는 다시 보내도 안전할 때만.
|
||||
@@ -0,0 +1,74 @@
|
||||
# 07. 권한
|
||||
|
||||
## 핵심
|
||||
|
||||
권한 검사는 두 층이다. **"이 종류의 작업을 해도 되나"**(권한 이름)는 유스케이스의 `@RequiresPermission`
|
||||
선언과 web이 켜는 method security가 맡는다. **"이 객체를 봐도 되나"**(소유자·tenant)는 유스케이스가
|
||||
객체를 읽은 뒤 직접 판정한다.
|
||||
|
||||
```text
|
||||
요청 ─▶ 인증 필터(JWT 또는 세션) ─▶ AuthenticatedPrincipal(roles, tenant)
|
||||
─▶ 컨트롤러 ─▶ [프록시] RequiresPermissionAuthorizationManager
|
||||
│ role → permission (app.authz.role-permissions)
|
||||
│ 없으면 403, 인증 없으면 401
|
||||
─▶ 유스케이스 본문 ─▶ 객체 로드 ─▶ 소유자·tenant 판정 ─▶ 남의 것이면 404(존재 숨김)
|
||||
```
|
||||
|
||||
## 작업 단위 권한: `@RequiresPermission`
|
||||
|
||||
| 무엇 | 어디 |
|
||||
| --- | --- |
|
||||
| 선언 | `src/application-core/src/main/java/dev/caskeleton/application/security/RequiresPermission.java` — 쓰기 유스케이스에 필수(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`) |
|
||||
| 검사 장치 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/authz/MethodSecurityConfig.java`의 advisor |
|
||||
| 켜는 곳 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMethodSecurityAutoConfiguration.java` |
|
||||
| 역할 → 권한 | `app.authz.role-permissions` (`src/app-bootstrap/src/main/resources/config/security.yml`), 바인딩 `RolePermissionPolicy` |
|
||||
| 프록시 가능 | `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/authz/RequiresPermissionProxyabilityTest.java` |
|
||||
|
||||
검사 자동 설정은 인증 체인(`WebSecurityAutoConfiguration`)과 **분리**되어 있다. 서비스가 자기 인증
|
||||
방식으로 인증 체인을 바꿔도 권한 검사는 꺼지지 않는다(1라운드 07-03 수정).
|
||||
|
||||
### 지켜야 할 것 셋
|
||||
|
||||
1. 유스케이스는 **bean**이다. 직접 `new` 하면 프록시가 없어 선언이 주석이 된다.
|
||||
2. 유스케이스 클래스와 그 public 메서드는 **final이 아니다**. final이면 프록시를 못 만들어 기동이 실패한다.
|
||||
3. 유스케이스 안에서 자기 다른 메서드를 부르면(self-invocation) 프록시를 거치지 않는다. 권한이 다른 두
|
||||
작업은 유스케이스 둘로 나눈다.
|
||||
|
||||
### 판단: 권한 이름과 역할 매핑
|
||||
|
||||
- **고르는 기준**: 운영자가 따로 주고 뺄 필요가 있는 작업인가.
|
||||
- **기본값**: `<resource>:<action>`, resource는 kebab-case(`purchase-order:create`). 생성 명령은
|
||||
`<f>:create` 하나를 만든다. 역할 매핑은 권한을 명시적으로 나열한다(와일드카드 없음).
|
||||
- **예외**: 같은 역할이 항상 함께 가지는 작업은 한 역할에 여러 권한을 준다
|
||||
(`operation-submit: operation:submit,operation:cancel`).
|
||||
- 매핑하지 않은 권한은 아무도 갖지 않는다. 새 기능의 쓰기는 매핑 전까지 모두 403이다 — 실수로 열리지
|
||||
않는 쪽.
|
||||
- 읽기 유스케이스는 선언이 필수가 아니다. 인증된 누구나 읽으면 안 되는 데이터면 선언하거나 객체 판정을 둔다.
|
||||
|
||||
### 역할은 어디서 오나
|
||||
|
||||
JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `resource_access.<client>.roles`만
|
||||
읽는다. audience는 필수다(1라운드 02-03 수정). 같은 issuer의 다른 client가 같은 이름의 역할을 정의해도
|
||||
이 서비스 권한이 되지 않는다(`JwtToAuthenticatedPrincipalConverter`, `docs/runbooks/auth-audience-mismatch.md`).
|
||||
|
||||
## 객체 단위 권한
|
||||
|
||||
- **고르는 기준**: 같은 권한을 가진 두 사람이 같은 객체에 대해 다른 답을 받아야 하는가(소유자, tenant).
|
||||
- **기본값**: 유스케이스가 객체를 읽은 뒤 판정하고, 남의 것이면 **없는 것과 같은 404**로 답한다.
|
||||
존재 여부도 정보다. 예: `GetDurableOperationUseCase`와 `DurableOperationAccessPolicy`
|
||||
(`src/application-core/src/main/java/dev/caskeleton/application/operation/`).
|
||||
- **예외**: 여러 전송이 같은 판정을 써야 하거나 목록에서 한 번에 판정해야 하면
|
||||
`ObjectAccessPolicy`(`src/application-core/src/main/java/dev/caskeleton/application/security/ObjectAccessPolicy.java`,
|
||||
batch 메서드로 N+1 회피)를 구현한다. 존재를 숨길 필요가 없는 관리 화면은 403도 된다.
|
||||
- tenant: 인증 정보에서만 만든 `TenantId`를 command에 싣는다. 요청 본문의 tenant 값을 믿지 않는다.
|
||||
|
||||
## 지금 확인되지 않는 것
|
||||
|
||||
- web이 빠진 조립(gRPC 전용·배치 전용)에서는 advisor가 없어 선언이 검사되지 않는다. 이때 기동을 막는
|
||||
장치는 아직 없다(리뷰 01-06). web 없이 조립하는 서비스는 그 전에 이 문제를 먼저 푼다.
|
||||
|
||||
## 지금 이해하면 되는 것
|
||||
|
||||
- 쓰기 = `@RequiresPermission` + non-final + bean + 역할 매핑.
|
||||
- 객체 판정은 유스케이스 안, 남의 것은 404.
|
||||
- 역할은 자기 client 것만 읽는다.
|
||||
@@ -0,0 +1,80 @@
|
||||
# 08. 테스트 작성 규칙
|
||||
|
||||
## 핵심
|
||||
|
||||
테스트 규칙의 정본은 `AGENTS.md` 「테스트 전략」이다. 이 장은 새 기능을 만들 때 그 규칙이 **어떤
|
||||
파일 배치가 되는지**와 **어느 단계(PR/main/integration)에서 도는지**를 적는다.
|
||||
|
||||
```text
|
||||
포트 XRepository (domain-core)
|
||||
├─ testFixtures: InMemoryXRepository (fake, 포트당 하나)
|
||||
├─ testFixtures: XRepositoryContract (abstract, 약속 목록)
|
||||
├─ test: InMemoryXRepositoryContractTest extends XRepositoryContract → ci (leaf test)
|
||||
└─ 저장 adapter leaf integrationTest:
|
||||
JpaXRepositoryContractTest extends XRepositoryContract → integrationCheck (실 PostgreSQL)
|
||||
|
||||
유스케이스 테스트 = 실제 유스케이스 + InMemoryXRepository + DirectTransactionPort
|
||||
```
|
||||
|
||||
fake와 실제 adapter가 **같은 계약**을 통과해야 fake 위의 유스케이스 테스트가 거짓 녹색이 되지 않는다.
|
||||
생성 명령은 이 배치를 그대로 만든다(01장).
|
||||
|
||||
## 계층별 테스트
|
||||
|
||||
| 계층 | 테스트 | 쓰는 대역 | 예 (생성 결과) |
|
||||
| --- | --- | --- | --- |
|
||||
| domain | 순수 JUnit. 불변식·id 문법 | 없음 | `<F>Test`, `<F>IdTest` |
|
||||
| domain 포트 | 공유 계약 | fake | `InMemory<F>RepositoryContractTest` |
|
||||
| application | 유스케이스 흐름·트랜잭션 경계·오류 코드 | 포트 소유자 testFixtures의 fake, `DirectTransactionPort` | `Create<F>UseCaseTest` |
|
||||
| outbound adapter | 같은 공유 계약을 실제 저장소로 | Testcontainers(strict lane) | 04장 4번 |
|
||||
| inbound | HTTP status·Envelope·오류 코드 | 실제 유스케이스 + fake, standalone MockMvc | `<F>ControllerTest` |
|
||||
| bootstrap | 조립 조건(있을 때 켜짐, 없을 때 없음), imports 등록 | fake bean | `<F>ConfigTest` |
|
||||
|
||||
## 작성 규칙 요약 (정본은 AGENTS.md)
|
||||
|
||||
1. 이름은 lowerCamelCase 행동 문장. 이름이 말한 성질을 단언한다. 예: 이름에 "트랜잭션 전에"를 넣었으면
|
||||
트랜잭션이 없었다는 것도 단언하거나, 이름에서 뺀다.
|
||||
2. `@DisplayName`은 메서드 이름으로 못 쓰는 내용(숫자, 기호, 이유)이 있을 때만, **한국어**로
|
||||
(소유자 결정 5). 예: `@DisplayName("이름이 NAME_MAX_LENGTH + 1자이면 거절한다")`.
|
||||
3. 본문 3문장 이상이면 `// given` `// when` `// then`. `// when`은 하나. 예외는 `catchThrowable`로 분리.
|
||||
4. then은 when의 결과 하나만. 예외는 타입과 reason/code를 함께.
|
||||
5. 포트 대역은 hand-rolled fake 하나, **포트 소유 leaf의 testFixtures**에. Mockito는 프레임워크 경계와
|
||||
장애 주입만.
|
||||
|
||||
### 판단: fake가 어디 사나
|
||||
|
||||
- **고르는 기준**: 포트 인터페이스가 어느 leaf에 있나.
|
||||
- **기본값**: 그 leaf의 `src/testFixtures/java/.../<f>/testkit/`. domain 포트면 domain-core,
|
||||
application 포트면 application-core. 소비 leaf는 `testImplementation testFixtures(project(':<owner>'))`.
|
||||
- **예외**: 없다. 테스트 안 private fake는 계약 밖에 있어 실제와 갈라진다(리뷰 01-05의 lock fake).
|
||||
|
||||
## lane과 단계
|
||||
|
||||
`ci`(PR)의 leaf `test`는 Docker 없이 빠르게 끝나야 한다. 실 DB·실 서버가 필요한 테스트는 strict
|
||||
lane으로 선언하고 단계를 지정한다. 선언은 `ca.strict-test-lane`(`src/build-logic/README.md`).
|
||||
|
||||
| lane 종류 | 선언 | 도는 단계 |
|
||||
| --- | --- | --- |
|
||||
| 단위·slice | 기본 `test` | `ci` |
|
||||
| 문서 대조·느린 계약 | 태그 lane + `mainStage()` | `mainCheck` |
|
||||
| 실 DB·컨테이너 | `integration()` + 자기 sourceSet(예: `integrationTest`) | `integrationCheck` |
|
||||
| 성능·부하 | performance 범주 | `performanceCheck` |
|
||||
| 외부 입력 필요(자격증명 등) | `explicitOnly(reason)` | 어떤 집계에도 안 들어가고 이유가 출력된다 |
|
||||
|
||||
예: `src/sample-portfolio/build.gradle`의 `strictTestLanes { lane('integrationTest') { integration() … } }`,
|
||||
`src/app-bootstrap/build.gradle`의 `publicPathSnapshotTest`(`mainStage()`).
|
||||
|
||||
### 판단: 새 테스트를 어느 lane에
|
||||
|
||||
- **고르는 기준**: Docker·네트워크·실 서버가 필요한가, 몇 초 넘게 걸리는가.
|
||||
- **기본값**: 필요 없으면 `test`(ci). 필요하면 integration lane.
|
||||
- **예외**: 반드시 실행돼야 하는 소수 테스트(계약 자격 검사)는 `requires(클래스)` + `rejectSkipped = true`로
|
||||
이름을 박는다. 이름이 바뀌거나 지워지면 lane이 실패한다.
|
||||
- 새 lane이 어떤 단계에도 속하지 않으면 PR 게이트의 `verifyStrictLaneStages --dry-run`이 실패한다
|
||||
(1라운드 08-01). 단계는 집계 태스크(`integrationCheck` 등)를 통해 붙고, workflow 파일을 고치지 않는다.
|
||||
|
||||
## 지금 이해하면 되는 것
|
||||
|
||||
- fake와 계약은 포트 주인 testFixtures에, adapter는 같은 계약을 실제 저장소로.
|
||||
- `@DisplayName`은 꼭 필요할 때만, 한국어로.
|
||||
- Docker가 필요한 테스트는 strict lane + 단계 지정. 단계 없는 lane은 PR에서 막힌다.
|
||||
@@ -0,0 +1,73 @@
|
||||
# 09. outbox·이벤트
|
||||
|
||||
## 핵심
|
||||
|
||||
업무 저장과 이벤트 발행을 **같은 DB 트랜잭션**에 묶는다. 유스케이스는 broker에 직접 보내지 않고,
|
||||
이벤트를 outbox 테이블에 업무 행과 함께 쓴다. 별도 relay가 커밋된 outbox 행을 broker로 옮긴다.
|
||||
|
||||
```text
|
||||
use case ── tx.inWrite ─┬─▶ repository.save(aggregate) ┐ 한 커밋
|
||||
└─▶ OutboxAppendPort.append(validated) ┘
|
||||
▲
|
||||
IntegrationEventDraft ──▶ IntegrationEventEncoderPort (계약으로 검증·인코딩)
|
||||
|
||||
(커밋 뒤, 따로) composition:outbox-relay ─▶ OutboxStorePort.claim(lease) ─▶ broker ─▶ 완료/재시도/DEAD
|
||||
```
|
||||
|
||||
DB 저장과 broker 발행을 따로 하면(dual write) 둘 중 하나만 성공하는 순간이 생긴다. outbox는 그 순간을
|
||||
없앤다. 대가는 **적어도 한 번** 전달이다 — 소비자는 event id로 중복을 걸러야 한다.
|
||||
|
||||
정본: `src/application-core/CLAUDE.md`(이벤트 타입 표), `docs/messaging/outbox-inbox.md`,
|
||||
`docs/messaging/delivery-guarantees.md`.
|
||||
|
||||
## 순서
|
||||
|
||||
1. 계약을 정한다: 계약 id(`<service>.<aggregate>.<event>`), 버전, payload record, JSON schema 파일과 해시.
|
||||
예: `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedContractContribution.java`,
|
||||
`src/sample-portfolio/src/main/resources/contracts/messaging/portfolio.worklog.reserved/v1.schema.json`(+ `.sha256`).
|
||||
2. payload record(`IntegrationPayload`)를 만든다.
|
||||
3. 유스케이스의 `tx.inWrite` 안에서 저장 뒤 draft → encode → append. 예:
|
||||
`CreateWorkLogUseCase`(sample)와 그 헬퍼 `PortfolioEventOutbox`.
|
||||
4. 계약 contribution을 조립에서 `@Bean`으로 등록한다. encoder는 컨텍스트의 계약 bean으로 만들어진다.
|
||||
등록을 빠뜨리면 append 때 실패한다. 예: `DurableOperationAutoConfiguration.durableOperationSubmittedContract()`.
|
||||
5. 테스트: 계약 contribution 테스트(해시 고정), 유스케이스가 append했는지(`InMemoryOutboxStore`),
|
||||
소비자 중복 제거 계약(sample `WorkLogReservedConsumerDedupeContractTest`).
|
||||
|
||||
## 판단 지점
|
||||
|
||||
### 도메인 이벤트가 필요한가, 통합 이벤트만인가
|
||||
|
||||
- **고르는 기준**: 같은 서비스 안에서 이 사실에 반응하는 코드가 있는가.
|
||||
- **기본값**: 통합 이벤트만. 유스케이스가 저장 뒤 바로 payload를 만든다.
|
||||
- **예외**: aggregate 안에서 일어난 사실을 여러 유스케이스가 같은 방식으로 내보내면 domain
|
||||
`@DomainEvent` record를 두고 유스케이스가 그것을 payload로 옮긴다(sample `WorkLogReserved`).
|
||||
|
||||
### payload에 무엇을 넣나
|
||||
|
||||
- **기본값**: id만(+ 소비자가 라우팅에 필요한 최소 값). 상태 전체를 넣으면 계약이 aggregate 변경마다 깨진다.
|
||||
- **예외**: 소비자가 원 서비스를 다시 조회할 수 없는 경우(외부 파트너)는 필요한 상태를 넣고 버전을 올린다.
|
||||
|
||||
### event id·correlation·순서
|
||||
|
||||
- event id: UUIDv7, 소비자 중복 제거 키. 같은 작업의 재시도가 같은 event id를 내야 하면(durable
|
||||
operation) 작업 id에서 파생한다.
|
||||
- correlation: 요청의 correlation id가 문법에 맞으면 그것, 아니면 event id. 문법 밖 헤더가 업무 쓰기를
|
||||
실패시키면 안 된다.
|
||||
- aggregate 순서: aggregate에 version 열이 있으면 그것, 없으면 발생 시각(µs).
|
||||
- 이 규칙은 아직 기능마다 다시 쓴다(sample `PortfolioEventOutbox`). application-core 헬퍼로 올리는 일은
|
||||
리뷰 01-09 후속이다. 그 전까지는 위 세 규칙을 지킨다.
|
||||
|
||||
## relay와 실패
|
||||
|
||||
- relay는 `composition:outbox-relay`가 조립한다. 유스케이스로 만든 relay를 bean으로 등록하지 않는다
|
||||
(스케줄러 스레드에는 인증이 없어 권한 프록시가 매번 거부한다).
|
||||
- broker의 **재시도 가능한** 거부는 DEAD가 아니라 backoff 재시도다. broker가 멈춰도 대량 DEAD가 되지
|
||||
않는다(1라운드 06-01·06-03). 진짜 인증 오류도 재시도로 남으니 경보로 잡는다.
|
||||
- 발행 응답을 못 받으면 결과 불명(`OutboxPublishAmbiguousException`) — 05장 규칙과 같다.
|
||||
- 운영: `docs/runbooks/outbox-dead-letter.md`, `docs/runbooks/outbox-publish-failed.md`.
|
||||
|
||||
## 지금 이해하면 되는 것
|
||||
|
||||
- 저장과 append는 같은 `tx.inWrite` 안.
|
||||
- 계약(id·버전·schema·해시)을 먼저 정하고 계약 bean을 등록한다.
|
||||
- 전달은 적어도 한 번. 소비자는 event id로 중복을 거른다.
|
||||
@@ -0,0 +1,65 @@
|
||||
# 10. capability 추가·제거
|
||||
|
||||
## 핵심
|
||||
|
||||
JPA·Redis·Kafka·알림·파일 서버 같은 부가 기능은 **의존성 한 줄로 켜지고, 그 줄을 지우면 사라지는
|
||||
모듈**이다. 서비스는 `src/app-bootstrap/build.gradle`에서 필요한 모듈만 `runtimeOnly`로 고른다.
|
||||
기본 조립은 web, 운영 관측, cores, support/identifier뿐이다. JPA도 한 줄로 켠다.
|
||||
|
||||
```text
|
||||
app-bootstrap/build.gradle
|
||||
runtimeOnly project(':adapter:outbound:persistence-jpa') ← 이 한 줄
|
||||
│
|
||||
▼
|
||||
모듈의 META-INF/spring/...AutoConfiguration.imports → 자동 설정 → 포트 구현 bean
|
||||
│
|
||||
▼
|
||||
기능 XConfig의 @ConditionalOnBean(포트) → 유스케이스·엔드포인트가 켜진다
|
||||
```
|
||||
|
||||
정본: `AGENTS.md` 「부가 기능(capability) 모듈 규칙」(완료 기준 7개),
|
||||
`docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md`, 현황은 `docs/capability-status.md`.
|
||||
|
||||
## 켜기
|
||||
|
||||
1. `src/app-bootstrap/build.gradle`의 해당 `runtimeOnly` 줄 주석을 푼다.
|
||||
2. lockfile 갱신: `./gradlew :app-bootstrap:resolveAndLockAll --write-locks`, 확인
|
||||
`./gradlew verifyDependencyLocks`.
|
||||
3. 모듈 README의 env 키를 채운다. 키 목록 정본은 `docs/registries/env-keys.yaml`.
|
||||
4. 기본값은 `config/module-defaults/<모듈>.yml`에 이미 있다. 서비스 값만 덮어쓴다.
|
||||
5. `./gradlew :app-bootstrap:check architectureCheck`. 공개 경로가 생기면 `verifyPublicPathSnapshot`.
|
||||
|
||||
## 끄기
|
||||
|
||||
줄을 지우고 lockfile을 갱신한다. 그 모듈의 포트에 기대던 기능(`@ConditionalOnBean`)은 함께 꺼진다.
|
||||
기능이 꺼지면 안 되는데 꺼졌다면, 그 기능이 다른 구현을 가져야 한다는 신호다.
|
||||
|
||||
## 판단: 서비스 코드가 모듈 타입을 직접 불러도 되나
|
||||
|
||||
- **기본값**: 안 된다. 서비스 코드는 application-core 포트만 부른다. 그래야 `runtimeOnly`로 받을 수 있다.
|
||||
- **예외**: 라이브러리형 기능(모듈 타입을 상속·호출해야 하는 것)은 서비스의 adapter leaf에서만
|
||||
`implementation`으로 받는다. 예: 서비스 persistence leaf가 `persistence-jpa`의 감사 base 타입을 상속.
|
||||
|
||||
## 새 capability 모듈을 만들 때
|
||||
|
||||
03장에서 ②(기능 leaf)를 골랐을 때만 해당한다. 완료 기준 7개를 모두 지킨다.
|
||||
|
||||
| # | 기준 | 확인 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 서비스는 포트만 호출 | `runtimeOnly`로 컴파일되는가 |
|
||||
| 2 | 자기 `AutoConfiguration.imports`, 필요하면 `enabled` 스위치, 순서는 `afterName` | 모듈 자동 설정 테스트 |
|
||||
| 3 | 켜면 완전히 동작. 동작하지 않는 설정 키는 두지 않는다 | 설정 바인딩 테스트 |
|
||||
| 4 | 설정 prefix 하나(`app.<모듈>`), `StrictSettingsBinder`, 검증은 record compact constructor | |
|
||||
| 5 | 포트 계약 테스트를 fake와 실제 adapter가 모두 통과, 실 벤더(Testcontainers) 1개 이상 | strict lane(08장) |
|
||||
| 6 | README: 제공하는 것, 추가할 한 줄, env 키 | |
|
||||
| 7 | 이 모듈을 아는 곳은 모듈 자신뿐. bootstrap scan·스위치 목록에 등록하지 않는다 | 줄을 지우면 기능이 완전히 사라지는가 |
|
||||
|
||||
등록할 공용 파일: `src/config/architecture/modules.json`(leaf와 허용 edge), `src/settings.gradle`이 읽는
|
||||
디렉터리 매핑, app-bootstrap의 허용 edge, 새 leaf lockfile. registry가 허용하지 않은 edge는
|
||||
`architectureCheck`(의존 방향)가 막는다.
|
||||
|
||||
## 지금 이해하면 되는 것
|
||||
|
||||
- 켜기 = `runtimeOnly` 한 줄 + lockfile + env 키.
|
||||
- 서비스 코드는 포트만 부른다.
|
||||
- 새 capability는 완료 기준 7개. 업무 기능은 capability로 만들지 않는다(03장).
|
||||
@@ -0,0 +1,67 @@
|
||||
# 11. 체크리스트 — PR 올리기 전
|
||||
|
||||
빠진 것이 있으면 해당 장으로 돌아간다. 검사 명령은 `src/`에서 실행한다.
|
||||
|
||||
## 배치·이름
|
||||
|
||||
- [ ] 배치를 03장 기준표로 정했다(기본: 계층 leaf 안 `<feature>` 패키지).
|
||||
- [ ] 패키지 이름이 템플릿 플랫폼 패키지와 겹치지 않는다.
|
||||
- [ ] 이름이 `src/application-core/CLAUDE.md` 「Naming convention」을 따른다.
|
||||
|
||||
## domain
|
||||
|
||||
- [ ] 불변식은 aggregate 안에 있고, 위반은 `XInvariantException(Reason)`이다.
|
||||
- [ ] id 문법은 id 값 객체 생성자가 검사한다.
|
||||
- [ ] Spring·JPA·전송 타입을 import하지 않는다.
|
||||
|
||||
## application
|
||||
|
||||
- [ ] 모든 유스케이스에 `@UseCaseCapability`, 선언과 `TransactionPort` 호출이 맞다.
|
||||
- [ ] 쓰기 유스케이스: `@RequiresPermission`, non-final, bean으로 조립.
|
||||
- [ ] 외부 호출은 트랜잭션 밖이다.
|
||||
- [ ] 멱등성 선언을 05장 기준으로 골랐다(재전송될 쓰기는 `KEYED`).
|
||||
- [ ] 클라이언트 탓 실패는 carrier 예외 + 기능 코드, 서버 탓은 `IllegalStateException`.
|
||||
|
||||
## persistence
|
||||
|
||||
- [ ] 저장 adapter가 서비스 전용 persistence leaf에 있다(persistence-jpa 아님).
|
||||
- [ ] 연관관계는 한쪽만(`mappedBy` 없음).
|
||||
- [ ] 중복 규칙은 DB 유일성 제약이 막고, adapter가 그 제약 위반만 기능 예외로 바꾼다.
|
||||
- [ ] 여러 인스턴스가 집는 작업은 트랜잭션 안 claim + lease.
|
||||
- [ ] 마이그레이션은 자기 스트림(자기 history table)에 있고, 적용된 파일을 고치지 않았다.
|
||||
- [ ] adapter가 `XRepositoryContract`를 실 DB lane에서 상속한다.
|
||||
|
||||
## inbound
|
||||
|
||||
- [ ] 컨트롤러는 변환만 한다. repository·엔티티를 모른다.
|
||||
- [ ] 경로는 lowerCamel 복수형(AIP-122). 생성은 201 + `Location`.
|
||||
- [ ] 도메인 규칙을 DTO bean validation에 다시 쓰지 않았다.
|
||||
|
||||
## 조립·권한
|
||||
|
||||
- [ ] `XConfig`가 `@ConditionalOnBean(포트)`이고 imports에 한 줄 있다. 포트가 다른 자동 설정에서 오면 `afterName`.
|
||||
- [ ] 역할 → 권한 매핑을 `app.authz.role-permissions`에 더했다.
|
||||
- [ ] 객체 단위 판정이 필요하면 유스케이스 안에서 하고, 남의 것은 404.
|
||||
|
||||
## 이벤트
|
||||
|
||||
- [ ] 저장과 outbox append가 같은 `tx.inWrite` 안이다.
|
||||
- [ ] 계약 id·버전·schema·해시를 정했고 계약 bean을 등록했다.
|
||||
|
||||
## 테스트
|
||||
|
||||
- [ ] 포트마다 fake 하나와 공유 계약이 포트 소유 leaf testFixtures에 있다.
|
||||
- [ ] 이름은 행동 문장, `@DisplayName`은 필요할 때만 한국어, GWT 주석, `// when` 하나.
|
||||
- [ ] Docker가 필요한 테스트는 strict lane이고 단계가 있다.
|
||||
|
||||
## 검사
|
||||
|
||||
```bash
|
||||
./gradlew <owner-leaf>:check --console=plain # 건드린 leaf마다
|
||||
./gradlew architectureCheck --console=plain # leaf 경계를 넘었으면
|
||||
./gradlew verifyPublicPathSnapshot # 공개 경로가 바뀌었으면
|
||||
./gradlew :app-bootstrap:verifyEnvKeys # env 키가 바뀌었으면
|
||||
./gradlew verifyDependencyLocks # 의존성이 바뀌었으면
|
||||
```
|
||||
|
||||
- [ ] 실행한 명령과 결과를 PR 본문 「검증」에 적었다. 못 돌린 것은 이유와 함께 적었다.
|
||||
@@ -0,0 +1,82 @@
|
||||
# 개발 매뉴얼 — 이 템플릿으로 기능을 만드는 순서와 판단 지점
|
||||
|
||||
이 매뉴얼은 **새 업무 기능을 추가하는 사람**이 읽는다. 무엇을 어떤 순서로 만들고, 갈림길마다
|
||||
무엇을 기준으로 고르는지를 적는다. 규칙의 정본은 따로 있다. 이 매뉴얼은 그 정본을 **가리키고**
|
||||
작업 순서로 엮을 뿐, 규칙을 다시 쓰지 않는다(아래 「정본 위치」).
|
||||
|
||||
판단 지점은 모두 같은 틀로 적는다.
|
||||
|
||||
- **고르는 기준** — 무엇을 보고 고르는가
|
||||
- **기본값** — 기준이 애매하면 이것
|
||||
- **예외** — 기본값을 벗어나도 되는 경우와 그때 같이 해야 하는 것
|
||||
|
||||
근거는 코드 경로로 단다. 경로는 저장소 루트 기준이다.
|
||||
|
||||
## 읽는 순서
|
||||
|
||||
처음이면 1 → 2 → 3을 읽고 생성 명령을 한 번 돌려 본다. 그다음은 기능에 필요한 장만 읽는다.
|
||||
|
||||
| 장 | 언제 읽나 |
|
||||
| --- | --- |
|
||||
| [01. 생성 명령](01-generator.md) | 새 기능 뼈대를 만들 때. 무엇을 만들고 무엇을 안 만드는지 |
|
||||
| [02. 새 도메인·유스케이스 추가](02-new-feature.md) | 기능 하나를 domain → application → outbound → inbound → bootstrap 순서로 만들 때 |
|
||||
| [03. 새 기능을 둘 곳 고르기](03-placement.md) | 계층 leaf 안 패키지 / `application-*` capability / 별도 수직 중 고를 때 |
|
||||
| [04. 영속성](04-persistence.md) | 저장 adapter, 엔티티 매핑, DB 제약과 충돌 변환, 마이그레이션 번호 |
|
||||
| [05. 멱등성·결과 불명](05-idempotency.md) | 재시도될 수 있는 쓰기, 409/422, `DB_COMPLETION_UNKNOWN` |
|
||||
| [06. 오류 모델](06-errors.md) | 실패를 클라이언트 탓/서버 탓으로 나누고 코드로 내보낼 때 |
|
||||
| [07. 권한](07-authorization.md) | `@RequiresPermission`, 역할 매핑, 객체 단위 인가 |
|
||||
| [08. 테스트 작성 규칙](08-testing.md) | 포트당 fake, 공유 계약, 이름·주석, lane 단계 지정 |
|
||||
| [09. outbox·이벤트](09-outbox-events.md) | 저장과 함께 이벤트를 내보낼 때 |
|
||||
| [10. capability 추가·제거](10-capabilities.md) | JPA·Redis·Kafka 같은 부가 기능을 켜고 끌 때 |
|
||||
| [11. 체크리스트](11-checklist.md) | PR 올리기 전 |
|
||||
| [부록. 공통 원칙 후보](appendix-common-principles.md) | 프론트·백엔드 공통 실무 원칙으로 옮길 후보 |
|
||||
|
||||
## 정본 위치
|
||||
|
||||
매뉴얼과 정본이 다르면 정본이 맞다. 매뉴얼을 고친다.
|
||||
|
||||
| 무엇 | 정본 |
|
||||
| --- | --- |
|
||||
| 계층 경계·금지 규칙·테스트 작성 규칙 | `AGENTS.md`(요약은 `CLAUDE.md`) |
|
||||
| leaf 목록·허용 의존 | `src/config/architecture/modules.json` |
|
||||
| 이름 규칙(유스케이스·포트·command·query) | `src/application-core/CLAUDE.md` 「Naming convention」. 기계 검사는 `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java`와 `ApplicationBoundaryArchitectureTest.java` |
|
||||
| 유스케이스 모양·트랜잭션 모양 | `src/application-core/CLAUDE.md` 「Canonical use case shape」「Allowed transactional shapes」 |
|
||||
| HTTP wire 계약(Envelope·멱등성 응답) | `docs/web/http-contract.md` |
|
||||
| 운영 오류 코드 | `docs/registries/error-codes.yaml`, `src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java` |
|
||||
| 엔티티 매핑·마이그레이션 | `docs/jpa/entity-mapping-guide.md`, `docs/jpa/migration-guide.md`, `docs/jpa/transaction-guide.md` |
|
||||
| capability 완료 기준 7개 | `AGENTS.md` 「부가 기능(capability) 모듈 규칙」 |
|
||||
|
||||
이름 규칙은 위 한 곳에만 둔다. 이 매뉴얼과 생성 명령은 그 규칙을 **따른 결과**를 보여 줄 뿐이고,
|
||||
규칙 문장을 복사하지 않는다. 생성 명령의 템플릿(`scripts/feature-scaffold/templates/`)이 규칙과
|
||||
어긋나면 `scripts/verify-feature-scaffold.sh`가 ArchUnit으로 잡는다.
|
||||
|
||||
## 따라 할 예시는 하나
|
||||
|
||||
예시가 셋(sample-portfolio 수직, onboarding fixture, durable operation)이라 어느 것을 베끼느냐에 따라
|
||||
배치가 달라졌다(리뷰 2026-11-01 01-01·07-09). 이제 **새 업무 기능의 예시는 생성 명령의 출력 하나**다.
|
||||
|
||||
| 코드 | 역할 | 따라 하나 |
|
||||
| --- | --- | --- |
|
||||
| `scripts/new-feature.sh` 출력 | 계층 leaf에 나눈 업무 기능 | **이것을 따른다** |
|
||||
| `src/sample-portfolio` | 한 leaf에 모든 계층을 둔 지울 수 있는 샘플. 개별 기법(조건부 PATCH, 페이지, outbox, DB 유일성 제약)의 참고 | 기법만 본다. 배치는 따르지 않는다 |
|
||||
| `src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/**` | ArchUnit 규칙이 새 기능 모양에 적용되는지 확인하는 테스트 fixture | 따르지 않는다 |
|
||||
| `application-core/.../operation` + `DurableOperationAutoConfiguration`(composition:durable-operation) | 템플릿 플랫폼 기능 | 조립 모양(`@ConditionalOnBean` + 유스케이스 `@Bean`)만 본다 |
|
||||
|
||||
## 1라운드 수정으로 생긴 패턴 (리뷰 README 13절)
|
||||
|
||||
리뷰 뒤 1라운드에서 굳은 모양이다. 각 장에 반영했다.
|
||||
|
||||
| 패턴 | 근거 코드 | 장 |
|
||||
| --- | --- | --- |
|
||||
| Envelope는 null 필드를 내보내지 않는다 | `docs/web/http-contract.md` 1절 | 06 |
|
||||
| 처리 중 409 `IDEMPOTENT_IN_FLIGHT`는 `retryable=true` + `Retry-After: 2`, 같은 키로 재전송 | `docs/web/http-contract.md` 2절 | 05 |
|
||||
| 커밋 중 연결이 끊기면 재시도 가능이 아니라 결과 불명(`DB_COMPLETION_UNKNOWN`, 500) | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java`, `docs/adr/ADR-JPA-003-completion-unknown.md` | 05 |
|
||||
| 중복 규칙은 조회 후 insert가 아니라 DB 유일성 제약, 위반은 같은 409로 변환 | `src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql`, `PosterRepositoryAdapter` | 04 |
|
||||
| 여러 인스턴스가 집는 작업은 lease 있는 claim | `ReconciliationJobStorePort.claimDue`(application-notification) | 04 |
|
||||
| 양방향 연관관계 금지를 ArchUnit으로 | `JpaArchitectureRules.associationsAreMappedFromOneSideOnly()` | 04 |
|
||||
| store는 호출자 트랜잭션을 요구한다 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CallerTransaction.java` | 04 |
|
||||
| `@RequiresPermission` 검사는 인증 체인과 분리된 자동 설정 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMethodSecurityAutoConfiguration.java` | 07 |
|
||||
| JWT audience 필수, 자기 client role만 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfig.java`, `docs/runbooks/auth-audience-mismatch.md` | 07 |
|
||||
| strict lane은 반드시 어떤 단계에 속한다 | `verifyStrictLaneStages`(`src/build.gradle` `strictLaneStages`) | 08 |
|
||||
| 샘플 마이그레이션은 별도 history table, 번호는 운영과 겹치지 않게 | `SamplePostgreSqlPersistenceConfig`, `V8_1__…` | 04 |
|
||||
| 재시도 가능한 broker 거부는 DEAD가 아니라 재시도 | `docs/runbooks/outbox-dead-letter.md` | 09 |
|
||||
@@ -0,0 +1,20 @@
|
||||
# 부록. 프론트·백엔드 공통 원칙 후보
|
||||
|
||||
사용자 결정(2026-11-01): 프론트·백엔드에 공통인 실무 원칙은 `desktop-server-git/design-docs/`에 둔다.
|
||||
그 위치는 이 repo 밖이라 여기서 쓰지 않는다. 이 매뉴얼을 쓰며 나온 **후보만** 적는다. 옮길 때는 원칙
|
||||
문장만 옮기고, 이 repo의 장은 그 원칙을 가리키도록 바꾼다(두 벌을 두지 않는다).
|
||||
|
||||
| # | 후보 원칙 | 이 repo에서 드러난 곳 | 프론트 쪽 짝 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 결과를 증명할 수 없으면 "모른다"로 분류한다. "실패(재시도 가능)"로 적지 않는다 | 05장, `DB_COMPLETION_UNKNOWN`, outbox ambiguous | 요청 분류기의 timeout·네트워크 오류 처리 |
|
||||
| 2 | 같은 요청의 재전송은 같은 멱등성 키로. 새 키는 새 작업이다 | `docs/web/http-contract.md` 2절 | 재시도 정책, 409 in-flight 처리 |
|
||||
| 3 | 중복·경쟁은 저장소의 제약이 막는다. 앞선 조회는 빠른 거절일 뿐이다 | 04장 | 낙관적 UI 갱신과 서버 409 |
|
||||
| 4 | 같은 규칙을 두 곳에 쓰지 않는다. 쓸 수밖에 없으면 하나가 다른 하나를 검사한다 | DTO 검증 vs aggregate(02장), 오류 코드 registry 대조 테스트 | 폼 검증 스키마 vs 서버 검증 |
|
||||
| 5 | 실패는 클라이언트 탓/서버 탓으로 먼저 나누고, 클라이언트에는 안정된 코드만 보낸다 | 06장 | 오류 코드 → 화면 문구 매핑 |
|
||||
| 6 | 권한이 없으면 닫힌 쪽이 기본이다(매핑 전 403, 남의 것은 404) | 07장 | 권한 없는 메뉴·라우트 숨김과 서버 거절 |
|
||||
| 7 | 계약은 버전·schema·해시로 고정하고, 바꾸면 소비자 계약 테스트가 깨진다 | 09장, Envelope wire 테스트 | 응답 스키마 strict 파싱 |
|
||||
| 8 | 포트(경계)마다 대역 하나, 대역과 실제가 같은 계약 테스트를 통과한다 | 08장 | API mock과 실제 서버의 계약 테스트 |
|
||||
| 9 | 선택 기능은 한 줄로 켜고 한 줄로 끈다. 그 기능을 아는 곳은 자기 자신뿐이다 | 10장 | feature flag·라우트 모듈 |
|
||||
| 10 | 위험은 코드에 드러나야 한다: 의도한 제약·생략은 주석과 테스트 이름에 적는다 | 생성 명령 템플릿의 Javadoc(`NOT_IDEMPOTENT` 이유 등) | 같음 |
|
||||
| 11 | 게이트는 지우지 않고 단계를 지정한다(PR / main / nightly) | 08장 lane 단계, `verifyStrictLaneStages` | 프론트 CI 단계 |
|
||||
| 12 | 선택지가 여럿이면 고른 것·버린 것·이유를 남긴다 | 각 장의 「고른 형태와 버린 대안」 | 같음 |
|
||||
@@ -1,5 +1,10 @@
|
||||
# Outbox · Inbox
|
||||
|
||||
> **이 템플릿 application의 소비 경로**: application의 `MessageHandler`와 inbox 부품(애플리케이션
|
||||
> DataSource 위 `JdbcInboxRepository`, `PlatformTransactionManager` 위 `TransactionRunner`)은
|
||||
> `adapter:inbound:messaging`(`src/adapter/inbound/messaging/README.md`)이 둔다. platform starter는 두
|
||||
> bean이 있을 때 `IdempotentConsumer`를 만들어 `INBOX_TRANSACTIONAL` destination의 handler를 감싼다.
|
||||
|
||||
## 두 패턴이 각각 무엇을 해결하는가
|
||||
|
||||
| 패턴 | 해결하는 문제 | 해결하지 않는 문제 |
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
# Mongo 소비 leaf 등록 절차
|
||||
|
||||
파생 서비스가 `adapter:outbound:persistence-mongo`를 실제로 쓰려면 **자기 Mongo 어댑터 leaf**를 하나
|
||||
만든다. 이 leaf(이하 "플랫폼 leaf")는 client·template·정책·실패 분류를 주고, document·repository·
|
||||
mapper·port 구현은 서비스 leaf가 가진다. 플랫폼 leaf에는 예시 도메인을 production으로 넣지 않는다
|
||||
(`src/adapter/outbound/persistence-mongo/CLAUDE.md` "Forbidden").
|
||||
|
||||
전체 흐름:
|
||||
|
||||
```text
|
||||
domain-core (Note) application-core (NoteStore port)
|
||||
\ /
|
||||
adapter:outbound:persistence-note ← 서비스가 새로 만드는 leaf
|
||||
NoteDocument / NoteDocumentMapper / NoteDocumentRepository / MongoNoteStore
|
||||
|
|
||||
| implementation
|
||||
v
|
||||
adapter:outbound:persistence-mongo ← 플랫폼 leaf (executor, 실패 분류, 정책)
|
||||
^
|
||||
| runtimeOnly (둘 다)
|
||||
app-bootstrap
|
||||
```
|
||||
|
||||
## 1. 동작하는 예시
|
||||
|
||||
예시 한 벌이 플랫폼 leaf의 테스트 소스에 있다. `mongoStableContractTest`(그래서 `check`)에서
|
||||
컴파일되고 실행되므로 API가 바뀌면 예시도 같이 깨진다.
|
||||
|
||||
| 역할 | 예시 타입 | 실제 서비스에서 둘 곳 |
|
||||
| --- | --- | --- |
|
||||
| 도메인 타입 | `Note` | `domain-core` |
|
||||
| outbound port, 도메인 예외 | `NoteStore`, `NoteStore.NoteAlreadyExistsException` | `application-core` |
|
||||
| 저장 형태 | `NoteDocument` (`@Document`, `@Id`, `@Field`) | 서비스 Mongo leaf |
|
||||
| 변환 | `NoteDocumentMapper` | 서비스 Mongo leaf |
|
||||
| collection 접근 | `NoteDocumentRepository` (`DefaultMongoImperativeExecutor` 사용) | 서비스 Mongo leaf |
|
||||
| port 구현, 예외 변환 | `MongoNoteStore` | 서비스 Mongo leaf |
|
||||
| 실행 확인 | `MongoNoteStoreExampleTest` | 서비스 Mongo leaf 테스트 |
|
||||
|
||||
위치: `src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/`.
|
||||
|
||||
testFixtures가 아니라 테스트 소스에 둔 이유: testFixtures는 소비 leaf의 테스트 classpath에 그대로
|
||||
올라가는 variant다. 예시 타입이 거기 있으면 API처럼 import된다. 테스트 소스는 아무 데도 export되지 않는다.
|
||||
|
||||
## 2. 레지스트리와 Gradle에 leaf 등록
|
||||
|
||||
leaf 목록과 허용 의존 방향의 원본은 `src/config/architecture/modules.json`이다. 레지스트리에 없는 edge는
|
||||
`verifyCleanArchitectureDependencies`가 거부한다.
|
||||
|
||||
1. `modules.json`의 `modules`에 서비스 leaf를 추가한다. 플랫폼 leaf로 가는 edge를 여기서 연다.
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "adapter-outbound-persistence-note",
|
||||
"gradle_path": ":adapter:outbound:persistence-note",
|
||||
"source_path": "src/adapter/outbound/persistence-note",
|
||||
"allowed_dependencies": [
|
||||
"domain-core",
|
||||
"application-core",
|
||||
"adapter-outbound-persistence-mongo"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
같은 모양의 선례: `adapter-outbound-persistence-notification`이 `adapter-outbound-persistence-jpa`를
|
||||
같은 방식으로 받는다.
|
||||
|
||||
2. `app-bootstrap`의 `allowed_dependencies`에 `"adapter-outbound-persistence-note"`를 더한다.
|
||||
`adapter-outbound-persistence-mongo`는 이미 들어 있다.
|
||||
|
||||
3. 서비스 leaf의 `build.gradle`:
|
||||
|
||||
```groovy
|
||||
dependencies {
|
||||
implementation project(':domain-core')
|
||||
implementation project(':application-core')
|
||||
implementation project(':adapter:outbound:persistence-mongo')
|
||||
}
|
||||
```
|
||||
|
||||
4. `app-bootstrap/build.gradle`에서 두 leaf를 켠다. 플랫폼 leaf 줄은 주석으로 이미 있다.
|
||||
|
||||
```groovy
|
||||
runtimeOnly project(':adapter:outbound:persistence-mongo')
|
||||
runtimeOnly project(':adapter:outbound:persistence-note')
|
||||
```
|
||||
|
||||
5. 확인: `./gradlew :adapter:outbound:persistence-note:check architectureCheck --console=plain`.
|
||||
|
||||
## 3. 서비스 leaf가 등록해야 하는 bean
|
||||
|
||||
자동 구성되는 `MongoCollectionProfileRegistry`는 **비어 있다**. 등록하지 않은 collection profile로
|
||||
executor를 부르면 거부된다. 서비스 leaf가 자기 collection을 등록한 registry bean을 준다.
|
||||
|
||||
```java
|
||||
@Bean
|
||||
MongoCollectionProfileRegistry mongoCollectionProfileRegistry() {
|
||||
return MongoCollectionProfileRegistry.builder()
|
||||
.register(NoteDocument.COLLECTION, NoteDocument.COLLECTION)
|
||||
.build();
|
||||
}
|
||||
```
|
||||
|
||||
여러 서비스 leaf가 각자 collection을 가지면 registry bean은 하나여야 하므로 composition(보통
|
||||
`app-bootstrap`)에서 합친다.
|
||||
|
||||
`DefaultMongoImperativeExecutor`는 자동 구성 bean이다. 서비스 leaf는 그것을 주입받아
|
||||
`NoteDocumentRepository`처럼 감싼다.
|
||||
|
||||
## 4. 예외 변환
|
||||
|
||||
- executor는 driver·Spring 실패를 한 번만 플랫폼 예외로 바꾼다:
|
||||
`MongoDuplicateKeyException`, `MongoTimeoutException`, `MongoWriteConcernException`,
|
||||
`MongoServerSelectionException` 등(`dev.caskeleton.adapter.outbound.mongo.api.error`).
|
||||
- port 구현은 **port가 약속한 실패만** 도메인 예외로 바꾼다. 예시에서는
|
||||
`MongoDuplicateKeyException` → `NoteAlreadyExistsException` 하나다.
|
||||
- 나머지는 그대로 내보낸다. 플랫폼 예외는 `outcome()`·`ambiguous()`로 "쓰기가 됐는지 모름"을 알려
|
||||
준다. 이것을 일반 도메인 예외로 감싸면 호출자가 재시도해도 되는지 판단할 근거가 사라진다.
|
||||
- 트랜잭션은 `MongoTransactionRetryCoordinator`로 실행한다. 본문의 `TransientTransactionError`는 새
|
||||
세션에서 본문을 다시 실행하고, commit 결과를 모르면 commit만 재시도한 뒤
|
||||
`MongoTransactionCommitUnknownException`으로 알린다. 본문은 재실행될 수 있으므로 본문 안에서 외부
|
||||
호출(메시지 발행, HTTP)을 하지 않는다.
|
||||
|
||||
## 5. 정책을 우회하는 경로 — 쓰기 전에 알 것
|
||||
|
||||
| 경로 | 받는 것 | 잃는 것 |
|
||||
| --- | --- | --- |
|
||||
| `DefaultMongoImperativeExecutor` (+ `MongoAtomicOperationsTemplate`, `MongoBulkExecutor`) | operation 이름, collection profile 확인, consistency, deadline, 관측, 실패 변환 | 없음. 기본 경로 |
|
||||
| Spring Data `MongoRepository` (adapter-local) | 짧은 CRUD 코드 | 위 전부. 실패가 Spring `DuplicateKeyException` 등으로 온다. derived query는 `MongoQueryPolicy`를 거치지 않는다. deadline·consistency profile이 붙지 않는다 |
|
||||
| `MongoTemplate` / `MongoClient` 직접 주입 | 모든 명령 | 위 전부 + collection 범위 확인 |
|
||||
|
||||
- `MongoRepository`는 adapter leaf 안에서만 허용된다
|
||||
(`MongoRepositoryArchitectureRules.allowedRepositorySuperTypes`). 고르면 예외 변환과 timeout을 서비스
|
||||
leaf가 직접 책임진다. 플랫폼 공통 CRUD base(`CommonMongoRepository` 등)는 만들지 않는다.
|
||||
- 사용자 입력으로 조건이 바뀌는 **동적 조회**는 `PolicyAwareMongoQueryBuilder`(`MongoQueryPolicy`
|
||||
allowlist)로 만든다. 예시의 `_id` 조회처럼 adapter 코드가 고정한 조건은 `Query`를 직접 써도 된다.
|
||||
- inbound adapter(controller 등)는 `MongoTemplate`·`MongoClient`를 갖지 않는다. 서비스 leaf 테스트에서
|
||||
플랫폼 testFixtures의 `MongoAccessRules.noMongoAccessFrom(...)`으로 확인할 수 있다
|
||||
(`testImplementation testFixtures(project(':adapter:outbound:persistence-mongo'))`).
|
||||
|
||||
## 6. 연결 설정
|
||||
|
||||
URI만 주는 배포(`SPRING_MONGODB_URI`)는 유한 timeout·pool 기본값을 받는다. 값과 바꾸는 법은
|
||||
`src/adapter/outbound/persistence-mongo/README.md`의 `SPRING_MONGODB_URI` 예시 바로 아래 문단과 `MongoUriOnlyClientDefaults`에 있다.
|
||||
production은 typed profile(`app.persistence-mongo.platform.profiles.*`)을 쓴다.
|
||||
@@ -259,9 +259,9 @@ env_keys:
|
||||
|
||||
- name: APP_MULTI_INSTANCE_ENABLED
|
||||
# source: feature-env-driven-runtime-configuration D8 (2026-06-06)
|
||||
# When true, StartupSafetyValidator (SmartInitializingSingleton) requires the 5
|
||||
# instance-coordination beans (distributed lock / cache-stampede / outbox leader
|
||||
# / rate-limiter / migration runner) to be present, else startup fails. Consumed
|
||||
# When true, StartupSafetyValidator (a StartupRule, run before any other singleton)
|
||||
# requires a cross-instance DistributedLockPort bean named distributedLockProvider,
|
||||
# else startup fails (exit 72). Consumed
|
||||
# by feature-runtime-health-lifecycle-contract, feature-background-job-async-contract,
|
||||
# feature-cache-consistency-contract, feature-domain-event-outbox-contract,
|
||||
# feature-rate-limit-idempotency-contract, feature-migration-startup-contract.
|
||||
@@ -2587,6 +2587,11 @@ env_keys:
|
||||
required_test: cache-contract:redis-soft-hard-ttl-order
|
||||
|
||||
- name: APP_CACHE_REDIS_TTL_JITTER
|
||||
# DEPRECATED 2026-11-02: no settings class binds it. Its only reader was a block in
|
||||
# sample-portfolio's application.yml that nothing bound either (07-10), removed with it.
|
||||
# Kept so a deployment still setting it is told it does nothing.
|
||||
deprecated_orphaned: true
|
||||
removal_deadline: 2027-02-28
|
||||
type: float
|
||||
default: 0.10
|
||||
allowed_values: null
|
||||
@@ -3710,7 +3715,7 @@ env_keys:
|
||||
property: spring.jpa.properties.hibernate.jdbc.batch_size
|
||||
owner_module: adapter-outbound-persistence-jpa
|
||||
type: integer
|
||||
default: 0
|
||||
default: 50
|
||||
allowed_values: null
|
||||
classification: public-config
|
||||
required: false
|
||||
@@ -3718,14 +3723,14 @@ env_keys:
|
||||
reload_policy: restart-only
|
||||
owner_branch: 2026-09-22-persistence-jpa-review-remediation
|
||||
validation: non_negative_integer
|
||||
compatibility_impact: additive
|
||||
compatibility_impact: behavior-change
|
||||
required_test: jpa-contract:hibernate-runtime-settings
|
||||
|
||||
- name: APP_JPA_HIBERNATE_ORDER_INSERTS
|
||||
property: spring.jpa.properties.hibernate.order_inserts
|
||||
owner_module: adapter-outbound-persistence-jpa
|
||||
type: boolean
|
||||
default: false
|
||||
default: true
|
||||
allowed_values: [true, false]
|
||||
classification: public-config
|
||||
required: false
|
||||
@@ -3733,14 +3738,14 @@ env_keys:
|
||||
reload_policy: restart-only
|
||||
owner_branch: 2026-09-22-persistence-jpa-review-remediation
|
||||
validation: boolean_strict
|
||||
compatibility_impact: additive
|
||||
compatibility_impact: behavior-change
|
||||
required_test: jpa-contract:hibernate-runtime-settings
|
||||
|
||||
- name: APP_JPA_HIBERNATE_ORDER_UPDATES
|
||||
property: spring.jpa.properties.hibernate.order_updates
|
||||
owner_module: adapter-outbound-persistence-jpa
|
||||
type: boolean
|
||||
default: false
|
||||
default: true
|
||||
allowed_values: [true, false]
|
||||
classification: public-config
|
||||
required: false
|
||||
@@ -3748,7 +3753,7 @@ env_keys:
|
||||
reload_policy: restart-only
|
||||
owner_branch: 2026-09-22-persistence-jpa-review-remediation
|
||||
validation: boolean_strict
|
||||
compatibility_impact: additive
|
||||
compatibility_impact: behavior-change
|
||||
required_test: jpa-contract:hibernate-runtime-settings
|
||||
|
||||
- name: APP_JPA_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE
|
||||
@@ -3920,6 +3925,81 @@ env_keys:
|
||||
compatibility_impact: behavior-change
|
||||
required_test: websocket-contract:canonical-property-namespace
|
||||
|
||||
- name: APP_WEBSOCKET_MESSAGE_SIZE_LIMIT
|
||||
# Spring's own default, now explicit (review 03-06); at most 2147483647 bytes.
|
||||
property: app.websocket.message-size-limit
|
||||
owner_module: adapter-inbound-websocket
|
||||
type: data_size
|
||||
default: 64KB
|
||||
allowed_values: null
|
||||
classification: public-config
|
||||
required: false
|
||||
reload_policy: restart-only
|
||||
owner_branch: 2026-11-01-maturity-review-round2
|
||||
validation: positive_data_size
|
||||
compatibility_impact: additive
|
||||
required_test: websocket-contract:canonical-property-namespace
|
||||
|
||||
- name: APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT
|
||||
# Spring's own default, now explicit (review 03-06); at most 2147483647 bytes.
|
||||
property: app.websocket.send-buffer-size-limit
|
||||
owner_module: adapter-inbound-websocket
|
||||
type: data_size
|
||||
default: 512KB
|
||||
allowed_values: null
|
||||
classification: public-config
|
||||
required: false
|
||||
reload_policy: restart-only
|
||||
owner_branch: 2026-11-01-maturity-review-round2
|
||||
validation: positive_data_size
|
||||
compatibility_impact: additive
|
||||
required_test: websocket-contract:canonical-property-namespace
|
||||
|
||||
- name: APP_WEBSOCKET_SEND_TIME_LIMIT
|
||||
# Spring's own default, now explicit (review 03-06); at most 2147483647 ms.
|
||||
property: app.websocket.send-time-limit
|
||||
owner_module: adapter-inbound-websocket
|
||||
type: duration
|
||||
default: 10s
|
||||
allowed_values: null
|
||||
classification: public-config
|
||||
required: false
|
||||
reload_policy: restart-only
|
||||
owner_branch: 2026-11-01-maturity-review-round2
|
||||
validation: positive_duration
|
||||
compatibility_impact: additive
|
||||
required_test: websocket-contract:canonical-property-namespace
|
||||
|
||||
- name: APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE
|
||||
# Spring's own default, now explicit (review 03-06); at most 2147483647 ms.
|
||||
property: app.websocket.time-to-first-message
|
||||
owner_module: adapter-inbound-websocket
|
||||
type: duration
|
||||
default: 60s
|
||||
allowed_values: null
|
||||
classification: public-config
|
||||
required: false
|
||||
reload_policy: restart-only
|
||||
owner_branch: 2026-11-01-maturity-review-round2
|
||||
validation: positive_duration
|
||||
compatibility_impact: additive
|
||||
required_test: websocket-contract:canonical-property-namespace
|
||||
|
||||
- name: APP_WEBSOCKET_MAX_CONNECTIONS
|
||||
# New per-node STOMP session ceiling (review 03-06); the next session is closed with 1013. 1000 x 512KB send buffer bounds worst-case outbound buffering near 512 MiB.
|
||||
property: app.websocket.max-connections
|
||||
owner_module: adapter-inbound-websocket
|
||||
type: integer
|
||||
default: 1000
|
||||
allowed_values: null
|
||||
classification: public-config
|
||||
required: false
|
||||
reload_policy: restart-only
|
||||
owner_branch: 2026-11-01-maturity-review-round2
|
||||
validation: positive_integer
|
||||
compatibility_impact: behavior-change
|
||||
required_test: websocket-contract:canonical-property-namespace
|
||||
|
||||
- name: APP_GRAPHQL_ENABLED
|
||||
# 2026-09-25 capability packaging: the module is on when present (its own config yml maps
|
||||
# this key with default true); false is the explicit off. Absent from the build is the
|
||||
@@ -4087,6 +4167,21 @@ env_keys:
|
||||
compatibility_impact: additive
|
||||
required_test: graphql-contract:wired-operator-settings
|
||||
|
||||
- name: APP_GRAPHQL_PER_PARENT_FETCH_WARNING_THRESHOLD
|
||||
property: app.graphql.limits.per-parent-fetch-warning-threshold
|
||||
owner_module: adapter-inbound-graphql
|
||||
type: integer
|
||||
default: 10
|
||||
allowed_values: null
|
||||
classification: public-config
|
||||
required: false
|
||||
required_when: APP_GRAPHQL_ENABLED=true
|
||||
reload_policy: restart-only
|
||||
owner_branch: 2026-11-01-maturity-review-round2
|
||||
validation: positive_integer
|
||||
compatibility_impact: additive
|
||||
required_test: graphql-contract:wired-operator-settings
|
||||
|
||||
- name: APP_OUTBOX_ENABLED
|
||||
# source: five-adapter-runtime-remediation §6.1 JPA-INT-004 — the outbox capability switch.
|
||||
# relay-enabled below only starts the scheduler; conflating the two meant a relay-off deployment
|
||||
|
||||
@@ -358,7 +358,15 @@
|
||||
| `-p optional-platforms ci` (gRPC 플랫폼) | rc=0 | 71초 | load 8.99 |
|
||||
| `:integrationCheck` (컨테이너 lane 37개 전부) | rc=1 — MinIO lane 2개만 실패(위와 같은 이유). 나머지 35 lane 통과: JPA 실 PostgreSQL 11 lane, notification·sample·Redis·Mongo·websocket nginx·messaging certification 등. 04-01·04-02·09-02 수정이 실 DB에서 함께 통과 | 794초 | load 23.84 |
|
||||
|
||||
남은 빨강은 05-09 하나(대체 이미지 미정)다. `releaseCheck`, `qualityCheck` 단독, `performanceCheck`, gRPC ledger PG lane(`-p optional-platforms integrationCheck`)은 합친 트리에서 다시 돌리지 않았다(ledger는 03-10 수정 에이전트가 30건 통과 확인).
|
||||
추가 실행(같은 합친 트리, 2026-11-01 23:32~23:45):
|
||||
|
||||
| 게이트 | 결과 | 시간 | 부하 |
|
||||
|---|---|---|---|
|
||||
| `-p optional-platforms integrationCheck` (gRPC ledger 실 PostgreSQL) | rc=0, 30건 통과 · skip 0 | 118초 | load 7.33 |
|
||||
| `:performanceCheck` (08-01로 신설) | rc=0 | 284초 | load 6.45 |
|
||||
| `:releaseCheck` | 인자 없이 rc=1 — `verifyReleaseProvenance: no source revision`(릴리스는 커밋 sha가 필요하다는 설계상 전제). `-PgitRevision=$(git rev-parse HEAD)`로 rc=0. 작업 트리가 미커밋이라 실제 릴리스 증거로는 쓸 수 없다 | 105초 | load 17.50 |
|
||||
|
||||
남은 빨강은 05-09 하나(대체 이미지 미정)다.
|
||||
|
||||
### 13.2 결정이 필요한 것 (수정 중 새로 생김)
|
||||
|
||||
@@ -378,3 +386,81 @@
|
||||
| 04-03 DisplayName | 에이전트가 AGENTS.md(영어)를 따름. 소유자 결정 5(한국어)와 AGENTS.md 불일치(08 영역 기존 지적) | AGENTS.md를 소유자 결정에 맞춘다 |
|
||||
| 05-09 MinIO 대체 이미지 | 여전히 미정. lane 2개는 구분된 메시지로 실패 | 소유자 결정 |
|
||||
|
||||
|
||||
## 14. 2라운드 조치 현황 (남은 P2·P3, 1라운드 후속, 매뉴얼)
|
||||
|
||||
사용자가 2026-11-01 23:20에 "남은 작업까지 모두 완수"를 지시했다. 1라운드 수정을 합친 상태를 임시 클론(baseline)으로 고정하고, 영역별 11개 묶음 에이전트가 각자 클론에서 RED→GREEN으로 고쳤다. 오케스트레이터가 패치를 메인 작업 트리에 합쳤다(커밋 없음). 사용량 한도로 모든 에이전트가 00:20쯤 한 번 멈췄다가 재개했다.
|
||||
|
||||
| 묶음 | 상태 | 검증 (에이전트 클론) | 처리 내용 | 합칠 때 조치·결정 필요 |
|
||||
|---|---|---|---|---|
|
||||
| r2-10 | 완료 | scaffold 왕복(5 leaf check+architectureCheck) rc=0, verifyDependencyLocks rc=0, verifyStrictLaneStages rc=0 | 01-01·07-09 완료, 01-12 부분(정본은 r2-01), 생성 명령 scripts/new-feature.sh + verifyFeatureScaffold(mainCheck) | 결정: JPA adapter는 생성 안 함(서비스 전용 persistence leaf 기본), 생성 권한은 역할 매핑 전 403 |
|
||||
| r2-02 | 완료(02-09 부분) | web·web-advanced·web-fileserver·sample check, architectureCheck, web 300, webSecurityBoundary 15, web systemTest 16, app-bootstrap test 321, sample webSystemTest 5 | 02-04~02-12 RED 확인 후 수정 | 결정: 비JSON 본문 상한 없음(엔드포인트가 직접), 새 오류 코드는 leaf enum(http-contract.md §4), correlation ID 규칙 밖이면 서버가 교체, sample 키 오류 BAD_PARAMETER→IDEMPOTENCY_KEY_INVALID(프론트 반영 필요) |
|
||||
| r2-09 | 완료 | sample check 307, systemTest 14, integrationTest 58, webSystemTest 5, web check 274, architectureCheck pass (에이전트). 합칠 때 EnvelopeBodyAdvice 충돌(02-06 vs 09-04)을 오케스트레이터가 byte[]만 제외로 합침 → web check + SampleApiDocsSystemTest 재실행 | 09-01 SQL 46→6, rps 765→2528, 09-04, 09-06, 09-07, 01-13, 09-02 후속 | 결정: batchCreate 상한 1000·한 트랜잭션 유지(원격 DB면 100으로 낮출지), 관리자도 남의 기록 수정 불가 |
|
||||
| r2-01 | 10 완료·3 부분·01-10 못함 | leaf check 11개, architectureCheck 2회, sample webSystemTest·systemTest, PG lock IT (에이전트) | 01-02,04,06,07,08,09,12,13,14 완료 / 01-03 부분(notification TenantId 유지), 01-05 부분(Transaction·Idempotency 계약 키트 못함), 01-11 부분(edge 없는 4 leaf) / 01-10 못함(패키지 규칙 선행) | 합칠 때: sample PortfolioErrorCode 충돌 → r2-09의 WORKLOG_NOT_OWNER와 r2-01의 WORKLOG_INVALID·OPERATION_NOT_FOUND 수동 합침. UpdateWorkLogUseCase "소유자 검사 없음" Javadoc은 r2-09가 소유자 검사를 넣어 사실이 아니게 되어 제외. 결정: sample 이벤트 tenant 범위 global, 새 오류 코드 2개 |
|
||||
| r2-03 | 10건 완료 | graphql test 388·systemTest 34·API surface, websocket check 92·qualification 7·Tomcat IT, grpc adapter check 61·transport 29, grpc 4 leaf check·ledger PG IT 35, -p optional-platforms ci, verifyEnvKeys 352 keys | 03-02~03-09, 03-11, 03-10 후속 | 결정: gRPC 기본값(스레드 32·큐 256·동시 100·deadline 10s·drain 2s), ledger claimTtl 5m·보존 24h·purge 스케줄은 adopter, websocket max-connections 1000·초과 시 1013, GraphQL per-parent 경고 임계 10 |
|
||||
| r2-07 | 대부분 완료(07-08·09-11 부분) | leaf check 11개, architectureCheck, verifyDependencyLocks, verifyEnvKeys 346, app-bootstrap systemTest 11·IT 10, sample systemTest 8·webSystemTest 5·IT 55, 실제 docker build+healthy | 07-02 후속, 02-03 후속(${} 자리표시자 거부), 07-04, 07-06, 07-07, 07-10~14, 09-08, 09-10 완료 / 07-08 부분(fileserver 볼륨 미룸), 09-11 부분(Jackson 2 유지: logstash·springdoc 요구), 07-03 advisor 규칙은 r2-01과 중복이라 제외 | 합칠 때 sample application.yml을 r2-09 JDBC batch 설정과 context 1줄로 합침. 결정: 새 leaf composition:durable-operation 등록, logback이 app.logging.* 읽음, APP_CACHE_REDIS_TTL_JITTER deprecated |
|
||||
| r2-08 | 대부분 완료(08-07 측정만, TEST-F-1 못함) | build-logic 94, ci verifyDependencyLocks, verifyStrictLaneStages, documentContractTest 60, 컨테이너 lane 12, -p optional-platforms ci integrationCheck (에이전트) | 1R-a(workflow --stacktrace 22곳), 08-02, 08-03, 08-04(MinIO 제외), 08-05, 08-06, 1R-b·c(AGENTS/CLAUDE 단계·DisplayName 한국어), O-10·O-11 완료 / 08-07 MEDIUM 298건 측정·계획만 / TEST-F-1 못함(포트 83개) | 합칠 때 app-bootstrap build.gradle·DeveloperExperienceContractTest·StructuredLogFieldContractTest를 r2-07과 수동 병합, r2-07이 새로 만든 저장소 읽는 테스트 4개(Dockerfile·compose 3, SampleRuntimeDefaults)에 repository-contract 태그 부여 |
|
||||
| r2-05b | 10 완료·3 부분 | objectstorage check 148 + MinIO 계약 14·fault 1 통과(새 이미지 pgsty/minio digest), support·identifier·httpclient·redis-runtime·redis-sdk·cache-redis·application-core check, app-bootstrap test 321, architectureCheck, verifyEnvKeys, 실 Redis topology, httpclient Toxiproxy | 05-09 완료(MinIO 대체: pgsty/minio@sha256:b6bfe723…, Chainguard 기각), 05-16 objectstorage 완료(S3 어댑터 결함 2개 발견·수정), 05-23b·d·e·f·g, 05-21, 05-05/06/14, 05-02/03/04/17/18 완료 / 05-15 부분(support binder 2단계 키), 05-16 Redis·HTTP 부분 / objectstorage 계약 testFixtures 이동 못함 | 합칠 때 objectstorage build.gradle, httpclient FailureInjectionContractTest를 r2-08 이미지 일원화와 수동 병합. 결정: AGENTS.md 규칙 4에 Redis 예외 한 줄 필요, objectstorage provider type 하나 추가 |
|
||||
| r2-06 | v2(baseline2 위 재작업) 완료, 06-08 부분 | application-core 264, outbox-relay 30, durable-operation 3, persistence-jpa 526, messaging 41, starter 74, inbound messaging 4, identifier 12, web 305, sample 319, architectureCheck, verifyDependencyLocks, verifyStrictLaneStages, Kafka relay 2, PG lane 5(28) | 06-02·06-01 후속, 06-04~06-07, 06-09 완료, durable operation id v4→v7 결함 RED→GREEN / 06-08 최소 경로(실 Kafka+PG 중복 전달 lane 없음) | 합칠 때 identifier README·CLAUDE.md를 r2-05b 문서 재작성과 수동 병합. r2-01 AggregateOrder.ofOccurrence(벽시계)를 지우고 OutboxAggregateSequencePort로 일원화 — ofOccurrence 테스트 2개 삭제·first() 테스트 1개로 대체. 결정: V20/V21, 새 leaf adapter:inbound:messaging, V21 유일 인덱스는 기존 중복 있으면 마이그레이션 실패 |
|
||||
| r2-04 | 13 완료·04-14/04-16/04-04후반 부분 | persistence-jpa 557, sample test 299, app-bootstrap 321, architectureTest 183, fileserver·notification·mongo leaf check, architectureCheck, verifyEnvKeys, verifyDependencyLocks, 실 PG lane(transaction 7, platformFailure 5, platformContract 244, fileserver 47, migration·notification 13, sample IT 55) | 04-05,06,07,08,10,11,12,13,15,17, 09-05, 09-07, 09-09 완료 / 04-14 부분(notification 포트 10개 계약 미이동), 04-16 부분(notification 패키지 분할 못함), 04-04 후반 부분(fileserver test 0→3) / 04-03 sample DisplayName 1개 못 고침 | 새 실 PG 테스트 3개는 수정 전 실패를 실 PG로 확인 안 함(단위 테스트로 RED). 결정: 트랜잭션 제한 30초, batch 기본 50, H2 운영 jar에서 제거, 격리 수준을 Hikari에서 고정, 포트 시그니처 변경(fileserver claimDue·markAbandoned·claimToken), 마이그레이션 notification V12 |
|
||||
| r2-05a | **합치지 않음** | — | 알림·파일 서버 묶음(05-10~13, 05-19, 05-20, 05-22, 05-23 일부, 05-16 일부, 05-07 쿼터 상한 등). 마감까지 패치·검증 보고가 없었다. 클론 `round2/wt-r2-05a-notif-file`에 미검증 변경 86개 파일이 있다 | 다음 작업에서 이 클론을 baseline 최신 상태로 다시 올려 검증 후 합친다 |
|
||||
|
||||
### 14.1 합칠 때 생긴 충돌과 처리
|
||||
|
||||
- `EnvelopeBodyAdvice`(r2-02 02-06 ↔ r2-09 09-04): springdoc 3.0이 OpenAPI 문서를 `byte[]`로 돌려주는 것을 jar에서 확인하고, `byte[]`만 감싸지 않고 `String`은 02-06대로 감싸게 합쳤다. web check·`SampleApiDocsSystemTest` 통과.
|
||||
- sample `PortfolioErrorCode`(r2-01 ↔ r2-09): 두 쪽 코드 모두 넣었다. r2-01의 "UpdateWorkLogUseCase는 소유자 검사 없음" Javadoc은 r2-09가 소유자 검사를 넣어 거짓이 되므로 넣지 않았다.
|
||||
- sample `application.yml`(r2-07 ↔ r2-09): context 1줄로 합쳐 JDBC batch 설정과 설정 정리 둘 다 반영.
|
||||
- app-bootstrap `build.gradle`·계약 테스트 2개(r2-08 ↔ r2-07): lane 분리 블록으로 바꾸고 r2-07의 sample yml 입력을 살렸다. r2-07이 새로 만든 저장소 읽는 테스트 4개에 `repository-contract` 태그를 달았다(태그 없으면 08-03 규칙상 `test` lane에서 실패). 합친 뒤 `:app-bootstrap:check`·`documentContractTest` 통과.
|
||||
- r2-06은 10개 파일 충돌로 baseline2(그 시점 메인 상태) 위에서 다시 작업시켰다(v2). r2-01의 `AggregateOrder.ofOccurrence`(벽시계)를 지우고 `OutboxAggregateSequencePort`로 일원화했다.
|
||||
- objectstorage `build.gradle`·httpclient `FailureInjectionContractTest`(r2-05b ↔ r2-08 이미지 일원화), identifier README·CLAUDE.md(r2-05b ↔ r2-06): 수동 병합.
|
||||
- 매뉴얼(`docs/manual/`)이 가리키던 `DurableOperationConfig`는 r2-07이 `composition:durable-operation`의 `DurableOperationAutoConfiguration`으로 옮겨서 경로를 고쳤다. 매뉴얼이 인용한 `src/`·`docs/` 경로를 전수 검사해 템플릿 자리표시자(`<f>`) 외에 없는 경로가 없음을 확인했다.
|
||||
|
||||
### 14.2 합친 뒤 전체 게이트
|
||||
|
||||
r2-05a를 뺀 10개 묶음을 합친 메인 작업 트리에서 오케스트레이터가 실행했다(공유 잠금).
|
||||
|
||||
첫 실행(05:40)은 실패 3건이었다. 모두 합치는 과정에서 생긴 문제라 고쳤다.
|
||||
|
||||
| 실패 | 원인 | 조치 |
|
||||
|---|---|---|
|
||||
| `ci` `verifyCleanArchitectureDependencies` | 08-05의 새 검사가 git-ignore 대상인 IDE 출력 `bin/` 안의 복사된 build 스크립트(`grpc-codegen/bin/test/...`)를 잡았다 | `ModuleRegistry.unregisteredBuildScripts`가 `bin/`을 건너뛴다 |
|
||||
| `mainCheck` `verifyFeatureScaffold` | 작업 트리 복사가 지웠지만 미커밋인 추적 파일 26개에서 `tar` 실패 | `scripts/verify-feature-scaffold.sh`가 `git ls-files -d` 경로를 뺀다 |
|
||||
| sample `WorkLogStatementCostSystemTest` | 기대 202, 실제 8. 04-17(`Persistable`) 뒤 컬렉션 행도 owner를 넘어 묶여 표마다 50행씩(2+4+2) | 기대값 8로, 테스트 설명·sample README·`application.yml` 주석 수정. 202·400 회귀는 계속 잡는다 |
|
||||
| (확인 중 발견) build-logic `PlatformModuleConventionTest` 6건 | 08-04 뒤 `java-conventions`가 이미지 목록 파일을 요구하는데 TestKit fixture에 없음 | fixture가 빈 목록 파일을 쓴다 |
|
||||
|
||||
재실행 결과:
|
||||
|
||||
| 게이트 | 결과 | 시간 | 실행 직전 부하 |
|
||||
|---|---|---|---|
|
||||
| `ci` | rc=0 | 365초 | load 4.24 |
|
||||
| `mainCheck` (`verifyFeatureScaffold` 생성 왕복 포함) | rc=0 | 171초 | load 15.86 |
|
||||
| `:integrationCheck` (MinIO 계약·fault 포함 전 컨테이너 lane) | rc=0 | 697초 | load 11.23 |
|
||||
| `-p optional-platforms ci integrationCheck` | rc=0 | 51초 | — |
|
||||
|
||||
1라운드 끝까지 빨갛던 MinIO lane이 05-09 대체 이미지(`pgsty/minio` digest)로 통과한다. 이 시점 기준으로 빨간 게이트는 없다. `releaseCheck`·`performanceCheck`는 2라운드 뒤 다시 돌리지 않았다.
|
||||
|
||||
|
||||
|
||||
### 14.3 남은 것 (2026-11-02 06:15 기준)
|
||||
|
||||
**합치지 않은 묶음**
|
||||
- r2-05a(알림·파일 서버). 06:45에 패치(`round2/patches/r2-05a-notif-file.patch`, 103파일)가 왔지만 합치지 않았다. 이유: 메인 작업 트리에 6곳 충돌(r2-04가 같은 fileserver fake를 testFixtures로 옮김, `application-fileserver` build.gradle·lockfile, `applied-migrations.sha256`, `NotificationFixtures`), 알림 마이그레이션 `V12`가 r2-04의 `V12__notification_suppression_target_unique`와 번호 충돌, 05-11은 수정 뒤 GREEN 실행 없음. 07:30 마감 안에 합치고 전체 게이트를 다시 돌릴 시간이 없어 초록 상태를 유지했다.
|
||||
- 묶음 보고상 완료: 파일 서버 05-07 후속(쿼터 상한·대상 namespace·MOVE/READ_METADATA 소유자 테스트)·05-12·05-13·05-22·05-23a, 알림 05-10(+ `collapse_key` 미저장 결함 발견)·05-23c·05-01 후속 테스트 이름. 부분: 05-11(GREEN 미실행), 05-16 fileserver. 못 함: 05-19, 05-20, 05-16 notification.
|
||||
- 다음 작업: 최신 메인 위로 다시 올리고 마이그레이션을 `V13`으로 바꾼 뒤 05-11 GREEN과 전체 게이트를 확인하고 합친다.
|
||||
|
||||
**부분 완료·못 한 것 (묶음 보고 기준, 이유는 14절 표)**
|
||||
- 01-03(notification `TenantId` 유지), 01-05(트랜잭션·멱등성 포트 공유 계약), 01-10(패키지 이동), 01-11(edge 없는 4 leaf)
|
||||
- 02-09(JSON 아닌 본문 상한 — 엔드포인트가 직접 두도록 문서화)
|
||||
- 04-14(notification 포트 10개 계약), 04-16(notification 패키지 분할), 04-04 후반(persistence-fileserver 테스트 3개만), 04-03 sample `@DisplayName` 1개
|
||||
- 05-15(support binder 2단계 키), 05-16 Redis·HTTP 계약 상속, objectstorage 계약 testFixtures 이동
|
||||
- 06-08(실 Kafka+PG 중복 전달 lane 없음)
|
||||
- 07-08(fileserver 볼륨), 09-11(Jackson 2는 logstash·springdoc 요구로 유지)
|
||||
- 08-07(SpotBugs MEDIUM 298건 — 측정과 단계 계획만), TEST-F-1(공유 계약 없는 포트 정리)
|
||||
|
||||
**결정 필요** — 13.2 표와 14절 표의 "결정" 칸. 파생 서비스 동작을 바꾸는 것: JWT audience 필수, JDBC batch 기본 켜기·H2 제거·트랜잭션 30초·격리 수준 Hikari 고정, gRPC·WebSocket·GraphQL 새 한도 기본값, 새 leaf 2개(`composition:durable-operation`, `adapter:inbound:messaging`) 등록, 새 마이그레이션(postgresql V20·V21, notification V11·V12, sample V8_1, grpc-ledger V002).
|
||||
|
||||
**짝 프론트가 맞출 것** — 처리 중 409 `retryable=true`+`Retry-After`, 키 재사용 `422 IDEMPOTENT_REQUEST_MISMATCH`, 키 형식 오류 `400 IDEMPOTENCY_KEY_INVALID`, Envelope null 필드 생략, 계약 §4.1·§6이 `docs/web/http-contract.md`를 가리키게.
|
||||
|
||||
**검증하지 않은 것** — 2라운드 뒤 `releaseCheck`·`performanceCheck`, GitHub Actions 실제 실행.
|
||||
|
||||
**커밋** — 하지 않았다(`human-only`). 1·2라운드 변경이 main 작업 트리에 미커밋으로 있다.
|
||||
|
||||
@@ -39,8 +39,8 @@ the time, and which half is not knowable from the status.
|
||||
escalate to the service owner. This is the case the keyed profile exists to avoid.
|
||||
|
||||
7. `IN_PROGRESS` means a claim exists and has not finished. If its owner died, the claim is not
|
||||
stuck forever: once it is older than the claim TTL (the `claimTtl` given to
|
||||
`GrpcIdempotencyInterceptor`), the next retry of the same request takes it over and runs again,
|
||||
stuck forever: once it is older than the claim TTL (`app.grpc.platform.operation-ledger-claim-ttl`,
|
||||
default 5m), the next retry of the same request takes it over and runs again,
|
||||
and a later reconciler pass sees that attempt's `COMMITTED` or `FAILED_TERMINAL`. Until a retry
|
||||
arrives, the case stays pending. The re-run is safe only when the ledger commit is recorded in the
|
||||
mutation's own transaction; if this service commits them separately, check the business resource
|
||||
@@ -52,6 +52,32 @@ retry arriving is a caller that gave up; it needs the business resource checked,
|
||||
|
||||
---
|
||||
|
||||
## The operation ledger table keeps growing
|
||||
|
||||
**What you are seeing.** `grpc_operation_ledger` grows without bound, or a retry of an old key runs
|
||||
the mutation again instead of replaying.
|
||||
|
||||
**What it means.** Finished rows (`COMMITTED`, `FAILED_TERMINAL`) are deleted only when something
|
||||
calls `GrpcOperationLedgerRetention.purgeExpired(now)`; the starter assembles that bean
|
||||
(`app.grpc.platform.operation-ledger-enabled=true`) but does not schedule it. A growing table means
|
||||
the service's scheduler is not calling it. A retry that re-ran after the retention
|
||||
(`app.grpc.platform.operation-ledger-retention`, default 24h) is the trade the retention makes: its
|
||||
record was purged, so it was a new operation.
|
||||
|
||||
**What to do.**
|
||||
|
||||
1. Check that the service schedules `purgeExpired`. Each call deletes in batches of 500 until a batch
|
||||
comes back short, never touching `IN_PROGRESS` rows.
|
||||
2. For a large backlog, call it repeatedly; each batch is a short transaction that skips rows another
|
||||
transaction holds.
|
||||
3. If retried keys re-run after the retention, raise the retention above the callers' retry window
|
||||
rather than skipping the purge.
|
||||
|
||||
**Escalate when** old `IN_PROGRESS` rows accumulate. Those are not purged by design; each is an
|
||||
abandoned claim no retry has taken over (see `IN_PROGRESS` above).
|
||||
|
||||
---
|
||||
|
||||
## A stream ended with FULL_RESYNC_REQUIRED
|
||||
|
||||
**What you are seeing.** A client's resume was refused and it was told to resynchronise.
|
||||
|
||||
@@ -8,7 +8,10 @@
|
||||
|
||||
- 응답 원문의 키 집합: `src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java`
|
||||
- 멱등성 응답의 status·code·retryable·`Retry-After`: `IdempotencyExceptionMappingTest`,
|
||||
`RetryAfterAdvisorTest`, `OperationalErrorTest`
|
||||
`RetryAfterAdvisorTest`, `OperationalErrorTest`, 키 형식은 `IdempotencyKeyHeaderTest`
|
||||
- 헤더 규칙(3절): `WebMvcRequestIdFilterTest`, `CorsSecurityFilterIntegrationTest`
|
||||
- web 전용 코드(4절): `TransportErrorHandlingTest`, `IdempotencyKeyHeaderTest`, web-advanced
|
||||
`WebAdvancedErrorMappingTest`
|
||||
|
||||
## 1. Envelope 키 존재 규칙
|
||||
|
||||
@@ -24,6 +27,8 @@ JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). **
|
||||
|
||||
- `success`가 판별자다. 클라이언트는 `success`로 갈라 읽고, 키가 있는지로 판단하지 않는다.
|
||||
- 성공인데 `data`가 `null`이면 `data` 키도 없다. 본문이 아예 없는 응답(204)은 Envelope가 아니다.
|
||||
- 컨트롤러가 `String`을 반환해도 JSON을 요청하면(`Accept: application/json`) 같은 Envelope로 나간다
|
||||
(`"data": "<문자열>"`). 텍스트를 요청하면 문자열 그대로다.
|
||||
- 빈 컬렉션 결과는 `"data": []`, 빈 bulk 결과는 `"results": []`, 항목 없는 부분 실패는
|
||||
`"details": []`로 나간다.
|
||||
|
||||
@@ -67,7 +72,7 @@ JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). **
|
||||
| 재생(replay): 같은 키·같은 본문, 첫 요청 완료 | 첫 요청과 같은 성공 status | — (성공 Envelope) | — | 없음 | 첫 요청의 결과로 받아들인다. `meta`의 id는 이번 요청의 것이다 |
|
||||
| 처리 중(in-flight): 같은 키, 첫 요청이 아직 실행 중 | 409 | `IDEMPOTENT_IN_FLIGHT` | `true` | `2` | 결과 불명. **같은 `Idempotency-Key`로** `Retry-After` 뒤 재전송한다. **새 키 금지** |
|
||||
| 본문 불일치(mismatch): 같은 키·다른 본문 | 422 | `IDEMPOTENT_REQUEST_MISMATCH` | `false` | 없음 | 클라이언트 버그. 다시 보내지 않는다. 새 작업이면 새 키를 만든다 |
|
||||
| 키 누락·형식 오류 | 400 | `BAD_PARAMETER` | `false` | 없음 | 키를 붙여 다시 보낸다 |
|
||||
| 키 누락·형식 오류 | 400 | `IDEMPOTENCY_KEY_INVALID` (`details.reason` = `MISSING`/`MALFORMED`) | `false` | 없음 | 문법에 맞는 키를 붙여 다시 보낸다 |
|
||||
|
||||
- **처리 중을 `retryable=true`로 두는 이유.** 같은 키 재전송은 서버가 재생·처리 중·불일치로 안전하게
|
||||
판정하므로, 다시 보내는 것이 맞는 행동이다. 새 키로 보내면 서버는 다른 요청으로 보고 막지 못해,
|
||||
@@ -77,9 +82,9 @@ JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). **
|
||||
결과가 바뀌지는 않는다. lease를 2초보다 짧게 설정한 서비스는 이 값이 lease를 넘으므로 값을 다시
|
||||
정한다(`RetryAfterAdvisor`, `docs/registries/error-codes.yaml`).
|
||||
- executor는 기다리지 않는다. 처리 중이면 바로 409를 돌려준다. 키로 결과를 조회하는 엔드포인트는 없다.
|
||||
- 키 누락 처리는 엔드포인트가 정한다(공용 검증 부품 없음, 리뷰 02-12). 템플릿 예시
|
||||
(`PosterImagePublicationController`)는 헤더가 없으면 `MissingRequestHeaderException`, 비었거나
|
||||
256자를 넘으면 `IllegalArgumentException`으로 둘 다 400 `BAD_PARAMETER`다. 키를 요구하지 않는
|
||||
- **키 문법**: 보이는 ASCII(`0x21`–`0x7E`) 1~256자. 서버는 trim하거나 고치지 않는다. 짝 프론트의
|
||||
`isValidIdempotencyKey`와 같은 규칙이다. KEYED 엔드포인트는 모두 `IdempotencyKeyHeader.parse`로 헤더를
|
||||
읽어 같은 코드로 거부한다(리뷰 02-12). 키 원문은 응답에 돌려 쓰지 않는다. 키를 요구하지 않는
|
||||
엔드포인트는 키 없이 보호 없이 실행된다.
|
||||
|
||||
같은 executor가 내는 나머지 두 실패:
|
||||
@@ -89,9 +94,54 @@ JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). **
|
||||
| 멱등성 저장소 응답 없음 | 503 | `IDEMPOTENCY_UNAVAILABLE` | `true` | 없음 | 작업 실행 전에 거부됐다. 같은 키로 나중에 다시 보낸다 |
|
||||
| 이전 시도의 효과를 증명할 수 없음 | 500 | `IDEMPOTENCY_RECOVERY_REQUIRED` | `false` | 없음 | 재전송도 재실행도 안전하지 않다. 업무 데이터로 결과를 확인한다 |
|
||||
|
||||
## 3. 바꿀 때
|
||||
## 3. 헤더
|
||||
|
||||
### 요청 id·correlation id
|
||||
|
||||
| 헤더 | 방향 | 규칙 |
|
||||
| --- | --- | --- |
|
||||
| `X-Request-Id` | 응답(항상) | 서버가 만든다. 신뢰 설정(`app.web.mvc.trust-inbound-request-id`)일 때만 요청 값을 받는다 |
|
||||
| `X-Correlation-Id` | 요청·응답(항상) | 요청 값이 `[A-Za-z0-9._-]{1,128}`(앞뒤 공백 제거 후)이면 그대로 잇고, 아니면 서버가 새로 만든다. 고치지 않고 바꾼다 |
|
||||
| `traceparent` | 요청·응답(항상) | 유효한 W3C 값이면 잇고, 아니면 새로 만든다 |
|
||||
|
||||
세 값은 응답 `meta`의 `requestId`·`correlationId`·`traceId`와 같다. 셋 다 짝 프론트의
|
||||
`[A-Za-z0-9._:-]{1,128}` 안에 든다.
|
||||
|
||||
### 브라우저가 읽을 수 있는 응답 헤더(CORS)
|
||||
|
||||
CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의 `Access-Control-Expose-Headers`에
|
||||
아래가 들어간다. 이 목록 밖의 헤더(안전 목록 `Cache-Control`·`Content-Type` 등 제외)는 브라우저 코드에서
|
||||
`null`로 보인다.
|
||||
|
||||
- 플랫폼(`CorsExposedHeaders.PLATFORM`): `Retry-After`, `X-Request-Id`, `X-Correlation-Id`,
|
||||
`traceparent`, `Location`, `ETag`, `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`
|
||||
- fileserver를 실은 배포: `Tus-Resumable`, `Tus-Version`, `Tus-Extension`, `Tus-Max-Size`,
|
||||
`Upload-Offset`, `Upload-Length`, `Upload-Defer-Length`, `Upload-Expires`, `Upload-Complete`,
|
||||
`Upload-Limit`, `Content-Disposition`, `Accept-Ranges`
|
||||
|
||||
새 응답 헤더를 쓰는 모듈은 `CorsExposedHeaders` bean으로 자기 헤더를 기여한다.
|
||||
|
||||
## 4. web 전용 오류 코드
|
||||
|
||||
`OperationalError`(`docs/registries/error-codes.yaml`) 밖에서 HTTP 어댑터가 내는 코드다.
|
||||
|
||||
| 코드 | status | category | `retryable` | `Retry-After` | 언제 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `REQUEST_TIMEOUT` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 없음 | 비동기 요청(`Callable`·`DeferredResult`·스트리밍)이 시간 안에 끝나지 않았다 |
|
||||
| `IDEMPOTENCY_KEY_INVALID` | 400 | `VALIDATION` | `false` | 없음 | 2절 |
|
||||
| `RATE_LIMIT_UNAVAILABLE` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 있음 | rate-limit 저장소 응답 없음(`docs/web/runbook.md`) |
|
||||
| `RATE_LIMIT_INCOMPATIBLE` | 503 | `INTERNAL` | `false` | 없음 | rate-limit 제공자가 계약과 맞지 않음 |
|
||||
|
||||
- 컨트롤러 파라미터 제약 위반(`@RequestParam @Max(10)`)은 요청 본문 위반과 같은
|
||||
`400 VALIDATION_FAILED`이고 `details`는 `[{field, code, message}]`다. 거절된 값은 싣지 않는다.
|
||||
- web-advanced를 실은 서비스의 예외 코드(`ADMISSION_REFUSED` 503 등 10종)는
|
||||
`src/adapter/inbound/web-advanced/README.md` 「오류 응답」이 정본이다.
|
||||
- 직접 쓰는 거부 응답(401·403·429·503)도 컨트롤러 응답과 같이 `application/json;charset=UTF-8`이다.
|
||||
|
||||
## 5. 바꿀 때
|
||||
|
||||
- 응답 키를 더하거나 빼면 `EnvelopeWireShapeTest`와 이 문서 1절을 같이 고친다.
|
||||
- 응답 헤더를 새로 쓰면 `CorsExposedHeaders`에 넣고 3절을 고친다.
|
||||
- 멱등성 코드의 status·retryable·`Retry-After`를 바꾸면 `OperationalError`, `RetryAfterAdvisor`,
|
||||
`docs/registries/error-codes.yaml`, 이 문서 2절을 같은 변경에서 고친다.
|
||||
- 짝 프론트의 백엔드 계약 문서(`clean-architecture-frontend-template`
|
||||
|
||||
@@ -139,10 +139,11 @@ application use cases: `adapter:inbound:web` `operation/DurableOperationControll
|
||||
`POST /operations` (202 + `Location`), `GET /operations/{id}`, `DELETE /operations/{id}` (202),
|
||||
answers in the `Envelope` contract, and a caller's operation that is not theirs is the same 404
|
||||
(`OPERATION_NOT_FOUND`) as one that does not exist. The controller and the three use cases are
|
||||
assembled by `app-bootstrap` `autoconfigure/operation/DurableOperationConfig`, which turns on only
|
||||
assembled by `composition:durable-operation` (`DurableOperationAutoConfiguration`), which turns on only
|
||||
when the operation store and the outbox append port exist (the JPA module with
|
||||
`app.outbox.enabled=true`). Submit and cancel need `operation:submit` / `operation:cancel`
|
||||
(`security.yml` grants both to the `operation-submit` role).
|
||||
(that module's `config/module-defaults/durable-operation.yml` grants both to the `operation-submit`
|
||||
role).
|
||||
|
||||
The state machine is enforced three times on purpose: in `DurableOperation`'s constructor, in the
|
||||
`CHECK` constraints of `V11__durable_operation.sql`, and in the `WHERE` clause of every statement
|
||||
|
||||
@@ -78,6 +78,12 @@ Two more start fine and still fail in the browser:
|
||||
- `https://*.example.com` in the origin list — it is compared as a literal and matches nothing.
|
||||
- An origin with a path (`https://app.example.com/ui`) — an origin is scheme, host and port only.
|
||||
|
||||
The response arrives but a header reads as `null` in browser code (`Retry-After`, `X-Request-Id`,
|
||||
`Location`, a tus `Upload-Offset`): the header is not in `Access-Control-Expose-Headers`. The exposed
|
||||
list is `CorsExposedHeaders.PLATFORM` plus each module's `CorsExposedHeaders` bean
|
||||
(`docs/web/http-contract.md` §3); a header a service adds needs its own bean. A proxy that strips or
|
||||
rewrites `Access-Control-Expose-Headers` has the same symptom.
|
||||
|
||||
A preflight answered `401` means CORS ran after authentication. Preflights carry no credentials by
|
||||
design; the order is asserted by `WebPipelineOrderContract`.
|
||||
|
||||
|
||||
@@ -6,12 +6,13 @@
|
||||
# on. The wrong-credential step is here because a bucket that accepts anyone is also "working".
|
||||
#
|
||||
# It runs on the MinIO server image rather than the mc client image, and the reason is worth keeping:
|
||||
# minio/mc ships mc and almost nothing else — no sed, no grep, no cmp — so steps 2 and 3 below called
|
||||
# The mc client image ships mc and almost nothing else — no sed, no grep, no cmp — so steps 2 and 3 below called
|
||||
# two binaries that are not there. The script had never run to find out. The wrapper's one-shot loop
|
||||
# lost its stdin to `docker compose run` and executed only the first client per lane, so this one was
|
||||
# skipped in every lane that declared it while all three lanes reported green.
|
||||
#
|
||||
# minio/minio carries mc, and also sha256sum, cut and tr. The lane already pulls it for the server,
|
||||
# The server image (now pgsty/minio, review 05-09; checked 2026-11-02) carries mc, and also
|
||||
# sha256sum, cut and tr. The lane already pulls it for the server,
|
||||
# so this costs no image, and the digest comparison is a stronger identity check than cmp: it fails
|
||||
# on any differing byte and says so without dumping the bytes.
|
||||
set -eu
|
||||
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package dev.caskeleton.adapter.inbound.web.__feature__;
|
||||
|
||||
/**
|
||||
* The body of {@code POST /__featurePath__}.
|
||||
*
|
||||
* <p>No bean-validation constraint on {@code name}: the aggregate owns the rule (blank, length) and
|
||||
* answers {@code __FEATURE___INVALID}. A constraint here would be a second copy of that rule that can
|
||||
* drift from the first. Put a constraint here only for what the domain cannot see — the wire shape.
|
||||
*
|
||||
* @param name the requested name
|
||||
*/
|
||||
public record Create__Feature__HttpRequest(String name) {}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package dev.caskeleton.adapter.inbound.web.__feature__;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory;
|
||||
import dev.caskeleton.application.__feature__.Create__Feature__Command;
|
||||
import dev.caskeleton.application.__feature__.Create__Feature__UseCase;
|
||||
import dev.caskeleton.application.__feature__.Get__Feature__Query;
|
||||
import dev.caskeleton.application.__feature__.Get__Feature__UseCase;
|
||||
import dev.caskeleton.application.__feature__.__Feature__View;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Id;
|
||||
import dev.caskeleton.shared.response.Envelope;
|
||||
import java.net.URI;
|
||||
import java.util.Objects;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
|
||||
/**
|
||||
* __Feature__ over HTTP. A transport only: it turns the request into a command or query, calls the
|
||||
* use case and wraps the view in an {@link Envelope}. Who may create is the use case's {@code
|
||||
* @RequiresPermission}; failures are {@code ApiErrorCarrier}s the global handler maps.
|
||||
*
|
||||
* <p>Registered by {@code __Feature__Config} in app-bootstrap, which exists only when a {@code
|
||||
* __Feature__Repository} adapter is on the classpath; not found by a component scan.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/__featurePath__")
|
||||
public class __Feature__Controller {
|
||||
|
||||
private final Create__Feature__UseCase create;
|
||||
private final Get__Feature__UseCase get;
|
||||
|
||||
/**
|
||||
* A controller over the two use cases.
|
||||
*
|
||||
* @param create creates a __Feature__
|
||||
* @param get reads one
|
||||
*/
|
||||
public __Feature__Controller(Create__Feature__UseCase create, Get__Feature__UseCase get) {
|
||||
this.create = Objects.requireNonNull(create, "create");
|
||||
this.get = Objects.requireNonNull(get, "get");
|
||||
}
|
||||
|
||||
/** Creates one; {@code 201} with its {@code Location}. */
|
||||
@PostMapping
|
||||
public ResponseEntity<Envelope<__Feature__HttpResponse>> create(
|
||||
@RequestBody Create__Feature__HttpRequest request) {
|
||||
__Feature__View created = create.handle(new Create__Feature__Command(request.name()));
|
||||
URI location =
|
||||
ServletUriComponentsBuilder.fromCurrentRequestUri()
|
||||
.path("/{id}")
|
||||
.buildAndExpand(created.id())
|
||||
.toUri();
|
||||
return ResponseEntity.created(location)
|
||||
.body(Envelope.ok(__Feature__HttpResponse.from(created), ResponseMetaFactory.fromMdc()));
|
||||
}
|
||||
|
||||
/** Reads one; {@code 404 __FEATURE___NOT_FOUND} when none has the id. */
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<Envelope<__Feature__HttpResponse>> get(@PathVariable String id) {
|
||||
__Feature__View found = get.handle(new Get__Feature__Query(__Feature__Id.of(id)));
|
||||
return ResponseEntity.ok(
|
||||
Envelope.ok(__Feature__HttpResponse.from(found), ResponseMetaFactory.fromMdc()));
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package dev.caskeleton.adapter.inbound.web.__feature__;
|
||||
|
||||
import dev.caskeleton.application.__feature__.__Feature__View;
|
||||
|
||||
/**
|
||||
* One __Feature__ on the wire. Its own type, so a change to the application view is a decision here
|
||||
* rather than a silent change of the HTTP contract.
|
||||
*
|
||||
* @param id the identifier
|
||||
* @param name the name
|
||||
*/
|
||||
public record __Feature__HttpResponse(String id, String name) {
|
||||
|
||||
static __Feature__HttpResponse from(__Feature__View view) {
|
||||
return new __Feature__HttpResponse(view.id(), view.name());
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package dev.caskeleton.adapter.inbound.web.__feature__;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice;
|
||||
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
|
||||
import dev.caskeleton.application.__feature__.Create__Feature__UseCase;
|
||||
import dev.caskeleton.application.__feature__.Get__Feature__UseCase;
|
||||
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Id;
|
||||
import dev.caskeleton.domain.__feature__.testkit.InMemory__Feature__Repository;
|
||||
import dev.caskeleton.domain.__feature__.testkit.Sequential__Feature__IdFactory;
|
||||
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.ResultActions;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
/**
|
||||
* The HTTP contract of {@code /__featurePath__} over the real use cases and the port owners' fakes.
|
||||
*
|
||||
* <p>Standalone MockMvc: no security filter chain and no method-security proxy, so the permission
|
||||
* on create is not exercised here. The composition test in app-bootstrap builds the beans the proxy
|
||||
* wraps.
|
||||
*/
|
||||
class __Feature__ControllerTest {
|
||||
|
||||
private static final __Feature__Id STORED = Sequential__Feature__IdFactory.idAt(1);
|
||||
|
||||
private final InMemory__Feature__Repository repository = new InMemory__Feature__Repository();
|
||||
private final DirectTransactionPort tx = new DirectTransactionPort();
|
||||
private final MockMvc mvc =
|
||||
MockMvcBuilders.standaloneSetup(
|
||||
new __Feature__Controller(
|
||||
new Create__Feature__UseCase(
|
||||
repository, new Sequential__Feature__IdFactory(), tx),
|
||||
new Get__Feature__UseCase(repository, tx)))
|
||||
.setControllerAdvice(
|
||||
new GlobalExceptionHandler(SpanErrorRecorder.NOOP), new EnvelopeBodyAdvice())
|
||||
.build();
|
||||
|
||||
@Test
|
||||
void aCreateAnswers201WithTheNewResourcesLocation() throws Exception {
|
||||
// when
|
||||
ResultActions response = create("{\"name\":\"first\"}");
|
||||
|
||||
// then
|
||||
response
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(header().string("Location", "http://localhost/__featurePath__/" + STORED.value()))
|
||||
.andExpect(jsonPath("$.data.name").value("first"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlankNameAnswers400WithTheFeaturesOwnCode() throws Exception {
|
||||
// when
|
||||
ResultActions response = create("{\"name\":\" \"}");
|
||||
|
||||
// then
|
||||
response
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.error.code").value("__FEATURE___INVALID"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStored__Feature__IsReadWith200() throws Exception {
|
||||
// given
|
||||
repository.save(__Feature__.create(STORED, "first"));
|
||||
|
||||
// when
|
||||
ResultActions response = mvc.perform(get("/__featurePath__/" + STORED.value()));
|
||||
|
||||
// then
|
||||
response.andExpect(status().isOk()).andExpect(jsonPath("$.data.name").value("first"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownIdAnswers404WithTheFeaturesOwnCode() throws Exception {
|
||||
// when
|
||||
ResultActions response = mvc.perform(get("/__featurePath__/" + STORED.value()));
|
||||
|
||||
// then
|
||||
response
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(jsonPath("$.error.code").value("__FEATURE___NOT_FOUND"));
|
||||
}
|
||||
|
||||
private ResultActions create(String body) throws Exception {
|
||||
return mvc.perform(
|
||||
post("/__featurePath__").contentType(MediaType.APPLICATION_JSON).content(body));
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package dev.caskeleton.adapter.outbound.identifier.__feature__;
|
||||
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Id;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__IdFactory;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Mints {@link __Feature__Id}s as random (version 4) UUIDs from the JDK's secure generator.
|
||||
*
|
||||
* <p>Random UUIDs scatter inserts across a B-tree primary key. When __Feature__ rows are written
|
||||
* often, switch to a time-ordered UUIDv7 as the sample's {@code UuidWorkLogIdFactory} does; the
|
||||
* domain contract (canonical UUID text) does not change.
|
||||
*/
|
||||
public final class Uuid__Feature__IdFactory implements __Feature__IdFactory {
|
||||
|
||||
@Override
|
||||
public __Feature__Id newId() {
|
||||
return __Feature__Id.of(UUID.randomUUID().toString());
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package dev.caskeleton.adapter.outbound.identifier.__feature__;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Id;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class Uuid__Feature__IdFactoryTest {
|
||||
|
||||
private final Uuid__Feature__IdFactory factory = new Uuid__Feature__IdFactory();
|
||||
|
||||
@Test
|
||||
void aThousandMintedIdsAreAllDifferent() {
|
||||
// when
|
||||
Set<__Feature__Id> ids =
|
||||
IntStream.range(0, 1000).mapToObj(i -> factory.newId()).collect(Collectors.toSet());
|
||||
|
||||
// then
|
||||
assertThat(ids).hasSize(1000);
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.__feature__;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.__feature__.__Feature__Controller;
|
||||
import dev.caskeleton.adapter.outbound.identifier.__feature__.Uuid__Feature__IdFactory;
|
||||
import dev.caskeleton.application.__feature__.Create__Feature__UseCase;
|
||||
import dev.caskeleton.application.__feature__.Get__Feature__UseCase;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__IdFactory;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Repository;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
/**
|
||||
* __Feature__: its use cases and its HTTP endpoints.
|
||||
*
|
||||
* <p>Turns itself on from what is on the classpath: a {@link __Feature__Repository} adapter and a
|
||||
* {@link TransactionPort}. Until a repository adapter exists the feature is absent rather than half
|
||||
* present (docs/manual/02-new-feature.md step 5). When the adapter comes from another
|
||||
* auto-configuration, name it in {@code afterName} so this condition sees its bean.
|
||||
*
|
||||
* <p>The use cases are beans, not objects the controller builds, because the method security
|
||||
* advisor proxies beans: {@code @RequiresPermission} on create is enforced by that proxy. Grant
|
||||
* {@code __feature_kebab__:create} to a role under {@code app.authz.role-permissions}; until then
|
||||
* every create is refused (docs/manual/07-authorization.md).
|
||||
*/
|
||||
@AutoConfiguration
|
||||
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
|
||||
@ConditionalOnBean({__Feature__Repository.class, TransactionPort.class})
|
||||
@Import(__Feature__Controller.class)
|
||||
public class __Feature__Config {
|
||||
|
||||
/** Server-assigned ids, unless the application supplies its own factory. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(__Feature__IdFactory.class)
|
||||
public __Feature__IdFactory __featureCamel__IdFactory() {
|
||||
return new Uuid__Feature__IdFactory();
|
||||
}
|
||||
|
||||
/** Creates a __Feature__. */
|
||||
@Bean
|
||||
public Create__Feature__UseCase create__Feature__UseCase(
|
||||
__Feature__Repository repository, __Feature__IdFactory ids, TransactionPort transactions) {
|
||||
return new Create__Feature__UseCase(repository, ids, transactions);
|
||||
}
|
||||
|
||||
/** Reads one __Feature__. */
|
||||
@Bean
|
||||
public Get__Feature__UseCase get__Feature__UseCase(
|
||||
__Feature__Repository repository, TransactionPort transactions) {
|
||||
return new Get__Feature__UseCase(repository, transactions);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.__feature__;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.__feature__.__Feature__Controller;
|
||||
import dev.caskeleton.application.__feature__.Create__Feature__UseCase;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Repository;
|
||||
import dev.caskeleton.domain.__feature__.testkit.InMemory__Feature__Repository;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.context.annotation.ImportCandidates;
|
||||
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
|
||||
|
||||
class __Feature__ConfigTest {
|
||||
|
||||
private final WebApplicationContextRunner runner =
|
||||
new WebApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(__Feature__Config.class));
|
||||
|
||||
@Test
|
||||
void bootDiscoversTheConfigurationThroughItsAutoConfigurationImports() {
|
||||
// when
|
||||
List<String> candidates =
|
||||
ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader()).getCandidates();
|
||||
|
||||
// then
|
||||
assertThat(candidates).contains(__Feature__Config.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutARepositoryAdapterTheFeatureIsAbsent() {
|
||||
runner
|
||||
.withBean(TransactionPort.class, DirectTransactionPort::new)
|
||||
.run(context -> assertThat(context).doesNotHaveBean(__Feature__Controller.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void withARepositoryAdapterTheUseCasesAndTheControllerAreBeans() {
|
||||
runner
|
||||
.withBean(TransactionPort.class, DirectTransactionPort::new)
|
||||
.withBean(__Feature__Repository.class, InMemory__Feature__Repository::new)
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context)
|
||||
.hasSingleBean(Create__Feature__UseCase.class)
|
||||
.hasSingleBean(__Feature__Controller.class));
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package dev.caskeleton.application.__feature__;
|
||||
|
||||
import dev.caskeleton.application.command.Command;
|
||||
|
||||
/**
|
||||
* The intent to create a __Feature__. Carries plain values; the aggregate checks them.
|
||||
*
|
||||
* @param name the requested name
|
||||
*/
|
||||
public record Create__Feature__Command(String name) implements Command {}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package dev.caskeleton.application.__feature__;
|
||||
|
||||
import dev.caskeleton.application.capability.Idempotency;
|
||||
import dev.caskeleton.application.capability.RepositoryAccess;
|
||||
import dev.caskeleton.application.capability.UseCaseCapability;
|
||||
import dev.caskeleton.application.security.RequiresPermission;
|
||||
import dev.caskeleton.application.transaction.TransactionMode;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.application.usecase.CommandUseCase;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__IdFactory;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__InvariantException;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Repository;
|
||||
|
||||
/**
|
||||
* Creates a __Feature__ under a server-minted id.
|
||||
*
|
||||
* <p>Not {@code final} and built as a bean: {@code @RequiresPermission} is enforced by the method
|
||||
* security proxy around the bean, and a class that cannot be proxied fails the boot
|
||||
* ({@code RequiresPermissionProxyabilityTest}). {@code NOT_IDEMPOTENT}: a retried request creates a
|
||||
* second __Feature__. Make it {@code KEYED} with {@code IdempotencyExecutor} when a client may
|
||||
* resend (docs/manual/05-idempotency.md).
|
||||
*/
|
||||
@RequiresPermission("__feature_kebab__:create")
|
||||
@UseCaseCapability(
|
||||
transactionMode = TransactionMode.WRITE,
|
||||
idempotency = Idempotency.NOT_IDEMPOTENT,
|
||||
repositoryAccess = RepositoryAccess.WRITE_REPOSITORY)
|
||||
public class Create__Feature__UseCase
|
||||
implements CommandUseCase<Create__Feature__Command, __Feature__View> {
|
||||
|
||||
private final __Feature__Repository repository;
|
||||
private final __Feature__IdFactory ids;
|
||||
private final TransactionPort tx;
|
||||
|
||||
/**
|
||||
* A use case over its ports.
|
||||
*
|
||||
* @param repository where the aggregate is stored
|
||||
* @param ids mints the new id
|
||||
* @param tx the transaction boundary
|
||||
*/
|
||||
public Create__Feature__UseCase(
|
||||
__Feature__Repository repository, __Feature__IdFactory ids, TransactionPort tx) {
|
||||
this.repository = repository;
|
||||
this.ids = ids;
|
||||
this.tx = tx;
|
||||
}
|
||||
|
||||
@Override
|
||||
public __Feature__View handle(Create__Feature__Command command) {
|
||||
__Feature__ created = build(command);
|
||||
return tx.inWrite(() -> __Feature__View.from(repository.save(created)));
|
||||
}
|
||||
|
||||
private __Feature__ build(Create__Feature__Command command) {
|
||||
try {
|
||||
return __Feature__.create(ids.newId(), command.name());
|
||||
} catch (__Feature__InvariantException invalid) {
|
||||
throw new __Feature__RejectedException(invalid);
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package dev.caskeleton.application.__feature__;
|
||||
|
||||
import dev.caskeleton.application.query.Query;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Id;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The intent to read one __Feature__.
|
||||
*
|
||||
* @param id the identifier to read
|
||||
*/
|
||||
public record Get__Feature__Query(__Feature__Id id) implements Query {
|
||||
|
||||
public Get__Feature__Query {
|
||||
Objects.requireNonNull(id, "id");
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package dev.caskeleton.application.__feature__;
|
||||
|
||||
import dev.caskeleton.application.capability.Idempotency;
|
||||
import dev.caskeleton.application.capability.RepositoryAccess;
|
||||
import dev.caskeleton.application.capability.UseCaseCapability;
|
||||
import dev.caskeleton.application.transaction.TransactionMode;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.application.usecase.QueryUseCase;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Repository;
|
||||
|
||||
/**
|
||||
* Reads one __Feature__. A read needs no {@code @RequiresPermission}; add one, or an object access
|
||||
* check, when not every authenticated caller may see every __Feature__
|
||||
* (docs/manual/07-authorization.md).
|
||||
*/
|
||||
@UseCaseCapability(
|
||||
transactionMode = TransactionMode.READ_ONLY,
|
||||
idempotency = Idempotency.IDEMPOTENT,
|
||||
repositoryAccess = RepositoryAccess.READ_REPOSITORY)
|
||||
public class Get__Feature__UseCase implements QueryUseCase<Get__Feature__Query, __Feature__View> {
|
||||
|
||||
private final __Feature__Repository repository;
|
||||
private final TransactionPort tx;
|
||||
|
||||
/**
|
||||
* A use case over its ports.
|
||||
*
|
||||
* @param repository where the aggregate is read from
|
||||
* @param tx the transaction boundary
|
||||
*/
|
||||
public Get__Feature__UseCase(__Feature__Repository repository, TransactionPort tx) {
|
||||
this.repository = repository;
|
||||
this.tx = tx;
|
||||
}
|
||||
|
||||
@Override
|
||||
public __Feature__View handle(Get__Feature__Query query) {
|
||||
return tx.inRead(
|
||||
() ->
|
||||
repository
|
||||
.findById(query.id())
|
||||
.map(__Feature__View::from)
|
||||
.orElseThrow(() -> new __Feature__NotFoundException(query.id())));
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package dev.caskeleton.application.__feature__;
|
||||
|
||||
import dev.caskeleton.shared.error.ApiErrorCode;
|
||||
import dev.caskeleton.shared.error.Category;
|
||||
|
||||
/**
|
||||
* The client-facing failures of the __Feature__ use cases. Every transport maps them through {@code
|
||||
* ApiErrorCarrier}; no handler names this feature. A service records its own codes in its own
|
||||
* registry, not in docs/registries/error-codes.yaml (docs/manual/06-errors.md).
|
||||
*/
|
||||
public enum __Feature__ErrorCode implements ApiErrorCode {
|
||||
__FEATURE___NOT_FOUND(Category.NOT_FOUND, 404),
|
||||
__FEATURE___INVALID(Category.VALIDATION, 400);
|
||||
|
||||
private final Category category;
|
||||
private final int httpStatus;
|
||||
|
||||
__Feature__ErrorCode(Category category, int httpStatus) {
|
||||
this.category = category;
|
||||
this.httpStatus = httpStatus;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String code() {
|
||||
return name();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Category category() {
|
||||
return category;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int httpStatus() {
|
||||
return httpStatus;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retryable() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package dev.caskeleton.application.__feature__;
|
||||
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Id;
|
||||
import dev.caskeleton.shared.error.ApiErrorCarrier;
|
||||
import dev.caskeleton.shared.error.ApiErrorCode;
|
||||
|
||||
/** No __Feature__ has the requested id. A client error: {@code __FEATURE___NOT_FOUND}, 404. */
|
||||
public class __Feature__NotFoundException extends RuntimeException implements ApiErrorCarrier {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* The failure for one id.
|
||||
*
|
||||
* @param id the id that was not found
|
||||
*/
|
||||
public __Feature__NotFoundException(__Feature__Id id) {
|
||||
super("__Feature__ not found: " + id.value());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiErrorCode errorCode() {
|
||||
return __Feature__ErrorCode.__FEATURE___NOT_FOUND;
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package dev.caskeleton.application.__feature__;
|
||||
|
||||
import dev.caskeleton.domain.__feature__.__Feature__InvariantException;
|
||||
import dev.caskeleton.shared.error.ApiErrorCarrier;
|
||||
import dev.caskeleton.shared.error.ApiErrorCode;
|
||||
|
||||
/**
|
||||
* The request asked for a __Feature__ that breaks an invariant. A client error: {@code
|
||||
* __FEATURE___INVALID}, 400. The domain exception stays the cause, so its {@code reason()} reaches
|
||||
* the logs; only the code reaches the client.
|
||||
*/
|
||||
public class __Feature__RejectedException extends RuntimeException implements ApiErrorCarrier {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* Wraps the broken invariant.
|
||||
*
|
||||
* @param cause the domain failure
|
||||
*/
|
||||
public __Feature__RejectedException(__Feature__InvariantException cause) {
|
||||
super("__Feature__ rejected: " + cause.reason(), cause);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiErrorCode errorCode() {
|
||||
return __Feature__ErrorCode.__FEATURE___INVALID;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package dev.caskeleton.application.__feature__;
|
||||
|
||||
import dev.caskeleton.domain.__feature__.__Feature__;
|
||||
|
||||
/**
|
||||
* What a use case hands back about one __Feature__. An application type, so a transport never
|
||||
* receives the aggregate itself.
|
||||
*
|
||||
* @param id the identifier text
|
||||
* @param name the name
|
||||
*/
|
||||
public record __Feature__View(String id, String name) {
|
||||
|
||||
static __Feature__View from(__Feature__ aggregate) {
|
||||
return new __Feature__View(aggregate.id().value(), aggregate.name());
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package dev.caskeleton.application.__feature__;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
|
||||
import dev.caskeleton.domain.__feature__.testkit.InMemory__Feature__Repository;
|
||||
import dev.caskeleton.domain.__feature__.testkit.Sequential__Feature__IdFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class Create__Feature__UseCaseTest {
|
||||
|
||||
private final InMemory__Feature__Repository repository = new InMemory__Feature__Repository();
|
||||
private final DirectTransactionPort tx = new DirectTransactionPort();
|
||||
private final Create__Feature__UseCase useCase =
|
||||
new Create__Feature__UseCase(repository, new Sequential__Feature__IdFactory(), tx);
|
||||
|
||||
@Test
|
||||
void aCreated__Feature__IsStoredUnderTheMintedId() {
|
||||
// when
|
||||
useCase.handle(new Create__Feature__Command("first"));
|
||||
|
||||
// then
|
||||
assertThat(repository.findById(Sequential__Feature__IdFactory.idAt(1)).map(found -> found.name()))
|
||||
.contains("first");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCreateCommitsOneWriteTransaction() {
|
||||
// when
|
||||
useCase.handle(new Create__Feature__Command("first"));
|
||||
|
||||
// then
|
||||
assertThat(tx.committed()).containsExactly(DirectTransactionPort.Boundary.WRITE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlankNameIsRejectedWithTheFeaturesInvalidCode() {
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> useCase.handle(new Create__Feature__Command(" ")));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOfSatisfying(
|
||||
__Feature__RejectedException.class, failure -> assertThat(failure.errorCode()).isEqualTo(__Feature__ErrorCode.__FEATURE___INVALID));
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package dev.caskeleton.application.__feature__;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Id;
|
||||
import dev.caskeleton.domain.__feature__.testkit.InMemory__Feature__Repository;
|
||||
import dev.caskeleton.domain.__feature__.testkit.Sequential__Feature__IdFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class Get__Feature__UseCaseTest {
|
||||
|
||||
private static final __Feature__Id STORED = Sequential__Feature__IdFactory.idAt(1);
|
||||
|
||||
private final InMemory__Feature__Repository repository = new InMemory__Feature__Repository();
|
||||
private final Get__Feature__UseCase useCase =
|
||||
new Get__Feature__UseCase(repository, new DirectTransactionPort());
|
||||
|
||||
@Test
|
||||
void aStored__Feature__IsReadAsItsView() {
|
||||
// given
|
||||
repository.save(__Feature__.create(STORED, "first"));
|
||||
|
||||
// when
|
||||
__Feature__View view = useCase.handle(new Get__Feature__Query(STORED));
|
||||
|
||||
// then
|
||||
assertThat(view).isEqualTo(new __Feature__View(STORED.value(), "first"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIdNothingIsStoredUnderIsNotFound() {
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> useCase.handle(new Get__Feature__Query(STORED)));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOfSatisfying(
|
||||
__Feature__NotFoundException.class, failure -> assertThat(failure.errorCode()).isEqualTo(__Feature__ErrorCode.__FEATURE___NOT_FOUND));
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package dev.caskeleton.domain.__feature__;
|
||||
|
||||
import dev.caskeleton.domain.stereotype.AggregateRoot;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The __Feature__ aggregate root: the only way its state changes.
|
||||
*
|
||||
* <p>Generated by {@code scripts/new-feature.sh} with one placeholder field, {@code name}. Replace it
|
||||
* with the feature's real state and keep each invariant in this class: a rule that must always hold
|
||||
* for one __Feature__ belongs here, not in a use case or a mapper (docs/manual/02-new-feature.md).
|
||||
*/
|
||||
@AggregateRoot
|
||||
public final class __Feature__ {
|
||||
|
||||
/** The longest name a __Feature__ accepts; the database column is sized to it. */
|
||||
public static final int NAME_MAX_LENGTH = 100;
|
||||
|
||||
private final __Feature__Id id;
|
||||
private final String name;
|
||||
|
||||
private __Feature__(__Feature__Id id, String name) {
|
||||
this.id = Objects.requireNonNull(id, "id");
|
||||
this.name = requireValidName(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* A new __Feature__.
|
||||
*
|
||||
* @param id the server-assigned identifier
|
||||
* @param name the name; not blank, at most {@link #NAME_MAX_LENGTH} characters
|
||||
* @return the new aggregate
|
||||
* @throws __Feature__InvariantException when the name breaks an invariant
|
||||
*/
|
||||
public static __Feature__ create(__Feature__Id id, String name) {
|
||||
return new __Feature__(id, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* A __Feature__ read back from storage. The same invariants hold: stored state that breaks them
|
||||
* is a defect, and it fails here rather than later.
|
||||
*
|
||||
* @param id the stored identifier
|
||||
* @param name the stored name
|
||||
* @return the aggregate
|
||||
*/
|
||||
public static __Feature__ restore(__Feature__Id id, String name) {
|
||||
return new __Feature__(id, name);
|
||||
}
|
||||
|
||||
public __Feature__Id id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
private static String requireValidName(String name) {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new __Feature__InvariantException(__Feature__InvariantException.Reason.NAME_BLANK);
|
||||
}
|
||||
if (name.length() > NAME_MAX_LENGTH) {
|
||||
throw new __Feature__InvariantException(__Feature__InvariantException.Reason.NAME_TOO_LONG);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package dev.caskeleton.domain.__feature__;
|
||||
|
||||
import dev.caskeleton.domain.identifier.ResourceId;
|
||||
import dev.caskeleton.domain.stereotype.ValueObject;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Identifier of a {@link __Feature__}: the canonical 36-character UUID text. The grammar is checked
|
||||
* here, at construction, so every layer that holds a __Feature__Id holds a valid one.
|
||||
*/
|
||||
@ValueObject
|
||||
public record __Feature__Id(String value) implements ResourceId<__Feature__Id> {
|
||||
|
||||
private static final Pattern CANONICAL_UUID =
|
||||
Pattern.compile(
|
||||
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
|
||||
|
||||
/**
|
||||
* Checks the grammar.
|
||||
*
|
||||
* @throws IllegalArgumentException when {@code value} is not canonical UUID text
|
||||
*/
|
||||
public __Feature__Id {
|
||||
if (value == null || !CANONICAL_UUID.matcher(value).matches()) {
|
||||
throw new IllegalArgumentException("invalid __Feature__Id: " + value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses identifier text.
|
||||
*
|
||||
* @param value canonical UUID text
|
||||
* @return the identifier
|
||||
*/
|
||||
public static __Feature__Id of(String value) {
|
||||
return new __Feature__Id(value);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package dev.caskeleton.domain.__feature__;
|
||||
|
||||
import dev.caskeleton.domain.identifier.IdFactory;
|
||||
|
||||
/**
|
||||
* Mints new {@link __Feature__Id}s. The domain owns the contract; an outbound adapter ({@code
|
||||
* adapter:outbound:identifier}) generates the value, and the create use case calls it.
|
||||
*/
|
||||
public interface __Feature__IdFactory extends IdFactory<__Feature__Id> {}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package dev.caskeleton.domain.__feature__;
|
||||
|
||||
/**
|
||||
* A {@link __Feature__} invariant was broken. Carries a {@link Reason} and nothing about error
|
||||
* codes or HTTP: the application turns it into a client error ({@code
|
||||
* Create__Feature__UseCase}), because domain-core cannot see shared-contract.
|
||||
*/
|
||||
public final class __Feature__InvariantException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** Which invariant was broken. Safe to show a client. */
|
||||
public enum Reason {
|
||||
NAME_BLANK,
|
||||
NAME_TOO_LONG
|
||||
}
|
||||
|
||||
private final Reason reason;
|
||||
|
||||
/**
|
||||
* An invariant failure.
|
||||
*
|
||||
* @param reason which invariant was broken
|
||||
*/
|
||||
public __Feature__InvariantException(Reason reason) {
|
||||
super("__Feature__ invariant violated: " + reason);
|
||||
this.reason = reason;
|
||||
}
|
||||
|
||||
public Reason reason() {
|
||||
return reason;
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package dev.caskeleton.domain.__feature__;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Stores and loads {@link __Feature__} aggregates, one whole aggregate at a time.
|
||||
*
|
||||
* <p>Domain-owned because it speaks only in aggregates. A read whose shape differs from the
|
||||
* aggregate is a separate application {@code *QueryPort} returning a projection
|
||||
* (docs/manual/02-new-feature.md, decision "저장 포트 소유자"). Every implementation passes {@code
|
||||
* __Feature__RepositoryContract} in this module's test fixtures.
|
||||
*/
|
||||
public interface __Feature__Repository {
|
||||
|
||||
/**
|
||||
* Saves the aggregate, inserting it or replacing the stored state with the same id.
|
||||
*
|
||||
* @param aggregate the aggregate to store
|
||||
* @return the stored aggregate as the store now holds it
|
||||
*/
|
||||
__Feature__ save(__Feature__ aggregate);
|
||||
|
||||
/**
|
||||
* Loads one aggregate.
|
||||
*
|
||||
* @param id the identifier
|
||||
* @return the aggregate, or empty when none has that id
|
||||
*/
|
||||
Optional<__Feature__> findById(__Feature__Id id);
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package dev.caskeleton.domain.__feature__;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.NullAndEmptySource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
class __Feature__IdTest {
|
||||
|
||||
@Test
|
||||
void canonicalUuidTextIsAccepted() {
|
||||
assertThat(__Feature__Id.of("0190a3c4-7b2e-7d4f-9a1b-2c3d4e5f6a7b").value())
|
||||
.isEqualTo("0190a3c4-7b2e-7d4f-9a1b-2c3d4e5f6a7b");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {"not-a-uuid", "0190a3c47b2e7d4f9a1b2c3d4e5f6a7b", "1"})
|
||||
void textThatIsNotCanonicalUuidIsRejected(String value) {
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> __Feature__Id.of(value));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageStartingWith("invalid __Feature__Id");
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package dev.caskeleton.domain.__feature__;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.NullAndEmptySource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
class __Feature__Test {
|
||||
|
||||
private static final __Feature__Id ID =
|
||||
__Feature__Id.of("00000000-0000-7000-8000-000000000001");
|
||||
|
||||
@Test
|
||||
void aCreated__Feature__KeepsItsIdAndName() {
|
||||
// when
|
||||
__Feature__ created = __Feature__.create(ID, "first");
|
||||
|
||||
// then
|
||||
assertThat(created).extracting(__Feature__::id, __Feature__::name).containsExactly(ID, "first");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" ", "\t"})
|
||||
void aBlankNameIsRejected(String name) {
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> __Feature__.create(ID, name));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(__Feature__InvariantException.class)
|
||||
.hasFieldOrPropertyWithValue("reason", __Feature__InvariantException.Reason.NAME_BLANK);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("이름이 NAME_MAX_LENGTH + 1자이면 거절한다")
|
||||
void aNameLongerThanTheLimitIsRejected() {
|
||||
// given
|
||||
String name = "x".repeat(__Feature__.NAME_MAX_LENGTH + 1);
|
||||
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> __Feature__.create(ID, name));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(__Feature__InvariantException.class)
|
||||
.hasFieldOrPropertyWithValue("reason", __Feature__InvariantException.Reason.NAME_TOO_LONG);
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package dev.caskeleton.domain.__feature__.testkit;
|
||||
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Repository;
|
||||
|
||||
class InMemory__Feature__RepositoryContractTest extends __Feature__RepositoryContract {
|
||||
|
||||
private final InMemory__Feature__Repository repository = new InMemory__Feature__Repository();
|
||||
|
||||
@Override
|
||||
protected __Feature__Repository repository() {
|
||||
return repository;
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package dev.caskeleton.domain.__feature__.testkit;
|
||||
|
||||
import dev.caskeleton.domain.__feature__.__Feature__;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Id;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Repository;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The one fake of {@link __Feature__Repository}, held to the same promises as every real adapter by
|
||||
* {@link __Feature__RepositoryContract}. Not thread-safe: a use case test is single-threaded.
|
||||
*/
|
||||
public final class InMemory__Feature__Repository implements __Feature__Repository {
|
||||
|
||||
private final Map<__Feature__Id, __Feature__> rows = new LinkedHashMap<>();
|
||||
|
||||
@Override
|
||||
public __Feature__ save(__Feature__ aggregate) {
|
||||
__Feature__ stored = __Feature__.restore(aggregate.id(), aggregate.name());
|
||||
rows.put(stored.id(), stored);
|
||||
return __Feature__.restore(stored.id(), stored.name());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<__Feature__> findById(__Feature__Id id) {
|
||||
return Optional.ofNullable(rows.get(id)).map(row -> __Feature__.restore(row.id(), row.name()));
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package dev.caskeleton.domain.__feature__.testkit;
|
||||
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Id;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__IdFactory;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/**
|
||||
* The one fake of {@link __Feature__IdFactory}: predictable ids, so a test can name the id a create
|
||||
* will mint ({@link #idAt(long)}).
|
||||
*/
|
||||
public final class Sequential__Feature__IdFactory implements __Feature__IdFactory {
|
||||
|
||||
private final AtomicLong next = new AtomicLong(1);
|
||||
|
||||
/**
|
||||
* The id this factory mints on its {@code n}th call, counting from 1.
|
||||
*
|
||||
* @param n the call number
|
||||
* @return that id
|
||||
*/
|
||||
public static __Feature__Id idAt(long n) {
|
||||
return __Feature__Id.of(String.format("00000000-0000-7000-8000-%012d", n));
|
||||
}
|
||||
|
||||
@Override
|
||||
public __Feature__Id newId() {
|
||||
return idAt(next.getAndIncrement());
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package dev.caskeleton.domain.__feature__.testkit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.domain.__feature__.__Feature__;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Id;
|
||||
import dev.caskeleton.domain.__feature__.__Feature__Repository;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* What every {@link __Feature__Repository} promises. {@link InMemory__Feature__Repository} extends
|
||||
* it in domain-core's tests; a real adapter extends it in a lane that runs against its real store
|
||||
* (docs/manual/04-persistence.md). Add a test here before adding a repository method.
|
||||
*/
|
||||
public abstract class __Feature__RepositoryContract {
|
||||
|
||||
private static final __Feature__Id FIRST = Sequential__Feature__IdFactory.idAt(1);
|
||||
private static final __Feature__Id UNKNOWN = Sequential__Feature__IdFactory.idAt(99);
|
||||
|
||||
/**
|
||||
* The repository under test, empty at the start of each test.
|
||||
*
|
||||
* @return the repository
|
||||
*/
|
||||
protected abstract __Feature__Repository repository();
|
||||
|
||||
@Test
|
||||
void aSaved__Feature__IsFoundByItsId() {
|
||||
// given
|
||||
repository().save(__Feature__.create(FIRST, "first"));
|
||||
|
||||
// when
|
||||
Optional<__Feature__> found = repository().findById(FIRST);
|
||||
|
||||
// then
|
||||
assertThat(found.map(__Feature__::name)).contains("first");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIdNothingWasSavedUnderIsNotFound() {
|
||||
assertThat(repository().findById(UNKNOWN)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void savingTheSameIdAgainReplacesTheStoredState() {
|
||||
// given
|
||||
repository().save(__Feature__.create(FIRST, "first"));
|
||||
|
||||
// when
|
||||
repository().save(__Feature__.restore(FIRST, "renamed"));
|
||||
|
||||
// then
|
||||
assertThat(repository().findById(FIRST).map(__Feature__::name)).contains("renamed");
|
||||
}
|
||||
}
|
||||
Executable
+157
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env bash
|
||||
# 새 업무 기능의 뼈대를 계층 leaf에 만든다.
|
||||
#
|
||||
# scripts/new-feature.sh <FeatureName> [--path <segment>] [--no-format]
|
||||
#
|
||||
# 예: scripts/new-feature.sh Invoice -> /invoices
|
||||
# scripts/new-feature.sh PurchaseOrder -> /purchaseOrders
|
||||
# scripts/new-feature.sh Person --path people -> /people
|
||||
#
|
||||
# 만드는 것(배치·이름 근거는 docs/manual/03-placement.md, 단계는 02-new-feature.md):
|
||||
# domain-core dev.caskeleton.domain.<f> aggregate·id·IdFactory·Repository·불변식 예외
|
||||
# testFixtures .../<f>/testkit 포트당 fake 하나 + 공유 계약(XxxRepositoryContract)
|
||||
# application-core dev.caskeleton.application.<f> Create/Get 유스케이스·command·query·view·오류 코드
|
||||
# outbound:identifier dev.caskeleton.adapter.outbound.identifier.<f> Uuid<F>IdFactory
|
||||
# inbound:web dev.caskeleton.adapter.inbound.web.<f> 컨트롤러·요청/응답 DTO
|
||||
# app-bootstrap dev.caskeleton.bootstrap.autoconfigure.<f> <F>Config + AutoConfiguration.imports 한 줄
|
||||
# 그리고 각 leaf의 테스트.
|
||||
#
|
||||
# 만들지 않는 것: 저장 adapter(JPA 엔티티·마이그레이션). 고를 저장소와 번호대가 서비스마다 달라
|
||||
# 사람이 정한다(docs/manual/04-persistence.md). 그 adapter가 생기기 전까지 <F>Config는 꺼져 있다.
|
||||
#
|
||||
# 생성 뒤 그대로 통과해야 하는 검사(scripts/verify-feature-scaffold.sh가 왕복으로 고정한다):
|
||||
# ./gradlew :domain-core:check :application-core:check :adapter:outbound:identifier:check \
|
||||
# :adapter:inbound:web:check :app-bootstrap:check architectureCheck
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'
|
||||
exit 2
|
||||
}
|
||||
|
||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
templates="$repo_root/scripts/feature-scaffold/templates"
|
||||
|
||||
name=""
|
||||
path_segment=""
|
||||
format=1
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--path) path_segment="${2:-}"; shift 2 ;;
|
||||
--no-format) format=0; shift ;;
|
||||
-h|--help) usage ;;
|
||||
-*) echo "알 수 없는 옵션: $1" >&2; usage ;;
|
||||
*) [ -z "$name" ] || usage; name="$1"; shift ;;
|
||||
esac
|
||||
done
|
||||
[ -n "$name" ] || usage
|
||||
|
||||
# --- 이름 검사 -----------------------------------------------------------------------------
|
||||
if ! [[ "$name" =~ ^[A-Z][a-z0-9]+([A-Z][a-z0-9]+)*$ ]]; then
|
||||
echo "기능 이름은 PascalCase여야 한다(예: Invoice, PurchaseOrder): $name" >&2
|
||||
exit 2
|
||||
fi
|
||||
package_name="$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')"
|
||||
camel="$(printf '%s' "${name:0:1}" | tr '[:upper:]' '[:lower:]')${name:1}"
|
||||
upper_snake="$(printf '%s' "$name" | sed -E 's/([a-z0-9])([A-Z])/\1_\2/g' | tr '[:lower:]' '[:upper:]')"
|
||||
kebab="$(printf '%s' "$name" | sed -E 's/([a-z0-9])([A-Z])/\1-\2/g' | tr '[:upper:]' '[:lower:]')"
|
||||
if [ -z "$path_segment" ]; then
|
||||
case "$camel" in
|
||||
*s|*x|*ch|*sh) path_segment="${camel}es" ;;
|
||||
*[!aeiou]y) path_segment="${camel%y}ies" ;;
|
||||
*) path_segment="${camel}s" ;;
|
||||
esac
|
||||
fi
|
||||
# AIP-122: 경로 조각은 소문자로 시작하는 영숫자(ForbiddenApiArchitectureTest.CONTROLLER_REQUEST_MAPPINGS_FOLLOW_AIP122).
|
||||
if ! [[ "$path_segment" =~ ^[a-z][a-zA-Z0-9]*$ ]]; then
|
||||
echo "--path는 AIP-122 모양([a-z][a-zA-Z0-9]*)이어야 한다: $path_segment" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Java 예약어와 플랫폼 패키지 이름은 패키지로 쓸 수 없거나 템플릿 코드와 섞인다.
|
||||
reserved=" abstract assert boolean break byte case catch char class const continue default do
|
||||
double else enum extends final finally float for goto if implements import instanceof int
|
||||
interface long native new package private protected public return short static strictfp super
|
||||
switch synchronized this throw throws transient try void volatile while record sealed permits
|
||||
var yield
|
||||
capability command query usecase transaction security tenant operation outbox idempotency lease
|
||||
lock cache messaging observability outbound realtime identifier stereotype notification
|
||||
fileserver objectstorage auth authz error envelope mvc "
|
||||
reserved=" $(printf '%s' "$reserved" | tr -s ' \n' ' ') "
|
||||
if [[ "$reserved" == *" $package_name "* ]]; then
|
||||
echo "'$package_name'는 Java 예약어이거나 템플릿 플랫폼 패키지 이름이다. 다른 이름을 고른다." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# --- 대상 경로 -----------------------------------------------------------------------------
|
||||
substitute() {
|
||||
sed -e "s/__Feature__/$name/g" \
|
||||
-e "s/__featureCamel__/$camel/g" \
|
||||
-e "s/__feature_kebab__/$kebab/g" \
|
||||
-e "s/__featurePath__/$path_segment/g" \
|
||||
-e "s/__FEATURE__/$upper_snake/g" \
|
||||
-e "s/__feature__/$package_name/g"
|
||||
}
|
||||
|
||||
mapfile -t sources < <(cd "$templates" && find . -type f -name '*.tmpl' | sort)
|
||||
[ "${#sources[@]}" -gt 0 ] || { echo "템플릿이 없다: $templates" >&2; exit 1; }
|
||||
|
||||
targets=()
|
||||
for source in "${sources[@]}"; do
|
||||
relative="${source#./}"
|
||||
target="$(printf '%s' "${relative%.tmpl}" | substitute)"
|
||||
if [ -e "$repo_root/$target" ]; then
|
||||
echo "이미 있다(덮어쓰지 않는다): $target" >&2
|
||||
exit 1
|
||||
fi
|
||||
targets+=("$target")
|
||||
done
|
||||
for package_dir in \
|
||||
"src/domain-core/src/main/java/dev/caskeleton/domain/$package_name" \
|
||||
"src/application-core/src/main/java/dev/caskeleton/application/$package_name" \
|
||||
"src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/$package_name"; do
|
||||
if [ -d "$repo_root/$package_dir" ]; then
|
||||
echo "패키지가 이미 있다: $package_dir" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
imports="$repo_root/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports"
|
||||
config_class="dev.caskeleton.bootstrap.autoconfigure.$package_name.${name}Config"
|
||||
[ -f "$imports" ] || { echo "없다: $imports" >&2; exit 1; }
|
||||
|
||||
# --- 생성 ----------------------------------------------------------------------------------
|
||||
for i in "${!sources[@]}"; do
|
||||
mkdir -p "$(dirname "$repo_root/${targets[$i]}")"
|
||||
substitute < "$templates/${sources[$i]#./}" > "$repo_root/${targets[$i]}"
|
||||
echo "생성 ${targets[$i]}"
|
||||
done
|
||||
# 파일 끝 줄바꿈이 없으면 붙이고 한 줄을 더한다.
|
||||
[ -z "$(tail -c1 "$imports")" ] || printf '\n' >> "$imports"
|
||||
printf '%s\n' "$config_class" >> "$imports"
|
||||
echo "추가 ${imports#"$repo_root/"}: $config_class"
|
||||
|
||||
leaves=(:domain-core :application-core :adapter:outbound:identifier :adapter:inbound:web :app-bootstrap)
|
||||
|
||||
# google-java-format은 Javadoc 줄바꿈을 이름 길이에 따라 다시 맞춘다. 템플릿만으로는 모든 이름에서
|
||||
# spotlessCheck를 통과시킬 수 없어 생성 직후 한 번 적용한다.
|
||||
if [ "$format" -eq 1 ]; then
|
||||
spotless=()
|
||||
for leaf in "${leaves[@]}"; do spotless+=("$leaf:spotlessApply"); done
|
||||
(cd "$repo_root/src" && ./gradlew -q --console=plain "${spotless[@]}")
|
||||
echo "포맷 spotlessApply (${leaves[*]})"
|
||||
fi
|
||||
|
||||
checks=()
|
||||
for leaf in "${leaves[@]}"; do checks+=("$leaf:check"); done
|
||||
cat <<EOF
|
||||
|
||||
$name 뼈대를 만들었다. 다음 순서로 진행한다(docs/manual/02-new-feature.md).
|
||||
|
||||
1. 검사: cd src && ./gradlew ${checks[*]} architectureCheck --console=plain
|
||||
2. 권한: app.authz.role-permissions에 역할 -> $kebab:create 를 준다(07-authorization.md).
|
||||
주기 전까지 POST /$path_segment 는 모두 403이다.
|
||||
3. 저장 adapter: ${name}Repository를 구현하고 ${name}RepositoryContract를 실제 저장소로 상속한다
|
||||
(04-persistence.md). 그 전까지 ${name}Config는 꺼져 있어 /$path_segment 가 없다.
|
||||
4. placeholder 필드 name을 실제 상태로 바꾸고 불변식을 ${name} 안에 둔다.
|
||||
EOF
|
||||
Executable
+88
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env bash
|
||||
# 생성 명령 왕복 검사: 새 기능을 만들면 그 결과가 손대지 않고 PR 게이트를 통과하는가.
|
||||
#
|
||||
# scripts/verify-feature-scaffold.sh [FeatureName ...]
|
||||
#
|
||||
# 작업 트리(추적 파일 + 무시되지 않은 새 파일)를 임시 디렉터리로 복사하고, 거기서
|
||||
# scripts/new-feature.sh를 이름마다 실행한 뒤, 생성물이 닿는 leaf의 check와 architectureCheck를
|
||||
# 돌린다. 작업 트리는 건드리지 않고, 임시 디렉터리는 끝나면 지운다(KEEP_SCAFFOLD_COPY=1이면 남긴다).
|
||||
#
|
||||
# 기본 이름 두 개: 한 단어(Invoice)와 여러 단어(PurchaseOrder). 여러 단어 이름은 패키지·경로·
|
||||
# 오류 코드·권한 이름이 서로 다른 모양으로 갈리고 Javadoc 줄바꿈이 달라지는 경우다.
|
||||
#
|
||||
# 루트 Gradle 태스크 `verifyFeatureScaffold`가 이 스크립트를 부르고 mainCheck에 들어 있다.
|
||||
set -euo pipefail
|
||||
|
||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
names=("$@")
|
||||
[ "${#names[@]}" -gt 0 ] || names=(Invoice PurchaseOrder)
|
||||
|
||||
parent="${TMPDIR:-/tmp}"
|
||||
copy="$(mktemp -d "$parent/feature-scaffold.XXXXXX")"
|
||||
cleanup() {
|
||||
if [ "${KEEP_SCAFFOLD_COPY:-0}" = "1" ]; then
|
||||
echo "복사본을 남겼다: $copy"
|
||||
else
|
||||
rm -rf "$copy"
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
# 작업 트리 그대로(커밋하지 않은 변경 포함). build 산출물은 .gitignore라 빠진다.
|
||||
# 지웠지만 아직 커밋하지 않은 추적 파일은 목록에서 뺀다(`-d`로 받은 경로를 거른다). 그대로 두면
|
||||
# tar가 없는 파일을 만나 실패한다.
|
||||
(cd "$repo_root" && git ls-files -co --exclude-standard -z \
|
||||
| grep -zvxF -f <(git ls-files -d -z | tr '\0' '\n' | sed '/^$/d'; echo '/dev/null/none')) \
|
||||
| (cd "$repo_root" && tar --null -T - -cf -) \
|
||||
| tar -xf - -C "$copy"
|
||||
# architectureCheck의 Git-carryable 검사와 sourceRevision은 Git 저장소를 읽는다.
|
||||
(
|
||||
cd "$copy"
|
||||
git init -q
|
||||
git add -A
|
||||
GIT_AUTHOR_NAME=scaffold GIT_AUTHOR_EMAIL=scaffold@invalid \
|
||||
GIT_COMMITTER_NAME=scaffold GIT_COMMITTER_EMAIL=scaffold@invalid \
|
||||
git commit -q -m "feature scaffold round trip baseline"
|
||||
)
|
||||
|
||||
for name in "${names[@]}"; do
|
||||
"$copy/scripts/new-feature.sh" "$name" > "$copy/new-feature-$name.log"
|
||||
echo "생성: $name"
|
||||
done
|
||||
|
||||
# 생성 명령이 정말로 무언가를 만들었는지(빈 왕복이 녹색이 되지 않게).
|
||||
for name in "${names[@]}"; do
|
||||
package_name="$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')"
|
||||
for required in \
|
||||
"src/domain-core/src/main/java/dev/caskeleton/domain/$package_name/${name}.java" \
|
||||
"src/application-core/src/main/java/dev/caskeleton/application/$package_name/Create${name}UseCase.java" \
|
||||
"src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/$package_name/${name}Controller.java" \
|
||||
"src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/$package_name/${name}Config.java"; do
|
||||
[ -f "$copy/$required" ] || { echo "생성되지 않았다: $required" >&2; exit 1; }
|
||||
done
|
||||
done
|
||||
|
||||
cd "$copy/src"
|
||||
./gradlew --console=plain --continue \
|
||||
:domain-core:check \
|
||||
:application-core:check \
|
||||
:adapter:outbound:identifier:check \
|
||||
:adapter:inbound:web:check \
|
||||
:app-bootstrap:check \
|
||||
architectureCheck
|
||||
|
||||
# 생성된 테스트가 실제로 실행되었는지: 각 leaf의 테스트 결과에 기능 테스트 클래스가 있어야 한다.
|
||||
for name in "${names[@]}"; do
|
||||
for result in \
|
||||
"domain-core/build/test-results/test/TEST-dev.caskeleton.domain.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').${name}Test.xml" \
|
||||
"application-core/build/test-results/test/TEST-dev.caskeleton.application.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').Create${name}UseCaseTest.xml" \
|
||||
"adapter/inbound/web/build/test-results/test/TEST-dev.caskeleton.adapter.inbound.web.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').${name}ControllerTest.xml" \
|
||||
"app-bootstrap/build/test-results/test/TEST-dev.caskeleton.bootstrap.autoconfigure.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').${name}ConfigTest.xml"; do
|
||||
[ -f "$result" ] || { echo "생성된 테스트가 실행되지 않았다: $result" >&2; exit 1; }
|
||||
if grep -q '<failure\|<error' "$result"; then
|
||||
echo "생성된 테스트가 실패했다: $result" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
done
|
||||
echo "feature scaffold 왕복 통과: ${names[*]}"
|
||||
@@ -19,7 +19,6 @@ from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
PLATFORM = REPO_ROOT / "src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient"
|
||||
BOOTSTRAP = REPO_ROOT / "src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/httpclient"
|
||||
DOCS_DIR = REPO_ROOT / "docs/httpclient"
|
||||
ENV_FIELD_MANIFEST = REPO_ROOT / "docs/httpclient/env-fields.yaml"
|
||||
|
||||
@@ -61,7 +60,9 @@ def violation_codes() -> list[str]:
|
||||
for source_file in [
|
||||
PLATFORM / "profile/ClientProfileValidator.java",
|
||||
PLATFORM / "security/TlsPolicyValidator.java",
|
||||
BOOTSTRAP / "HttpClientStartupValidator.java",
|
||||
# The startup validator moved from app-bootstrap into the leaf; the old path made this
|
||||
# script fail on a missing file before it checked anything.
|
||||
PLATFORM / "autoconfigure/HttpClientStartupValidator.java",
|
||||
]:
|
||||
source = source_file.read_text(encoding="utf-8")
|
||||
codes.update(re.findall(r'"([A-Z][A-Z0-9_]{4,})"', source))
|
||||
|
||||
+10
-3
@@ -257,9 +257,9 @@ APP_ASYNC_EXECUTOR_CORE_SIZE=10
|
||||
APP_ASYNC_EXECUTOR_MAX_SIZE=50
|
||||
APP_ASYNC_EXECUTOR_QUEUE_CAPACITY=200
|
||||
APP_PERSISTENCE_JPA_ENABLED=true
|
||||
APP_JPA_HIBERNATE_BATCH_SIZE=0
|
||||
APP_JPA_HIBERNATE_ORDER_INSERTS=false
|
||||
APP_JPA_HIBERNATE_ORDER_UPDATES=false
|
||||
APP_JPA_HIBERNATE_BATCH_SIZE=50
|
||||
APP_JPA_HIBERNATE_ORDER_INSERTS=true
|
||||
APP_JPA_HIBERNATE_ORDER_UPDATES=true
|
||||
APP_JPA_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE=0
|
||||
APP_JPA_HIBERNATE_GENERATE_STATISTICS=false
|
||||
APP_PERSISTENCE_MONGO_ENABLED=true
|
||||
@@ -279,6 +279,8 @@ APP_GRAPHQL_MAXIMUM_COMPLEXITY=10000
|
||||
APP_GRAPHQL_PREPARSED_CACHE_ENTRIES=1000
|
||||
APP_GRAPHQL_PREPARSED_CACHE_WEIGHT=10000000
|
||||
APP_GRAPHQL_PREPARSED_CACHE_EXPIRE_AFTER_ACCESS=30m
|
||||
# 한 요청에서 같은 필드가 DataLoader 없이 이 횟수보다 많이 resolve 되면 WARN + metric (N+1 신호)
|
||||
APP_GRAPHQL_PER_PARENT_FETCH_WARNING_THRESHOLD=10
|
||||
|
||||
# Optional build-composition: these bind only when :adapter:inbound:websocket is present.
|
||||
# The default bootJar does not contain that leaf.
|
||||
@@ -287,6 +289,11 @@ APP_WEBSOCKET_ENDPOINT=/ws
|
||||
APP_WEBSOCKET_ALLOWED_ORIGINS=http://localhost:3000
|
||||
APP_WEBSOCKET_BROADCAST_DESTINATION=/topic/events
|
||||
APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY=10000
|
||||
APP_WEBSOCKET_MESSAGE_SIZE_LIMIT=64KB
|
||||
APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT=512KB
|
||||
APP_WEBSOCKET_SEND_TIME_LIMIT=10s
|
||||
APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE=60s
|
||||
APP_WEBSOCKET_MAX_CONNECTIONS=1000
|
||||
APP_OUTBOX_ENABLED=false
|
||||
APP_OUTBOX_RELAY_ENABLED=false
|
||||
APP_NOTIFICATION_PLATFORM_ENABLED=true
|
||||
|
||||
+4
-2
@@ -198,8 +198,10 @@ EXPOSE 8080 9001
|
||||
# the actuator work lived on an unmerged branch. It has been merged for some time, and a stale
|
||||
# warning about a healthcheck is the kind of comment that gets a real red container ignored.)
|
||||
#
|
||||
# A readiness failure here is a correct UNHEALTHY, not a broken probe: the readiness group includes
|
||||
# the datasource, so a container started with no reachable PostgreSQL is genuinely not ready.
|
||||
# A readiness failure here is a correct UNHEALTHY, not a broken probe. In the default composition
|
||||
# the readiness group is readinessState alone (config/observability.yml); a capability that owns a
|
||||
# connection adds its own indicator when it is selected — the JPA module adds the datasource — so a
|
||||
# container started without that dependency reachable is genuinely not ready.
|
||||
# Kubernetes ignores HEALTHCHECK and uses its own probes against the same path; this exists for
|
||||
# docker and Compose.
|
||||
#
|
||||
|
||||
+12
-2
@@ -18,8 +18,12 @@
|
||||
#
|
||||
# The multi-stage build, --parents descriptor glob, STRICT lock verification,
|
||||
# non-root user, read-only-root-fs writable mounts, and JVM container ergonomics
|
||||
# are all identical to src/Dockerfile — only the bootJar target differs. Keep the
|
||||
# two files' builder stages in sync.
|
||||
# are all identical to src/Dockerfile — only the bootJar target differs.
|
||||
#
|
||||
# Two files rather than one with a COMPOSITION=sample argument: the release image refuses to build
|
||||
# without version and source metadata, and folding a zero-argument demo into it would make that
|
||||
# refusal conditional. The part that must not drift — the dependency stage's COPY lines — is held
|
||||
# equal by DeveloperExperienceContractTest.
|
||||
# =============================================================================
|
||||
|
||||
# Demo defaults so the image builds with zero build-args. Two format constraints from the root
|
||||
@@ -49,8 +53,14 @@ WORKDIR /build/src
|
||||
# (Requires the labs Dockerfile frontend — see the `# syntax` directive at the top of this file.)
|
||||
COPY gradlew ./
|
||||
COPY gradle/ gradle/
|
||||
COPY gradle.properties ./
|
||||
COPY config/ ./config/
|
||||
COPY --parents settings.gradle build.gradle **/build.gradle **/gradle.lockfile ./
|
||||
# The convention plugins, whole — see src/Dockerfile. Without them settings.gradle's
|
||||
# includeBuild('build-logic') has no version catalog and no plugins, and this stage failed before
|
||||
# resolving anything (07-04). DeveloperExperienceContractTest holds these COPY lines equal to the
|
||||
# release image's.
|
||||
COPY build-logic/ ./build-logic/
|
||||
|
||||
# Resolve every module configuration in STRICT mode (no --write-locks in a demo build either).
|
||||
RUN test -n "${RELEASE_VERSION}" \
|
||||
|
||||
@@ -162,6 +162,8 @@ health 스키마만 소유한다.
|
||||
| 관측 tag cardinality (`observation/`) | `wired` | `runtime/GraphQlRequestObservationConventionAdapter` 가 Spring 의 `ExecutionRequestObservationConvention` 을 구현해 Boot 의 `GraphQlObservationAutoConfiguration` 이 이 컨벤션을 가져간다. `autoconfigure/GraphQlObservationWiringTest`(프레임워크가 실제로 해석), `runtime/GraphQlRequestObservationConventionAdapterTest`(실제 `MeterRegistry` 에 임의 이름 10,000개 → series 1개) |
|
||||
| object 인가 (`security/`) | `modelled` | 답하는 계약은 중립 `dev.caskeleton.application.security.ObjectAccessPolicy` 가 소유하고 이 leaf 는 `ApplicationObjectAuthorization` 매핑만 가진다. 실행 경로에 연결하는 configuration 은 없다 |
|
||||
| DataLoader/batching (`dataloader/`) | `wired` | `runtime/GraphQlBatchLoaderRegistrationTest` (실제 graphql-java 실행 + Spring `BatchLoaderRegistry`, 50 parent → 3 downstream 호출), `dataloader/GraphQlBatchContractTest` |
|
||||
| 요청 deadline (`maxExecutionTime`) | `wired` | `systemTest/runtime/GraphQlRequestDeadlineTest`(virtual thread: deadline 근처 `REQUEST_TIMEOUT`, 하위 필드 미실행), `GraphQlRequestDeadlineOnRequestThreadTest`(요청 스레드: 느린 resolver 가 끝난 뒤 응답 — 한계). 이미 도는 resolver 는 끊지 않는다(README 「요청 deadline」) |
|
||||
| per-parent fetch(N+1) 신호 | `wired` | `systemTest/runtime/GraphQlPerParentFetchTest`(일반 `@SchemaMapping` 자식 → WARN 1줄 + `graphql.per.parent.fetch`, registrar 자식 → 조용함). 거부하지 않는다 |
|
||||
| cursor 서명·connection (`pagination/`), fetch profile (`fetch/`) | 라이브러리 | 요청 경로에 없다. 서비스가 직접 호출한다 — README "라이브러리 API". `autoconfigure/GraphQlPolicyRequestPathTest` 가 auto-configuration 이 codec·key ring 을 만들지 않음을 고정 |
|
||||
| 실부하·장애 | 미달성 | 증거 없음 |
|
||||
|
||||
|
||||
@@ -126,6 +126,7 @@ app:
|
||||
preparsed-cache-entries: 1000
|
||||
preparsed-cache-weight: 10000000
|
||||
preparsed-cache-expire-after-access: 30m
|
||||
per-parent-fetch-warning-threshold: 10 # 아래 「N+1」 절
|
||||
observed-operation-names: [] # 비우면 모든 operation 이름이 `other` 로 접힌다
|
||||
```
|
||||
|
||||
@@ -238,9 +239,82 @@ tenant/정렬 축으로 넘어가는 것을 막기 위함이며, 키 회전은 `
|
||||
|
||||
## DataLoader 는 요청 스코프, 캐시 키는 actor·tenant 지문으로 격리
|
||||
|
||||
`dataloader/GraphQlDataLoaderRequestRegistry` 는 요청마다 새 인스턴스를 만든다. 전역 캐시는
|
||||
tenant 간 데이터 누출 경로가 된다. `security/GraphQlBatchContext.cacheScope()` 는 raw tenant id 가
|
||||
아니라 **sha256 지문**을 캐시 스코프에 쓴다(로그·메트릭에 tenant 원문이 새지 않도록).
|
||||
요청 스코프는 Spring 이 준다. `runtime/GraphQlBatchLoaderRegistrar.register` 는 loader 를 Spring 의
|
||||
`BatchLoaderRegistry` 에 등록하고, Spring 은 실행마다 새 `DataLoaderRegistry` 를 만든다. 그래서
|
||||
loader 캐시는 그 요청이 끝나면 함께 사라지고, 한 호출자가 받은 행이 다음 호출자에게 가지 않는다
|
||||
(`GraphQlBatchLoaderRegistrationTest.oneRequestsCacheIsNotHandedToTheNext`). 전역 캐시는 tenant 간
|
||||
데이터 누출 경로가 된다. 각 chunk 는 `dataloader/GraphQlBatchContext` 를 받고, 그
|
||||
`cacheScope()` 는 raw tenant id 가 아니라 actor·tenant 의 **sha256 지문**이다(로그·메트릭에 tenant
|
||||
원문이 새지 않도록).
|
||||
|
||||
요청마다 새로 만든다고 설명하던 `GraphQlDataLoaderRequestRegistry` 와
|
||||
`GraphQlDataLoaderFactory.newRequestRegistry()` 는 어느 요청 경로에도 연결되지 않아 2026-11-02 에
|
||||
삭제했다(리뷰 03-04).
|
||||
|
||||
플랫폼 context 없이 batch 가 불리면(transport interceptor 미배선) `GraphQlPlatformContextMissingException`
|
||||
으로 거부한다. wire 는 `INTERNAL_ERROR` + `constraint: PLATFORM_CONTEXT`, 로그는 WARN 한 줄이다.
|
||||
instrumentation 이 context 없는 요청을 거부할 때와 같은 constraint 다. 예전에는 `REQUEST_TIMEOUT` 으로
|
||||
나가서 조립 오류가 "느리다"로 보였고 클라이언트가 재시도했다(리뷰 03-05).
|
||||
|
||||
## N+1 — list 부모 아래 자식 필드는 `GraphQlBatchLoaderRegistrar.register` 로
|
||||
|
||||
플랫폼의 batch 보호(chunk 크기, 요청 deadline 으로 줄인 batch 예산, actor·tenant scope)는
|
||||
`GraphQlBatchLoaderRegistrar.register` 로 등록한 loader 에만 붙는다. 조립 예시는 복사본을 두지 않고
|
||||
컴파일·실행되는 테스트 소스를 가리킨다:
|
||||
[`src/systemTest/java/.../example/OrderCustomerBatchLoading.java`](src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/example/OrderCustomerBatchLoading.java).
|
||||
세 부분이다 — loader 이름의 `GraphQlBatchPolicy` 를 담은 `GraphQlBatchPolicyRegistry` bean, 생성자에서
|
||||
`registrar.register(batchLoaders, CUSTOMER_BY_ID, (ids, batch) -> customers.findByIds(ids))` 한 번,
|
||||
자식 필드 `@SchemaMapping` 은 `environment.getDataLoader(...).load(key)` 만 한다.
|
||||
`GraphQlPerParentFetchTest` 가 이 예시로 부모 8개 → downstream 1번을 확인한다.
|
||||
|
||||
같은 일을 하는 다른 길과의 차이:
|
||||
|
||||
| 방법 | 부모 N개일 때 downstream 호출 | chunk·deadline·tenant scope |
|
||||
| --- | --- | --- |
|
||||
| `GraphQlBatchLoaderRegistrar.register` | batch 당 1번(policy 의 `maxBatchSize` 로 chunk) | 적용 |
|
||||
| Spring `@BatchMapping` | 1번 | 미적용 — 크기 상한·deadline·tenant 지문이 없다 |
|
||||
| 부모마다 부르는 일반 `@SchemaMapping` | N번 | 미적용 |
|
||||
|
||||
adopter 가 잊었을 때를 위해 `runtime/GraphQlPerParentFetchInstrumentation` 이 실행을 센다. 한
|
||||
요청에서 같은 필드 좌표가 **DataLoader 를 거치지 않고**(환경에서 DataLoader·registry 를 꺼내지 않고)
|
||||
resolver 를 `app.graphql.limits.per-parent-fetch-warning-threshold`(기본 10)번보다 많이 부르면 그
|
||||
좌표로 WARN 한 줄과 `graphql.per.parent.fetch` observation(태그 `graphql.schema.coordinate`) 하나를
|
||||
남긴다. 거부하지는 않는다 — 부모마다 부르는 resolver 가 싼지는 adopter 만 안다. property 읽기 같은
|
||||
trivial fetcher 는 세지 않는다. 기본 10 은 기본 page 크기 20 보다 작아서 기본 page 아래의 N+1 은
|
||||
잡히고, 보통 문서가 alias 로 root 를 몇 번 부르는 정도로는 울리지 않는 값이다. metric 은 애플리케이션의
|
||||
`ObservationRegistry` 로 나가며(Actuator 가 있으면 timer 로 집계), 없으면 WARN 만 남는다.
|
||||
|
||||
버린 대안: 카탈로그에 등록되지 않은 list 자식 필드를 기동 때 경고 — 모든 list 필드를 adopter 가
|
||||
카탈로그에 등록해야 의미가 생겨 비용에 비해 효과가 작다. 재검토 조건: sample 에 GraphQL feature 가
|
||||
들어오면 그 코드가 위 예시를 대신한다.
|
||||
|
||||
## 요청 deadline — 무엇이 끊기고 무엇이 안 끊기나
|
||||
|
||||
`GraphQlClientPolicy.maxExecutionTime`(기본 10초)으로 만든 `GraphQlDeadline` 하나를 다음이 읽는다.
|
||||
|
||||
- `runtime/GraphQlPlatformWebInterceptor`: deadline 까지 남은 시간으로 응답에 timer 를 건다. 시간이
|
||||
지나면 클라이언트는 `REQUEST_TIMEOUT`(category `TIMEOUT`)을 받고, Spring 이 실행을 cancel 해서
|
||||
graphql-java 가 다음 필드를 더 dispatch 하지 않는다.
|
||||
- `runtime/GraphQlDeadlineInstrumentation`: deadline 이 지난 뒤에는 non-trivial resolver 를 부르지 않고
|
||||
그 필드를 `REQUEST_TIMEOUT` 으로 실패시킨다.
|
||||
- `GraphQlCostBudgetHandler`: deadline 이 이미 지났으면 실행을 시작하지 않는다.
|
||||
- `GraphQlBatchExecutor`: registrar 로 등록한 batch 예산을 남은 시간으로 줄이고, chunk 사이에서 멈춘다.
|
||||
|
||||
**한계(테스트로 고정).** 이미 돌고 있는 resolver 는 끊지 않는다. 그 스레드는 resolver 가 끝날 때까지
|
||||
돌고, 그 안의 DB·HTTP 호출은 각 client 의 timeout 이 끊는다 — JPA/Mongo/HTTP client 에 deadline 을
|
||||
넘겨주는 장치는 없다. 응답이 deadline 에 바로 나가는지는 resolver 가 어느 스레드에서 도는지에 달렸다.
|
||||
|
||||
| 실행 스레드 | 클라이언트가 응답을 받는 때 | 테스트 |
|
||||
| --- | --- | --- |
|
||||
| virtual thread 켬(템플릿 기본 `SPRING_THREADS_VIRTUAL_ENABLED=true`): Spring 이 blocking controller 를 executor 에서 부른다 | deadline 근처 | `GraphQlRequestDeadlineTest` |
|
||||
| virtual thread 끔: blocking controller 가 요청 스레드에서 돈다 | 느린 resolver 가 끝난 뒤. 그 아래 필드는 실행되지 않는다 | `GraphQlRequestDeadlineOnRequestThreadTest` |
|
||||
|
||||
고른 방법과 버린 대안: deadline 은 플랫폼 interceptor 안에서 요청 context 의 `GraphQlDeadline` 값
|
||||
그대로 건다. Spring 의 `TimeoutWebGraphQlInterceptor` 는 GraphQL 본문 없는 HTTP 408 로 끝나 플랫폼
|
||||
`REQUEST_TIMEOUT` 코드를 잃고, 자기 duration 을 따로 받아 deadline 과 갈라질 수 있어 쓰지 않았다.
|
||||
resolver 마다 deadline 을 검사하게 하는 방법은 adopter 가 기억해야 하는 숨은 규칙이 되어 버렸다.
|
||||
예산을 좁히기만 하던 `execution/GraphQlTimeoutPolicy` 는 main 호출자가 없었고 같은 계산이
|
||||
`GraphQlBatchExecutor.effectiveBudget` 에 있어 삭제했다(리뷰 03-02).
|
||||
|
||||
## 관측은 저-카디널리티 강제
|
||||
|
||||
|
||||
@@ -119,7 +119,6 @@ strictTestLanes {
|
||||
description = 'Runs exact no-skip GraphQL conditional transport wire evidence.'
|
||||
requires 'dev.caskeleton.adapter.inbound.graphql.GraphqlHttpBoundaryQualificationTest'
|
||||
rejectSkipped = true
|
||||
jvmArgs '-Duser.timezone=UTC'
|
||||
}
|
||||
// The transport-boundary ArchUnit suite runs in `test` too; this lane is the guard that it is
|
||||
// still discovered and not skipped — a missing class leaves `test` green.
|
||||
@@ -127,7 +126,6 @@ strictTestLanes {
|
||||
description = 'Runs the GraphQL transport-boundary architecture suite and fails if it is gone or skipped.'
|
||||
requires 'dev.caskeleton.adapter.inbound.graphql.GraphQlTransportBoundaryArchitectureTest'
|
||||
rejectSkipped = true
|
||||
jvmArgs '-Duser.timezone=UTC'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+31
@@ -9,15 +9,19 @@ import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
|
||||
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionPipeline;
|
||||
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
|
||||
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlCostBudgetHandler;
|
||||
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDeadlineInstrumentation;
|
||||
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDocumentAuthorizationHandler;
|
||||
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionChain;
|
||||
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlOperationSelectionHandler;
|
||||
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPerParentFetchInstrumentation;
|
||||
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformInstrumentation;
|
||||
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationInterceptor;
|
||||
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationPolicy;
|
||||
import graphql.execution.instrumentation.Instrumentation;
|
||||
import io.micrometer.observation.ObservationRegistry;
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -130,4 +134,31 @@ class GraphQlExecutionChainConfiguration {
|
||||
GraphQlExecutionChain chain, GraphQlWireErrorMapper errors) {
|
||||
return new GraphQlPlatformInstrumentation(chain, errors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses to start a resolver after the request deadline (review 03-02).
|
||||
*
|
||||
* <p>The transport interceptor's timer answers the client at the deadline; this is the part that
|
||||
* still holds when the execution runs on the request thread and the timer cannot fire in time.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(GraphQlDeadlineInstrumentation.class)
|
||||
Instrumentation graphQlDeadlineInstrumentation(Clock graphQlPlatformClock) {
|
||||
return new GraphQlDeadlineInstrumentation(graphQlPlatformClock);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs and records a field that resolves per parent without a DataLoader (review 03-03).
|
||||
*
|
||||
* <p>Records through the application's {@link ObservationRegistry} when there is one, the same
|
||||
* registry Spring for GraphQL's own observations use; without one only the WARN line remains.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(GraphQlPerParentFetchInstrumentation.class)
|
||||
Instrumentation graphQlPerParentFetchInstrumentation(
|
||||
GraphQlPlatformSettings properties, ObjectProvider<ObservationRegistry> observations) {
|
||||
return new GraphQlPerParentFetchInstrumentation(
|
||||
properties.limits().perParentFetchWarningThreshold(),
|
||||
observations.getIfAvailable(() -> ObservationRegistry.NOOP));
|
||||
}
|
||||
}
|
||||
|
||||
+8
-2
@@ -82,17 +82,23 @@ public record GraphQlPlatformSettings(
|
||||
* @param preparsedCacheEntries largest number of cached parsed documents
|
||||
* @param preparsedCacheWeight largest total cached document weight, in characters
|
||||
* @param preparsedCacheExpireAfterAccess how long an unused cached document is kept
|
||||
* @param perParentFetchWarningThreshold how many times one field coordinate may run a resolver
|
||||
* without a DataLoader in one request before it is logged and recorded as a likely N+1
|
||||
* ({@code GraphQlPerParentFetchInstrumentation}). 10 sits below the default page size of 20,
|
||||
* so a default page whose child resolves per parent is reported, and above the handful of
|
||||
* aliased root calls an ordinary document makes
|
||||
*/
|
||||
public record Limits(
|
||||
@DefaultValue("100") int maximumPageSize,
|
||||
@DefaultValue("10000") long maximumComplexity,
|
||||
@DefaultValue("1000") long preparsedCacheEntries,
|
||||
@DefaultValue("10000000") long preparsedCacheWeight,
|
||||
@DefaultValue("30m") Duration preparsedCacheExpireAfterAccess) {
|
||||
@DefaultValue("30m") Duration preparsedCacheExpireAfterAccess,
|
||||
@DefaultValue("10") int perParentFetchWarningThreshold) {
|
||||
|
||||
/** The declared defaults, for programmatic construction. */
|
||||
public static Limits defaults() {
|
||||
return new Limits(100, 10_000, 1_000, 10_000_000, Duration.ofMinutes(30));
|
||||
return new Limits(100, 10_000, 1_000, 10_000_000, Duration.ofMinutes(30), 10);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
@@ -52,6 +52,9 @@ public final class GraphQlPlatformStartupValidator {
|
||||
if (properties.limits().maximumComplexity() < 1) {
|
||||
problems.add("maximum complexity must be positive");
|
||||
}
|
||||
if (properties.limits().perParentFetchWarningThreshold() < 1) {
|
||||
problems.add("per-parent fetch warning threshold must be positive");
|
||||
}
|
||||
return List.copyOf(problems);
|
||||
}
|
||||
|
||||
|
||||
+18
-4
@@ -7,10 +7,24 @@ import java.time.Instant;
|
||||
/**
|
||||
* The absolute instant a GraphQL request must be finished by.
|
||||
*
|
||||
* <p>A deadline rather than a duration, because the same budget has to be handed down to resolvers,
|
||||
* DataLoader batches and the JPA/Mongo/HTTP client deadlines without each layer restarting the
|
||||
* clock. Remaining time is always computed from an injected {@link Clock} so the value stays
|
||||
* testable and the record itself holds no mutable state.
|
||||
* <p>A deadline rather than a duration, so every reader measures against the same instant instead
|
||||
* of restarting the clock. Who reads it today, and nothing more:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code GraphQlPlatformWebInterceptor} ends the request with {@code REQUEST_TIMEOUT} when it
|
||||
* passes, and Spring cancels the execution so no further field is dispatched. A resolver
|
||||
* already running is not interrupted.
|
||||
* <li>{@code GraphQlCostBudgetHandler} refuses to start an execution whose deadline has passed.
|
||||
* <li>{@code GraphQlBatchExecutor} clamps each platform-registered DataLoader batch to what is
|
||||
* left, and stops between chunks once it is spent.
|
||||
* </ul>
|
||||
*
|
||||
* <p>It is <em>not</em> handed to JPA, Mongo or HTTP client calls. A resolver that calls one is
|
||||
* bounded by that client's own timeout; a resolver that wants the request's remainder reads it from
|
||||
* {@link GraphQlRequestContext#deadline()} and passes it on itself.
|
||||
*
|
||||
* <p>Remaining time is always computed from an injected {@link Clock} so the value stays testable
|
||||
* and the record itself holds no mutable state.
|
||||
*
|
||||
* @param value the instant at which the request budget is exhausted
|
||||
*/
|
||||
|
||||
+4
-8
@@ -5,10 +5,11 @@ import java.time.Clock;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Creates the loaders for one execution.
|
||||
* Supplies the per-loader batch executor and the per-execution batch context.
|
||||
*
|
||||
* <p>A factory rather than a bean per loader: instances must be created per execution, and a
|
||||
* factory is what makes that structurally true instead of a convention someone has to remember.
|
||||
* <p>It does not hold loader instances. The request scope is Spring's: {@code
|
||||
* GraphQlBatchLoaderRegistrar} registers with Spring's {@code BatchLoaderRegistry}, and Spring
|
||||
* builds a fresh {@code DataLoaderRegistry} — and so a fresh loader cache — for every execution.
|
||||
*/
|
||||
public final class GraphQlDataLoaderFactory {
|
||||
|
||||
@@ -33,11 +34,6 @@ public final class GraphQlDataLoaderFactory {
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
}
|
||||
|
||||
/** A registry holding this execution's loader instances. */
|
||||
public GraphQlDataLoaderRequestRegistry newRequestRegistry() {
|
||||
return new GraphQlDataLoaderRequestRegistry();
|
||||
}
|
||||
|
||||
/** The batch context for this execution. */
|
||||
public GraphQlBatchContext batchContext(GraphQlRequestContext context) {
|
||||
return GraphQlBatchContext.from(context);
|
||||
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
package dev.caskeleton.adapter.inbound.graphql.dataloader;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The DataLoader instances belonging to one GraphQL execution (design §13).
|
||||
*
|
||||
* <p>A new registry per execution, never a shared singleton. The request-scoped cache is the
|
||||
* reason: it is keyed by entity id and holds whatever the loader returned for <em>this</em> caller,
|
||||
* so sharing it across requests means one user's cached order is served to the next user who asks
|
||||
* for the same id.
|
||||
*
|
||||
* <p>Cross-request caching is a separate concern with a different key model, and belongs to the
|
||||
* cache capability rather than here.
|
||||
*/
|
||||
public final class GraphQlDataLoaderRequestRegistry {
|
||||
|
||||
private final Map<GraphQlDataLoaderName, Object> loaders = new LinkedHashMap<>();
|
||||
|
||||
/** Whether any loader has been created for this execution. */
|
||||
public boolean isEmpty() {
|
||||
return loaders.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a loader instance for this execution.
|
||||
*
|
||||
* @throws IllegalArgumentException when the loader is already registered for this execution
|
||||
*/
|
||||
public GraphQlDataLoaderRequestRegistry register(GraphQlDataLoaderName name, Object loader) {
|
||||
if (name == null || loader == null) {
|
||||
throw new IllegalArgumentException("loader name and instance are required");
|
||||
}
|
||||
if (loaders.putIfAbsent(name, loader) != null) {
|
||||
throw new IllegalArgumentException("loader " + name.value() + " is already registered");
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* The loader instance registered for this execution.
|
||||
*
|
||||
* @throws IllegalArgumentException when it was not registered
|
||||
*/
|
||||
public Object require(GraphQlDataLoaderName name) {
|
||||
Object loader = loaders.get(name);
|
||||
if (loader == null) {
|
||||
throw new IllegalArgumentException("loader " + name.value() + " is not registered");
|
||||
}
|
||||
return loader;
|
||||
}
|
||||
|
||||
/** Loader names registered for this execution. */
|
||||
public Set<GraphQlDataLoaderName> loaderNames() {
|
||||
return Set.copyOf(loaders.keySet());
|
||||
}
|
||||
|
||||
/** Releases every loader when the execution finishes, so nothing outlives the request. */
|
||||
public void clear() {
|
||||
loaders.clear();
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -6,7 +6,10 @@ import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
|
||||
import dev.caskeleton.shared.error.Category;
|
||||
|
||||
/**
|
||||
* Raised when work continues after the request was cancelled or its budget expired.
|
||||
* Raised when the request budget ({@code GraphQlClientPolicy.maxExecutionTime}) has run out.
|
||||
*
|
||||
* <p>Two places raise it: the cost stage, when the deadline passed before execution started, and
|
||||
* the transport interceptor, when it passes while the execution is running.
|
||||
*
|
||||
* <p>Carries the stable timeout error code and no request content.
|
||||
*/
|
||||
@@ -17,12 +20,12 @@ public class GraphQlRequestCancelledException extends RuntimeException
|
||||
|
||||
/** Creates the failure. */
|
||||
public GraphQlRequestCancelledException() {
|
||||
super("GraphQL request was cancelled: " + GraphQlTimeoutPolicy.TIMEOUT_ERROR_CODE);
|
||||
super("GraphQL request was cancelled: " + GraphQlErrorCode.REQUEST_TIMEOUT);
|
||||
}
|
||||
|
||||
/** The stable error code clients see. */
|
||||
public String code() {
|
||||
return GraphQlTimeoutPolicy.TIMEOUT_ERROR_CODE;
|
||||
return GraphQlErrorCode.REQUEST_TIMEOUT;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package dev.caskeleton.adapter.inbound.graphql.execution;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* A remaining time budget that only ever narrows (design §10).
|
||||
*
|
||||
* <p>Every layer below GraphQL — resolver, DataLoader batch, database statement, HTTP call — asks
|
||||
* this for its own budget, and gets the smaller of what it asked for and what is actually left.
|
||||
* Without that clamp a five-second database timeout under a two-second request budget keeps the
|
||||
* connection busy for three seconds after the client has already been answered.
|
||||
*
|
||||
* @param remaining time left in the parent budget
|
||||
*/
|
||||
public record GraphQlTimeoutPolicy(Duration remaining) {
|
||||
|
||||
/** Stable error code emitted when the request budget is exhausted. */
|
||||
public static final String TIMEOUT_ERROR_CODE = "REQUEST_TIMEOUT";
|
||||
|
||||
public GraphQlTimeoutPolicy {
|
||||
if (remaining == null || remaining.isZero() || remaining.isNegative()) {
|
||||
throw new IllegalArgumentException("remaining time must be positive");
|
||||
}
|
||||
}
|
||||
|
||||
/** The budget a child operation may use: never more than what remains. */
|
||||
public Duration child(Duration requested) {
|
||||
if (requested == null || requested.isZero() || requested.isNegative()) {
|
||||
throw new IllegalArgumentException("requested budget must be positive");
|
||||
}
|
||||
return requested.compareTo(remaining) < 0 ? requested : remaining;
|
||||
}
|
||||
|
||||
/** A policy for the child budget, for chaining further down. */
|
||||
public GraphQlTimeoutPolicy childPolicy(Duration requested) {
|
||||
return new GraphQlTimeoutPolicy(child(requested));
|
||||
}
|
||||
}
|
||||
+7
@@ -18,5 +18,12 @@ public final class GraphQlObservationNames {
|
||||
/** One DataLoader batch. */
|
||||
public static final String DATA_LOADER = "graphql.dataloader";
|
||||
|
||||
/**
|
||||
* The platform's own: one request in which a field coordinate crossed the per-parent fetch
|
||||
* threshold ({@code GraphQlPerParentFetchInstrumentation}). Not emitted by Spring; tagged only
|
||||
* with the schema coordinate.
|
||||
*/
|
||||
public static final String PER_PARENT_FETCH = "graphql.per.parent.fetch";
|
||||
|
||||
private GraphQlObservationNames() {}
|
||||
}
|
||||
|
||||
+12
-2
@@ -3,13 +3,14 @@ package dev.caskeleton.adapter.inbound.graphql.runtime;
|
||||
import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext;
|
||||
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchContext;
|
||||
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchExecutor;
|
||||
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException;
|
||||
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderFactory;
|
||||
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.BiFunction;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.graphql.execution.BatchLoaderRegistry;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@@ -31,6 +32,8 @@ import reactor.core.publisher.Mono;
|
||||
*/
|
||||
public final class GraphQlBatchLoaderRegistrar {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(GraphQlBatchLoaderRegistrar.class);
|
||||
|
||||
private final GraphQlDataLoaderFactory factory;
|
||||
|
||||
/**
|
||||
@@ -73,7 +76,14 @@ public final class GraphQlBatchLoaderRegistrar {
|
||||
if (context == null) {
|
||||
// Fail closed. A loader running without the platform context has no deadline, no
|
||||
// tenant and no actor, and would happily batch across whatever the caller was.
|
||||
return Mono.error(new GraphQlBatchTimeoutException(loaderName.value()));
|
||||
// Reported as the assembly fault it is, the same way the instrumentation reports a
|
||||
// request without the context: INTERNAL_ERROR on the wire, the cause in the log.
|
||||
LOG.warn(
|
||||
"graphql batch rejected: no platform context (loader={});"
|
||||
+ " the platform transport interceptor is not wired",
|
||||
loaderName.value());
|
||||
return Mono.error(
|
||||
new GraphQlPlatformContextMissingException("loader " + loaderName.value()));
|
||||
}
|
||||
GraphQlBatchContext batchContext = factory.batchContext(context);
|
||||
return Mono.fromCallable(
|
||||
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package dev.caskeleton.adapter.inbound.graphql.runtime;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext;
|
||||
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException;
|
||||
import graphql.execution.instrumentation.InstrumentationState;
|
||||
import graphql.execution.instrumentation.SimplePerformantInstrumentation;
|
||||
import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters;
|
||||
import graphql.schema.DataFetcher;
|
||||
import java.time.Clock;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Refuses to start a resolver once the request deadline has passed (review 03-02).
|
||||
*
|
||||
* <p>The transport interceptor ends the request at its deadline with a timer, and that is enough
|
||||
* whenever the execution runs off the request thread. It is not enough when it runs on it: on a
|
||||
* servlet stack without virtual threads Spring for GraphQL invokes a blocking controller method on
|
||||
* the request thread, the whole execution happens inside the subscription, and the timer only
|
||||
* starts after it has finished. This check is what still holds there: every non-trivial fetch after
|
||||
* the deadline fails with {@code REQUEST_TIMEOUT} instead of calling the resolver, so a slow parent
|
||||
* does not drag its children's downstream calls behind it.
|
||||
*
|
||||
* <p>Trivial fetchers (property reads) are left alone: they do no downstream work, and checking the
|
||||
* clock on every one of them would cost more than it saves. A resolver already running is not
|
||||
* interrupted — nothing here can stop a blocking call it did not start.
|
||||
*
|
||||
* <p>Chosen over cancelling the {@code ExecutionInput}: graphql-java answers a cancelled execution
|
||||
* with its own {@code AbortExecutionException} message, which would replace the platform's {@code
|
||||
* REQUEST_TIMEOUT} code with an unmapped one.
|
||||
*/
|
||||
public final class GraphQlDeadlineInstrumentation extends SimplePerformantInstrumentation {
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
/**
|
||||
* Creates the instrumentation.
|
||||
*
|
||||
* @param clock the clock the request deadline is measured against
|
||||
*/
|
||||
public GraphQlDeadlineInstrumentation(Clock clock) {
|
||||
this.clock = Objects.requireNonNull(clock, "clock is required");
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataFetcher<?> instrumentDataFetcher(
|
||||
DataFetcher<?> dataFetcher,
|
||||
InstrumentationFieldFetchParameters parameters,
|
||||
InstrumentationState state) {
|
||||
if (parameters.isTrivialDataFetcher()) {
|
||||
return dataFetcher;
|
||||
}
|
||||
return environment -> {
|
||||
GraphQlRequestContext context =
|
||||
environment.getGraphQlContext().get(GraphQlRequestContext.CONTEXT_KEY);
|
||||
if (context != null && context.deadline().expired(clock)) {
|
||||
throw new GraphQlRequestCancelledException();
|
||||
}
|
||||
return dataFetcher.get(environment);
|
||||
};
|
||||
}
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
package dev.caskeleton.adapter.inbound.graphql.runtime;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationNames;
|
||||
import graphql.execution.ExecutionStepInfo;
|
||||
import graphql.execution.instrumentation.InstrumentationState;
|
||||
import graphql.execution.instrumentation.SimplePerformantInstrumentation;
|
||||
import graphql.execution.instrumentation.parameters.InstrumentationCreateStateParameters;
|
||||
import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters;
|
||||
import graphql.schema.DataFetcher;
|
||||
import graphql.schema.DataFetchingEnvironment;
|
||||
import graphql.schema.DelegatingDataFetchingEnvironment;
|
||||
import io.micrometer.observation.Observation;
|
||||
import io.micrometer.observation.ObservationRegistry;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.dataloader.DataLoader;
|
||||
import org.dataloader.DataLoaderRegistry;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Makes an N+1 resolver visible: counts, per request, how often one field coordinate runs a
|
||||
* resolver that did not go through a DataLoader (review 03-03).
|
||||
*
|
||||
* <p>The platform's batch protection — chunking, the request deadline, the tenant-scoped cache —
|
||||
* reaches only loaders registered through {@link GraphQlBatchLoaderRegistrar}. A child field under
|
||||
* a list parent written as a plain {@code @SchemaMapping} calls its downstream once per parent, and
|
||||
* nothing in the platform can see that from the schema. What it can see is the execution: the same
|
||||
* coordinate fetched again and again in one request, each time without touching a DataLoader.
|
||||
*
|
||||
* <p>"Through a DataLoader" means the resolver asked its {@code DataFetchingEnvironment} for one or
|
||||
* for the registry. Spring resolves a {@code DataLoader} method argument that way,
|
||||
* {@code @BatchMapping} does too, and so does a hand-written fetcher; none of those are counted.
|
||||
* Trivial property reads are not counted either. Counting is by invocation, not by thread, so a
|
||||
* resolver Spring runs on the executor (virtual threads) is counted the same as one on the request
|
||||
* thread.
|
||||
*
|
||||
* <p>When a coordinate crosses the threshold in one request this logs one WARN for it and records
|
||||
* one {@value GraphQlObservationNames#PER_PARENT_FETCH} observation tagged with the schema
|
||||
* coordinate, which is bounded by the schema. It never rejects: a per-parent resolver may be
|
||||
* perfectly cheap, and only the adopter knows. The signal exists so an expensive one is found in
|
||||
* the log or a dashboard rather than in a database incident.
|
||||
*
|
||||
* <p>Chosen over a startup check of unregistered list children (review 03-03 option c): that needs
|
||||
* every list field registered in the cost catalog before it can say anything, while this needs
|
||||
* nothing from the adopter.
|
||||
*/
|
||||
public final class GraphQlPerParentFetchInstrumentation extends SimplePerformantInstrumentation {
|
||||
|
||||
private static final Logger LOG =
|
||||
LoggerFactory.getLogger(GraphQlPerParentFetchInstrumentation.class);
|
||||
|
||||
/** The metric tag carrying the field coordinate; allowlisted by the cardinality policy. */
|
||||
public static final String COORDINATE_TAG = "graphql.schema.coordinate";
|
||||
|
||||
private final int warningThreshold;
|
||||
private final ObservationRegistry observations;
|
||||
|
||||
/**
|
||||
* Creates the instrumentation.
|
||||
*
|
||||
* @param warningThreshold per-parent fetches of one coordinate in one request that are still
|
||||
* quiet; one more logs and records
|
||||
* @param observations where the crossing is recorded; {@link ObservationRegistry#NOOP} records
|
||||
* nothing
|
||||
*/
|
||||
public GraphQlPerParentFetchInstrumentation(
|
||||
int warningThreshold, ObservationRegistry observations) {
|
||||
if (warningThreshold < 1) {
|
||||
throw new IllegalArgumentException("per-parent fetch warning threshold must be positive");
|
||||
}
|
||||
this.warningThreshold = warningThreshold;
|
||||
this.observations = Objects.requireNonNull(observations, "observation registry is required");
|
||||
}
|
||||
|
||||
@Override
|
||||
public InstrumentationState createState(InstrumentationCreateStateParameters parameters) {
|
||||
return new Counts();
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataFetcher<?> instrumentDataFetcher(
|
||||
DataFetcher<?> dataFetcher,
|
||||
InstrumentationFieldFetchParameters parameters,
|
||||
InstrumentationState state) {
|
||||
if (parameters.isTrivialDataFetcher() || !(state instanceof Counts counts)) {
|
||||
return dataFetcher;
|
||||
}
|
||||
return environment -> {
|
||||
LoaderTracking tracking = new LoaderTracking(environment);
|
||||
Object value = dataFetcher.get(tracking);
|
||||
if (!tracking.usedDataLoader) {
|
||||
record(counts, coordinate(environment.getExecutionStepInfo()));
|
||||
}
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
private void record(Counts counts, String coordinate) {
|
||||
int fetches =
|
||||
counts
|
||||
.byCoordinate
|
||||
.computeIfAbsent(coordinate, key -> new AtomicInteger())
|
||||
.incrementAndGet();
|
||||
if (fetches != warningThreshold + 1) {
|
||||
return;
|
||||
}
|
||||
LOG.warn(
|
||||
"graphql field {} resolved per parent more than {} times in one request without a"
|
||||
+ " DataLoader; register it with GraphQlBatchLoaderRegistrar",
|
||||
coordinate,
|
||||
warningThreshold);
|
||||
Observation.createNotStarted(GraphQlObservationNames.PER_PARENT_FETCH, observations)
|
||||
.lowCardinalityKeyValue(COORDINATE_TAG, coordinate)
|
||||
.observe(() -> {});
|
||||
}
|
||||
|
||||
private static String coordinate(ExecutionStepInfo step) {
|
||||
return step.getObjectType().getName() + "." + step.getFieldDefinition().getName();
|
||||
}
|
||||
|
||||
/** Per-execution counts, one per coordinate. */
|
||||
private static final class Counts implements InstrumentationState {
|
||||
private final Map<String, AtomicInteger> byCoordinate = new ConcurrentHashMap<>();
|
||||
}
|
||||
|
||||
/** Notes whether the resolver reached for a DataLoader; changes nothing it sees. */
|
||||
private static final class LoaderTracking extends DelegatingDataFetchingEnvironment {
|
||||
|
||||
private volatile boolean usedDataLoader;
|
||||
|
||||
LoaderTracking(DataFetchingEnvironment delegate) {
|
||||
super(delegate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K, V> DataLoader<K, V> getDataLoader(String dataLoaderName) {
|
||||
usedDataLoader = true;
|
||||
return super.getDataLoader(dataLoaderName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataLoaderRegistry getDataLoaderRegistry() {
|
||||
usedDataLoader = true;
|
||||
return super.getDataLoaderRegistry();
|
||||
}
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package dev.caskeleton.adapter.inbound.graphql.runtime;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
|
||||
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
|
||||
import dev.caskeleton.shared.error.Category;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Raised when platform machinery runs without the request context the transport interceptor puts in
|
||||
* place.
|
||||
*
|
||||
* <p>That is an assembly fault — the interceptor is not wired — not anything the client did, so the
|
||||
* client sees an opaque {@code INTERNAL_ERROR} carrying the {@value #CONSTRAINT} constraint and the
|
||||
* operator gets the WARN line naming the cause. It replaced the batch registrar's {@code
|
||||
* GraphQlBatchTimeoutException}, which reported the same fault as a retryable {@code
|
||||
* REQUEST_TIMEOUT}: a mis-assembled deployment looked slow, and clients retried it (review 03-05).
|
||||
*
|
||||
* <p>Package-private: only the runtime machinery raises it, and the wire mapper reads it through
|
||||
* {@link GraphQlPlatformRejection}, so no adopter code needs the type.
|
||||
*/
|
||||
final class GraphQlPlatformContextMissingException extends RuntimeException
|
||||
implements GraphQlPlatformRejection {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** The constraint identity every missing-context rejection carries on the wire. */
|
||||
static final String CONSTRAINT = "PLATFORM_CONTEXT";
|
||||
|
||||
/**
|
||||
* Creates the failure.
|
||||
*
|
||||
* @param where bounded name of the machinery that found the context missing
|
||||
*/
|
||||
GraphQlPlatformContextMissingException(String where) {
|
||||
super("no GraphQL platform context in " + where);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GraphQlErrorCode wireCode() {
|
||||
return GraphQlErrorCode.platform(GraphQlErrorCode.INTERNAL_ERROR);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Category failureCategory() {
|
||||
return Category.INTERNAL;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> constraint() {
|
||||
return Optional.of(CONSTRAINT);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -36,7 +36,8 @@ public final class GraphQlPlatformInstrumentation extends SimplePerformantInstru
|
||||
private static final Logger LOG = LoggerFactory.getLogger(GraphQlPlatformInstrumentation.class);
|
||||
|
||||
/** Constraint reported when the request arrived without a platform context. */
|
||||
public static final String MISSING_CONTEXT_CONSTRAINT = "PLATFORM_CONTEXT";
|
||||
public static final String MISSING_CONTEXT_CONSTRAINT =
|
||||
GraphQlPlatformContextMissingException.CONSTRAINT;
|
||||
|
||||
private final GraphQlExecutionChain chain;
|
||||
private final GraphQlWireErrorMapper errors;
|
||||
|
||||
+25
-1
@@ -6,6 +6,7 @@ import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext;
|
||||
import dev.caskeleton.adapter.inbound.graphql.context.TenantContext;
|
||||
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext;
|
||||
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
|
||||
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException;
|
||||
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlExtensionsPolicy;
|
||||
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlJsonStructurePolicy;
|
||||
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestSize;
|
||||
@@ -18,6 +19,7 @@ import graphql.ExecutionInput;
|
||||
import graphql.ExecutionResult;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
@@ -38,6 +40,10 @@ import reactor.core.publisher.Mono;
|
||||
* the context this interceptor puts into the GraphQL context, so a deployment that omits it gets a
|
||||
* rejected request rather than an unpoliced one.
|
||||
*
|
||||
* <p>It also ends the request at its deadline: the execution is answered with {@code
|
||||
* REQUEST_TIMEOUT} when {@code GraphQlClientPolicy.maxExecutionTime} runs out, whatever is still
|
||||
* running (see {@link #intercept} for what that does and does not stop).
|
||||
*
|
||||
* <p>The document size check is here rather than in a policy object for the same reason: the
|
||||
* transport is where the size is known, and refusing a large document before parsing is the only
|
||||
* place the refusal is cheap.
|
||||
@@ -111,7 +117,25 @@ public final class GraphQlPlatformWebInterceptor implements WebGraphQlIntercepto
|
||||
|
||||
// Also on the Reactor context, so a reactive resolver reads the same value rather than a
|
||||
// second one assembled from whatever it can reach.
|
||||
return chain.next(request).contextWrite(view -> view.put(GraphQlRequestContext.class, context));
|
||||
//
|
||||
// The timeout is the request deadline itself, read from the context just built, so the budget
|
||||
// the pipeline and the DataLoader batches check and the one that ends the request are one value
|
||||
// (review 03-02). On expiry the client gets REQUEST_TIMEOUT and Spring cancels the execution,
|
||||
// which stops graphql-java from dispatching further fields. A resolver already running is not
|
||||
// interrupted: it finishes on its own thread, and its downstream timeouts are what bound it. On
|
||||
// a servlet stack without virtual threads that resolver is running on the request thread, so
|
||||
// the answer can only leave when it returns (GraphQlRequestDeadlineOnRequestThreadTest).
|
||||
//
|
||||
// Chosen over Spring's TimeoutWebGraphQlInterceptor: that one answers with an HTTP 408 and no
|
||||
// GraphQL body, so the client would lose the platform's REQUEST_TIMEOUT code, and it needs its
|
||||
// own duration — a second copy of the budget that could drift from this deadline.
|
||||
Duration budget = context.deadline().remaining(clock);
|
||||
return chain
|
||||
.next(request)
|
||||
.contextWrite(view -> view.put(GraphQlRequestContext.class, context))
|
||||
.timeout(
|
||||
budget,
|
||||
Mono.fromSupplier(() -> reject(request, new GraphQlRequestCancelledException())));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -22,6 +22,9 @@ app:
|
||||
preparsed-cache-entries: ${APP_GRAPHQL_PREPARSED_CACHE_ENTRIES:1000}
|
||||
preparsed-cache-weight: ${APP_GRAPHQL_PREPARSED_CACHE_WEIGHT:10000000}
|
||||
preparsed-cache-expire-after-access: ${APP_GRAPHQL_PREPARSED_CACHE_EXPIRE_AFTER_ACCESS:30m}
|
||||
# 한 요청에서 같은 필드 좌표가 DataLoader 없이 resolver 를 이 횟수보다 많이 부르면 WARN 한 줄과
|
||||
# graphql.per.parent.fetch metric 을 남긴다(N+1 신호, 거부하지 않는다). 기본 10 = 기본 page 크기 20 보다 작다.
|
||||
per-parent-fetch-warning-threshold: ${APP_GRAPHQL_PER_PARENT_FETCH_WARNING_THRESHOLD:10}
|
||||
|
||||
# /actuator/info 에 싣는 이 모듈의 상태(management.info.env). compose smoke 가 lane 이 실제로 켠
|
||||
# capability 를 이 값으로 확인한다. 위 스위치를 해석한 값이고, 기본값은 GraphQlRootAutoConfiguration 의
|
||||
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package dev.caskeleton.adapter.inbound.graphql.example;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchPolicy;
|
||||
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchPolicyRegistry;
|
||||
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName;
|
||||
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBatchLoaderRegistrar;
|
||||
import graphql.schema.DataFetchingEnvironment;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.graphql.data.method.annotation.SchemaMapping;
|
||||
import org.springframework.graphql.execution.BatchLoaderRegistry;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
/**
|
||||
* The README example "a child field under a list parent" — compiled and executed here.
|
||||
*
|
||||
* <p>{@code src/adapter/inbound/graphql/README.md} points at this file instead of carrying a copy,
|
||||
* so the example cannot drift from code that compiles. {@code GraphQlPerParentFetchTest} runs it
|
||||
* over the real endpoint and counts the downstream calls.
|
||||
*
|
||||
* <p>Three parts, all on the adopter's side:
|
||||
*
|
||||
* <ol>
|
||||
* <li>a policy for the loader name (batch size and batch timeout), as a {@link
|
||||
* GraphQlBatchPolicyRegistry} bean;
|
||||
* <li>the downstream call, registered once through {@link GraphQlBatchLoaderRegistrar} — the
|
||||
* platform wraps it in chunking, the request deadline and the request's actor/tenant scope;
|
||||
* <li>the child field, which only asks the DataLoader for its key.
|
||||
* </ol>
|
||||
*/
|
||||
@Controller
|
||||
public class OrderCustomerBatchLoading {
|
||||
|
||||
/** The loader's platform name; the policy and the registration meet on it. */
|
||||
public static final GraphQlDataLoaderName CUSTOMER_BY_ID =
|
||||
new GraphQlDataLoaderName("customer-by-id");
|
||||
|
||||
/** The adopter's downstream port: one call for many ids. */
|
||||
public interface CustomerDirectory {
|
||||
Map<String, Customer> findByIds(List<String> ids);
|
||||
}
|
||||
|
||||
public record Order(String id, String customerId) {}
|
||||
|
||||
public record Customer(String id, String name) {}
|
||||
|
||||
public OrderCustomerBatchLoading(
|
||||
BatchLoaderRegistry batchLoaders,
|
||||
GraphQlBatchLoaderRegistrar registrar,
|
||||
CustomerDirectory customers) {
|
||||
// The batch context carries the request's actor, tenant, deadline and cache scope; a downstream
|
||||
// that filters by tenant reads it from there rather than from a thread-local.
|
||||
registrar.<String, Customer>register(
|
||||
batchLoaders, CUSTOMER_BY_ID, (ids, batch) -> customers.findByIds(ids));
|
||||
}
|
||||
|
||||
/** The child field: one {@code load} per parent, one downstream call per batch. */
|
||||
@SchemaMapping(typeName = "Order", field = "customer")
|
||||
public CompletableFuture<Customer> customer(Order order, DataFetchingEnvironment environment) {
|
||||
return environment
|
||||
.<String, Customer>getDataLoader(CUSTOMER_BY_ID.value())
|
||||
.load(order.customerId());
|
||||
}
|
||||
|
||||
/** The loader's policy: at most 100 keys per downstream call, two seconds per batch. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public static class Policies {
|
||||
|
||||
@Bean
|
||||
GraphQlBatchPolicyRegistry graphQlBatchPolicyRegistry() {
|
||||
return new GraphQlBatchPolicyRegistry()
|
||||
.register(new GraphQlBatchPolicy(CUSTOMER_BY_ID, 100, Duration.ofSeconds(2), true));
|
||||
}
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
package dev.caskeleton.adapter.inbound.graphql.runtime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import dev.caskeleton.adapter.inbound.graphql.example.OrderCustomerBatchLoading;
|
||||
import dev.caskeleton.adapter.inbound.graphql.example.OrderCustomerBatchLoading.Customer;
|
||||
import dev.caskeleton.adapter.inbound.graphql.example.OrderCustomerBatchLoading.CustomerDirectory;
|
||||
import dev.caskeleton.adapter.inbound.graphql.example.OrderCustomerBatchLoading.Order;
|
||||
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationNames;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.observation.DefaultMeterObservationHandler;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import io.micrometer.observation.ObservationRegistry;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringBootConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.resttestclient.TestRestTemplate;
|
||||
import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.graphql.data.method.annotation.Argument;
|
||||
import org.springframework.graphql.data.method.annotation.QueryMapping;
|
||||
import org.springframework.graphql.data.method.annotation.SchemaMapping;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
/**
|
||||
* A child field resolved once per parent is reported; the same field through the registrar is not
|
||||
* (review 03-03).
|
||||
*
|
||||
* <p>Both children of {@code Order} return the same customer. {@code customerPerParent} is the
|
||||
* plain {@code @SchemaMapping} an adopter writes first; {@code customer} is the README example
|
||||
* ({@link OrderCustomerBatchLoading}). The downstream counter is what tells them apart; the WARN
|
||||
* line and the metric are what an operator would see.
|
||||
*/
|
||||
@SpringBootTest(
|
||||
classes = GraphQlPerParentFetchTest.TestApplication.class,
|
||||
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
properties = {
|
||||
"app.graphql.enabled=true",
|
||||
"app.graphql.deployment-mode=LOCAL",
|
||||
"spring.graphql.graphiql.enabled=false",
|
||||
"app.graphql.limits.per-parent-fetch-warning-threshold=5",
|
||||
RuntimeLimitsTestSupport.SCHEMA_LOCATIONS,
|
||||
RuntimeLimitsTestSupport.SCHEMA_FILES
|
||||
})
|
||||
@AutoConfigureTestRestTemplate
|
||||
class GraphQlPerParentFetchTest {
|
||||
|
||||
private static final AtomicInteger DOWNSTREAM_CALLS = new AtomicInteger();
|
||||
|
||||
@LocalServerPort int port;
|
||||
|
||||
@Autowired TestRestTemplate http;
|
||||
|
||||
@Autowired MeterRegistry meters;
|
||||
|
||||
private final ListAppender<ILoggingEvent> warnings = new ListAppender<>();
|
||||
|
||||
private final Logger logger =
|
||||
(Logger) LoggerFactory.getLogger(GraphQlPerParentFetchInstrumentation.class);
|
||||
|
||||
@BeforeEach
|
||||
void captureWarningsAndReset() {
|
||||
meters.clear();
|
||||
DOWNSTREAM_CALLS.set(0);
|
||||
warnings.start();
|
||||
logger.addAppender(warnings);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void releaseCapture() {
|
||||
logger.detachAppender(warnings);
|
||||
warnings.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("list 부모 아래 일반 @SchemaMapping 자식이 임계값을 넘으면 WARN 한 줄과 좌표 metric 이 남는다")
|
||||
void aChildResolvedPerParentPastTheThresholdIsLoggedOnceAndCounted() {
|
||||
// when
|
||||
ResponseEntity<String> response =
|
||||
RuntimeLimitsTestSupport.post(
|
||||
http, port, "{ orders(count: 8) { id customerPerParent { name } } }");
|
||||
|
||||
// then
|
||||
assertThat(response.getBody()).contains("\"name\":\"customer c-7\"");
|
||||
assertThat(DOWNSTREAM_CALLS).as("eight parents, eight downstream calls").hasValue(8);
|
||||
assertThat(warnings.list)
|
||||
.singleElement()
|
||||
.extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage)
|
||||
.containsExactly(
|
||||
Level.WARN,
|
||||
"graphql field Order.customerPerParent resolved per parent more than 5 times in one"
|
||||
+ " request without a DataLoader; register it with GraphQlBatchLoaderRegistrar");
|
||||
assertThat(
|
||||
meters
|
||||
.get(GraphQlObservationNames.PER_PARENT_FETCH)
|
||||
.tag(GraphQlPerParentFetchInstrumentation.COORDINATE_TAG, "Order.customerPerParent")
|
||||
.timer()
|
||||
.count())
|
||||
.isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("registrar 로 조립한 자식은 한 번의 downstream 호출로 끝나고 경고하지 않는다")
|
||||
void theSameChildThroughTheRegistrarIsOneCallAndStaysQuiet() {
|
||||
// when
|
||||
ResponseEntity<String> response =
|
||||
RuntimeLimitsTestSupport.post(http, port, "{ orders(count: 8) { id customer { name } } }");
|
||||
|
||||
// then
|
||||
assertThat(response.getBody()).contains("\"name\":\"customer c-7\"");
|
||||
assertThat(DOWNSTREAM_CALLS).as("eight parents, one batch").hasValue(1);
|
||||
assertThat(warnings.list).isEmpty();
|
||||
assertThat(meters.find(GraphQlObservationNames.PER_PARENT_FETCH).timer()).isNull();
|
||||
}
|
||||
|
||||
/** The list parent and the per-parent child an adopter writes before knowing better. */
|
||||
@Controller
|
||||
static class OrderController {
|
||||
|
||||
private final CustomerDirectory customers;
|
||||
|
||||
OrderController(CustomerDirectory customers) {
|
||||
this.customers = customers;
|
||||
}
|
||||
|
||||
@QueryMapping
|
||||
List<Order> orders(@Argument int count) {
|
||||
return IntStream.range(0, count)
|
||||
.mapToObj(index -> new Order("o-" + index, "c-" + index))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@SchemaMapping(typeName = "Order", field = "customerPerParent")
|
||||
Customer customerPerParent(Order order) {
|
||||
return customers.findByIds(List.of(order.customerId())).get(order.customerId());
|
||||
}
|
||||
}
|
||||
|
||||
@SpringBootConfiguration
|
||||
@EnableAutoConfiguration
|
||||
@Import({
|
||||
RuntimeLimitsTestSupport.Transport.class,
|
||||
OrderController.class,
|
||||
OrderCustomerBatchLoading.class,
|
||||
OrderCustomerBatchLoading.Policies.class
|
||||
})
|
||||
static class TestApplication {
|
||||
|
||||
/** A downstream that counts its calls. */
|
||||
@Bean
|
||||
CustomerDirectory customerDirectory() {
|
||||
return ids -> {
|
||||
DOWNSTREAM_CALLS.incrementAndGet();
|
||||
Map<String, Customer> rows = new LinkedHashMap<>();
|
||||
ids.forEach(id -> rows.put(id, new Customer(id, "customer " + id)));
|
||||
return rows;
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
SimpleMeterRegistry meterRegistry() {
|
||||
return new SimpleMeterRegistry();
|
||||
}
|
||||
|
||||
/** Observations become meters, as they do in a deployment with Actuator. */
|
||||
@Bean
|
||||
ObservationRegistry observationRegistry(SimpleMeterRegistry meters) {
|
||||
ObservationRegistry registry = ObservationRegistry.create();
|
||||
registry.observationConfig().observationHandler(new DefaultMeterObservationHandler(meters));
|
||||
return registry;
|
||||
}
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package dev.caskeleton.adapter.inbound.graphql.runtime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
|
||||
import dev.caskeleton.adapter.inbound.graphql.runtime.RuntimeLimitsTestSupport.SlowWork;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringBootConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.resttestclient.TestRestTemplate;
|
||||
import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
/**
|
||||
* The limit of the request deadline, pinned so nobody reads more into it (review 03-02).
|
||||
*
|
||||
* <p>With virtual threads off, Spring for GraphQL runs a blocking controller method on the servlet
|
||||
* thread that is executing the request. The deadline still fires on time and cancels the execution,
|
||||
* but the thread that would write the answer is the one stuck in the resolver: the client receives
|
||||
* {@code REQUEST_TIMEOUT} only when that resolver returns. Nothing in the JVM can stop a blocking
|
||||
* call it did not start; the resolver's own downstream timeouts are what bound it.
|
||||
*/
|
||||
@SpringBootTest(
|
||||
classes = GraphQlRequestDeadlineOnRequestThreadTest.TestApplication.class,
|
||||
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
properties = {
|
||||
"app.graphql.enabled=true",
|
||||
"app.graphql.deployment-mode=LOCAL",
|
||||
"spring.graphql.graphiql.enabled=false",
|
||||
"spring.threads.virtual.enabled=false",
|
||||
RuntimeLimitsTestSupport.SCHEMA_LOCATIONS,
|
||||
RuntimeLimitsTestSupport.SCHEMA_FILES
|
||||
})
|
||||
@AutoConfigureTestRestTemplate
|
||||
class GraphQlRequestDeadlineOnRequestThreadTest {
|
||||
|
||||
private static final Duration BUDGET = Duration.ofMillis(500);
|
||||
private static final int SLOW_RESOLVER_MILLIS = 2_000;
|
||||
|
||||
@LocalServerPort int port;
|
||||
|
||||
@Autowired TestRestTemplate http;
|
||||
|
||||
@BeforeEach
|
||||
void warmUpAndReset() {
|
||||
RuntimeLimitsTestSupport.post(http, port, "{ _health }");
|
||||
SlowWork.reset();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("요청 스레드에서 도는 blocking resolver 는 끝난 뒤에 REQUEST_TIMEOUT 이 나가고 하위 필드는 실행되지 않는다")
|
||||
void aBlockingResolverOnTheRequestThreadDelaysTheTimeoutAnswerUntilItReturns() {
|
||||
// given
|
||||
long started = System.nanoTime();
|
||||
|
||||
// when
|
||||
ResponseEntity<String> response =
|
||||
RuntimeLimitsTestSupport.post(
|
||||
http, port, "{ slowNode(millis: " + SLOW_RESOLVER_MILLIS + ") { id detail } }");
|
||||
|
||||
// then
|
||||
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started);
|
||||
assertThat(response.getBody())
|
||||
.contains("\"code\":\"REQUEST_TIMEOUT\"")
|
||||
.doesNotContain("detail-of-");
|
||||
assertThat(SlowWork.DETAIL_INVOCATIONS)
|
||||
.as("the cancelled execution stops before the child field")
|
||||
.hasValue(0);
|
||||
assertThat(elapsedMillis)
|
||||
.as("the servlet thread was inside the resolver; the answer could not leave earlier")
|
||||
.isGreaterThanOrEqualTo(SLOW_RESOLVER_MILLIS);
|
||||
}
|
||||
|
||||
@SpringBootConfiguration
|
||||
@EnableAutoConfiguration
|
||||
@Import({RuntimeLimitsTestSupport.Transport.class, RuntimeLimitsTestSupport.SlowController.class})
|
||||
static class TestApplication {
|
||||
|
||||
@Bean
|
||||
GraphQlClientPolicy shortBudgetClientPolicy() {
|
||||
return RuntimeLimitsTestSupport.policyWithExecutionBudget(BUDGET);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user