fix!: 성숙도 리뷰의 High·P1 결함 19건을 고친다
문제: 2026-11-01 성숙도 리뷰에서 High 21건·P1 25건이 나왔다. 결과를 모르는 일을 "확실함"으로 기록했다(발송 중 죽은 알림 재발송, 커밋 중 끊긴 쓰기를 재시도 가능으로 응답, 재시도 가능한 거부를 DEAD로). 중복을 DB가 아니라 코드 순서로 막았다(정산 job, 포스터 제목). 짝 프론트와 wire 계약이 달랐고(처리 중 409, Envelope null), JWT audience 검증이 기본으로 꺼져 있었고, 트레이스가 나가지 않았고, CI가 strict lane 14개를 한 번도 돌리지 않았다. 방법: 발견마다 실패하는 테스트를 먼저 쓰고 고쳤다. 주요 선택: - 알림 attempt는 처음부터 "시작 여부 모름"으로 쓴다(호출 직전 갱신은 쓰기가 하나 늘어 버림). - 정산 job claim은 lease·fence를 갱신하는 UPDATE 한 문장(처리 전체를 트랜잭션으로 감싸는 안은 외부 호출 동안 잠금을 잡아 버림). - 커밋 단계 연결 끊김은 DB_COMPLETION_UNKNOWN(재시도 불가). - 처리 중 409는 retryable=true + Retry-After: 2, Envelope null 필드는 web Jackson mixin으로 생략(shared-contract는 stdlib only). - 트레이싱은 자체 Tracer를 지우고 Boot 4 tracing·OTLP로. - strict lane을 단계에 연결하고 verifyStrictLaneStages가 고아를 막는다. 발견별 RED·GREEN·버린 대안은 리뷰 README 13절 표에 있다. 위험·한계: JWT 모드는 APP_SECURITY_JWT_AUDIENCE가 없으면 기동하지 않는다. 짝 프론트는 409 retryable과 Envelope 키 규칙을 맞춰야 한다. 이 커밋 시점에는 MinIO 공식 이미지가 사라져 MinIO 2 lane이 실패한다 (다음 커밋에서 대체 이미지로 해결). 검증: ci 통과. mainCheck·integrationCheck는 MinIO 2 lane만 실패(이미지 pull 거부). -p optional-platforms ci integrationCheck, performanceCheck, releaseCheck(-PgitRevision) 통과. Refs: docs/reviews/2026-11-01-maturity-review/README.md 2·13절 BREAKING CHANGE: JWT 모드에서 APP_SECURITY_JWT_AUDIENCE가 필수가 되고 role은 audience client와 realm 것만 읽는다. IDEMPOTENT_IN_FLIGHT가 retryable=true, Retry-After: 2로 바뀌고 Envelope는 null 필드를 보내지 않는다.
This commit is contained in:
@@ -49,6 +49,12 @@ jobs:
|
||||
- name: Run the pull-request gate
|
||||
working-directory: src
|
||||
run: ./gradlew :ci :verifyDependencyLocks --warning-mode=fail --stacktrace
|
||||
# Plans every stage (`--dry-run`: nothing executes) and fails when a strict lane is in no stage
|
||||
# a workflow executes, or a stage is executed by no workflow (review 2026-11-01 08-01). A new
|
||||
# lane fails here, on its own pull request, instead of running nowhere after it merges.
|
||||
- name: Require every strict lane to be in an executed stage
|
||||
working-directory: src
|
||||
run: ./gradlew :verifyStrictLaneStages --dry-run --stacktrace
|
||||
- name: Verify Compose profile contracts render exactly as declared
|
||||
run: bash scripts/verify-compose-profile-contracts.sh
|
||||
|
||||
|
||||
@@ -15,11 +15,13 @@ name: integration-main
|
||||
# shared. They now run on every push to main as well as nightly, which is strictly more often
|
||||
# than before.
|
||||
#
|
||||
# 2. Lanes that were registered in Gradle and invoked by nothing — the MongoDB container lanes and
|
||||
# app-bootstrap's Testcontainers `integrationTest` — existed, failed closed, and executed in no
|
||||
# workflow. A lane nobody runs is not coverage; it is a file that looks like coverage. They
|
||||
# are here rather than in stage 1 because every one of them either starts containers or re-runs
|
||||
# suites the PR gate already covers, and the pull-request budget is minutes for the whole gate.
|
||||
# 2. The container-backed lanes, run as the root category aggregates `:integrationCheck` and
|
||||
# `:performanceCheck` rather than one workflow line per lane. A lane nobody runs is not coverage;
|
||||
# it is a file that looks like coverage — and naming lanes here one by one is how fourteen of
|
||||
# them came to run nowhere (review 2026-11-01 08-01). The pull-request gate's
|
||||
# `verifyStrictLaneStages` now fails when a strict lane is in no stage a workflow executes. They
|
||||
# are here rather than in stage 1 because every one of them starts containers or real servers,
|
||||
# and the pull-request budget is minutes for the whole gate.
|
||||
#
|
||||
# What is deliberately NOT here: the web "Advanced capability" nightly lane that used to exist as
|
||||
# web-advanced-nightly.yml (websocket-advanced-nightly.yml went with the websocket Advanced code,
|
||||
@@ -78,8 +80,13 @@ jobs:
|
||||
- uses: ./.github/actions/setup-gradle-java
|
||||
- name: Run the main-branch stage
|
||||
working-directory: src
|
||||
run: ./gradlew :mainCheck --warning-mode=fail --stacktrace
|
||||
# `--continue`: one failed lane (an external image that cannot be pulled, say) must not stop
|
||||
# the other main-stage gates from reporting (review 2026-11-01 08-04).
|
||||
run: ./gradlew :mainCheck --continue --warning-mode=fail --stacktrace
|
||||
|
||||
# Storability only: the `--dry-run` below plans `integrationCheck` without running a lane. The
|
||||
# lanes run in `integration-check`.
|
||||
#
|
||||
# Two questions. Can every task in the repository-wide gates be *stored* (a property of the task
|
||||
# graph, so `--dry-run` answers it for all of them in seconds)? And is a stored entry *reused* while
|
||||
# the build still executes its work (checked on the two core leaves)?
|
||||
@@ -128,63 +135,71 @@ jobs:
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Load, abuse and graceful shutdown measure behaviour that degrades gradually rather than breaking
|
||||
# outright — which is exactly the kind of regression a per-PR gate never catches.
|
||||
web-load-abuse-and-shutdown:
|
||||
# The integration stage: every integration-category strict lane (`:integrationCheck`).
|
||||
#
|
||||
# This job replaced six jobs that named lanes one by one — the MongoDB lanes, app-bootstrap's
|
||||
# Testcontainers lane, the moved messaging/object-storage/sample contracts, six of the
|
||||
# persistence-jpa PostgreSQL contracts and the httpclient fault injection. Naming lanes was how
|
||||
# eleven persistence-jpa readiness lanes ended up running nowhere: a lane added to Gradle without a
|
||||
# workflow line was declared, failed closed, and executed on no machine (review 2026-11-01 08-01).
|
||||
# The aggregate is the list now. A lane joins it by declaring `integration()`, and the root
|
||||
# `verifyStrictLaneStages` (pull-request gate) fails when a strict lane is in no stage a workflow
|
||||
# executes.
|
||||
#
|
||||
# `--continue` so that one red lane does not hide the others: every failed lane is named in the
|
||||
# same run. Lanes that need an input this job does not have (the Redis topology coordinates, the
|
||||
# protected AWS sandbox) are `explicitOnly`; the aggregate prints which ones it left out.
|
||||
# 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.
|
||||
integration-check:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
timeout-minutes: 240
|
||||
env:
|
||||
# Reuse would hand the failover lane a replica set another lane had already faulted.
|
||||
TESTCONTAINERS_REUSE_ENABLE: "false"
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2
|
||||
- uses: ./.github/actions/setup-gradle-java
|
||||
- name: Run the load, abuse and shutdown lanes on every container
|
||||
- name: Run every integration-category strict lane
|
||||
working-directory: src
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:inbound:web:test
|
||||
:adapter:inbound:web:webJettyCompatTest
|
||||
|
||||
--stacktrace
|
||||
- name: Publish the test reports
|
||||
run: ./gradlew :integrationCheck --continue --stacktrace
|
||||
- name: Publish the integration lane reports
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2
|
||||
with:
|
||||
name: web-integration-reports
|
||||
path: src/adapter/inbound/web/build/reports/tests/
|
||||
name: integration-check-reports
|
||||
path: src/**/build/reports/tests/
|
||||
if-no-files-found: warn
|
||||
|
||||
# Needs a container runtime and real time (design §29). Separated from the per-PR gate rather than
|
||||
# made optional inside it: a lane that cannot run here fails, it does not skip.
|
||||
httpclient-fault-injection:
|
||||
# The performance stage: every performance-category strict lane (`:performanceCheck`) — Tomcat and
|
||||
# Jetty load, slow-client and graceful shutdown, the Hikari pool contract, the httpclient pool,
|
||||
# streaming, retry and rotation bounds, the MongoDB resource budget. They measure behaviour that
|
||||
# degrades gradually rather than breaking outright, which is the kind of regression a per-PR gate
|
||||
# never catches. This job replaced `web-load-abuse-and-shutdown`, which despite its name ran
|
||||
# `:adapter:inbound:web:test` and `webJettyCompatTest` — two lanes the pull-request and main stages
|
||||
# already run — and never the load lanes (review 2026-11-01 08-01), and `httpclient-performance`.
|
||||
performance-check:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2
|
||||
- uses: ./.github/actions/setup-gradle-java
|
||||
- name: Inject TCP faults against a real upstream
|
||||
working-directory: src
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:outbound:httpclient:httpClientFailureInjectionTest
|
||||
|
||||
--stacktrace
|
||||
|
||||
httpclient-performance:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
# A project property rather than a command-line flag, so the run command stays a plain,
|
||||
# verifiable task invocation while the machine-dependent bounds are still asserted.
|
||||
GRADLE_OPTS: -Dorg.gradle.project.performance.assertions.enabled=true
|
||||
TESTCONTAINERS_REUSE_ENABLE: "false"
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2
|
||||
- uses: ./.github/actions/setup-gradle-java
|
||||
- name: Certify pool, streaming, retry, and rotation bounds
|
||||
- name: Run every performance-category strict lane
|
||||
working-directory: src
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:outbound:httpclient:httpClientPerformanceTest
|
||||
|
||||
--stacktrace
|
||||
run: ./gradlew :performanceCheck --continue --stacktrace
|
||||
- name: Publish the performance lane reports
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2
|
||||
with:
|
||||
name: performance-check-reports
|
||||
path: src/**/build/reports/tests/
|
||||
if-no-files-found: warn
|
||||
|
||||
httpclient-http3-experimental:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -198,123 +213,7 @@ jobs:
|
||||
- uses: ./.github/actions/setup-gradle-java
|
||||
- name: Exercise the experimental HTTP/3 opt-in
|
||||
working-directory: src
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:outbound:httpclient:test
|
||||
-Phttp3.tests.enabled=true
|
||||
|
||||
--stacktrace
|
||||
|
||||
# The six Docker-backed MongoDB lanes. Until now they ran in no workflow at all: the leaf excludes
|
||||
# every one of their tags from `test` (build.gradle "Docker-backed lanes are excluded from the
|
||||
# default unit run"), `check` gains only the hermetic `mongoStableContractTest`, and the only thing
|
||||
# that named them was scripts/verify-mongodb-platform.sh, which nothing in .github invokes. Six
|
||||
# lanes that fail closed without Docker, and no machine with Docker was ever asked to run them.
|
||||
#
|
||||
# Stage 2 rather than stage 1 because each lane starts real MongoDB containers — mongo:8.0.16,
|
||||
# mongo:7.0.28 and a Toxiproxy in front of a three-node replica set. That is minutes per lane, and
|
||||
# the pull-request budget is minutes for the whole gate.
|
||||
#
|
||||
# One single-line `./gradlew <task>` step per lane, not one folded command running six, because
|
||||
# These command lines name each lane explicitly so that a lane which stops being invoked is
|
||||
# actually executed — a folded command would leave six matrix rows unverifiable. It also means a
|
||||
# red replica-set lane does not hide the compatibility lane behind it.
|
||||
mongo-container-lanes:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
# Reuse would hand the failover lane a replica set another lane had already faulted.
|
||||
TESTCONTAINERS_REUSE_ENABLE: "false"
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2
|
||||
- uses: ./.github/actions/setup-gradle-java
|
||||
- name: Single-node replica set contract lane
|
||||
working-directory: src
|
||||
run: ./gradlew :adapter:outbound:persistence-mongo:mongoReplicaSetTest --stacktrace
|
||||
- name: Run MongoDB integration lanes
|
||||
working-directory: src
|
||||
run: >-
|
||||
./gradlew
|
||||
:adapter:outbound:persistence-mongo:mongoReplicaSetTest
|
||||
:adapter:outbound:persistence-mongo:mongoFailoverTest
|
||||
:adapter:outbound:persistence-mongo:mongoMigrationTest
|
||||
:adapter:outbound:persistence-mongo:mongoCompatibilityTest
|
||||
:adapter:outbound:persistence-mongo:mongoSecurityIntegrationTest
|
||||
:adapter:outbound:persistence-mongo:mongoPerformanceTest
|
||||
--stacktrace
|
||||
- name: Publish the MongoDB lane reports
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2
|
||||
with:
|
||||
name: mongo-lane-reports
|
||||
path: src/adapter/outbound/persistence-mongo/build/reports/tests/
|
||||
if-no-files-found: warn
|
||||
|
||||
# app-bootstrap's Testcontainers lane. The leaf gave it a source set of its own precisely so that
|
||||
# `./gradlew :app-bootstrap:test` would not require a Docker daemon — and the consequence nobody
|
||||
# closed is that a source set outside `test` is also outside `check`, so the real-PostgreSQL
|
||||
# outbox and idempotency contracts compiled on every build and executed on none.
|
||||
bootstrap-integration:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
TESTCONTAINERS_REUSE_ENABLE: "false"
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2
|
||||
- uses: ./.github/actions/setup-gradle-java
|
||||
- name: Run the real-PostgreSQL integration contracts
|
||||
working-directory: src
|
||||
run: ./gradlew :app-bootstrap:integrationTest --stacktrace
|
||||
|
||||
# Container contracts moved out of the default `test` source sets must remain executed after the
|
||||
# ownership split. One step per lane keeps a failure attributable to the capability that broke.
|
||||
moved-container-contracts:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
TESTCONTAINERS_REUSE_ENABLE: "false"
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2
|
||||
- uses: ./.github/actions/setup-gradle-java
|
||||
- name: Messaging outbox, inbox and admin-journal PostgreSQL contracts
|
||||
working-directory: src
|
||||
run: ./gradlew :messaging:messaging-reliability-jdbc-postgresql:integrationTest --stacktrace
|
||||
- name: Messaging starter Kafka round trip
|
||||
working-directory: src
|
||||
run: ./gradlew :messaging:messaging-spring-boot-starter:integrationTest --stacktrace
|
||||
- name: Object storage MinIO contract
|
||||
working-directory: src
|
||||
run: ./gradlew :adapter:outbound:objectstorage:integrationTest --stacktrace
|
||||
- name: Standalone sample PostgreSQL contract
|
||||
working-directory: src
|
||||
run: ./gradlew :sample-portfolio:integrationTestLaneCheck --stacktrace
|
||||
|
||||
# These six PostgreSQL contracts moved from app-bootstrap into persistence-jpa. They are named
|
||||
# directly instead of relying on readiness-card membership: provider ownership and evidence
|
||||
# grading are different questions, and CI execution must not disappear when a card changes.
|
||||
jpa-provider-ownership-contracts:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
TESTCONTAINERS_REUSE_ENABLE: "false"
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2
|
||||
- uses: ./.github/actions/setup-gradle-java
|
||||
- name: Distributed lock contract
|
||||
working-directory: src
|
||||
run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlDistributedLockIntegrationTest --stacktrace
|
||||
- name: Integer lock migration compatibility
|
||||
working-directory: src
|
||||
run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlIntLockMigrationCompatibilityIntegrationTest --stacktrace
|
||||
- name: Outbox transactional append
|
||||
working-directory: src
|
||||
run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlOutboxAppendTransactionalIntegrationTest --stacktrace
|
||||
- name: Outbox concurrent relay
|
||||
working-directory: src
|
||||
run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlOutboxConcurrentRelayIntegrationTest --stacktrace
|
||||
- name: Outbox row lifecycle
|
||||
working-directory: src
|
||||
run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlOutboxRowLifecycleIntegrationTest --stacktrace
|
||||
run: ./gradlew :adapter:outbound:httpclient:test -Phttp3.tests.enabled=true --stacktrace
|
||||
|
||||
# The optional gRPC platform build declares one strict INTEGRATION lane —
|
||||
# `grpc-operation-ledger-jpa:integrationTest`, which certifies the atomic
|
||||
|
||||
@@ -139,12 +139,22 @@ jobs:
|
||||
:grpc:grpc-testkit:grpcNettyContractTest
|
||||
:grpc:grpc-testkit:grpcFaultTest
|
||||
--stacktrace
|
||||
# The operation ledger's real-PostgreSQL lane ran only on main and nightly
|
||||
# (integration-main.yml), so a tag could be cut from a main whose ledger lane was red. It needs
|
||||
# Docker, which a release runner has (review 2026-11-01 03-12).
|
||||
- name: Certify the gRPC operation ledger against real PostgreSQL
|
||||
working-directory: src
|
||||
env:
|
||||
TESTCONTAINERS_REUSE_ENABLE: "false"
|
||||
run: ./gradlew -p optional-platforms integrationCheck --stacktrace
|
||||
- name: Publish the gRPC release evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2
|
||||
with:
|
||||
name: grpc-release-evidence
|
||||
path: src/grpc/grpc-testkit/build/reports/tests/
|
||||
path: |
|
||||
src/grpc/grpc-testkit/build/reports/tests/
|
||||
src/grpc/grpc-operation-ledger-jpa/build/reports/tests/
|
||||
if-no-files-found: warn
|
||||
|
||||
# Each gate runs as its own single-line `./gradlew <task>` step so that a failure names the gate
|
||||
|
||||
@@ -11,6 +11,19 @@
|
||||
# checks this file against them.
|
||||
# =============================================================================
|
||||
|
||||
# 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.
|
||||
#
|
||||
# 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}"
|
||||
|
||||
services:
|
||||
# ---- PostgreSQL --------------------------------------------------------------
|
||||
db:
|
||||
@@ -180,7 +193,7 @@ services:
|
||||
profiles:
|
||||
- shared-infra
|
||||
- prod-smoke
|
||||
image: minio/minio:RELEASE.2024-09-13T20-26-02Z
|
||||
image: *local-minio-image
|
||||
command: ["server", "/data"]
|
||||
environment:
|
||||
MINIO_ROOT_USER: "${MINIO_ROOT_USER:-caskeleton}"
|
||||
@@ -422,7 +435,7 @@ services:
|
||||
profiles:
|
||||
- shared-infra
|
||||
- prod-smoke
|
||||
image: minio/minio:RELEASE.2024-09-13T20-26-02Z
|
||||
image: *local-minio-image
|
||||
depends_on:
|
||||
minio-init:
|
||||
condition: service_completed_successfully
|
||||
|
||||
@@ -47,6 +47,26 @@ retries when everything is failing, which is the behaviour that lets a dependenc
|
||||
transaction annotations, deliberately: a `REQUIRES_NEW` would put the claim in its own transaction and
|
||||
reintroduce the window where the write is durable and the claim is not.
|
||||
|
||||
**A claim expires instead of blocking its key forever** (review 2026-11-01, 03-10). A claim still
|
||||
`IN_PROGRESS` after the claim TTL is presumed abandoned by a dead owner, and the next retry of the same
|
||||
request takes it over with `GrpcOperationLedger.reclaimStale` — one conditional
|
||||
`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.
|
||||
|
||||
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
|
||||
turns an abandoned claim into an unknown outcome, and a takeover can run the mutation twice. A takeover
|
||||
of an owner that is merely slow does the same, which is why the TTL must exceed the slowest keyed
|
||||
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.
|
||||
|
||||
**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
|
||||
answer.
|
||||
|
||||
@@ -39,6 +39,16 @@ which idempotency record, business row, or outbox entry proves the write happene
|
||||
|
||||
## Enforcement
|
||||
|
||||
`JpaFailureContextTest`;
|
||||
`PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsAFailureAndIsNeverRetried`
|
||||
(also the `jpa-failure` lane, i.e. release gate `completion-unknown-no-retry`).
|
||||
Production path: `SpringTransaction` records when the action has returned in a write transaction it
|
||||
began; a failure after that point goes through
|
||||
`PersistenceExceptionTranslator#translateCommitFailure`, which builds this exception for `08*`,
|
||||
`40003`, a vendor termination state (`SqlStateErrorMapping#commitOutcomeUnknownStates`, PostgreSQL
|
||||
`57P01`/`57P02`) or a transport break. Hibernate's flush inside the commit is not separated from the
|
||||
COMMIT itself, so a connection lost during that flush is also reported as unknown — the safe side.
|
||||
Until review 04-01 (2026-11-01) nothing constructed the exception and a commit-phase `08*` reached
|
||||
callers as the retryable `DB_UNAVAILABLE`.
|
||||
|
||||
`JpaFailureContextTest`; `SpringTransactionTest`; `PersistenceExceptionTranslatorTest`;
|
||||
`PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsCompletionUnknownAndIsNeverRetried`
|
||||
(asserts `DB_COMPLETION_UNKNOWN`; also the `jpa-failure` lane, i.e. release gate
|
||||
`completion-unknown-no-retry`).
|
||||
|
||||
@@ -27,15 +27,15 @@ lanes and CI; it is not a deployment artifact.
|
||||
|
||||
| Capability | Enabled key (property / env, default) | IMPLEMENTED | WIRED | QUALIFIED | Evidence |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| Relational persistence (JPA/PostgreSQL) | `ca-skeleton.persistence-jpa.enabled` / `APP_PERSISTENCE_JPA_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-jpa')`) | yes | Not in the default composition. The one line brings everything — its own `AutoConfiguration.imports` (`PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig`, `JpaStartupAutoConfiguration`), its environment handling (`JpaActivationEnvironmentPostProcessor`, `spring.factories`: readiness `db` while on; with `false` it also excludes Boot's JDBC, Hibernate, Spring Data JPA and Flyway auto-configuration, so no DataSource is bound), the startup guards (Flyway strategy, datasource/OSIV/DDL/pool/TLS/vendor checks, exit codes unchanged) and its settings (`config/module-defaults/persistence-jpa.yml`). `persistence-jpa:PersistenceJpaCapabilityAssemblyTest` proves the module assembles on its own; six `postgresql*IntegrationTest` lanes, run by `integration-main.yml` → `jpa-provider-ownership-contracts`, qualify it against PostgreSQL. `sample-portfolio` selects it by its build dependency and the module's auto-configuration (no broad scan of the persistence package). `bootRunH2` adds the module to its own classpath only. |
|
||||
| Document persistence (MongoDB) | `ca-skeleton.persistence-mongo.enabled` / `APP_PERSISTENCE_MONGO_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-mongo')`) | yes | On when present; `false` also excludes Boot's Mongo auto-configuration (`MongoCapabilityActivationTest`). The connection-source rule (`SPRING_MONGODB_URI` or the selected profile's `uri-secret`) is checked by the module's own `MongoDefaultsEnvironmentPostProcessor`. Six container lanes (`mongoReplicaSetTest`, `mongoFailoverTest`, …), run by `integration-main.yml` → `mongo-container-lanes` |
|
||||
| Relational persistence (JPA/PostgreSQL) | `ca-skeleton.persistence-jpa.enabled` / `APP_PERSISTENCE_JPA_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-jpa')`) | yes | Not in the default composition. The one line brings everything — its own `AutoConfiguration.imports` (`PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig`, `JpaStartupAutoConfiguration`), its environment handling (`JpaActivationEnvironmentPostProcessor`, `spring.factories`: readiness `db` while on; with `false` it also excludes Boot's JDBC, Hibernate, Spring Data JPA and Flyway auto-configuration, so no DataSource is bound), the startup guards (Flyway strategy, datasource/OSIV/DDL/pool/TLS/vendor checks, exit codes unchanged) and its settings (`config/module-defaults/persistence-jpa.yml`). `persistence-jpa:PersistenceJpaCapabilityAssemblyTest` proves the module assembles on its own; the `postgresql*IntegrationTest` readiness lanes, run by `integration-main.yml` → `integration-check` (`:integrationCheck`), qualify it against PostgreSQL. `sample-portfolio` selects it by its build dependency and the module's auto-configuration (no broad scan of the persistence package). `bootRunH2` adds the module to its own classpath only. |
|
||||
| Document persistence (MongoDB) | `ca-skeleton.persistence-mongo.enabled` / `APP_PERSISTENCE_MONGO_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-mongo')`) | yes | On when present; `false` also excludes Boot's Mongo auto-configuration (`MongoCapabilityActivationTest`). The connection-source rule (`SPRING_MONGODB_URI` or the selected profile's `uri-secret`) is checked by the module's own `MongoDefaultsEnvironmentPostProcessor`. Six container lanes (`mongoReplicaSetTest`, `mongoFailoverTest`, …), run by `integration-main.yml` → `integration-check` (`:integrationCheck`) |
|
||||
| Messaging (Kafka) | `app.messaging.enabled` / `APP_MESSAGING_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:messaging-kafka')`, which brings the application bridge, the legacy `KafkaSender` seam and the vendored platform with its Kafka transport) | Kafka only | On when present (`KafkaCapabilityActivationTest`). `messaging-kafka:messagingCertificationTest` behind `verifyMessagingCertificationEvidence`, run by `messaging-certification.yml`; the starter's `integrationTest` is the live Kafka round trip. Kafka is the only registered broker; the RabbitMQ broker keys were removed (no transport). |
|
||||
| Redis capabilities (cache / rate-limit / lease / idempotency) | `app.redis.enabled` / `APP_REDIS_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:cache-redis')`, which brings `redis-runtime`) | yes | `cache-redis:redisTopologyTest`, run by `redis-sdk-topology.yml`. Not in the default composition. On when present; `false` contributes no Redis bean — no settings, client, connection, thread or health contributor. The module owns its readiness contribution (`RedisReadinessGroupPostProcessor`, `spring.factories`) and its settings (`config/module-defaults/cache-redis.yml`: `app.redis.enabled`, `app.rate-limit.*`, the Redis `ca-skeleton.capabilities.*`). No `app-bootstrap` main source names a Redis type. |
|
||||
| Request idempotency | `APP_IDEMPOTENCY_PROVIDER` (`disabled` \| `redis` \| `postgresql`; a selector, not an on/off key) | yes | yes | Redis only | One generation: the application `IdempotencyExecutor`, built once by `app-bootstrap` `IdempotencyProviderSelectionConfig` over the one store the selected provider contributes (`cache-redis` or `persistence-jpa`); startup is refused unless exactly one store exists. `sample-portfolio` cannot depend on `app-bootstrap`, so its own `SampleIdempotencyConfig` builds its one executor from the same keys. Redis is covered by the row above. PostgreSQL has `persistence-jpa:postgresqlIdempotencyIntegrationTest`, but no workflow runs it. The `postgresql` provider refuses a non-PostgreSQL data source, so `bootRunH2` uses `disabled` or `redis`.. The executor stays in the composition root on purpose — it needs only application-core and its settings — while each store comes with its module: `postgresql` needs the persistence-jpa line, `redis` the cache-redis one. |
|
||||
| Transactional outbox relay | `ca-skeleton.outbox.enabled` / `APP_OUTBOX_ENABLED`, `false` (+ `APP_OUTBOX_RELAY_ENABLED`, `false`; persistence-jpa settings) | yes | yes (with the persistence-jpa line; the scheduler also needs the messaging-kafka line) | yes | The store and its settings are persistence-jpa's; the relay (`OutboxConfig`) is application composition in `app-bootstrap` because a driven adapter must not build or call a use case. It turns on only when an `OutboxStorePort` bean exists, and the scheduler only when an `OutboxMessagePublishPort` does (the messaging bridge), each ordered after its contributor by `afterName` — so an environment with no publisher keeps its PENDING rows. The bridge registers no stand-in publisher: a present-and-enabled bridge with a blank broker and no canonical transport is refused at startup. `postgresqlLegacyOutboxConcurrentRelayIntegrationTest` qualifies claim/fencing against PostgreSQL. |
|
||||
| Notification platform | `ca-skeleton.notification.platform.enabled` / `APP_NOTIFICATION_PLATFORM_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':composition:notification-platform')`, plus the persistence-jpa line) | claim-scoped | Not in the default composition. The one line brings the use-case assembly, `adapter:outbound:notification`, the HTTP surface `adapter:inbound:web-notification` and its own settings (`config/module-defaults/notification.yml`), each registered through the module's own `AutoConfiguration.imports`; `adapter:inbound:web` no longer depends on `application-notification`. `verifyNotificationEvidence` refuses a grade in `docs/notification/support-matrix.md` that no proven claim backs; run by `notification-platform.yml`. There is no real-SMTP lane, and the matrix says so rather than implying one. |
|
||||
| File server platform | `app.fileserver-platform.enabled` / `APP_FILESERVER_PLATFORM_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':composition:fileserver-platform')`, plus the persistence-jpa line) | yes | On when present; module-owned `config/module-defaults/fileserver.yml` also carries the servlet multipart ceiling. `app-bootstrap:integrationTest` → `FileserverCompositionIntegrationTest` (required by the strict lane), run by `integration-main.yml` → `bootstrap-integration` |
|
||||
| Outbound HTTP client | `app.httpclient.enabled` / `APP_HTTPCLIENT_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:httpclient')`) | yes | On when present (`HttpClientPlatformActivationTest`). `httpclient:httpClientFailureInjectionTest` against a faulted upstream, run by `integration-main.yml` → `httpclient-fault-injection` |
|
||||
| File server platform | `app.fileserver-platform.enabled` / `APP_FILESERVER_PLATFORM_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':composition:fileserver-platform')`, plus the persistence-jpa line) | yes | On when present; module-owned `config/module-defaults/fileserver.yml` also carries the servlet multipart ceiling. `app-bootstrap:integrationTest` → `FileserverCompositionIntegrationTest` (required by the strict lane), run by `integration-main.yml` → `integration-check` (`:integrationCheck`) |
|
||||
| Outbound HTTP client | `app.httpclient.enabled` / `APP_HTTPCLIENT_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:httpclient')`) | yes | On when present (`HttpClientPlatformActivationTest`). `httpclient:httpClientFailureInjectionTest` against a faulted upstream, run by `integration-main.yml` → `integration-check` (`:integrationCheck`) |
|
||||
| GraphQL transport | `backend.graphql.enabled` / `APP_GRAPHQL_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:graphql')`) | leaf-level | On when present; `false` also excludes Spring GraphQL's own auto-configuration, so no `/graphql` (`GraphQlCapabilityActivationTest`). `graphqlTransportQualificationTest` runs the HTTP boundary. The deployment-mode/runtime-profile rule is the module's own `GraphQlPlatformStartupValidator`. The default jar does not ship GraphQL, so a compose lane that exercises it runs the qualification jar. |
|
||||
| Object storage | `app.object-storage.enabled` (no `APP_*` row), `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:objectstorage')`) | MinIO only | Own `ObjectStorageAutoConfiguration` (was bound through bootstrap's properties scan); on when present, `false` leaves only the explicit legacy seam (`ObjectStorageAutoConfigurationTest`). `app-bootstrap:integrationTest` assembles it against digest-pinned MinIO. |
|
||||
| gRPC platform | — (build-level) | yes | **no** | yes | Absent from the main build entirely: `optional-platforms` is a separate Gradle build, so the switch is the `include`, not an environment variable. `-p optional-platforms ci` runs on every PR and `integrationCheck` certifies the operation ledger against real PostgreSQL. |
|
||||
|
||||
@@ -36,7 +36,7 @@ diverge, retries are absorbing failures — which is the first thing to look at
|
||||
| logical calls fine, attempts spiking | upstream degraded, retries absorbing it | `http.client.retry.count` by reason |
|
||||
| `http.client.ambiguous` non-zero | non-idempotent writes reaching `SENT_NO_RESPONSE` | reconcile with the upstream; consider an idempotency key |
|
||||
| pool pending climbing | pool too small or upstream slow | `http.client.pool.acquire.duration`, `pool.connections` |
|
||||
| circuit open | sustained upstream failure | `http.client.circuit.state`; local rejections do not open it |
|
||||
| circuit open | sustained upstream failure: transport errors, 5xx, 408, 429 | `http.client.circuit.state`; local rejections and other 4xx do not open it |
|
||||
| `http.client.ssrf.rejected` non-zero | a caller is submitting internal URLs | Dynamic Target policy and audit trail |
|
||||
|
||||
## Actuator
|
||||
|
||||
@@ -49,12 +49,49 @@ never stays in cache and write amplification grows with the table.
|
||||
|
||||
## Associations
|
||||
|
||||
- To-one associations are `LAZY`. JPA's default is `EAGER`, which means every query that loads a
|
||||
child also queries for its parent — the most common accidental N+1 in a JPA application.
|
||||
- The owning side holds the foreign key. Adding to the inverse collection alone leaves the row
|
||||
unlinked, so aggregates expose an association helper that sets both sides.
|
||||
- `CascadeType.ALL` with `orphanRemoval` is correct only for a child the aggregate genuinely owns.
|
||||
Between independent aggregates it deletes rows another part of the system still owns.
|
||||
Map each association from **one side only**. A JPA association between two entities is one foreign
|
||||
key column. A bidirectional pair (`@ManyToOne` on the child plus `@OneToMany(mappedBy = ...)` on
|
||||
the parent) stores that one column in two Java fields, and JPA writes only the owning one. The pair
|
||||
stays consistent only while every caller remembers to update both fields, and nothing fails when
|
||||
someone forgets.
|
||||
|
||||
What to use, in order of preference:
|
||||
|
||||
1. **An ID reference between aggregates.** Hold the other aggregate's identifier as a plain column
|
||||
(`UUID ownerId`). This is what every production entity in the template does today. Loading the
|
||||
other aggregate is an explicit repository call, so a cross-aggregate load is visible in the code.
|
||||
2. **A unidirectional `@ManyToOne` inside one aggregate**, always `fetch = FetchType.LAZY`. JPA's
|
||||
default for a to-one association is `EAGER`, so every query that loads a child also queries for
|
||||
its parent — the most common accidental N+1 in a JPA application.
|
||||
3. **A collection is a query, not a field.** "The children of X" is a repository method
|
||||
(`findByParentId`, or a fetch-join or projection query that pages in SQL). The query states its
|
||||
own fetch plan and page, where a mapped collection hides both.
|
||||
4. **Values the aggregate owns** — a list of tags, a set of codes — are `@ElementCollection`
|
||||
(`LAZY`), not entities.
|
||||
|
||||
A unidirectional `@OneToMany` with its own `@JoinColumn` is the exception, not the default. Use it
|
||||
only for child entities the root genuinely owns and changes only through itself (the testkit's
|
||||
`LifecycleParent` and `PagedParent` are this shape). It still costs an `UPDATE` per child when the
|
||||
join column is nullable, and the collection still loads as a unit.
|
||||
|
||||
`CascadeType.ALL` with `orphanRemoval` is correct only for a child the aggregate genuinely owns.
|
||||
Between independent aggregates it deletes rows another part of the system still owns — another
|
||||
reason those are ID references.
|
||||
|
||||
`JpaArchitectureRules.associationsAreMappedFromOneSideOnly()` (testkit) fails the build on any
|
||||
`@OneToMany`, `@OneToOne` or `@ManyToMany` that declares `mappedBy`, on `@Entity`,
|
||||
`@MappedSuperclass` and `@Embeddable` types. `JpaProductionArchitectureTest` (app-bootstrap
|
||||
`architectureTest`) runs it over the production graph and `SampleArchitectureTest` over the sample.
|
||||
The failure message names the field and these alternatives.
|
||||
|
||||
Chosen and rejected:
|
||||
|
||||
| Option | Decision | Why |
|
||||
| --- | --- | --- |
|
||||
| One side only (ID reference, unidirectional `@ManyToOne`, collection by query), enforced by ArchUnit | Chosen | The link lives in one field, so there is nothing to keep in step. The rule turns a developer-memory convention into a build failure |
|
||||
| Bidirectional with `mappedBy` and an `addChild`/`removeChild` helper that sets both sides | Rejected | The helper is the only thing keeping the two fields in step, and it must be remembered by every caller, every serializer (cycles in `toString`/JSON) and every cascade decision. A missed update leaves a row unlinked or a graph that disagrees with the database, with no error |
|
||||
| Ban `@OneToMany` entirely | Rejected for now | It also bans a root-owned child collection, which has no second field to forget. Revisit if a real need for child entities that are read or changed on their own appears — that need is a sign they are a separate aggregate |
|
||||
| Document only | Rejected | A convention the build does not check is invisible where the mapping is written, and the next copy of the template inherits whatever the examples show |
|
||||
|
||||
## Entities never leave the transaction
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ A connection can break while a commit is in flight; the server may have committe
|
||||
acknowledgement was lost. `TransactionCompletionUnknownException` is never retried, and the type
|
||||
system enforces it: `JpaFailureContext` refuses to represent a retryable completion-unknown failure.
|
||||
The port itself retries nothing, so such a commit surfaces to the caller as a failure exactly once
|
||||
(`PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsAFailureAndIsNeverRetried`).
|
||||
(`PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsCompletionUnknownAndIsNeverRetried`).
|
||||
|
||||
Recovery is reconciliation, not retry:
|
||||
|
||||
|
||||
@@ -19,7 +19,12 @@ public enum PublishCompletion { CONFIRMED, REJECTED, AMBIGUOUS }
|
||||
```
|
||||
|
||||
`REJECTED`와 `AMBIGUOUS`를 하나의 "실패"로 합치면 중복 주문이 만들어진다.
|
||||
전자는 broker가 저장하지 않았음이 **확정**되어 포기해도 안전하고, 후자는 그렇지 않다.
|
||||
전자는 broker가 저장하지 않았음이 **확정**되어 중복 걱정 없이 다시 보내거나 포기할 수 있고, 후자는 그렇지 않다.
|
||||
|
||||
`REJECTED`가 곧 "포기해도 된다"는 뜻은 아니다. 거부 이유가 그 순간에 속하면(종료 중
|
||||
`SHUTTING_DOWN`, permit 대기 초과, `PUBLISH_RUNTIME_UNAVAILABLE`, `KAFKA_TRANSPORT_CLOSED`, Kafka
|
||||
인증·인가 실패) `failure().retryable()`이 true이고, 호출자는 같은 메시지를 나중에 다시 보내야 한다.
|
||||
포기해도 되는 것은 `retryable=false`인 거부뿐이다.
|
||||
|
||||
| 상황 | 결과 |
|
||||
|---|---|
|
||||
|
||||
@@ -543,6 +543,9 @@ env_keys:
|
||||
- name: OTEL_EXPORTER_OTLP_ENDPOINT
|
||||
# source: feature-distributed-tracing-contract 2026-05-22
|
||||
# "Micrometer Tracing + OpenTelemetry exporter를 기본 기준으로 둠"
|
||||
# OTLP base address (OpenTelemetry spec). TracingEnvironmentPostProcessor bridges it to
|
||||
# management.opentelemetry.tracing.export.otlp.endpoint as <value>/v1/traces (OTLP/HTTP);
|
||||
# blank = no span exporter bean (review 07-01, 2026-11-01).
|
||||
type: url
|
||||
default: null
|
||||
allowed_values: null
|
||||
@@ -573,7 +576,7 @@ env_keys:
|
||||
# "trace sampling rate default = prod 1%, dev/local 100%"
|
||||
# D-1 ISSUE-1 fix (2026-06-16): blank = per-profile resolver 기본값 사용.
|
||||
# RuntimeEnvironment is the profile SSOT; resolver policy is prod=0.01, dev/local=1.0.
|
||||
# TracingSamplingEnvironmentPostProcessor bridges resolved rate to
|
||||
# TracingEnvironmentPostProcessor bridges resolved rate to
|
||||
# management.tracing.sampling.probability.
|
||||
type: string
|
||||
default: ""
|
||||
|
||||
@@ -399,12 +399,13 @@ errors:
|
||||
compatibility_impact: none
|
||||
required_test: contract-verification:rate-limit
|
||||
|
||||
# source: feature-rate-limit-idempotency-contract L71 — "200ms 초과 시 409 IDEMPOTENT_IN_FLIGHT (retryable=false, client는 polling)"
|
||||
# source: docs/web/http-contract.md §2 (2026-11-01 소유자 결정, 리뷰 02-01 대안 A) — 결과 불명. 같은 Idempotency-Key로 Retry-After 뒤 재전송. 새 키 금지.
|
||||
# 2초 = 기본 processing lease(30s)보다 짧은 고정값. 이전 "client는 polling"(retryable=false)은 조회 엔드포인트가 없어 폐기.
|
||||
- code: IDEMPOTENT_IN_FLIGHT
|
||||
category: CONFLICT
|
||||
http_status: 409
|
||||
retryable: false
|
||||
retry_after_seconds: null
|
||||
retryable: true
|
||||
retry_after_seconds: 2
|
||||
owner_branch: feature-rate-limit-idempotency-contract
|
||||
owner_layer: application
|
||||
client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다."
|
||||
|
||||
@@ -0,0 +1,490 @@
|
||||
# 01. 코어(domain-core · shared-contract · application-core)와 기능 개발 패턴 리뷰
|
||||
|
||||
대상 leaf: `domain-core`(`:domain-core`), `shared-contract`(`:shared-contract`), `application-core`(`:application-core`).
|
||||
추가 범위: repo 전체의 폴더 구조, 중복 복사본·갈라진 유틸, 새 기능을 추가하는 작업 순서(sample-portfolio 포함).
|
||||
|
||||
경로는 `src/`를 생략한다. 패키지 앞부분이 긴 경로는 `.../`로 줄인다.
|
||||
|
||||
## 1. 범위
|
||||
|
||||
| 항목 | 기록 |
|
||||
| --- | --- |
|
||||
| 대상 | `clean-architecture-backend-template`, 브랜치 `main`, 커밋 `01a8a2a70` |
|
||||
| 확인 시점 | 2026-11-01 |
|
||||
| 목적과 실행 구성 | 템플릿(파생 서비스의 시작점). 코어 세 leaf는 모든 조립에 들어간다(`app-bootstrap/build.gradle:149-150,214`). 업무 도메인은 비어 있고 예시는 `sample-portfolio`에 있다. |
|
||||
| 규모·운영 목표 | 합의된 SLO·처리량 없음. 이 영역은 성능 목표보다 "새 기능을 넣는 사람이 틀리지 않는가"를 본다. |
|
||||
| 읽은 범위 | 세 leaf의 main·test·testFixtures 전부(domain-core main 7파일 110줄, shared-contract main 42파일 2,115줄, application-core main 130파일 5,080줄). 세 leaf의 `CLAUDE.md`·`README.md`, 루트 `AGENTS.md`·`CLAUDE.md`, `config/architecture/modules.json`. 기능 패턴을 따라가려고 sample-portfolio의 domain·application 전부와 web·persistence·bootstrap 중 WorkLog·Poster 경로, `app-bootstrap`의 `DurableOperationConfig`, onboarding fixture(`app-bootstrap/src/test/java/dev/caskeleton/onboarding/**`)와 `DomainFeatureOnboardingContractTest`, ArchUnit 규칙(`ApplicationBoundaryArchitectureTest`, `NamingConventionTest`, `ForbiddenApiArchitectureTest`, `RequiresPermissionProxyabilityTest`), web의 `MethodSecurityConfig`·`RequiresPermissionAuthorizationManager`·`GlobalExceptionHandler`, support의 `JsonIntegrationEventEncoder`. 중복 탐색은 repo 전체 main을 grep으로 훑었다(같은 단순 이름 클래스, SHA-256·HMAC 직접 구현, 식별자 문법). |
|
||||
| 실행한 것 | ① 게이트 결과 읽기: `ci` rc=0(세 leaf `test`·`check`, `:app-bootstrap:architectureTest` 181개 통과), `mainCheck` rc=1(objectstorage MinIO 이미지 pull 404, 이 영역 밖). ② `build/test-results` XML 집계(ci가 20:36~20:38에 만든 결과). ③ 별도 worktree(`wt-01`)에서 `flock` 잠금으로 기준 실행 1회와 변이 실험 5회(아래 표). worktree는 끝나고 지웠다. |
|
||||
| 확인 못 한 것 | 실제 Postgres·Redis로 도는 포트 어댑터 계약 lane(이 영역 소유 아님), 앱 기동 상태에서의 인가 프록시 동작(정적 근거와 기존 테스트로만 판단), 부하 측정. 지난 리뷰의 실행 결과는 증거로 쓰지 않았다. |
|
||||
| 비교 가능한 범위 | techlead `01-core.md`, followup-status 「A Core」「S1 Core」「X1/X2」. 파생 서비스 `tech-log-backend`의 현재 작업 트리를 참고 자료로 읽었다(이 repo의 커밋이 아니므로 판정 근거가 아니라 "실제로 어떻게 쓰였는가"의 사례로만 쓴다). |
|
||||
|
||||
### 변이 실험 (worktree `wt-01`, 실행 후 원복·삭제)
|
||||
|
||||
기준 실행: `./gradlew :domain-core:test :shared-contract:test :application-core:test` rc=0 (부하 21.4, 캐시 적중으로 1초).
|
||||
|
||||
| # | 바꾼 코드 | 돌린 테스트 (부하) | 결과 |
|
||||
| --- | --- | --- | --- |
|
||||
| M1 | `DurableOperationAccessPolicy.java` `mayAccess`에서 tenant 비교 삭제 | `:application-core:test` (13.0) | 잡힘 — 217개 중 5개 실패 |
|
||||
| M2 | `TenantId.java:22` 문법에 `/` 허용 | `:application-core:test` | **살아남음** — 전부 통과 (01-03) |
|
||||
| M3 | `PublishPendingOutboxEventsUseCase.java:112` 정렬을 역순으로 | `:application-core:test` | 잡힘 — 3개 실패 |
|
||||
| M4 | `Backoff.java` `ceiling`의 overflow 방어 삭제 | `:shared-contract:test` | 잡힘 — 260개 중 2개 실패 |
|
||||
| M5 | `IntegrationEventDraft.java:49` correlation 길이 상한 96→200 | `:application-core:test` | **살아남음** — 전부 통과 (01-07) |
|
||||
|
||||
테스트 실행 시간(ci 결과): domain-core 2개 0.13초, shared-contract 260개 0.81초, application-core 217개 1.38초. `:app-bootstrap:architectureTest` 181개 17.1초. 변이 1회당 leaf 재실행은 2~4초였다. 과하지 않다.
|
||||
|
||||
## 2. 지난 발견 재확인
|
||||
|
||||
상태: 해결 / 남음 / 바뀜(형태가 달라짐) / 일부.
|
||||
|
||||
| ID | 상태 | 근거 |
|
||||
| --- | --- | --- |
|
||||
| techlead C1 application-core가 HTTP 프로토콜 구현 | 해결 | application-core main에 HTTP 타입 0건. "http"는 `SubmitDurableOperationUseCase` 주석과 schema 파일에만 있다. fileserver 프로토콜은 `application-fileserver`·`adapter:inbound:web-fileserver`로 갔다 |
|
||||
| techlead C2 HTTP 요청 DTO가 inbound port 인자 | 해결 | ArchUnit `APPLICATION_METHODS_DO_NOT_ACCEPT_WEB_DTOS`(`ApplicationBoundaryArchitectureTest.java:855`)가 ci에서 통과 |
|
||||
| techlead H1 `inNew` 프로덕션 미사용 | 바뀜 | 이제 `CreateUploadApplicationUseCase.java:143`, `FinalizeUploadApplicationUseCase.java:332`(application-fileserver)가 쓴다 |
|
||||
| techlead H4 application-core 76%가 고르지 않은 제품 | 바뀜 | main 35,894줄 → 5,080줄. 알림·파일·객체 저장소는 별도 leaf로 나갔다. 남은 플랫폼 기능(outbox·idempotency·operation·lease·lock·cache·realtime)은 01-10 |
|
||||
| techlead H5 캐시 엔진·lease watchdog 미조립 | 일부 | 캐시 엔진·watchdog 삭제. `lease/*`는 남았고 main 호출자는 Redis 구현뿐(`RedisLeaseConfig.java:29`). 소유자 결정 8(유지)로 의도된 확장 지점 |
|
||||
| techlead H8 알림 멱등키 `Objects.hash` | > 05 영역 | application-notification으로 이동. 이 영역 밖 |
|
||||
| techlead M6 application-core 정적 `ThreadLocal` | 해결 | `static.*ThreadLocal` 0건 |
|
||||
| techlead M10 domain-core 테스트 0줄 | 해결(형식만) | `DomainCoreContractTest` 2개. 마커의 retention·target만 본다. domain-core에 행위가 없어서 충분하다 |
|
||||
| A-2b `RuntimeProfileSnapshot` "유일한 reader" 주장 | 남음 | `adapter/outbound/support/.../runtime/RuntimeProfileSnapshot.java:12-13` 그대로. 실제 reader는 5곳(`RuntimeProfileAccessArchitectureTest` 허용 목록) |
|
||||
| A-2d `RuntimeEnvironment` Javadoc이 bridge를 app-bootstrap 소유로 서술 | 남음 | `shared-contract/.../runtime/RuntimeEnvironment.java:32-33` "app-bootstrap's RuntimeProfileSnapshot" (실제 support leaf) |
|
||||
| A-5a README "1001번째 tenant부터 bucket folding 자동" | 남음 | `shared-contract/README.md:374`. 적용 코드 없음 |
|
||||
| A-6a application-core 문서가 알림 타입을 core 것으로 설명, operation·cache·lease·realtime 절 없음 | 남음 | `application-core/CLAUDE.md:78-82`, `README.md:501-537`(알림 절). README에 operation·cache·lease·realtime·tenant·outbound 절 없음 |
|
||||
| A-6e shared-contract README의 없는 `RateLimiter` 인용 | 해결 | `RateLimiter` 0건 |
|
||||
| S1-#3b `lease/*` use case 호출자 0 | 바뀜 | 소유자 결정 8로 capability 유지. 계약 키트 `DistributedLeaseContract`(testFixtures)를 in-memory·Redis 둘 다 상속 |
|
||||
| S1-#15d shared-contract CLAUDE.md 책임 목록이 일부 패키지만 설명 | 남음 | `concurrency`·`operation`·`ratelimit`·`runtime`·`security` 패키지가 `shared-contract/CLAUDE.md`에 없다. 빈 패키지 `annotation`·`headers`·`registry`(`.gitkeep`만)도 설명 없음 |
|
||||
| S1-#19 이력 주석 | 일부 | 코어 main에서 리뷰 ID를 적은 주석 2곳(`TenantId.java:12`, `MdcKeys.java`) |
|
||||
| X1-#3a `TransactionPort` fake를 testFixtures 1개로 | 일부 | `DirectTransactionPort`(testFixtures)가 생겼고 sample·web이 쓴다. 그러나 다른 구현 9개가 남음: application-core 테스트 4곳(`SubmitDurableOperationUseCaseTest`, `OutcomeAwareRelayTest`, `PublishPendingOutboxEventsUseCaseTest`, `TransactionPortTest`), `application-fileserver/.../testkit/DirectTransactions.java`, application-notification 테스트 4곳 |
|
||||
| X1-#3b 포트별 계약 키트를 소유 leaf testFixtures에 | 일부 | 있음: `DurableOperationStoreContract`, `DistributedLeaseContract`, `OutboxLeaseFencingContract`. 없음: `IdempotencyStorePort`, `DistributedLockPort`, `TransactionPort`, `CacheRegionPort`, `LiveEventReplayPort`, `IntegrationEventEncoderPort`. 01-05 |
|
||||
| X1-#3d `DistributedLockPortContractTest`가 테스트 안 fake를 검증 | 남음 | `application-core/src/test/.../lock/DistributedLockPortContractTest.java:35-46` |
|
||||
| X1-#6b lock과 lease 중 하나만 | 바뀜 | 소유자 결정 8: 둘 다 유지 + 공통 계약 테스트. lease는 키트가 있고 lock은 없다(위 X1-#3d) |
|
||||
| X1-#6d `ClaimFencingContract`를 row lease store마다 | 일부 | outbox는 `OutboxLeaseFencingContract`를 in-memory·JPA가 실행. durable operation lease에 fencing 시나리오가 있는지는 확인 못 함 |
|
||||
| X1-#10b / X2-P1-5 SHA-256 헬퍼 → `Sha256` | 일부 | 대부분 정리. 잔존 복사본은 01-11 |
|
||||
| X2-P1-2b httpclient `RuntimeEnvironment`가 정본과 이름이 같음 | 남음 | `adapter/outbound/httpclient/.../profile/RuntimeEnvironment.java` |
|
||||
| X2-P2-6a 같은 이름 `TenantContext` 2개, 문법이 다름 | 바뀜 | web·GraphQL은 `application-core` `TenantId` 하나로 통일. 그러나 `TenantId` 자체가 3벌, 문법 3가지 — 01-03 |
|
||||
|
||||
## 3. 새 발견
|
||||
|
||||
High 이상은 없다. Medium은 필요한 필드를 모두, Low는 필요한 필드만 쓴다. 설계 선택이 아닌 단순 결함은 "대안 비교: 적용 제외 — 이유"로 둔다.
|
||||
|
||||
### 01-01 새 기능을 어느 leaf에 두는지 세 가지 모양이 있고, 고르는 기준이 없다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 2, 3, 4, 20, 23, 25 |
|
||||
| 근거 | ① 공유 계층 leaf 안의 패키지: durable operation은 `application-core/.../operation/*` + `persistence-jpa` + web `DurableOperationController` + `app-bootstrap/.../DurableOperationConfig.java`. ② 기능 전용 application leaf: `application-notification`, `application-fileserver`, `application-objectstorage`와 짝이 되는 `persistence-notification`·`persistence-fileserver`·`composition:*`. ③ 한 leaf 수직 슬라이스: `sample-portfolio`가 domain·application·adapter·bootstrap 패키지를 한 leaf에 둔다. `AGENTS.md:128-141` 「기능 개발 프로토콜」은 "새 비즈니스 개념은 domain-core에 먼저 둔다"고만 쓰고, 언제 ②를 고르는지는 어디에도 없다. 유일하게 끝까지 동작하는 예시(sample)는 ③이고 `AGENTS.md:259`는 그것을 "격리된 예시"라고 부른다. 계층 leaf에 기능을 넣는 모양(①)은 테스트 fixture(`app-bootstrap/src/test/java/dev/caskeleton/onboarding/**`)에만 있다. |
|
||||
| 사례(참고) | 파생 서비스 `tech-log-backend` 작업 트리: 기능 파일이 `application-core` 273개, web 53개, persistence-jpa 41개, app-bootstrap 6개, **domain-core 0개**. 도메인 모델은 `application/techlog/*/model`에 있고 `@AggregateRoot`·`ResourceId` 사용 0건. 템플릿의 domain-core 경로가 실제로는 쓰이지 않았다. 이 repo 커밋의 증거가 아니라 사례로만 적는다. |
|
||||
| 발생 조건 | 개발자가 첫 업무 기능을 추가한다. |
|
||||
| 영향 | 기능마다 배치가 달라진다. 계층 leaf(①)에 넣으면 upstream 템플릿 파일과 같은 leaf·같은 패키지 트리에서 병합 충돌이 난다(`persistence-jpa`는 capability 모듈 규칙 7 "이 모듈을 아는 곳은 모듈 자신뿐"과도 부딪힌다). ②를 고르면 `modules.json`·`settings.gradle`·`app-bootstrap/build.gradle`을 고쳐야 한다. domain-core를 건너뛰는 선택은 ArchUnit의 domain 순수성 규칙 밖으로 빠진다(규칙은 `..domain..` 패키지만 본다). |
|
||||
| 심각도·우선순위 | Medium / P2. 기능이 깨지지는 않지만 템플릿의 핵심 약속("경계를 지키며 기능을 추가")을 사용자가 매번 스스로 해석해야 한다. 파생 서비스로 그대로 복제된다. |
|
||||
| 확실성 | 세 모양은 코드로 확인(E1). 각 모양의 병합 비용은 측정 안 함. |
|
||||
| 결정의 근거 | 기록된 의도: 메모와 `AGENTS.md:259`는 "sample은 삭제 가능한 fixture", 실제 기능은 계층 leaf로. 소유자 결정 3·33·34는 ②(별도 leaf)를 기능 플랫폼에 썼다. 두 방향이 문서로 합쳐지지 않았다. |
|
||||
| 이해 비용 | 첫 기능 작성자가 sample·onboarding fixture·durable operation·notification 네 곳을 읽고 공통점을 직접 뽑아야 한다. |
|
||||
| 최소 개선 방향 | `docs/manual/`(또는 `AGENTS.md` 「기능 개발 프로토콜」)에 배치 규칙 표 하나를 둔다: 업무 기능 기본 = ①(domain-core·application-core 아래 `<feature>` 패키지, persistence는 기능 전용 adapter leaf 또는 persistence-jpa 아래 `<feature>` 패키지 중 하나로 고정), 독립 배포·선택 조립이 필요하면 ②. 그리고 ①의 끝까지 동작하는 예시를 하나 둔다(아래 01-02의 onboarding fixture를 그 예시로 키우는 것이 가장 싸다). |
|
||||
| 대안 비교 | (a) 위 방법: 문서 1개 + 예시 1개. (b) sample을 계층 leaf로 쪼갠다: 예시가 실제 모양과 같아지지만 sample 삭제가 어려워진다(지금은 leaf 하나 지우면 끝). (c) 업무 기능도 항상 ② 별도 leaf: 경계가 가장 선명하지만 기능마다 registry 3파일을 고친다. (a)를 고른다. sample의 "통째로 지운다" 성질을 지키면서 판단 기준만 추가한다. |
|
||||
| 비용·부작용 | 문서 유지. 예시 fixture를 실제 컴파일·기동 대상으로 올리면 테스트 시간이 조금 는다. |
|
||||
| 재검토 조건 | 파생 서비스가 2개 이상 생기거나 기능 leaf 추가가 반복되면 (c)와 registry 오버레이(메모의 `modules.project.json` 안)를 다시 비교한다. |
|
||||
| 완료 기준 | 새 기능 작성자가 문서 하나로 "어느 leaf, 어느 패키지, 어떤 이름"을 정할 수 있고, 그 모양의 예시가 ci에서 컴파일·테스트된다. |
|
||||
| 검증 방법 | 예시 기능에 대해 `DomainFeatureOnboardingContractTest`류 검사가 production 규칙(`ProductionClassImportOption` 대상 규칙 포함)을 그대로 통과하는지 본다. |
|
||||
|
||||
### 01-02 onboarding fixture가 "새 기능의 계약 모양"으로 박아 둔 유스케이스가 실제로는 기동에 실패하는 모양이다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 10, 20, 21, 23 |
|
||||
| 근거 | ① `app-bootstrap/src/test/java/dev/caskeleton/onboarding/application/usecase/CreateFeatureAggregateUseCase.java:15,20` — `@RequiresPermission` + `public final class`. ② 같은 조합을 금지하는 규칙 `RequiresPermissionProxyabilityTest.java:44`는 `ProductionClassImportOption`으로 test 클래스를 뺀다. 그래서 fixture는 검사받지 않는다. ③ 규칙의 설명(`:26-34`)은 "final 클래스를 bean으로 만들면 'Cannot subclass final class'로 기동 실패, 16개 유스케이스가 이 상태였다"고 적는다. ④ fixture의 `FeatureAggregateIdFactory`는 `IdFactory<FeatureAggregateId>`를 상속하지 않는다(sample `WorkLogIdFactory`는 상속). ⑤ fixture의 쓰기 포트는 application 쪽 `FeatureAggregateWritePort`, sample은 domain 쪽 `WorkLogRepository` — 같은 역할에 이름·위치가 다르다. `DomainFeatureOnboardingContractTest.java:63-78`는 이 이름들을 "최소 계약"으로 고정한다. |
|
||||
| 발생 조건 | 개발자가 onboarding fixture를 복사해 첫 쓰기 유스케이스를 만들고 bean으로 등록한다. |
|
||||
| 영향 | 앱이 기동하지 않는다(시끄럽지만 늦게 드러난다). bean으로 등록하지 않고 직접 `new` 하면 권한 검사가 조용히 빠진다. |
|
||||
| 심각도·우선순위 | Medium / P2. 템플릿이 "이 모양으로 만들라"고 제시하는 유일한 계층 예시라 복제 범위가 넓다. production ArchUnit이 같은 규칙으로 잡으므로(production 코드로 옮기면 ci가 실패) 피해는 개발 시간 손실이다. |
|
||||
| 확실성 | 정적 확인(E1). fixture를 bean으로 띄워 보지는 않았다. 규칙 설명의 실패 메시지는 규칙 작성자의 기록이다. |
|
||||
| 결정의 근거 | 적용 제외 — fixture가 production 규칙을 따라가지 못한 단순 drift다. |
|
||||
| 최소 개선 방향 | `CreateFeatureAggregateUseCase`에서 `final`을 빼고, `FeatureAggregateIdFactory extends IdFactory<FeatureAggregateId>`로, 쓰기 포트 이름·위치를 sample과 같은 규칙으로 맞춘다(01-12에서 규칙을 정한 뒤). `DomainFeatureOnboardingContractTest`에 `RequiresPermissionProxyabilityTest`의 두 규칙과 `NamingConventionTest`를 fixture에도 평가하는 단언을 추가한다. |
|
||||
| 완료 기준 | fixture가 production에 적용되는 모든 application·domain ArchUnit 규칙을 통과한다. |
|
||||
| 검증 방법 | fixture에 `final`을 다시 넣었을 때 `DomainFeatureOnboardingContractTest`가 실패하는지 변이로 확인한다. |
|
||||
|
||||
### 01-03 `TenantId`가 3벌이고 받아들이는 문법이 셋 다 다르다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(갈라진 중복 복사본) |
|
||||
| 관련 관점 | 11, 15, 17, 23 |
|
||||
| 근거 | ① `application-core/.../tenant/TenantId.java:22` `[A-Za-z0-9][A-Za-z0-9_.-]{0,63}` (1~64자, 대문자·점 허용). web·GraphQL 전송이 인증 토큰에서 만든다(`JwtToAuthenticatedPrincipalConverter.java:60-62`). ② `application-notification/.../platform/api/TenantId.java:6-12` 공백 아님 + 100자 이하뿐(어떤 문자든 허용). 41개 파일이 쓴다. 값은 요청 tenant가 아니라 설정의 `SingleTenantContext`(`adapter/outbound/notification/.../SingleTenantContext.java:20`)에서 오고, `EmailAttachments.java:47`은 환경 이름(`profile().environment()`)으로 TenantId를 만든다. ③ `persistence-jpa/.../experimental/tenant/TenantId.java:17` `[a-z0-9][a-z0-9_-]{1,62}` (2~63자, 소문자만, 점 불가). RLS binder가 쓴다. ④ 변이 M2: 정본 문법에 `/`를 허용해도 `TenantIdTest` 전부 통과. `../public` 케이스는 첫 글자 규칙에서 막혀 `/` 검사를 증명하지 못한다. X2-P2-6a는 `TenantContext` 2개를 하나로 합치며 "완료"됐지만 그 아래 값 타입은 그대로 갈라져 있다. |
|
||||
| 발생 조건 | 파생 서비스가 멀티 테넌시를 켠다. 예: 토큰의 tenant가 `Acme.EU`면 web은 받고, experimental RLS binder는 거부한다. 알림은 요청 tenant를 아예 모른다. |
|
||||
| 영향 | tenant는 보안 경계다. 같은 tenant가 계층마다 다르게 읽히거나 거부되면, 거부 쪽은 기능 실패, 허용 쪽은 경로·키 구성에 들어가는 문자(`/`, 공백)를 막지 못한다. 알림 쪽은 tenant가 요청과 연결되지 않아 tenant 격리 검사를 둘 자리가 없다. |
|
||||
| 심각도·우선순위 | Medium / P2. 기본 조립은 단일 tenant라 지금 피해는 없다. 멀티 테넌시를 켜는 순간 세 문법을 사용자가 직접 맞춰야 하고, 템플릿이 이를 알려 주지 않는다. |
|
||||
| 확실성 | 세 문법은 코드로 확인(E1), 테스트 공백은 변이로 확인(E2). 알림이 요청 tenant를 써야 하는지는 05 영역 판단이 필요하다. |
|
||||
| 결정의 근거 | 정본 `TenantId`의 Javadoc(`:7-12`)은 "모든 전송이 받는 하나의 문법"을 목표로 적는다. 알림·experimental은 그 정리 이전에 만들어졌다. 둘 다 `application-core` edge가 있어(`modules.json`) 정본을 쓸 수 있다. |
|
||||
| 최소 개선 방향 | 알림·experimental의 `TenantId`를 정본으로 바꾼다. RLS가 더 좁은 문법(소문자)을 원하면 binder가 정본을 받아 자기 제약을 추가 검사한다(새 타입을 만들지 않는다). `TenantIdTest` 거부 목록에 `acme/eu`, `acme:eu`를 넣는다. |
|
||||
| 대안 비교 | (a) 위 방법. (b) 문법 문자열만 정본에서 가져다 쓰기: 타입이 셋으로 남아 같은 값을 세 번 검사한다. (c) 현상 유지 + 문서화: 멀티 테넌시를 켜는 사람이 세 곳을 기억해야 한다(원칙상 결함). (a)를 고른다. |
|
||||
| 단순화의 보존 조건 | 알림 DB에 이미 저장된 tenant 값이 정본 문법을 만족하는지 먼저 확인한다(기본값 확인 필요). 만족하지 않으면 읽기 경로에서 거부되므로 이행 순서를 정한다. |
|
||||
| 완료 기준 | `record TenantId` 정의가 repo에 하나뿐이다(messaging vendored 제외). 거부 목록 테스트가 `/`를 포함한다. |
|
||||
| 검증 방법 | 변이 M2를 다시 돌려 테스트가 실패하는지 본다. `git ls-files '*/main/*TenantId.java'`가 1건. |
|
||||
|
||||
### 01-04 `IllegalArgumentException` 하나가 "입력이 틀렸다"와 "서버 조립이 틀렸다"를 함께 뜻하고, web은 둘 다 로그 없이 400으로 바꾼다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 5, 6, 8, 17 |
|
||||
| 근거 | ① `adapter/inbound/web/.../error/GlobalExceptionHandler.java:75-81` — `IllegalArgumentException`이면 `BAD_PARAMETER`(400, retryable false)로 응답하고 로그를 남기지 않는다(같은 파일의 `log.error`는 `:154-194` 다른 경로에만). ② 서버 조립 결함도 IAE로 던져진다: `adapter/outbound/support/.../JsonIntegrationEventEncoder.java:100-102` "no integration event contract is registered", `:104-110` 목적지 불일치, `:113-116` payload 타입 불일치, `:119-127` 크기 초과. ③ 코어 값 객체도 불변식 위반에 IAE를 쓴다(`ValidatedIntegrationEvent`, `ContractDescriptor.java:20-47`, `SchemaResourceId`). 이 값 객체는 요청 입력이 아니라 서버 코드가 만든다. ④ 유스케이스 테스트의 표준 fake `FakeIntegrationEventEncoder`(application-core testFixtures)는 어떤 계약이든 받아 준다(01-05). |
|
||||
| 발생 조건 | 개발자가 새 이벤트 계약을 만들고 bean 등록(`SampleApplicationUseCaseConfig.java:60-93`처럼 계약마다 `@Bean`)을 빠뜨린다. 또는 payload record를 바꾸고 계약의 `exactPayloadRecordType`을 안 바꾼다. |
|
||||
| 영향 | 그 기능의 모든 쓰기 요청이 400 "잘못된 요청"으로 끝난다. 트랜잭션은 롤백되어 데이터 손상은 없다. 서버 로그에 아무것도 없고 5xx 경보도 울리지 않는다. 클라이언트는 자기 요청을 고치려 한다. fake로 쓴 유스케이스 테스트는 통과한다. |
|
||||
| 심각도·우선순위 | Medium / P2. 기능 전체가 멈추지만 실제 encoder로 도는 통합 테스트가 있으면 잡힌다. 진단이 어렵다는 점이 핵심이다. |
|
||||
| 확실성 | 경로는 정적 확인(E1). 실제 요청으로 재현하지는 않았다. |
|
||||
| 결정의 근거 | `X2-P2-2b`(IAE는 모든 전송에서 400)는 현황표의 "에이전트가 정한 것(소유자가 뒤집을 수 있음)" 목록에 있다. 이 발견은 그 결정을 뒤집자는 것이 아니라, 결정이 전제한 "IAE = 입력 오류"가 코어·adapter 코드에서 지켜지지 않는다는 것이다. |
|
||||
| 이해 비용 | 400 하나를 받은 운영자가 원인을 찾으려면 디버거를 붙여야 한다. |
|
||||
| 최소 개선 방향 | 서버 조립 결함을 IAE가 아닌 `IllegalStateException`(→ 기존 catch-all 500 + `log.error`)으로 바꾼다: encoder의 미등록 계약·타입 불일치, 서버가 만드는 값 객체(`ValidatedIntegrationEvent`, `ContractDescriptor`)의 불변식. 요청 크기 초과처럼 입력 탓일 수 있는 것은 IAE로 둔다. 그리고 400 응답에도 WARN 한 줄(예외 타입만)을 남긴다. |
|
||||
| 대안 비교 | (a) 위 방법: 던지는 쪽을 고친다. 소유자 결정을 유지한다. (b) 전송이 IAE를 500으로: 진짜 입력 오류가 500이 된다 — X2-P2-2b와 충돌. (c) 전용 `ServerMisconfigurationException`(shared-contract) 추가: 의미는 가장 선명하지만 타입이 하나 는다. 지금 규모에서는 (a)로 충분하고, IAE/ISE 구분이 반복해서 흐려지면 (c)로 간다. |
|
||||
| 비용·부작용 | encoder·값 객체 테스트의 예외 타입 단언을 바꿔야 한다. |
|
||||
| 완료 기준 | 미등록 계약으로 encode하면 500 + `log.error`가 남는다. |
|
||||
| 검증 방법 | web slice 테스트: 미등록 계약 draft를 append하는 유스케이스를 부르면 500 `INTERNAL_ERROR`, 로그에 원인 메시지. |
|
||||
|
||||
### 01-05 application-core가 소유한 포트 중 절반이 "fake와 실제 adapter가 같은 계약 테스트를 통과한다"는 규칙 밖에 있다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 10, 21, 23 |
|
||||
| 근거 | `AGENTS.md:168-170` 테스트 규칙 6: 포트당 fake 하나를 소유 leaf testFixtures에, fake와 adapter가 같은 추상 계약 테스트를 통과. application-core 포트 17개(`*Port` 인터페이스) 중 계약 키트가 있는 것: `DurableOperationStorePort`(in-memory·JPA), `DistributedLeasePort`(in-memory·Redis), `OutboxStorePort` fencing(in-memory·JPA). 없는 것 중 adapter가 있는 포트: `IdempotencyStorePort`(Redis·PostgreSQL 두 adapter + `InMemoryIdempotencyStore` fake, 공통 계약 없음), `TransactionPort`(`SpringTransaction` vs `DirectTransactionPort` + 다른 구현 9개), `DistributedLockPort`(JPA adapter, fake는 테스트 안 private 클래스 `DistributedLockPortContractTest.java:46`), `CacheRegionPort`(Redis만), `LiveEventReplayPort`(JPA만), `IntegrationEventEncoderPort`(`JsonIntegrationEventEncoder` vs `FakeIntegrationEventEncoder`). `OutboxAppendContract`는 JPA만 상속하고 `InMemoryOutboxStore`는 상속하지 않는다. |
|
||||
| 발생 조건 | 사용 프로젝트가 fake로 유스케이스 테스트를 쓰고 실제 adapter로 배포한다. |
|
||||
| 영향 | fake가 실제와 다르게 동작하면 테스트가 거짓 녹색이다. 예: `FakeIntegrationEventEncoder`는 미등록 계약·목적지 불일치·payload 타입 불일치를 거부하지 않는다 — 01-04의 결함이 단위 테스트에서 안 보이는 이유. 멱등성은 05-02(Redis renew 결함을 fake가 그대로 따라 함)가 실제 사례다. |
|
||||
| 심각도·우선순위 | Medium / P2. 결함 자체가 아니라 결함을 못 잡는 구조다. 멱등성·트랜잭션은 중복 실행·부분 커밋과 직결된다. |
|
||||
| 확실성 | 키트 유무는 grep으로 전수 확인(E1). |
|
||||
| 결정의 근거 | 규칙과 일부 키트(outbox·operation·lease)는 이미 있다. 나머지가 비어 있는 것은 작업 미완(X1-#3a/b/d 남음)이다. |
|
||||
| 최소 개선 방향 | 우선순위: ① `IdempotencyStoreContract`(05-02와 같은 작업), ② `TransactionPortContract`(inRootWrite 중첩 거부, 예외 시 롤백, inNew 독립 커밋) — `SpringTransaction` IT와 `DirectTransactionPort`가 상속, 다른 구현 9개는 `DirectTransactionPort`로 교체, ③ `FakeIntegrationEventEncoder`가 생성자에서 계약 목록을 받아 미등록·목적지·타입을 실제와 같은 예외로 거부, ④ lock fake를 testFixtures로 옮기고 키트화. |
|
||||
| 대안 비교 | (a) 위 순서. (b) fake를 없애고 Testcontainers만: 계약은 맞지만 유스케이스 테스트가 느려지고 application-core가 Spring·DB를 알게 된다. (c) 현상 유지. (a)를 고른다. 규칙과 기존 키트 모양을 그대로 따른다. |
|
||||
| 완료 기준 | adapter가 있는 application-core 포트마다 testFixtures에 `XxxContract`가 있고, fake와 모든 adapter 테스트가 상속한다. `implements TransactionPort`가 main 1개 + testFixtures 1개뿐이다. |
|
||||
| 검증 방법 | 키트마다 fake에 결함 하나를 넣어 키트가 실패하는지 변이로 확인한다. |
|
||||
|
||||
### 01-06 `@RequiresPermission`은 application 계약인데, 검사는 web leaf가 켜 주는 AOP에만 있다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 5, 15, 21, 27 |
|
||||
| 근거 | ① 선언: `application-core/.../security/RequiresPermission.java`. ArchUnit `MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`(`ApplicationBoundaryArchitectureTest.java:404-425`)이 쓰기 유스케이스에 선언을 강제한다. ② 검사: `adapter/inbound/web/.../authz/MethodSecurityConfig.java:26-60`의 advisor 하나. `WebSecurityAutoConfiguration.java:47`이 import한다. web 외 전송(GraphQL·gRPC·WebSocket)과 composition 모듈에는 검사 장치가 없다. web이 빠진 조립에서 선언만 남는지 확인하는 기동 검사도 없다(app-bootstrap main에서 `RequiresPermission` 참조는 `DurableOperationConfig` 주석뿐). ③ 시스템이 부르는 유스케이스: `PublishPendingOutboxEventsUseCase.java:31` `@RequiresPermission("outbox:relay")`는 relay가 bean이 아니라 `new`로 만들어져(`composition/outbox-relay/.../OutboxRelayAutoConfiguration.java:76-77`) 한 번도 검사되지 않는다. 규칙을 통과하려고 붙인 선언이다. ④ 그 이유를 설명하는 `application-core/README.md:389-391`은 "final 클래스라 프록시 불가"라고 적지만 지금 클래스는 final이 아니다(`:37`). 남은 진짜 이유(스케줄러 스레드엔 Authentication이 없어 bean으로 만들면 매 tick 거부)는 README에만 있고 코드에는 없다. |
|
||||
| 발생 조건 | (가) 파생 서비스가 gRPC 전용·배치 전용으로 `adapter:inbound:web`을 뺀다(`app-bootstrap/build.gradle:213`). (나) 누군가 relay 유스케이스를 bean으로 등록한다. |
|
||||
| 영향 | (가) 권한 선언이 있는 모든 유스케이스가 검사 없이 실행된다. 기동은 정상이다. (나) relay가 매 tick 거부되어 outbox가 쌓인다. |
|
||||
| 심각도·우선순위 | Medium / P3. 기본 조립에는 web이 `implementation`으로 고정이라 (가)는 사용자가 구조를 바꿀 때만 생긴다. 생기면 조용한 인가 우회다. |
|
||||
| 확실성 | 정적 확인(E1). web 없는 조립을 띄워 보지는 않았다. |
|
||||
| 결정의 근거 | `application-core/README.md:161-188`: 결정(포트)은 framework-free, 메커니즘(AOP)은 web. 이 분리 자체는 타당하다. 빠진 것은 "메커니즘이 없을 때 실패하는 장치"와 "시스템 호출자의 권한 표현"이다. 41절 검토는 5.1. |
|
||||
| 최소 개선 방향 | ① `@RequiresPermission` 선언 bean이 있는데 advisor bean이 없으면 기동 실패하는 검사를 support 또는 composition:service-runtime에 둔다. ② 시스템 호출 유스케이스는 `@RequiresPermission` 대신 `@UseCaseCapability`에 "시스템 전용" 표시를 두고 ArchUnit 규칙이 그 경우를 면제한다. 그리고 그 클래스 Javadoc에 "bean으로 만들지 말 것, 이유"를 적는다. ③ README:389-391을 고친다. |
|
||||
| 대안 비교 | (a) 위 방법. (b) 유스케이스 본문에서 `AuthorizationPort`를 직접 부른다: 전송과 무관하게 검사되지만 principal을 command에 실어야 하고 모든 유스케이스 시그니처가 바뀐다. (c) composition이 유스케이스를 데코레이터로 감싼다: AOP 의존은 없어지지만 bean 등록 규칙이 하나 더 생긴다. (a)를 고른다. 지금 구조를 유지하면서 빠지는 경우만 시끄럽게 만든다. |
|
||||
| 완료 기준 | web을 뺀 조립에서 선언 bean이 있으면 기동이 실패한다. relay 유스케이스에 장식용 권한 선언이 없다. |
|
||||
| 검증 방법 | `ApplicationContextRunner`로 web 없이 `@RequiresPermission` bean 하나를 등록해 기동 실패를 단언한다. |
|
||||
|
||||
### 01-07 이벤트 식별자 문법이 다섯 곳에 복사되어 있고 길이 상한이 둘로 갈린다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(갈라진 중복) |
|
||||
| 관련 관점 | 10, 17, 23 |
|
||||
| 근거 | `[A-Za-z0-9][A-Za-z0-9._:-]` 문법: `EventId.java:6,9`(96자), `IntegrationEventDraft.java:22,49` correlation(96자), `ValidatedIntegrationEvent.java:37` correlation·causation(128자), `SubmitDurableOperationUseCase.java:67-68`(복사, 96자), sample `PortfolioEventOutbox.java:41-42`(복사, 96자). 변이 M5: draft 상한 96→200이어도 테스트 전부 통과. 같은 encoder를 가리키는 `ContractDescriptor.serializerId`가 `"json-envelope-v1"`(`PortfolioEventContract.java:46`, `DurableOperationSubmittedContract.java:44`)과 `"json-schema-envelope-v1"`(`WorkLogReservedContractContribution.java:28`) 두 표기다. serializerId는 검증 없이 catalog revision 해시에만 들어간다(`JsonIntegrationEventEncoder.java:267`). |
|
||||
| 발생 조건 | 누가 한 곳의 상한을 바꾼다. 또는 draft를 거치지 않고 DB에서 복원한 이벤트(128자 correlation)를 다시 draft 경로로 보낸다. |
|
||||
| 영향 | 같은 값이 경로에 따라 통과·거부가 갈린다. serializerId 표기 차이는 지금은 해시 값만 바꾸지만, 나중에 serializer 선택에 쓰이면 한 계약이 조용히 다른 serializer를 고른다. |
|
||||
| 심각도·우선순위 | Low / P3. 지금 상한은 draft(96) ≤ validated(128)라 정상 경로에서 충돌하지 않는다. |
|
||||
| 결정의 근거 | 적용 제외 — 같은 규칙의 복사본을 하나로 모으는 단순 정리다. |
|
||||
| 최소 개선 방향 | application-core `messaging.event`에 `IntegrationIdentity.GRAMMAR`·`MAX_LENGTH`(또는 `isCanonical(String)`) 하나를 두고 다섯 곳이 쓴다. correlation 상한은 DB 열(varchar 128)에 맞춰 하나로 정한다. serializerId는 encoder가 아는 값 목록과 대조해 모르는 값이면 기동 시 거부한다. draft 상한 경계값 테스트를 추가한다. |
|
||||
| 완료 기준 | 문법 문자열 리터럴이 main에 한 번만 나온다. M5 변이가 실패한다. |
|
||||
| 검증 방법 | grep + 변이 M5 재실행. |
|
||||
|
||||
### 01-08 장기 실행 작업(LRO) 공개 계약이 두 벌이다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험(갈라진 중복) |
|
||||
| 관련 관점 | 17, 23, 24, 27 |
|
||||
| 근거 | ① shared-contract `operation/Operation.java`·`OperationStatus.java`: 필드 `status`, 값 `PENDING·RUNNING·SUCCEEDED·FAILED·CANCELLED`, Javadoc이 `GET /v1/operations/{id}`의 본문이라고 선언. main 소비자는 sample의 `OperationsController`·`SampleOperationStore`뿐. ② application-core `DurableOperation`·`DurableOperationState`(`CANCELED`·`EXPIRED` 포함, 철자 다름) + web `OperationHttpResponse`(필드 `state`, `submittedAt`·`progress`·`expiresAt` 등) — 같은 경로 `GET /operations/{operationId}`(`DurableOperationController.java:48,106`). 소유자 결정 15·26은 ②를 정본 HTTP 어댑터로 정했다. |
|
||||
| 발생 조건 | 파생 서비스가 LRO를 만들 때 shared-contract의 이름이 "skeleton-wide 계약"이라 ①을 고른다. 또는 sample 경로와 durable operation을 함께 켠다(두 컨트롤러가 같은 경로를 잡는다). |
|
||||
| 영향 | 같은 개념에 두 개의 공개 응답 모양과 두 개의 상태 어휘가 생긴다. 클라이언트 SDK가 둘 다 처리해야 한다. 같은 앱에 둘 다 있으면 경로 충돌로 기동이 실패한다(sample 앱은 app-bootstrap을 쓰지 않아 지금은 충돌 없음). sample은 모르는 id에 IAE를 던져 404가 아니라 400을 준다(`OperationsController.java` `poll`). |
|
||||
| 심각도·우선순위 | Medium / P3. 공개 계약의 일관성 문제이고, 템플릿 사용자가 고를 때 틀린 쪽을 고르기 쉽다. |
|
||||
| 결정의 근거 | 기록된 결정은 ②를 정본으로 만들었고 ①을 정리하는 결정은 없다. |
|
||||
| 최소 개선 방향 | ①을 sample leaf로 옮기거나 삭제한다. sample LRO 예시는 ②의 유스케이스로 다시 쓰거나, sample 전용 타입으로 남기고 shared-contract에서는 뺀다. shared-contract README의 operation 절(`README.md:293-`)을 정리한다. |
|
||||
| 대안 비교 | (a) ①을 sample로 내림: shared-contract가 줄고 정본이 하나가 된다. sample의 wire 모양은 유지. (b) ①을 정본으로 하고 ②의 HTTP 응답을 ①에 맞춤: 소유자 결정 26과 충돌. (c) 둘 다 유지 + 문서: 원칙상 결함 유지. (a)를 고른다. |
|
||||
| 단순화의 보존 조건 | sample의 `POST /worklogs:export` 응답 모양(202 + Location + 상태 enum)과 그 계약 테스트는 그대로 통과해야 한다. |
|
||||
| 완료 기준 | shared-contract에 `operation` 패키지가 없거나, 있으면 production 소비자가 있다. |
|
||||
| 검증 방법 | sample web contract 테스트 통과, `git grep shared.operation`이 sample 밖에서 0건. |
|
||||
|
||||
### 01-09 통합 이벤트를 만드는 규칙(tenant 범위·순서·correlation)을 기능마다 다시 정한다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 3, 11, 20, 22, 23 |
|
||||
| 근거 | `IntegrationEventDraft`는 10개 필드를 받는다. 채우는 규칙이 두 곳에서 다르게 정해졌다. ① durable operation `SubmitDurableOperationUseCase.java:64,66,143-157`: tenant 범위는 상수 `"global"`(요청에는 `command.tenantId()`가 있는데 쓰지 않음), 순서 `(1,0)` 고정, correlation = 이벤트 id. ② sample `PortfolioEventOutbox.java:39-42,72-97`: tenant 범위 `"portfolio"`, 순서 = 발생 시각 마이크로초, correlation = 요청 correlation(문법에 안 맞으면 이벤트 id). 조립 헬퍼(②)는 sample에만 있어 production 기능은 ①처럼 직접 조립한다. 도메인 이벤트 쪽도 틀만 있다: `@DomainEvent` 마커는 있지만 aggregate가 이벤트를 모으는 수단은 없고, sample `CreateWorkLogUseCase.java:79-84`는 `WorkLogReserved`(category·periodStart 포함)를 만들어 id만 꺼내 쓴다. |
|
||||
| 발생 조건 | 새 기능이 이벤트를 발행한다. |
|
||||
| 영향 | 같은 outbox·relay를 지나는 이벤트가 tenant 범위와 순서의 의미를 기능마다 다르게 가진다. 소비자가 tenant로 나누거나 순서로 중복을 거르면 기능마다 다르게 동작한다. tenant가 있는 durable operation 이벤트가 `"global"`로 나가 소비자 쪽 tenant 격리 근거가 사라진다. |
|
||||
| 심각도·우선순위 | Medium / P3. 지금 소비자가 템플릿 안에 없다. 이벤트를 쓰는 첫 파생 기능부터 갈라진다. |
|
||||
| 결정의 근거 | `PortfolioEventOutbox` Javadoc(`:19-35`)이 규칙과 이유를 잘 적어 두었다. 그 결정을 application-core로 올리지 않은 것이 빠진 부분이다. |
|
||||
| 최소 개선 방향 | application-core에 `IntegrationEventAppender`(이름은 예시) 하나: 입력은 계약·aggregate 종류·aggregate id·tenant(`TenantId` 또는 "단일 tenant" 상수)·payload, 순서·correlation 규칙은 한 곳에서. sample과 durable operation이 이것을 쓴다. 도메인 이벤트→통합 이벤트 변환 위치는 01-01 문서의 판단 지점으로 적는다. |
|
||||
| 대안 비교 | (a) 헬퍼 승격. (b) 규칙을 문서로만: 기능마다 다시 구현한다. (c) aggregate가 도메인 이벤트를 모으고 저장 시 adapter가 변환(Spring Data `@DomainEvents` 방식): 도메인이 프레임워크 없이 이벤트를 들 수 있지만 domain-core에 베이스 클래스가 생기고 변환 위치가 persistence로 간다. (a)를 고른다. (c)는 두 번째 이벤트 소비자가 생기면 다시 본다. |
|
||||
| 완료 기준 | `new IntegrationEventDraft<>(`가 main에서 헬퍼 한 곳에만 있다. |
|
||||
| 검증 방법 | 헬퍼 단위 테스트(tenant·순서·correlation 규칙)와 grep. |
|
||||
|
||||
### 01-10 application-core 한 이름공간에 커널·플랫폼 기능·(파생 시) 업무 기능이 섞인다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 개선 제안 |
|
||||
| 관련 관점 | 2, 4, 24, 25 |
|
||||
| 근거 | `application-core/src/main/java/dev/caskeleton/application/` 아래 17개 패키지: 커널(`usecase`·`command`·`query`·`capability`·`transaction`·`security`·`tenant`), 플랫폼 기능(`outbox`·`idempotency`·`operation`·`lease`·`lock`·`cache`·`realtime`·`messaging`), 묶음 이름만 있는 `outbound`(`CallBudget`·`SecretReference`·`SecretSourcePort` — 서로 관계없음), `observability`. 01-01의 ①을 따르면 업무 기능도 같은 수준(`application/<feature>`)에 들어간다(파생 사례: `application/techlog`). |
|
||||
| 영향 | 업무 기능 이름이 플랫폼 패키지와 겹칠 수 있다(`operation`, `lock`, `cache`). 새 사람은 어느 패키지가 "건드리지 말 템플릿"이고 어느 것이 "우리 기능"인지 경로로 구분할 수 없다. upstream 병합 시 충돌 범위도 같은 트리다. |
|
||||
| 심각도·우선순위 | Low / P3. |
|
||||
| 최소 개선 방향 | 업무 기능 패키지 규칙을 01-01 문서에서 정한다(예: `dev.caskeleton.application.feature.<name>` 또는 파생 서비스 루트 패키지). `outbound` 패키지는 내용별로 흩는다(`SecretSourcePort`·`SecretReference` → `secret`, `CallBudget` → 사용처). 이름 변경은 API surface 파일과 함께 한 번에. |
|
||||
| 대안 비교 | (a) 패키지 규칙만. (b) 플랫폼 기능을 `application-platform` leaf로 분리: 경계는 선명하지만 registry·edge가 늘고 결정 34(edge를 늘리지 않음)와 같은 비용 판단이 필요. (a)를 고른다. |
|
||||
|
||||
### 01-11 공용 다이제스트 헬퍼가 있는데 복사본이 남아 있고, 일부 leaf는 registry 때문에 복사가 강제된다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(갈라진 중복) |
|
||||
| 관련 관점 | 16, 23 |
|
||||
| 근거 | shared-contract `digest/Sha256`·`HmacSha256`이 정본이다(`shared-contract/CLAUDE.md` 책임 목록). shared-contract edge가 **있는데** 복사한 곳: `application-fileserver/.../observability/SafeFileFingerprint.java:37-43`(`HmacSha256.sign` + hex 앞 16자와 같음), `cache-redis/.../capability/RedisKeys.java:59-71`(inline FQN `javax.crypto.Mac`). edge가 **없어서** 복사할 수밖에 없는 곳: `identifier/HmacUserPrincipalPseudonymizer.java:38`, `persistence-mongo`의 `MongoTenantContext.java:28`·`MongoCredentialReference.java:57`·`MongoAdminCommand.java:98`·`MongoKeysetCursorCodec.java:160`, `application-objectstorage`의 `ObjectIdentitySupport.java:77`·`ObjectDigest.java:35`, `redis-sdk/ConfiguredRedisPolicyAuthority.java:85`. X1-#10b·X2-P1-5는 "완료"로 닫혔다. |
|
||||
| 영향 | 다음 수정(예: 키 길이 검사, constant-time 비교)이 정본에만 들어가고 복사본은 남는다. |
|
||||
| 심각도·우선순위 | Low / P3. 지금 복사본에 알려진 결함은 없다. |
|
||||
| 최소 개선 방향 | edge가 있는 두 곳은 정본으로 바꾼다. edge가 없는 leaf는 registry에 `shared-contract` edge를 줄지(stdlib 전용 leaf라 방향상 문제 없음), 복사를 허용하고 그 사실을 leaf CLAUDE.md에 적을지 정한다. |
|
||||
| 대안 비교 | (a) edge 추가: 복사 제거, 대신 shared-contract가 더 많은 leaf의 공통 의존이 된다. (b) 복사 허용 + 문서: edge 그래프 유지. messaging·gRPC는 이미 (b)를 의도로 적었다(`shared-contract/CLAUDE.md` "keep their own copies"). 템플릿 자체 leaf는 (a), vendored 플랫폼은 (b)를 권한다. |
|
||||
|
||||
### 01-12 이름 규칙의 정본 문서가 없고, 같은 역할에 이름이 여러 가지다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(문서) + 개선 제안 |
|
||||
| 관련 관점 | 4, 23, 24 |
|
||||
| 근거 | `NamingConventionTest.java:12-17`이 이름 규칙의 SSOT로 `.agents/plugins/ca-superpowers/rules/code-conventions.md`를 가리키고 "[판단] 규칙(N2/N7/N8...)은 리뷰가 맡는다"고 적는다. 그 파일은 repo에 없다(`git ls-files` 0건). 실제 이름: 유스케이스 `*UseCase`(application-core 7, sample 21) vs `*ApplicationUseCase`(fileserver 21, notification 7) + `*Service`(notification 8, fileserver 4). 저장 포트 `*Repository`(sample domain) vs `*StorePort`(application-core 3, notification 12) vs `*WritePort`(onboarding fixture) vs `*QueryPort`. id 팩토리는 `IdFactory` 상속(sample) vs 상속 안 함(onboarding, `OutboxEventIdFactory`). |
|
||||
| 영향 | 새 기능 작성자가 어느 이름을 따라야 할지 정할 근거가 없다. 판단 규칙을 "리뷰가 맡는다"고 했는데 리뷰가 볼 문서가 없다. |
|
||||
| 심각도·우선순위 | Low / P3. |
|
||||
| 최소 개선 방향 | 이름 규칙 표를 `application-core/CLAUDE.md`(이미 "Naming convention" 절이 있음, `:84-90`)에 합치고 `NamingConventionTest`의 링크를 그쪽으로 바꾼다. 저장 포트는 "domain이 소유하면 `*Repository`, application이 소유하면 `*StorePort`" 같은 한 줄 기준을 적는다. |
|
||||
|
||||
### 01-13 참조 예시의 수정 유스케이스에 소유자 검사가 없다는 사실이 코드에 보이지 않는다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 개선 제안(위험 가시성) |
|
||||
| 관련 관점 | 5, 15, 20 |
|
||||
| 근거 | `sample-portfolio/.../UpdateWorkLogUseCase.java:31-74`는 `worklog:write` 권한만 보고 `WorkLog.owner()`를 확인하지 않는다. 다른 사용자의 work log를 고칠 수 있다. `sample-portfolio/README.md:259-263`은 "소유자 범위 인가(ABAC)는 의도적으로 뒤로 미룬 확장"이라고 적는다. 코드에는 그 표시가 없다. 템플릿의 객체 인가 포트 `application-core/.../security/ObjectAccessPolicy.java`는 sample에서 쓰이지 않고, durable operation은 자기 전용 `DurableOperationAccessPolicy`를 쓴다. 객체 인가의 모양이 셋(없음 / 전용 정책 / `ObjectAccessPolicy`)이다. |
|
||||
| 영향 | 사용자가 sample을 복사하면 객체 인가 없는 수정이 그대로 복제된다(가이드 31절 "다른 사용자 리소스 접근"). |
|
||||
| 심각도·우선순위 | Low / P3. sample은 fixture이고 의도가 README에 있다. 그러나 원칙상 코드에 드러나야 한다. |
|
||||
| 최소 개선 방향 | `UpdateWorkLogUseCase` Javadoc 첫 줄에 "소유자 검사 없음 — 의도적, README 링크"를 적는다. 더 나은 방법은 sample의 수정·삭제 하나를 `ObjectAccessPolicy`로 보호해 객체 인가 예시를 만드는 것이다. |
|
||||
|
||||
### 01-14 작은 결함 묶음 (각각 독립, Low / P3)
|
||||
|
||||
| 항목 | 근거 | 개선 |
|
||||
| --- | --- | --- |
|
||||
| README가 relay 유스케이스를 final이라고 설명 | `application-core/README.md:389-391` vs 클래스 `PublishPendingOutboxEventsUseCase.java:37`(non-final) | 01-06의 ③ |
|
||||
| shared-contract 빈 패키지 3개 | `shared/annotation`·`headers`·`registry`에 `.gitkeep`만. 무엇을 둘 자리인지 설명 없음 | 쓰임을 CLAUDE.md에 적거나 삭제 |
|
||||
| `IdempotencyContractTest`·`CacheRegionContractTest`가 이름은 계약 테스트인데 값 타입 테스트다 | `application-core/src/test/.../idempotency/IdempotencyContractTest.java`, `cache/CacheRegionContractTest.java` — 포트 구현을 받지 않는다. 01-05의 진짜 계약 키트와 이름이 겹친다 | `*ValueTest` 등으로 이름 변경 |
|
||||
| sample `OutboxEventIdFactory`가 domain 패키지에 있다 | `sample-portfolio/.../domain/worklog/OutboxEventIdFactory.java` — outbox는 도메인 개념이 아니고 이 팩토리는 `application/event/PortfolioEventOutbox`만 쓴다 | application 쪽으로 이동 |
|
||||
| `WorkLogInvariantException.TITLE_BLANK`이 409로 나간다 | `DomainExceptionHandler.java` `handleWorkLogInvariant` → `WORKLOG_CONFLICT` | reason별 매핑(Poster처럼) |
|
||||
|
||||
## 4. 31절 시나리오 추적
|
||||
|
||||
### 4.1 정상 쓰기 요청 — sample `POST /worklogs` (적용)
|
||||
|
||||
```text
|
||||
HTTP 요청
|
||||
→ (web 보안 필터) JWT 검증 → AuthenticatedPrincipal(roles, tenant)
|
||||
→ WorkLogController.create(@Valid CreateWorkLogRequest) ── 입력 검증(Bean Validation)
|
||||
→ WorkLogWebMapper.toCommand(body, 소유자=토큰 subject) ── DTO → Command
|
||||
→ [AOP 프록시] RequiresPermissionAuthorizationManager ── "worklog:write" 권한 검사
|
||||
→ CreateWorkLogUseCase.handle
|
||||
tx.inWrite { ── 트랜잭션 시작
|
||||
WorkLog.create(...) ── 불변식(제목 공백 등)
|
||||
WorkLogRepository.save → WorkLogRepositoryAdapter(JPA) ── INSERT + 감사 필드
|
||||
PortfolioEventOutbox.append → encoder → OutboxAppendPort ── 같은 트랜잭션에 outbox INSERT
|
||||
} ── 커밋
|
||||
→ 200 + ETag + WorkLogResponse
|
||||
(커밋 뒤) outbox relay가 따로 claim → 발행
|
||||
```
|
||||
|
||||
| 항목 | 관찰 |
|
||||
| --- | --- |
|
||||
| 입력 신뢰 수준 | 본문은 신뢰하지 않음 → `@Valid`와 `CreateWorkLogCommand` compact constructor(`CreateWorkLogCommand.java:24-30`)가 두 번 검사. 소유자는 본문이 아니라 검증된 토큰에서 온다(`WorkLogController.java:217-`). |
|
||||
| 인가 위치 | 유스케이스 bean의 AOP 프록시. 유스케이스 코드 안에는 없다(01-06). 객체 인가는 생성이라 해당 없음. |
|
||||
| 규칙 소유 객체 | `WorkLog`(aggregate). 기본 소유자 상수 `"sample-owner"`(`WorkLog.java:16`)가 남아 있어 owner 없는 `create` 오버로드가 호출되면 가짜 소유자가 찍힌다 — 현재 호출자는 owner 있는 쪽만. |
|
||||
| 트랜잭션 | `tx.inWrite` 하나. 저장과 outbox append가 한 커밋이다(이중 쓰기 없음). |
|
||||
| 외부 부작용 | 요청 안에서는 없다. 발행은 relay가 커밋 뒤에 한다. |
|
||||
| 성공의 의미 | 200은 "DB와 outbox에 커밋됨"이다. 이벤트 발행 완료는 아니다. 생성인데 201이 아니라 200이다. |
|
||||
| 오류 변환 | 불변식 → `DomainExceptionHandler`(sample, web 전용) → `PortfolioErrorCode`. GraphQL·gRPC로 같은 유스케이스를 열면 이 매핑을 다시 써야 한다(4.4·7절 판단 지점). 서버 조립 오류는 400으로 숨는다(01-04). |
|
||||
| 진단 정보 | correlation id가 MDC와 이벤트 correlation에 같이 실린다(`PortfolioEventOutbox`). 400 경로에는 로그가 없다. |
|
||||
| 성능 | 생성 1건 = INSERT 2(work_log, outbox). 수정은 `WorkLogRepositoryAdapter.save`가 감사 필드를 옮기려고 `findById`를 한 번 더 부른다(유스케이스의 `findById` 포함 SELECT 2 + UPDATE 1). 같은 영속성 컨텍스트라 두 번째 SELECT는 1차 캐시에서 끝날 수 있지만 코드상 보장은 아니다. |
|
||||
|
||||
### 4.2 다른 사용자 리소스 접근 (적용)
|
||||
|
||||
- sample `PATCH /worklogs/{id}`: 권한만 보고 소유자는 안 본다. 다른 사용자의 글을 고칠 수 있다(01-13, README상 의도).
|
||||
- core `GET /operations/{id}`: `DurableOperationAccessPolicy.mayAccess`가 principal과 tenant를 둘 다 비교하고, 실패하면 없는 것과 같은 404를 준다. 변이 M1(tenant 비교 삭제)을 테스트 5개가 잡았다. 템플릿 안에서 객체 인가가 가장 잘 된 경로다.
|
||||
|
||||
### 4.3 중복·동시 요청 (적용, 범위 한정)
|
||||
|
||||
- sample 생성은 `NOT_IDEMPOTENT`로 선언하고 `Idempotency-Key`를 받지 않는다(`sample-portfolio/README.md:253-255`). 선언과 동작이 맞다.
|
||||
- sample 수정은 `If-Match` 버전을 트랜잭션 안에서 비교한다(`UpdateWorkLogUseCase.java:39-41`) + JPA `@Version`. 동시 수정은 412 또는 낙관적 락 충돌로 끝난다.
|
||||
- durable operation 제출은 store가 `ON CONFLICT`로 "이미 있음"을 답하고, 새로 만든 경우에만 outbox에 append한다(`SubmitDurableOperationUseCase.java:124-131`).
|
||||
- 멱등성 executor 자체의 경쟁은 05 영역(05-02)에서 다룬다.
|
||||
|
||||
### 4.4 선택 어댑터 제거 — `adapter:inbound:web`을 뺀다 (적용, 정적 추적)
|
||||
|
||||
`@RequiresPermission` 검사기가 함께 사라지고, 기동 검사가 없어 선언만 남는다(01-06). 이 영역 코어 타입(shared-contract `ApiErrorCarrier`·`ApiErrorCode`)은 GraphQL·gRPC 오류 매퍼도 쓰므로 web을 빼도 오류 모델은 남는다.
|
||||
|
||||
### 적용 제외·다른 영역
|
||||
|
||||
| 시나리오 | 사유 |
|
||||
| --- | --- |
|
||||
| 외부 응답 지연·유실 | > 05(httpclient·알림). 코어는 `CallBudget` 값 타입만 소유 |
|
||||
| DB 오류·경쟁 | > 03(persistence). 코어는 `TransactionPort` 계약만 소유 — 계약 키트 공백은 01-05 |
|
||||
| 메시지 중복·역순 | > 메시징 영역. 코어 쪽 영향(순서·tenant 규칙 분기)은 01-09 |
|
||||
| 신·구 버전 공존 | 이벤트 payload 버전(`payloadVersion`)과 schema 해시 고정은 확인. 실제 v1→v2 공존 예시가 없어 미검증 |
|
||||
| 여러 서버의 작업 실행 | > outbox relay·lock(03/메시징). 코어 쪽 fencing 키트는 2절 X1-#6d |
|
||||
| 세션·토큰 갱신 경쟁 | > web 영역 |
|
||||
| 큰 입력·목록 조회 | sample 배치 생성 1000건 상한 확인(`README.md:256-258`). 페이지 조회는 web·persistence 영역 |
|
||||
| 종료·재시작 | > bootstrap 영역 |
|
||||
|
||||
## 5. 41절 설계 선택 검토
|
||||
|
||||
### 5.1 `@RequiresPermission`: 선언은 application, 검사는 web의 AOP
|
||||
|
||||
| 질문 | 답 |
|
||||
| --- | --- |
|
||||
| 1. 무엇이 필요한가 | 쓰기 유스케이스가 권한 없이 실행되지 않는다. application-core는 Spring을 모른다. |
|
||||
| 2. 지킬 성질 | 선언된 모든 유스케이스 호출은 검사를 거친다. 검사 장치가 없으면 실행되지 않는다(fail-closed). |
|
||||
| 3. 현재 보장 | 선언 강제(ArchUnit D4), 프록시 가능성 강제(`RequiresPermissionProxyabilityTest`), 검사(`MethodSecurityConfig`), 인증 없으면 거부. **보장하지 않는 것**: web이 없을 때, bean이 아니게 만들었을 때, self-invocation. 마지막 둘은 README가 "정적 분석 사각지대"로 적었다. |
|
||||
| 4. 대안 | (a) 현행 + 장치 부재 시 기동 실패. (b) 유스케이스 본문에서 `AuthorizationPort` 직접 호출. (c) composition이 데코레이터로 감싸기. |
|
||||
| 5. 득실 | (a) 변경 작고 기존 구조 유지, AOP 사각지대는 남음. (b) 전송·bean 여부와 무관하게 검사, 대신 principal을 command에 실어야 하고 모든 유스케이스·테스트가 바뀜. (c) AOP 없이 명시적, 대신 bean 등록 규칙 하나 추가. |
|
||||
| 6. 현재 조건에서의 선택 | 기본 조립에 web이 고정이므로 (a)가 비용 대비 맞다. 01-06. |
|
||||
| 7. 바뀔 조건 | web 없는 조립(gRPC 전용·배치 전용)이 실제로 생기거나, 시스템 호출 유스케이스가 늘면 (b)를 다시 본다. |
|
||||
|
||||
### 5.2 새 기능의 배치: 계층 leaf 패키지 vs 기능 leaf vs 수직 슬라이스
|
||||
|
||||
| 질문 | 답 |
|
||||
| --- | --- |
|
||||
| 1. 무엇이 필요한가 | 파생 서비스가 업무 기능을 추가해도 upstream 변경을 계속 받고(메모의 운영 방식), 경계 검사가 기능 코드에도 적용된다. |
|
||||
| 2. 지킬 성질 | 의존 방향(registry), domain 순수성, 유스케이스 계약. 그리고 템플릿 파일과 기능 파일이 섞이지 않아 병합이 쉽다. |
|
||||
| 3. 현재 보장 | 의존 방향은 leaf 단위로 강제된다. 패키지 수준 규칙은 `..domain..`·`..application..`·`..adapter..` 이름에 걸린다 — 어느 leaf에 두든 패키지 이름을 지키면 검사된다. 배치 자체에 대한 규칙·문서는 없다(01-01). |
|
||||
| 4. 대안 | ① 공유 계층 leaf 안 `<feature>` 패키지. ② 기능별 leaf(`application-<f>`, `persistence-<f>`, `composition:<f>`). ③ 한 leaf 수직 슬라이스(sample). |
|
||||
| 5. 득실 | ① 파일 추가만으로 끝나 시작이 빠르다. 템플릿 leaf와 같은 트리라 병합 충돌 면이 넓고, persistence-jpa 같은 capability 모듈에 업무 코드가 섞인다. ② 경계·삭제가 가장 선명하다. 기능마다 registry 3파일을 고친다. ③ 기능 하나를 통째로 지울 수 있다. 대신 leaf 하나가 모든 계층에 의존해 leaf 단위 방향 검사가 기능 안에서는 무력하고 ArchUnit 패키지 규칙에만 기댄다. |
|
||||
| 6. 현재 조건에서의 선택 | 업무 기능 기본은 ①(파생 사례도 이쪽), 단 persistence 위치는 하나로 고정. 선택 조립이 필요한 플랫폼 기능은 ②(이미 그렇게 함). ③은 fixture 전용. 이 선택을 문서와 예시로 고정하는 것이 01-01. |
|
||||
| 7. 바뀔 조건 | 파생 서비스가 여럿이 되어 같은 업무 기능을 공유하거나, 한 서비스의 기능 수가 늘어 application-core 컴파일·테스트 시간이 문제가 되면 ②로 옮긴다. |
|
||||
|
||||
### 5.3 `TransactionPort`: 콜백 포트로 트랜잭션 경계를 유스케이스 본문에 둔다
|
||||
|
||||
| 질문 | 답 |
|
||||
| --- | --- |
|
||||
| 1. 무엇이 필요한가 | 유스케이스가 트랜잭션 경계를 정하되 Spring `@Transactional`을 import하지 않는다. |
|
||||
| 2. 지킬 성질 | 저장과 outbox append가 한 커밋. 외부 호출은 트랜잭션 밖. root write는 바깥 트랜잭션이 있으면 거부. |
|
||||
| 3. 현재 보장 | 인터페이스(`TransactionPort.java`), ArchUnit `USE_CASE_CAPABILITY_MATCHES_TRANSACTION_PORT_BOUNDARY`·`APPLICATION_DOES_NOT_USE_SPRING_TRANSACTIONAL_ANNOTATION`, `@UseCaseCapability.transactionMode` 선언과 실제 호출의 대조. **보장하지 않는 것**: fake와 `SpringTransaction`이 같은 의미라는 것(공통 계약 없음, 01-05). Runnable 기본 메서드는 `TransactionPortTest`가 위임을 검사한다. |
|
||||
| 4. 대안 | (a) 현행 콜백 포트. (b) composition이 유스케이스 bean에 `@Transactional` 프록시를 씌움. (c) 유스케이스마다 "unit of work" 객체를 주입. |
|
||||
| 5. 득실 | (a) 경계가 본문에 보이고, 트랜잭션 밖 외부 호출을 코드 모양으로 강제할 수 있다(relay가 그렇게 씀). 람다 중첩이 생기고 checked 예외를 못 던진다(문서화됨). (b) 본문이 깨끗하지만 경계가 선언으로 숨어 "어디까지가 한 커밋인가"를 코드로 못 본다. 01-06과 같은 AOP 사각지대도 생긴다. (c) 더 유연하지만 지금 요구보다 무겁다. |
|
||||
| 6. 현재 조건에서의 선택 | (a)가 맞다. "위험은 코드에 드러나야 한다"는 기준에 가장 잘 맞는다. 남은 일은 계약 키트(01-05)다. |
|
||||
| 7. 바뀔 조건 | 한 유스케이스 안에서 여러 저장소(JPA + Mongo)를 묶는 요구가 생기면 `TransactionPort` 의미(어느 리소스의 트랜잭션인가)를 다시 정해야 한다. |
|
||||
|
||||
## 6. 리팩토링 후보
|
||||
|
||||
| # | 무엇을 | 왜 | 보존해야 할 것 |
|
||||
| --- | --- | --- | --- |
|
||||
| R1 | `TenantId` 3벌 → application-core 하나 (01-03) | 보안 경계 값의 문법 통일 | 이미 저장된 알림 tenant 값 읽기, RLS가 원하는 소문자 제약(binder의 추가 검사로) |
|
||||
| R2 | 이벤트 식별자 문법 5곳 → `IntegrationIdentity` 하나 (01-07) | 상한 분기 제거 | event id 96자, outbox correlation 열 128자, 기존 테스트의 거부 메시지 |
|
||||
| R3 | `PortfolioEventOutbox` 규칙을 application-core 헬퍼로 승격 (01-09) | 기능마다 tenant·순서·correlation 재정의 방지 | 저장과 append가 같은 트랜잭션, 문법 밖 correlation이 쓰기를 실패시키지 않음, durable operation의 "같은 operation → 같은 event id" |
|
||||
| R4 | shared-contract `operation` → sample로 (01-08) | 공개 계약 하나 | sample `POST /worklogs:export` wire 모양과 계약 테스트 |
|
||||
| R5 | `TransactionPort` 구현 10개 → `SpringTransaction` + `DirectTransactionPort` (01-05) | fake 의미 통일 | 각 테스트가 단언하던 경계 기록(`committed()` 순서), notification 테스트의 nesting 거부 |
|
||||
| R6 | `SafeFileFingerprint` → `HmacSha256.sign` (01-11) | 복사 제거 | 출력: hex 앞 16자, 키 최소 16바이트 거부 |
|
||||
| R7 | `PublishPendingOutboxEventsUseCase`의 장식용 `@RequiresPermission` 제거 + 시스템 전용 표시 (01-06) | 거짓 선언 제거 | ArchUnit D4가 다른 쓰기 유스케이스에는 계속 선언을 강제 |
|
||||
|
||||
## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료)
|
||||
|
||||
### 7.1 템플릿이 주는 틀 — 단계별
|
||||
|
||||
```text
|
||||
domain-core ─▶ application-core ─▶ outbound adapter ─▶ inbound adapter ─▶ bootstrap 조립
|
||||
(모델·불변식) (유스케이스·포트) (저장·외부) (전송·DTO·오류) (bean·조건)
|
||||
```
|
||||
|
||||
| 단계 | 템플릿이 주는 것 | 빠진 것 |
|
||||
| --- | --- | --- |
|
||||
| domain | `@AggregateRoot`·`@ValueObject`·`@DomainEvent` 마커(ArchUnit이 setter·no-arg 생성자·전송 타입 import를 검사), `ResourceId<SELF>`(Long id 금지 규칙 D17), `IdFactory<T>` 포트. 예시: sample `WorkLog`·`WorkLogId`·`WorkLogInvariantException(Reason)` | aggregate가 도메인 이벤트를 모으는 수단, 도메인 예외의 공통 모양(각자 `RuntimeException` + `Reason` enum), domain-core가 shared-contract를 못 봐서 도메인 예외는 오류 코드를 가질 수 없다는 안내 |
|
||||
| application | `CommandUseCase`/`QueryUseCase`, `Command`/`Query` 마커, `@UseCaseCapability`(필수, ArchUnit이 트랜잭션 호출과 대조), `@RequiresPermission`(쓰기 필수), `TransactionPort`, `IdempotencyExecutor`, `OutboxAppendPort` + `IntegrationEventEncoderPort`, `ObjectAccessPolicy`, `CorrelationIdPort`, `TenantId`. `*QueryPort`는 projection만 반환(ArchUnit). testFixtures: `DirectTransactionPort`, `InMemoryOutboxStore`, `FakeIntegrationEventEncoder`, `InMemoryIdempotencyStore`, `InMemoryDurableOperationStore` | 이벤트 draft 조립 헬퍼(01-09), application 예외가 `ApiErrorCarrier`를 구현하는 예시(sample은 web 핸들러로 매핑), 저장 포트 이름·위치 규칙(01-12), 객체 인가 예시(01-13) |
|
||||
| outbound | persistence-jpa의 `SpringTransaction`, outbox store, `CallerTransaction.require`, Flyway. 계약 키트 3개(operation·lease·outbox fencing). 예시: sample `WorkLogRepositoryAdapter` + `WorkLogEntity` + mapper + `WorkLogRepositoryAdapterContractTest`(integrationTest) + `InMemoryWorkLogRepositoryContractTest` | 기능 adapter를 둘 leaf의 기준(01-01), Flyway 번호대 규칙(메모에만 있음: 프로덕션·sample 번호 충돌), 감사 필드 처리 위치 안내 |
|
||||
| inbound | web `GlobalExceptionHandler`(`ApiErrorCarrier`·`ApiErrorCode`·`Envelope`), `ErrorResponseFactory`, `Patch<T>`(PATCH 3상태), `MethodSecurityConfig`, `TenantContext`. 예시: sample `WorkLogController`·`WorkLogWebMapper`·DTO·`DomainExceptionHandler`·`PortfolioErrorCode` | 비-web 전송에서 같은 유스케이스를 여는 예시, 기능 오류 코드를 어디에 두는지(sample은 web 패키지) |
|
||||
| bootstrap | `DurableOperationConfig` 모양: `@AutoConfiguration` + `@ConditionalOnBean(포트들)` + 유스케이스 `@Bean`(프록시를 위해 bean 필수) + 이벤트 계약 `@Bean` 등록 | 계약 bean 등록 누락을 기동 때 잡는 장치(01-04), role→permission 매핑 추가 위치 안내 |
|
||||
|
||||
### 7.2 개발자가 내려야 하는 판단 (순서대로)
|
||||
|
||||
1. **배치**: 이 기능은 공유 계층 leaf의 패키지인가, 별도 leaf인가? (선택 조립·삭제가 필요하면 별도 leaf, 아니면 계층 leaf.) 업무 패키지 이름이 플랫폼 패키지(`operation`·`lock`·`cache`)와 겹치지 않는가?
|
||||
2. **id**: 서버가 만드는가(`IdFactory` 상속 포트 + identifier adapter), 클라이언트가 주는가? id 문법은 어디서 검사하는가(값 객체 생성자)?
|
||||
3. **불변식 위치**: aggregate 메서드인가, 유스케이스인가? 둘 이상의 aggregate에 걸치면 유스케이스 + 트랜잭션.
|
||||
4. **저장 포트 소유자**: domain(`*Repository`, aggregate 단위 저장)인가 application(`*StorePort`, 기술적 저장·조회)인가? 읽기 모양이 쓰기와 다르면 `*QueryPort` + projection.
|
||||
5. **트랜잭션 모양**: `inWrite`(기본) / `inRootWrite`(커밋 후 결과 노출, 중첩 금지) / `inRead` / `inNew`(감사·보상만, 루프 금지). 외부 호출은 트랜잭션 밖.
|
||||
6. **멱등성**: `NOT_IDEMPOTENT`·`IDEMPOTENT`·`KEYED` 중 무엇인가? KEYED면 scope digest와 fingerprint를 무엇으로 만드는가?
|
||||
7. **인가**: 권한 이름(`resource:action`)과 role 매핑. 객체 인가가 필요한가(소유자·tenant)? 필요하면 `ObjectAccessPolicy` 구현을 어디에 두는가? 실패 시 403인가 404인가(존재 숨김)?
|
||||
8. **tenant**: 이 데이터는 tenant 범위인가? `TenantId`를 command에 싣는가? 이벤트 tenant 범위는 무엇인가?
|
||||
9. **이벤트**: 도메인 이벤트가 필요한가, 통합 이벤트만 필요한가? payload에 무엇을 넣는가(id만 vs 상태)? 계약 id·버전·schema 파일·해시·descriptor(크기 상한·순서 필요·민감도)를 정하고 계약을 bean으로 등록했는가?
|
||||
10. **오류 모델**: 실패마다 "클라이언트 탓(4xx)인가 서버 탓(5xx)인가"를 정한다. 클라이언트 탓이면 `ApiErrorCode` 하나와 carrier 예외, 서버 탓이면 `IllegalStateException`(01-04). 도메인 예외의 매핑을 application에서 할지 전송 핸들러에서 할지 정한다(여러 전송이면 application 쪽 carrier가 낫다).
|
||||
11. **성공의 의미**: 200/201/202 중 무엇이고, 응답 시점에 무엇이 보장되는가(커밋됨 vs 발행됨)?
|
||||
12. **테스트**: 포트마다 fake + 추상 계약 테스트를 testFixtures에, adapter는 같은 계약을 실제 저장소로 상속. 유스케이스는 `DirectTransactionPort`와 fake로.
|
||||
13. **조립**: 유스케이스는 bean으로(권한 프록시), `@ConditionalOnBean`으로 필요한 포트가 있을 때만. Flyway 번호대, env 키(`docs/registries/env-keys.yaml`), 공개 경로 스냅숏이 바뀌면 해당 검사를 돌린다.
|
||||
|
||||
### 7.3 스캐폴드 명령이 만든다면 (후보 목록, 만들지 않음)
|
||||
|
||||
입력: 기능 이름 `X`, 배치(계층 leaf / 별도 leaf), 쓰기·읽기 여부, 이벤트 여부.
|
||||
|
||||
| 계층 | 생성 파일 |
|
||||
| --- | --- |
|
||||
| domain | `X`(`@AggregateRoot`, private 생성자 + `create`/`restore`), `XId`(`record implements ResourceId<XId>`, `@ValueObject`, 문법 검사), `XIdFactory extends IdFactory<XId>`, `XRepository`, `XInvariantException`(+ `Reason` enum), 선택 `XCreated`(`@DomainEvent` record) |
|
||||
| application | `CreateXCommand implements Command`, `GetXQuery implements Query`, `CreateXUseCase`(non-final, `@UseCaseCapability(WRITE, NOT_IDEMPOTENT, WRITE_REPOSITORY)`, `@RequiresPermission("x:write")`, `tx.inWrite`), `GetXUseCase`(`READ_ONLY`, `READ_REPOSITORY`, `tx.inRead`), `XNotFoundException implements ApiErrorCarrier`, `XErrorCode implements ApiErrorCode`. 이벤트면 `XCreatedPayload implements IntegrationPayload`, 계약 contribution, `contracts/messaging/x.created/v1.schema.json`과 해시 고정 테스트 |
|
||||
| testFixtures | `InMemoryXRepository`, `XRepositoryContract`(abstract), `InMemoryXRepositoryContractTest` |
|
||||
| test | `CreateXUseCaseTest`·`GetXUseCaseTest`(`DirectTransactionPort` + fake, GWT 주석), `XTest`(불변식), `XIdTest` |
|
||||
| outbound | `XEntity`, `XPersistenceMapper`, `XJpaRepository`, `XRepositoryAdapter`, `UuidXIdFactory`(identifier), Flyway `V<번호대>__x.sql`, `JpaXRepositoryContractTest extends XRepositoryContract`(Testcontainers) |
|
||||
| inbound | `XController`, `CreateXRequest`·`XResponse`, `XWebMapper`, web slice 테스트(400·403·404·성공) |
|
||||
| bootstrap | `XUseCaseConfig`(`@AutoConfiguration`, `@ConditionalOnBean`, 유스케이스·계약 `@Bean`), `AutoConfiguration.imports` 한 줄, role→permission 정책에 `x:write`·`x:read` |
|
||||
| 검증 | 생성 직후 `:app-bootstrap:architectureTest`, 소유 leaf `test`, 공개 경로가 바뀌면 `verifyPublicPathSnapshot` |
|
||||
|
||||
스캐폴드의 템플릿 원본은 onboarding fixture를 01-02대로 고친 뒤 그것으로 삼는 것이 가장 싸다. fixture가 이미 `DomainFeatureOnboardingContractTest`로 production 규칙과 대조되고 있기 때문이다.
|
||||
|
||||
## 8. 28개 관점 판정표
|
||||
|
||||
기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역.
|
||||
|
||||
| # | 관점 | 판정 | 한 줄 이유 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 코드 성숙도 | O | 코어 값 객체가 생성자에서 검사하고, 지난 리뷰의 죽은 코드가 정리됐다(main 5,080줄) |
|
||||
| 2 | 구조적 성숙도 | P | leaf 방향은 강제되나 기능 배치 모양이 셋(01-01), application-core 이름공간 혼합(01-10) |
|
||||
| 3 | 변경 용이성 | P | 이벤트 조립 규칙·식별자 문법이 여러 곳에 복사(01-07, 01-09) |
|
||||
| 4 | 인지 부하 | P | 첫 기능 작성자가 네 예시에서 공통점을 뽑아야 함, 이름 규칙 문서 없음(01-12) |
|
||||
| 5 | 위험 가시성 | P | 설계 이유는 README에 잘 적혔으나 일부 제약이 코드에 없음(01-06 relay, 01-13 소유자 검사) |
|
||||
| 6 | 실패 성숙도 | P | 결과 불명을 타입으로 표현(outbox·idempotency outcome)하나, 서버 조립 오류가 400으로 숨는다(01-04) |
|
||||
| 7 | 운영 성숙도 | > | bootstrap·운영 영역 |
|
||||
| 8 | 디버깅 가능성 | P | correlation 전파는 있음, IAE 400 경로에 로그 없음(01-04) |
|
||||
| 9 | 유지보수 성숙도 | P | 문서 drift 남음(A-2b, A-2d, A-5a, A-6a, 01-14) |
|
||||
| 10 | 테스트 성숙도 | P | 코어 테스트 빠르고 변이 5개 중 3개를 잡음. 계약 키트 절반 공백(01-05), fixture가 규칙 밖(01-02) |
|
||||
| 11 | 데이터 성숙도 | P | 저장+outbox 한 트랜잭션은 강제, 이벤트 tenant 범위 규칙이 기능마다 다름(01-09) |
|
||||
| 12 | 동시성 성숙도 | P | inRootWrite 중첩 거부·outbox fencing 키트 있음, lock 계약 키트 없음 |
|
||||
| 13 | 확장성 | - | 코어 영역에 규모 목표 없음 |
|
||||
| 14 | 성능 성숙도 | O | 코어는 CPU 작업뿐(이벤트당 SHA-256 3~4회, 128KB 상한). 테스트 2.3초 |
|
||||
| 15 | 보안 성숙도 | P | 쓰기 권한 선언 강제·fail-closed, 단 검사기가 web에 묶임(01-06), TenantId 3벌(01-03) |
|
||||
| 16 | 의존성 성숙도 | O | domain-core·shared-contract stdlib 전용, 방향 게이트 통과(ci). 복사 강제 leaf는 01-11 |
|
||||
| 17 | API / Contract 성숙도 | P | Envelope·ApiErrorCode 하나로 통일됨, LRO 계약 2벌(01-08) |
|
||||
| 18 | 배포 성숙도 | > | CI·배포 영역 |
|
||||
| 19 | 설정 성숙도 | - | 코어는 설정을 읽지 않는다(ArchUnit D11·K6) |
|
||||
| 20 | 개발자 경험 | X | 새 기능을 끝까지 따라갈 문서·예시·스캐폴드가 없음(01-01, 01-02, 7절) |
|
||||
| 21 | Guardrail 성숙도 | P | ArchUnit 규칙이 촘촘함, 단 test fixture는 production 규칙 밖(01-02), web 없는 조립 검사 없음(01-06) |
|
||||
| 22 | 추상화 성숙도 | P | 포트·값 타입은 적절, draft 조립 헬퍼가 없어 10필드 생성자를 직접 다룸(01-09) |
|
||||
| 23 | 일관성 | X | TenantId 3벌, LRO 2벌, 식별자 문법 5곳, 이름 규칙 여러 개(01-03, 01-07, 01-08, 01-12) |
|
||||
| 24 | 네이밍 / 의미 성숙도 | P | `*ApplicationUseCase`/`*UseCase`, `*Repository`/`*StorePort`/`*WritePort`, "Contract"라는 이름의 값 테스트(01-12, 01-14) |
|
||||
| 25 | 조직 확장성 | P | 파생 서비스 기능이 템플릿과 같은 leaf·트리에 섞여 병합 충돌 면이 넓다(01-01, 01-10) |
|
||||
| 26 | Ownership 성숙도 | P | leaf별 CLAUDE.md·README 있음, 코어 README가 다른 leaf 타입을 설명(A-6a) |
|
||||
| 27 | 삭제 가능성 | P | sample은 leaf 하나로 지울 수 있음, shared-contract `operation`이 sample 전용인데 코어에 있음(01-08) |
|
||||
| 28 | 회복 가능성 | > | persistence·운영 영역 |
|
||||
|
||||
## 발견 요약
|
||||
|
||||
| 심각도 | 건수 | ID |
|
||||
| --- | --- | --- |
|
||||
| Critical | 0 | |
|
||||
| High | 0 | |
|
||||
| Medium | 8 | 01-01, 01-02, 01-03, 01-04, 01-05, 01-06, 01-08, 01-09 |
|
||||
| Low | 6 | 01-07, 01-10, 01-11, 01-12, 01-13, 01-14 |
|
||||
|
||||
| 우선순위 | 건수 | ID |
|
||||
| --- | --- | --- |
|
||||
| P2 | 5 | 01-01, 01-02, 01-03, 01-04, 01-05 |
|
||||
| P3 | 9 | 01-06 ~ 01-14 |
|
||||
@@ -0,0 +1,420 @@
|
||||
# 02 inbound HTTP (web · web-notification · web-fileserver · web-advanced · 멱등성 HTTP 계약)
|
||||
|
||||
## 1. 범위
|
||||
|
||||
| 항목 | 기록 |
|
||||
| --- | --- |
|
||||
| 대상 | `clean-architecture-backend-template`, `main` 커밋 `01a8a2a70` |
|
||||
| 맡은 leaf | `:adapter:inbound:web`, `:adapter:inbound:web-notification`, `:adapter:inbound:web-fileserver`, `:adapter:inbound:web-advanced`, 그리고 `:composition:idempotency`가 만든 executor의 HTTP 쪽 계약 |
|
||||
| 목적·지원 구성 | 서비스가 파생해 쓰는 템플릿. 기본 조립은 servlet(Spring MVC) + JWT 보안 체인. 짝 프론트 템플릿(`clean-architecture-frontend-template`)이 이 서버를 부른다고 가정한다 |
|
||||
| 읽은 코드 | web main 68파일 전부, testFixtures 중 계약·장애 fixture, web-notification main 16파일, web-fileserver의 보안·오류·tus·admin 컨트롤러, web-advanced의 예외 10종·자동 구성 3개·`VirtualThreadMvcConfiguration`, `composition:idempotency` main 2파일과 README, application-core `idempotency/` 예외 4종과 `IdempotencyExecutor`의 claim·complete 분기, sample `PosterImagePublicationController`·`PublishPosterImageUseCase`(멱등 HTTP 경로 추적용) |
|
||||
| 읽은 문서 | `AGENTS.md`·`CLAUDE.md`, web `README.md`·`CLAUDE.md`, web-advanced `README.md`, `composition/idempotency/README.md`, `docs/web/*.md`, `docs/registries/error-codes.yaml`·`env-keys.yaml`, 지난 리뷰 `2026-09-18-techlead-review/02-inbound-web.md`, `2026-09-25-review-followup-status.md`(I Web, S5, 소유자 결정, P6-new-2). 짝 프론트의 `docs/architecture/backend-api-and-server-state-contract.md` §4·§6과 `src/adapters/http/schema-registry.ts` |
|
||||
| 게이트 결과(오케스트레이터 실행, 다시 돌리지 않음) | `ci` rc=0. web 테스트 259건·web-fileserver 142건·web-advanced 184건·web-notification 16건 모두 통과(`build/test-results/test` XML, 11:39Z). `mainCheck` rc=1 — 원인은 objectstorage MinIO 이미지 pull 404(이 영역 아님). 같은 실행에서 `:adapter:inbound:web:systemTest`, `webJettyCompatTest`는 통과 |
|
||||
| 직접 실행(격리 worktree, `flock` 사용) | ① 실제 Tomcat에서 429 본문 문자셋 실험 ② `@WebMvcTest`로 실제 Envelope JSON과 in-flight 409 관찰 ③ MockMvc로 `HandlerMethodValidationException`·`AsyncRequestTimeoutException`·`String` 반환·`AdmissionRefusedException`의 응답 관찰 ④ 변이 실험 3건. 실행 직전 load average 5.6~21. 결과는 각 발견에 적었다. 실험 코드는 scratchpad `review02-experiments/`에 보관, worktree는 삭제 |
|
||||
| 확인 못 한 것 | 짝 프론트를 실제 백엔드에 붙여 실행하지 않았다(프론트 쪽은 코드 읽기만). actuator 응답이 `EnvelopeBodyAdvice`로 감싸지는지 실행하지 않았다. Redis·PostgreSQL 멱등성 저장소에서 같은 키 동시 요청을 실제로 보내 보지 않았다(application·persistence 영역). 성능은 테스트 시간만 쟀고 부하는 걸지 않았다 |
|
||||
|
||||
## 2. 지난 발견 재확인
|
||||
|
||||
followup-status에서 이 영역에 `남음`·`보류`로 남았던 항목과, 이번에 관련 코드를 다시 본 항목만 적는다. 나머지 I-*·S5-* `완료`/`해당 없음` 항목은 표의 근거 경로를 열어 같은 상태임을 확인했다.
|
||||
|
||||
| ID | 상태 | 근거 |
|
||||
| --- | --- | --- |
|
||||
| I-2c / TEST-F-2d (콜백 크기 테스트가 컨버터 경로를 건너뜀) | 바뀜 | 컨트롤러가 `HttpServletRequest`를 직접 읽게 바뀌어 컨버터 버퍼링 경로는 사라졌다(`web-notification/.../callback/NotificationCallbackMvcController.java` `callback`). 테스트는 여전히 컨트롤러를 직접 호출한다(`NotificationCallbackMvcControllerTest.java:109-140`). 남은 위험은 "필터 체인의 무엇인가가 form 본문을 먼저 파싱해 서명할 원본 바이트를 잃는 경우"이며 MockMvc 경로 테스트가 없다 |
|
||||
| I-3c (필수 파라미터·헤더 누락, `HandlerMethodValidationException` 형식 테스트 0) | 바뀜(일부 해결) | 누락 헤더·파라미터 테스트 추가됨 `TransportErrorHandlingTest.java:105,114`. `HandlerMethodValidationException`은 여전히 테스트가 없고, 실행해 보니 `BAD_PARAMETER`·details 없음으로 나간다 → 02-08 |
|
||||
| I-7 (`wire-type-manifest.yaml`이 런타임에 없는 wire 계약 공개) | 남음 | `web-advanced/src/main/resources/META-INF/web/wire-type-manifest.yaml`, `web-advanced/.../advanced/contract/WebWireTypeManifest.java`. 적용하는 Jackson 설정은 여전히 없다 |
|
||||
| S5-#12 (profile-name record 5개가 같은 정규식 복사) | 남음 | `web-advanced/.../operation/{Admission,Authorization,Response}ProfileName.java:17`, `CachePolicyName.java:17`, `budget/WebBudgetProfileName.java:17` |
|
||||
| S5-#14c (web-fileserver·web-notification에 README/CLAUDE.md 없음) | 남음 | 두 leaf 루트에 `*.md` 0개 |
|
||||
| TEST-FAKE-UploadApplicationService (tus fake와 실제 서비스가 같은 계약이 아님) | 남음 | `web-fileserver/src/test/.../testkit/InMemoryUploadApplicationService.java`. 공통 추상 계약 테스트 없음 |
|
||||
| P6-new-2 (complete가 UNAVAILABLE이면 action 뒤에도 `IdempotencyUnavailableException`) — 결정 24 "현재 동작 유지 + 문서화" | 남음(문서화 안 됨) | `IdempotencyExecutor.java:233`이 action 실행 뒤 complete 단계에서 던진다. 그런데 예외 Javadoc은 "raised before an action"(`IdempotencyUnavailableException.java:7`), web README는 "action 전에 거부"(`adapter/inbound/web/README.md:214`). HTTP 계약 표가 이 경우를 거짓으로 설명한다 |
|
||||
| L-11a (테스트·sample yml이 `ca-skeleton.rate-limit.*`) | 해결 | `sample-portfolio/src/main/resources/application.yml:189`, `app-bootstrap/src/test/resources/application-test.yml:113` 모두 `app.rate-limit` |
|
||||
| I-3a (Spring MVC 예외가 problem+json으로 샘) | 해결 유지 | `GlobalExceptionHandler.java:332-351`. 다만 상태→코드 표가 503을 500으로 바꾼다 → 02-08 |
|
||||
| I-4a·I-4b (요청 ID가 보안 체인 뒤에서 생성, trace 두 벌) | 해결 유지 | `WebMvcRequestIdFilter.java:103-122`(HIGHEST+10, 보안 체인 앞) |
|
||||
| I-5a (XFF 맨 왼쪽으로 rate-limit 키) | 해결 유지 | `RateLimitKeyResolver.java`는 `getRemoteAddr()`만, `RateLimitWebConfig`가 `forward-headers-strategy=framework`면 기동 거부 |
|
||||
|
||||
지난 리뷰에서 남은 High/P1은 이 영역에 없다. 새로 찾은 High 3건은 아래에 있다.
|
||||
|
||||
## 3. 새 발견
|
||||
|
||||
| ID | 제목 | 심각도·우선순위 |
|
||||
| --- | --- | --- |
|
||||
| 02-01 | "처리 중" 409(`IDEMPOTENT_IN_FLIGHT`)의 클라이언트 행동이 코드·문서·짝 계약에서 서로 다르다 | High · P1 |
|
||||
| 02-02 | 실제 Envelope JSON이 `data:null`·`error:null`·`meta.page`를 항상 싣는데 짝 프론트 계약은 이를 거절한다 | High · P1 |
|
||||
| 02-03 | JWT audience 검증이 기본으로 꺼져 있고, 모든 client의 role을 합친다 | High · P1 |
|
||||
| 02-04 | rate-limit 거부 본문이 실제 Tomcat에서 ISO-8859-1로 나가 한국어 문구가 `???`가 된다 | Medium · P2 |
|
||||
| 02-05 | CORS에 노출 헤더가 없어 브라우저가 `Retry-After`·`X-Request-Id`·`Location`·tus 헤더를 못 읽는다 | Medium · P2 |
|
||||
| 02-06 | `String`을 반환하는 컨트롤러는 `Accept: application/json`에서 500(ClassCastException)이 된다 | Medium · P2 |
|
||||
| 02-07 | web-advanced 예외 10종이 문서에 적힌 상태(409·503 등) 대신 500 `INTERNAL_ERROR`로 나간다 | Medium · P2 |
|
||||
| 02-08 | Spring MVC 예외의 상태→코드 변환이 의미를 잃는다(503→500, 메서드 검증→details 없는 `BAD_PARAMETER`) | Low · P2 |
|
||||
| 02-09 | JSON 본문 상한의 두 갈래가 테스트로 묶여 있지 않고(변이 2건 생존), JSON 아닌 본문은 상한이 없다 | Low · P2 |
|
||||
| 02-10 | `GlobalExceptionHandler`가 두 경로로 등록되어 `app.web.mvc.enabled=false`가 말한 대로 동작하지 않는다 | Low · P3 |
|
||||
| 02-11 | `X-Correlation-Id` 허용 문자·길이가 요청 ID 규칙·짝 계약과 다르다 | Low · P3 |
|
||||
| 02-12 | `Idempotency-Key` 헤더 검증이 공용 부품 없이 컨트롤러마다 새로 쓰인다 | Low · P3 |
|
||||
|
||||
집계: High 3, Medium 4, Low 5 / P1 3, P2 6, P3 3.
|
||||
|
||||
### 02-01 "처리 중" 409의 클라이언트 행동이 코드·문서·짝 계약에서 서로 다르다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(계약 불일치) |
|
||||
| 관련 관점 | 17, 6, 5, 23, 12, 28 |
|
||||
| 근거 | **코드가 실제로 내는 응답**: `@WebMvcTest` 실행 결과 `status=409`, `Retry-After` 없음, 본문 `{"success":false,"data":null,"error":{"code":"IDEMPOTENT_IN_FLIGHT","category":"CONFLICT","message":"현재 상태에서는 요청을 처리할 수 없습니다.","retryable":false,"details":null},"meta":{…}}`. 정의 `shared-contract/.../OperationalError.java:47`(`CONFLICT, 409, false`), 발생 `IdempotencyExecutor.java:104-105`(claim 단계), `:136-137`(재조정 단계). executor는 기다리지 않는다. `Retry-After` 표에 이 코드가 없다(`RetryAfterAdvisor.java:14-23`), retryable=false라 표를 보지도 않는다(`:36-38`). 메시지는 일반 충돌과 같은 CONFLICT 문구다. **백엔드 문서**: web README 표 `adapter/inbound/web/README.md:216`은 409·retryable=false·"executor는 기다리지 않는다"까지만 적고 클라이언트가 할 일은 없다. `docs/registries/error-codes.yaml:402-406`은 근거 주석에 "200ms 초과 시 409 … client는 polling"이라 적었지만 executor에는 대기도, 키로 조회하는 HTTP 엔드포인트도 없다. `docs/web/runbook.md:41-42`는 "the caller should retry after `Retry-After`"라고 적었지만 이 응답에는 그 헤더가 없다. "같은 키로 다시 보내라"는 문장은 백엔드 어디에도 없다. `docs/web/repository-adaptation.md` §6(`:75-104`)은 모듈 소유권만 다룬다. **짝 프론트 계약**: `clean-architecture-frontend-template/docs/architecture/backend-api-and-server-state-contract.md:211`은 409를 "fingerprint, revision 또는 semantic conflict"로, `:298`은 키 재사용을 `409 IDEMPOTENCY_KEY_REUSED`로, `:299-300`은 처리 중을 "bounded `IN_PROGRESS` 결과"로만 적는다. 백엔드의 키 재사용은 `422 IDEMPOTENT_REQUEST_MISMATCH`다(`OperationalError.java:48`) |
|
||||
| 발생 조건 | 쓰기 응답을 잃은 클라이언트(게이트웨이 504, 클라이언트 타임아웃)가 첫 요청이 아직 처리 중일 때 같은 키로 다시 보낸다. 느린 쓰기에서 흔한 순서다 |
|
||||
| 영향 | `retryable:false`는 "이 요청은 실패했고 다시 보내지 말라"로 읽힌다. 이 필드만 보는 클라이언트(파생 서비스의 다른 앱, 프론트의 다른 기능 패키지)는 사용자에게 다시 제출하게 하고, 그 제출은 새 키라 서버가 막지 못한다. 첫 요청이 끝나면 같은 작업이 두 번 적용된다. 프론트는 코드 이름으로 이 경우를 따로 처리하게 바뀌었지만(`reference-feature-contract-contribution.ts:33-51`), 그 근거가 백엔드 문서에 없으니 다른 소비자는 같은 판단을 할 수 없다 |
|
||||
| 심각도·우선순위 | High · P1. 35.2의 "결과 불명 작업의 무방비 재실행"에 해당하고, 기본 응답과 기본 문서만으로 생기는 경로다. 실제 중복을 관측하지는 않았다 |
|
||||
| 통제·증거 | 통제 M1(README 표에 status·code는 있음, 클라이언트 행동은 없음) · 증거 E2(백엔드 `@WebMvcTest` 출력, `IdempotencyExceptionMappingTest.inFlightMapsToNonRetryable409ConflictWithTheConflictMessage`) + E1(문서·짝 계약 읽기) |
|
||||
| 확실성과 남은 가정 | status·code·retryable·헤더 없음은 실행으로 확인했다. 파생 서비스(tech-log)가 같은 값을 쓰는지는 이번에 보지 않았다 |
|
||||
| 결정의 근거 | `[사실]` retryable=false는 2026-05의 "client polls" 결정에서 왔다(`error-codes.yaml:402` 주석, `OperationalErrorTest.java:232` 주석). `[사실]` 그 뒤 poll 대상이 될 키 조회 엔드포인트는 만들어지지 않았다. `[추론]` "다시 보내지 말고 조회하라"는 전제가 없어진 채 플래그만 남았다 |
|
||||
| 이해 비용 | 새 KEYED 엔드포인트를 만드는 사람은 README 표, error-codes.yaml, runbook, `IdempotencyExecutor` 분기, 짝 프론트 §6을 모두 읽어야 409의 뜻을 안다. 다섯 곳의 말이 다르다 |
|
||||
| 최소 개선 방향 | 백엔드 HTTP 계약 문서 한 곳(아래 대안 A)에 멱등성 응답 4종을 status·code·retryable·`Retry-After`·클라이언트 행동으로 고정한다. in-flight는 "결과 불명. 같은 `Idempotency-Key`로 `Retry-After` 뒤 재전송. 새 키 금지"로 적는다. 그에 맞게 `IDEMPOTENT_IN_FLIGHT`에 `Retry-After`(예: processing-lease 이하의 고정 초)를 붙이고, runbook·error-codes.yaml 주석을 같은 문장으로 고친다 |
|
||||
| 대안 비교 | A) **retryable=true + `Retry-After` + 문서 고정**(권장): 일반 클라이언트도 "같은 요청을 나중에 다시"로 읽는다. 같은 키 재전송은 서버가 replay·in-flight·mismatch로 안전하게 판정하므로 retryable=true가 거짓이 아니다. 비용은 registry·enum·테스트 3곳 수정. B) **retryable=false 유지 + 문서에만 "같은 키 재전송"**: 코드 변경이 없지만 필드와 문서가 반대 말을 한다. 필드만 읽는 소비자는 계속 틀린다. C) **executor가 짧게 기다렸다가 결과를 replay**: 클라이언트 단순화. 대가로 요청 스레드 점유와 대기 상한 설계가 필요하고, 결국 시간 초과면 409가 다시 나간다. D) **키 조회 엔드포인트 추가 후 "poll"을 실제로 만들기**: 원래 의도대로지만 엔드포인트·인가·보존 기간이 새로 생긴다. 지금 요구에는 과하다 |
|
||||
| 단순화의 보존 조건 | 같은 키·같은 fingerprint는 replay, 다른 fingerprint는 422, 진단 정보(scope digest)는 클라이언트에 나가지 않는다 |
|
||||
| 비용·부작용 | A는 retryable 의미 변경이므로 짝 프론트의 분류기·테스트(`reference-http-problem-mapping.test.ts:152`)와 같이 바꿔야 한다 |
|
||||
| 재검토 조건 | executor가 대기 방식으로 바뀌거나 키 조회 엔드포인트가 생기면 다시 비교한다 |
|
||||
| 완료 기준 | 백엔드 계약 문서 한 곳과 README·runbook·error-codes.yaml이 in-flight에 대해 같은 status·code·retryable·헤더·행동을 말한다. 짝 프론트 §6이 그 문서를 가리킨다 |
|
||||
| 검증 방법 | `IdempotencyExceptionMappingTest`에 `Retry-After`·retryable 단언 추가. 문서 문장은 리뷰로 확인 |
|
||||
|
||||
### 02-02 실제 Envelope JSON이 `data:null`·`error:null`·`meta.page`를 싣는데 짝 프론트 계약은 이를 거절한다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(짝 계약 불일치) + 테스트 공백 |
|
||||
| 관련 관점 | 17, 10, 23, 5 |
|
||||
| 근거 | `@WebMvcTest`(Boot의 ObjectMapper) 실행 결과: 성공 `{"success":true,"data":{"k":"v"},"error":null,"meta":{"requestId":…,"traceId":…,"correlationId":…,"page":null}}`, 실패 `{"success":false,"data":null,"error":{…,"details":null},"meta":{…,"page":null}}`. `shared-contract/.../response/Envelope.java`는 record 4필드 그대로이고 저장소 전체에 `JsonInclude`·`non_null` 설정이 없다(grep 0). 짝 프론트는 `successEnvelopeSchema`·`failureEnvelopeSchema`를 `.strict()`로 둬(`frontend/src/adapters/http/schema-registry.ts:12-34`) 성공에 `error` 키, 실패에 `data` 키가 있으면 거절한다. 프론트 계약 §4.1도 "Envelope 최상위 unknown field는 현재 거절된다"(`backend-api-and-server-state-contract.md:195`). 백엔드 테스트 `EnvelopeBodyAdviceTest.rawBodyIsWrappedInEnvelope`는 `jsonPath("$.error").doesNotExist()`(`:57`)로 단언하는데, Spring의 `doesNotExist`는 값이 `null`이어도 통과하므로 이 차이를 잡지 못한다 |
|
||||
| 발생 조건 | 짝 프론트의 기본 HTTP 클라이언트(`client.ts:917`의 `validateEnvelope`)가 이 백엔드의 아무 JSON 응답이나 받을 때 |
|
||||
| 영향 | 성공 응답이 `ENVELOPE_MISMATCH`, 실패 응답이 `HTTP_FAILURE`로 바뀐다. 실패 쪽에서는 `error.code`가 분류기에 닿지 않아 02-01의 `IDEMPOTENT_IN_FLIGHT` 구분도 동작하지 않는다. 두 템플릿을 그대로 붙인 첫 화면에서 드러날 결함이라 탐지는 쉽지만, 원인이 "null 필드"라는 것은 양쪽 테스트가 모두 숨긴다 |
|
||||
| 심각도·우선순위 | High · P1. 짝 템플릿을 같이 쓰는 기본 조합에서 모든 응답이 계약 위반이다 |
|
||||
| 통제·증거 | 백엔드 쪽 통제 M0(wire 모양을 고정하는 문서·테스트 없음) · 증거 E2(백엔드 실행) + E1(프론트 코드 읽기, 프론트 실행 안 함) |
|
||||
| 확실성과 남은 가정 | 백엔드 JSON은 실행으로 확인했다. 프론트가 `validateEnvelope` 전에 null을 지우는 단계가 있는지는 `client.ts:899-917`까지 읽어 없음을 확인했지만 실제 결합 실행은 안 했다 |
|
||||
| 결정의 근거 | `[사실]` Envelope 하나로 통일은 소유자 결정 2다. 이 발견은 결정을 뒤집지 않는다. `[사실]` 백엔드에는 소비자가 읽을 wire 계약 문서가 없고(README의 예외 표뿐), 프론트가 자기 문서에 백엔드 모양을 추측해 적었다 |
|
||||
| 이해 비용 | 파생 서비스 개발자는 Envelope record를 보고는 null 필드가 나가는지 알 수 없다. ObjectMapper 기본값을 알아야 한다 |
|
||||
| 최소 개선 방향 | 백엔드에 HTTP wire 계약 문서를 하나 둔다(`docs/web/http-contract.md` 같은 이름). Envelope의 필드 존재 규칙(성공은 `success·data·meta`, 실패는 `success·error·meta`, null 필드 생략)과 `meta`의 키를 적고, `Envelope`·`ApiError`·`ResponseMeta`에 `@JsonInclude(NON_NULL)`을 붙인다. 테스트는 `doesNotExist` 대신 원문 JSON의 키 집합을 단언한다 |
|
||||
| 대안 비교 | A) **백엔드가 null 필드를 생략**(권장): shared-contract 타입 3개에 한 줄씩. GraphQL·STOMP 등 다른 전송도 같은 타입을 쓰면 함께 바뀌므로 그쪽 계약도 확인해야 한다. B) **프론트가 `.strict()`를 풀거나 null 허용**: 백엔드 변경 없음. 대신 "unknown field 거절"이라는 프론트의 방어 규칙을 약하게 만든다. C) **둘 다 문서만 맞춤**: 실행 결과가 바뀌지 않는다. 기각 |
|
||||
| 단순화의 보존 조건 | `success` 판별자, `error.code` 안정성, 빈 목록(`[]`)과 null의 구분(목록 필드는 생략하지 않음) |
|
||||
| 비용·부작용 | A는 shared-contract 변경이라 모든 전송의 직렬화 테스트를 한 번 돌려야 한다. `details:null`을 기대하는 기존 테스트가 있으면 같이 고친다 |
|
||||
| 재검토 조건 | 프론트가 envelope 검증을 느슨하게 바꾸기로 결정하면 B로 간다 |
|
||||
| 완료 기준 | 성공 응답 원문에 `error` 키가 없고 실패 응답 원문에 `data` 키가 없다. 계약 문서에 키 목록이 있고 짝 프론트 §4.1이 그 문서를 가리킨다 |
|
||||
| 검증 방법 | `EnvelopeBodyAdviceTest`와 `GlobalExceptionHandlerTest`에 응답 원문 JSON의 최상위 키 집합 단언. 프론트 fixture를 백엔드 실제 응답 문자열로 한 번 교체해 `validateEnvelope` 통과 확인 |
|
||||
|
||||
### 02-03 JWT audience 검증이 기본으로 꺼져 있고, 모든 client의 role을 합친다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(안전하지 않은 기본값, 문서와 코드 불일치) |
|
||||
| 관련 관점 | 15, 19, 21, 5 |
|
||||
| 근거 | `SecuritySettings.java:35-42`: audience가 null이면 WARN 한 줄을 남기고 `""`로 둔다. 빈 문자열이면 경고도 없다. `JwtDecoderConfig.java:80-82`: 비어 있으면 audience validator를 넣지 않는다. 기본 설정은 `config/security.yml:11-12`(`audience: ${APP_SECURITY_JWT_AUDIENCE}`, 주석 "blank to skip"), `.env.example:97`(`APP_SECURITY_JWT_AUDIENCE=` 빈 값). 반면 env 레지스트리는 `required: true`, `validation: csv_non_empty`, 타입 `csv_list`(`docs/registries/env-keys.yaml:1177-1187`). 코드는 값 하나만 비교하므로(`JwtDecoderConfig.java:101-104`, `contains(audience)`) `a,b`처럼 목록을 주면 모든 토큰이 거절된다. role 추출은 `resource_access`의 **모든 client** role을 합친다(`JwtToAuthenticatedPrincipalConverter.java:79-87`) |
|
||||
| 발생 조건 | 같은 issuer(예: Keycloak realm 하나)에 이 서비스 말고 다른 client가 있다. 운영자가 `APP_SECURITY_JWT_AUDIENCE`를 비워 둔 채 배포한다(템플릿 기본값) |
|
||||
| 영향 | 다른 앱을 위해 발급된 토큰도 이 API에서 인증된다. 그 토큰의 `resource_access.<다른 client>.roles`에 이 서비스의 role 이름(예: `operation-submit`, `ROLE_FILE_ADMIN`)과 같은 값이 있으면 권한까지 얻는다. 기본 role-permission 표(`security.yml` `app.authz.role-permissions`)가 일반적인 이름을 쓰므로 겹칠 여지가 있다 |
|
||||
| 심각도·우선순위 | High · P1. 인증 경계의 기본값이 열려 있고, 레지스트리는 "필수"라고 말해 운영자가 안심한다. 실제 다른 client 토큰으로 접근한 실험은 하지 않아 Critical로 올리지 않았다 |
|
||||
| 통제·증거 | 통제 M1(레지스트리에 required로 명시, 코드는 강제 안 함) · 증거 E1(코드·설정 읽기). audience 불일치 거부 자체는 기존 테스트가 있다(`JwtDecoderConfigTest`) |
|
||||
| 확실성과 남은 가정 | 코드 경로는 확정. `verifyEnvKeys`가 런타임 값의 비어 있음을 막지 않는다는 것은 레지스트리 형식과 `.env.example` 빈 값으로 추론했다(실행 안 함) |
|
||||
| 결정의 근거 | `[기록된 의도]` "blank to skip audience check"(`security.yml:11`). `[추론]` 로컬·테스트 편의를 위한 기본값이 운영 기본값으로 남았다. local·test 프로필은 audience를 채운다(`application-local.yml:174`, `application-test.yml:54`) |
|
||||
| 이해 비용 | 운영자는 레지스트리의 `required: true`를 믿고, 개발자는 WARN 로그를 보지 않는다. 두 문서를 대조해야 위험이 보인다 |
|
||||
| 최소 개선 방향 | JWT 모드에서 audience가 비면 기동을 거부한다(issuer와 같은 방식, `SecuritySettings.java:30-33`). 목록을 받으려면 `List<String>`으로 바인딩하고 "하나라도 포함"으로 비교한다. role 추출은 `resource_access` 중 audience(또는 설정한 client id)의 role만 읽는다 |
|
||||
| 대안 비교 | A) **audience 필수 + 자기 client role만**(권장): 기본값이 닫힌다. 비용은 기존 배포가 env 하나를 채워야 한다는 것. B) **prod 프로필에서만 필수**: 로컬 편의 유지. 대신 프로필 이름에 보안이 걸리고 dev·staging이 열린다. C) **현상 유지 + 문서 강조**: 숨은 위험이 그대로 남는다. 사용자 원칙("위험은 코드에 드러나야 한다")에 어긋나 기각 |
|
||||
| 단순화의 보존 조건 | issuer·timestamp 검증, 오류 코드 `AUTH_AUDIENCE_MISMATCH` 401, realm role 읽기 |
|
||||
| 비용·부작용 | 기존 파생 서비스의 기동이 env 누락으로 실패할 수 있다. 실패 메시지에 env 키 이름을 넣는다 |
|
||||
| 재검토 조건 | issuer를 서비스 전용으로 쓰는 배포만 지원한다고 명시하면 A의 role 범위 부분은 완화할 수 있다 |
|
||||
| 완료 기준 | JWT 모드에서 audience가 비면 기동 실패. 다른 client의 role만 가진 토큰이 권한을 얻지 못한다 |
|
||||
| 검증 방법 | `SecuritySettingsTest`에 빈 audience 거부, `JwtToAuthenticatedPrincipalConverterTest`에 "다른 client의 role은 무시" 케이스 |
|
||||
|
||||
### 02-04 rate-limit 거부 본문이 실제 Tomcat에서 ISO-8859-1로 나가 한국어 문구가 깨진다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 1, 17, 23, 10 |
|
||||
| 근거 | `RateLimitInterceptor.java:77-81`은 `setContentType("application/json")` 뒤 `getWriter()`로 쓴다. 문자셋을 정하지 않는다. 같은 일을 하는 `AuthErrorResponseWriter.java:43-44`와 `GraphQlRequestBodyLimitFilter.java:119-120`은 UTF-8을 지정한다. **실험(E3)**: 실제 embedded Tomcat + Spring Boot 기본값과 같은 `CharacterEncodingFilter("UTF-8", forceRequest=true, forceResponse=false)`로 거부 응답을 받으니 `content-type=application/json;charset=ISO-8859-1`, 본문 `"message":"??? ?? ????. ?? ? ?? ??? ???."`. 기존 `RateLimitInterceptorTest`는 code·category·retryable만 단언해 이 문제를 못 잡는다 |
|
||||
| 발생 조건 | `app.rate-limit.enabled=true`에서 429 `RATE_LIMIT_EXCEEDED`, 503 `RATE_LIMIT_UNAVAILABLE`·`RATE_LIMIT_INCOMPATIBLE` 응답 |
|
||||
| 영향 | 사용자에게 보일 문구가 `?`로 바뀐다. `content-type`의 문자셋도 틀린다. code·retryable은 ASCII라 기계 판정은 유지된다 |
|
||||
| 심각도·우선순위 | Medium · P2. 기능 판정은 살아 있고 문구만 망가진다 |
|
||||
| 통제·증거 | M0(이 경로의 문자셋 통제 없음) · E3(실제 Tomcat 실험) |
|
||||
| 확실성과 남은 가정 | Boot의 Tomcat factory가 응답 문자셋을 따로 정하지 않는다는 것은 `spring-boot-tomcat-4.0.8.jar`에서 `setResponseCharacterEncoding` 호출이 없음을 확인해 판단했다 |
|
||||
| 결정의 근거 | 적용 제외 — 같은 저장소의 다른 writer가 이미 UTF-8을 지정하고 있어 고를 선택지가 없는 단순 누락 |
|
||||
| 이해 비용 | 필터·인터셉터에서 본문을 직접 쓰는 곳이 셋이고 각각 문자셋을 기억해야 한다(41절 C 참고) |
|
||||
| 최소 개선 방향 | `RateLimitInterceptor.reject`에 `setCharacterEncoding(UTF_8)`. 더 나은 방법은 "직접 쓰는 Envelope 응답" writer 하나를 두고 셋이 그것을 쓰게 하는 것(리팩토링 후보 R-1) |
|
||||
| 대안 비교 | 적용 제외 — 단순 결함 수정 |
|
||||
| 완료 기준 | 실제 Tomcat에서 429 본문이 UTF-8이고 문구가 `ClientErrorMessages`와 같다 |
|
||||
| 검증 방법 | `RateLimitInterceptorTest`에 `getContentAsString(UTF_8)`의 message 단언 + `getCharacterEncoding()`이 UTF-8임을 단언 |
|
||||
|
||||
### 02-05 CORS에 노출 헤더가 없어 브라우저가 계약 헤더를 못 읽는다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(설정 공백) |
|
||||
| 관련 관점 | 17, 15, 19, 8 |
|
||||
| 근거 | `SecurityConfig.java:150-156`은 origins·methods·headers·credentials·maxAge만 설정하고 `setExposedHeaders`가 없다. `CorsSettings`에도 해당 필드가 없다. 저장소 전체에서 `exposedHeaders`는 gRPC-Web 계약 클래스에만 있다 |
|
||||
| 발생 조건 | 브라우저 앱이 API와 다른 origin에서 부른다(`app.cors.enabled=true`, sample 기본값 `http://localhost:3000`) |
|
||||
| 영향 | 브라우저는 CORS 안전 목록 밖의 응답 헤더를 숨긴다. `Retry-After`(429·503, 그리고 02-01의 개선안), `X-Request-Id`(지원 문의용), `Location`(202 operation, poster publication), `ETag`(조건부 쓰기), `X-RateLimit-*`, tus의 `Upload-Offset`·`Location`·`Tus-Resumable`이 모두 `null`로 보인다. 짝 프론트는 `Retry-After`를 읽는다(`frontend/src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts:20`). cross-origin tus 업로드는 offset을 못 읽어 재개가 깨진다 |
|
||||
| 심각도·우선순위 | Medium · P2. same-origin(BFF·리버스 프록시) 배포에는 영향이 없다 |
|
||||
| 통제·증거 | M0 · E1(코드·설정 읽기). 브라우저 실행은 안 함 |
|
||||
| 확실성과 남은 가정 | CORS 안전 목록 동작은 Fetch 표준의 정의다. 배포가 프록시에서 `Access-Control-Expose-Headers`를 붙이는지는 템플릿 밖이라 모른다 |
|
||||
| 결정의 근거 | 적용 제외 — 노출할 헤더는 이미 계약에 있는 헤더라 선택지가 아니라 누락이다. 다만 목록을 설정으로 열지 고정할지는 아래에서 비교 |
|
||||
| 최소 개선 방향 | `CorsSettings`에 `exposedHeaders`를 추가하고 기본값을 플랫폼 계약 헤더(`ApiHeaders`의 `Retry-After`·`X-Request-Id`·`X-Correlation-Id`·`Location`·`ETag`·`X-RateLimit-*`)로 둔다. fileserver composition은 tus·draft-12 헤더를 기여한다 |
|
||||
| 대안 비교 | A) 기본 목록 + 설정 확장(권장). B) env 하나로 전부 운영자에게 맡김: 기본 배포가 계속 깨진다. C) `*` 노출: credentials 모드에서 `*`는 리터럴로 취급돼 동작하지 않는다 |
|
||||
| 완료 기준 | CORS preflight·실 요청 응답에 `Access-Control-Expose-Headers`가 위 목록을 담는다 |
|
||||
| 검증 방법 | `CorsSecurityFilterIntegrationTest`에 노출 헤더 단언 |
|
||||
|
||||
### 02-06 `String`을 반환하는 컨트롤러는 `Accept: application/json`에서 500이 된다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(숨은 함정) |
|
||||
| 관련 관점 | 5, 21, 20, 1 |
|
||||
| 근거 | `EnvelopeBodyAdvice.java:45-48`은 선택된 content type이 JSON이면 무엇이든 `Envelope`로 바꾼다. `String` 반환은 `StringHttpMessageConverter`가 고르므로 바뀐 `Envelope`를 String 컨버터가 받는다. **실행(E2)**: `Accept: application/json` → `500`, `ClassCastException`, 본문 `INTERNAL_ERROR`. `Accept: */*` → `200 text/plain "hello"`. 같은 엔드포인트가 curl에서는 되고 JSON 클라이언트에서는 깨진다. 이를 막는 ArchUnit 규칙(`WebArchitectureRules`)이나 문서가 없다 |
|
||||
| 발생 조건 | 파생 서비스 개발자가 `@GetMapping String ...`을 만든다 |
|
||||
| 영향 | 그 엔드포인트가 JSON 클라이언트에서 항상 500이고, 로그에는 ERROR로 ClassCastException이 남는다 |
|
||||
| 심각도·우선순위 | Medium · P2. 개발 중 바로 보이지만 원인 추적이 어렵고, 템플릿이 숨긴 규칙이다 |
|
||||
| 통제·증거 | M0 · E2 |
|
||||
| 결정의 근거 | 적용 제외 — 동작 결함. 막는 방식만 고른다 |
|
||||
| 최소 개선 방향 | `beforeBodyWrite`에서 `selectedConverterType`이 `StringHttpMessageConverter`면 감싸지 않거나, `supports`에서 String 반환을 제외한다. 또는 `WebArchitectureRules`에 "컨트롤러는 `String`을 반환하지 않는다" 규칙을 둔다 |
|
||||
| 대안 비교 | A) advice가 String을 통과(텍스트로 응답): 간단하지만 "모든 JSON은 Envelope"가 깨진다. B) ArchUnit으로 금지(권장): 규칙이 코드에 드러난다. C) String 컨버터 앞에 Jackson을 두기: 전역 컨버터 순서를 바꿔 다른 곳에 영향 |
|
||||
| 완료 기준 | String 반환 컨트롤러가 빌드에서 거부되거나 200으로 응답한다 |
|
||||
| 검증 방법 | `EnvelopeBodyAdviceTest`에 String probe 추가 또는 `WebArchitectureRulesTest`에 위반 fixture |
|
||||
|
||||
### 02-07 web-advanced 예외 10종이 문서의 상태 대신 500으로 나간다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(라이브러리 계약 미연결) |
|
||||
| 관련 관점 | 17, 6, 23, 22 |
|
||||
| 근거 | `web-advanced/src/main/java/.../advanced/` 아래 예외 10종(`AdmissionRefusedException`, `JsonPatchTestFailedException`, `JsonPatchRejectedException`, `PatchAuthorizationException`, `UnsupportedApiVersionException`, `SunsetViolationException`, `UntrustedTenantInputException`, `ReplayCursorExpiredException`, `StreamItemTooLargeException`, `RouteInventoryMismatchException`)이 모두 `RuntimeException`만 상속하고 `ApiErrorCarrier`가 아니다. leaf에 `@ExceptionHandler`도 없다. 문서는 상태를 약속한다: "maps to 503 with a Retry-After"(`AdmissionRefusedException.java:6`), "A failed `test` is 409"(`docs/web/patch-contract.md:66`). **실행(E2)**: `AdmissionRefusedException` → `500 INTERNAL_ERROR`, `Retry-After` 없음, 그리고 `GlobalExceptionHandler.handleUnknown`이 ERROR 로그를 남긴다 |
|
||||
| 발생 조건 | 서비스가 web-advanced의 admission guard, JSON Patch, API 버전 정책을 컨트롤러에서 쓴다(opt-in, 현재 운영 소비자 0) |
|
||||
| 영향 | 부하 거절이 500으로 보여 클라이언트가 재시도하지 않고, 알림이 장애로 울린다. patch `test` 실패가 500이라 "다시 읽고 재시도"를 못 한다 |
|
||||
| 심각도·우선순위 | Medium · P2. 기본 조합에는 없지만 라이브러리를 켜는 순간 모든 서비스에 복제된다 |
|
||||
| 통제·증거 | M1(Javadoc·문서) · E2(AdmissionRefused 한 종 실행, 나머지는 E1) |
|
||||
| 결정의 근거 | `[사실]` S5 정리 때 problem 어휘(`WebProblem`)를 지우면서 이 예외들의 매핑도 같이 사라졌다(`docs/capability-status.md` 「제거된 코드」 표 「WebProblem 어휘」). `[추론]` 예외는 남고 변환만 빠졌다 |
|
||||
| 최소 개선 방향 | 각 예외가 `ApiErrorCarrier`를 구현하고 코드 enum 하나(`WebAdvancedError`: 상태·category·retryable)를 둔다. 그러면 `GlobalExceptionHandler.handleCarrier` 한 분기로 처리되고 `Retry-After`도 `RetryAfterAdvisor` 표로 붙는다 |
|
||||
| 대안 비교 | A) carrier + enum(권장): 기존 한 분기 재사용. B) web-advanced 전용 `@RestControllerAdvice`: 오류 경로가 하나 더 생긴다(지난 리뷰가 지운 모양). C) 문서에서 상태 약속 삭제: 라이브러리의 쓸모가 줄고 500은 그대로 |
|
||||
| 완료 기준 | 10종 각각이 문서의 상태·코드로 나간다. 문서와 enum이 같은 값을 말한다 |
|
||||
| 검증 방법 | web-advanced에 예외별 MockMvc 매핑 테스트(실험 코드 `Review02AdvancedExceptionStatusExperimentTest`를 그대로 시작점으로) |
|
||||
|
||||
### 02-08 Spring MVC 예외의 상태→코드 변환이 의미를 잃는다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 17, 23, 6 |
|
||||
| 근거 | `GlobalExceptionHandler.java:353-369`의 표는 4xx 나머지를 `BAD_PARAMETER`, 5xx를 전부 `INTERNAL_ERROR`로 보낸다. **실행(E2)**: `AsyncRequestTimeoutException`(Spring은 503) → `500 INTERNAL_ERROR retryable=false`. `@RequestParam @Max(10) int limit`에 99 → `HandlerMethodValidationException` → `400 BAD_PARAMETER details:null`. 같은 종류의 위반을 `ConstraintViolationException` 경로는 `VALIDATION_FAILED` + 필드 details로 낸다(`GlobalExceptionHandler.java:83-88`) |
|
||||
| 발생 조건 | async·streaming(web-advanced) 타임아웃, 컨트롤러 파라미터에 Bean Validation 제약 |
|
||||
| 영향 | 일시적 타임아웃이 재시도 불가 내부 오류로 보인다. 클라이언트는 어느 파라미터가 틀렸는지 모른다. 같은 위반이 경로에 따라 코드가 다르다 |
|
||||
| 심각도·우선순위 | Low · P2 |
|
||||
| 통제·증거 | M2(변환은 있음, 의미는 틀림) · E2 |
|
||||
| 결정의 근거 | 적용 제외 — 표에 두 줄을 더하는 단순 수정 |
|
||||
| 최소 개선 방향 | 503 → 일시적 코드(retryable), `handleHandlerMethodValidationException` override로 `VALIDATION_FAILED` + `ClientSafeValidationDetails` |
|
||||
| 완료 기준 | 위 두 요청이 각각 503 retryable, 400 `VALIDATION_FAILED` + field details |
|
||||
| 검증 방법 | `TransportErrorHandlingTest`에 두 케이스(I-3c의 남은 부분도 여기서 닫힌다) |
|
||||
|
||||
### 02-09 JSON 본문 상한의 두 갈래가 테스트로 묶여 있지 않고, JSON 아닌 본문은 상한이 없다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(테스트 공백) + 구조적 위험 |
|
||||
| 관련 관점 | 15, 10, 14 |
|
||||
| 근거 | **변이 실험**: ① `JsonBodyLimitFilter.java:87`의 선언 길이 사전 거부를 `if (false)`로 바꿈 → `JsonBodyLimitFilterTest`·`RequestBodyBoundaryTest`·`GlobalExceptionHandlerTest`·`TransportErrorHandlingTest` 모두 통과(생존). Javadoc이 약속한 "읽기 전에 거부"가 깨져도 아무 테스트도 실패하지 않는다. ② `shouldNotFilter`의 `+json` 분기 삭제(`:57-58`) → 생존. `application/merge-patch+json` 본문이 상한 없이 읽혀도 모른다. ③ 대조군: `handleCarrier`의 `Retry-After` 줄 삭제 → 5건 실패(죽음), 하네스가 정상임을 확인. 또 `shouldNotFilter`는 content type이 JSON이 아니면 통과시킨다(`:50-61`). `@RequestBody String`·`byte[]`를 `text/plain`·`application/octet-stream`·XML로 받는 엔드포인트에는 상한이 없다. Javadoc은 "Other media types keep their own ceilings"라고 적지만 multipart·form·tus·콜백 외에는 없다 |
|
||||
| 발생 조건 | 누군가 사전 거부를 리팩터링으로 지우거나, 서비스가 JSON 아닌 `@RequestBody`를 받는다 |
|
||||
| 영향 | 인증된 호출자가 큰 본문으로 힙을 채울 수 있다(인증 전 경로는 Tomcat이 막지 않는다) |
|
||||
| 심각도·우선순위 | Low · P2. 기본 조합의 JSON 경로는 스트림 계수로 여전히 막힌다 |
|
||||
| 통제·증거 | M2(구현) · M3 아님(변이 생존) · E2(변이 실험) |
|
||||
| 최소 개선 방향 | 테스트 2개 추가(선언 길이 초과면 `getInputStream`을 부르기 전에 예외, `+json` 본문도 상한 적용). JSON 아닌 본문은 같은 래퍼를 "multipart·form·등록된 업로드 경로 제외 전부"에 적용하는 쪽을 검토 |
|
||||
| 대안 비교 | A) 상한 대상을 "JSON"에서 "예외 목록 외 전부"로 뒤집기: 새 media type이 자동으로 보호된다. 업로드 경로를 빠뜨리면 업로드가 막히므로 예외 목록 테스트가 필요. B) JSON만 유지 + 문서에 "다른 타입은 직접 상한": 숨은 규칙이 남는다 |
|
||||
| 완료 기준 | 변이 ①②가 테스트에서 죽는다 |
|
||||
| 검증 방법 | 같은 변이를 다시 적용해 실패 확인 |
|
||||
|
||||
### 02-10 `GlobalExceptionHandler`가 두 경로로 등록된다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(Javadoc과 동작 불일치) |
|
||||
| 관련 관점 | 4, 24, 19, 27 |
|
||||
| 근거 | `WebAdapterAutoConfiguration.java:47`이 `GlobalExceptionHandler.class`를 조건 없이 `@Import`한다. `WebMvcPlatformAutoConfiguration.java:46-52`는 같은 타입을 `@ConditionalOnMissingBean`으로 다시 정의하는데, 앞의 import가 먼저라 이 정의는 실행되지 않는다. `WebMvcPlatformAutoConfiguration` Javadoc은 "off means no beans"라고 하지만 `app.web.mvc.enabled=false`여도 핸들러는 남고, 꺼지는 것은 요청 ID 필터와 JSON 본문 상한뿐이다 |
|
||||
| 발생 조건 | 서비스가 자기 오류 핸들러로 바꾸려고 스위치를 끄거나 같은 타입의 bean을 등록한다 |
|
||||
| 영향 | 끄면 보안 관련 본문 상한만 조용히 빠진다. 같은 타입 bean을 하나 더 두면 `@RestControllerAdvice` 두 개가 생기고 어느 쪽이 이길지 순서에 달린다 |
|
||||
| 심각도·우선순위 | Low · P3 |
|
||||
| 통제·증거 | M1 · E1 |
|
||||
| 최소 개선 방향 | 등록 경로를 하나로(Platform 쪽 `@Bean`만 남기고 `@Import` 목록에서 제거). 스위치가 무엇을 끄는지 README 한 줄 |
|
||||
| 완료 기준 | `enabled=false`에서 무엇이 남는지 테스트가 단언한다 |
|
||||
| 검증 방법 | `WebMvcPlatformAutoConfigurationTest`에 스위치 off 케이스 |
|
||||
|
||||
### 02-11 `X-Correlation-Id` 허용 문자·길이가 요청 ID 규칙·짝 계약과 다르다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(계약 불일치) |
|
||||
| 관련 관점 | 8, 17, 23 |
|
||||
| 근거 | 요청 ID는 `[A-Za-z0-9._-]{1,128}`만 받는다(`WebMvcRequestIdFilter.java:62`). correlation ID는 `HeaderSanitizer`가 `0x20` 미만만 지우고 200자까지 그대로 둔다(`HeaderSanitizer.java:19`, `WebMvcRequestIdFilter.java:64,160-165`). 공백·유니코드·`DEL`이 응답 헤더와 `meta.correlationId`로 그대로 돌아간다. 짝 계약은 세 ID 모두 "1..128 안전한 opaque"(`backend-api-and-server-state-contract.md:199-200`)이고, 프론트 스키마는 `[A-Za-z0-9._:-]{1,128}`로 검증한다(`schema-registry.ts:6-8`) |
|
||||
| 발생 조건 | 프록시나 다른 클라이언트가 규칙 밖의 correlation ID를 보낸다 |
|
||||
| 영향 | 그 응답의 envelope 검증이 프론트에서 실패한다. 로그 검색 키가 공백·유니코드를 담는다 |
|
||||
| 심각도·우선순위 | Low · P3 |
|
||||
| 통제·증거 | M2(개행 제거는 됨) · E1 |
|
||||
| 최소 개선 방향 | correlation ID도 요청 ID와 같은 패턴을 쓰고, 맞지 않으면 새로 발급한다 |
|
||||
| 완료 기준 | 규칙 밖 값이 들어오면 서버가 만든 값이 응답에 나간다 |
|
||||
| 검증 방법 | `WebMvcRequestIdFilterTest`에 공백·유니코드·129자 케이스 |
|
||||
|
||||
### 02-12 `Idempotency-Key` 헤더 검증이 컨트롤러마다 새로 쓰인다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 개선 제안(구조적 위험) |
|
||||
| 관련 관점 | 20, 23, 3, 25 |
|
||||
| 근거 | web leaf는 헤더 이름 상수만 준다(`ApiHeaders.java:10`). 키 추출은 "구체 엔드포인트의 몫"이라고 정했다(`docs/web/repository-adaptation.md:99`). 유일한 운영 예시 `PosterImagePublicationController.java:61-69`는 blank·256자 초과면 `IllegalArgumentException`(→ `BAD_PARAMETER`), 문자 집합 규칙 없음, 헤더가 아예 없으면 Spring의 `MissingRequestHeaderException`(→ `BAD_PARAMETER`, 같은 코드). testFixtures의 `FaultFixtureController`는 또 다른 방식으로 받는다 |
|
||||
| 발생 조건 | 서비스가 KEYED 엔드포인트를 늘린다 |
|
||||
| 영향 | 엔드포인트마다 길이·문자·누락 처리·오류 코드가 갈라진다. 클라이언트는 "키 형식 오류"와 "다른 파라미터 오류"를 구분하지 못한다 |
|
||||
| 심각도·우선순위 | Low · P3 |
|
||||
| 통제·증거 | M1 · E1 |
|
||||
| 결정의 근거 | `[기록된 의도]` claim·fingerprint는 use case가 소유(`README.md:460-466`). 이 제안은 그 결정을 바꾸지 않고 "헤더 → 검증된 값" 한 단계만 공용으로 만든다 |
|
||||
| 최소 개선 방향 | web leaf에 `IdempotencyKeyHeader`(값 객체 + argument resolver 또는 정적 parse)를 두고 길이·문자 규칙과 전용 코드(예: `IDEMPOTENCY_KEY_INVALID` 400)를 한 곳에서 정한다. sample이 그것을 쓴다 |
|
||||
| 대안 비교 | A) 공용 parse(권장). B) 현상 유지 + 문서 규칙: 복사본이 갈라지는 것을 막지 못한다. C) 필터로 모든 POST에 강제: KEYED가 아닌 엔드포인트까지 막는다 |
|
||||
| 완료 기준 | KEYED 컨트롤러가 같은 parse를 쓰고, 형식 오류는 한 코드로 나간다 |
|
||||
| 검증 방법 | parse 단위 테스트 + sample 컨트롤러 테스트 |
|
||||
|
||||
## 4. 31절 시나리오 추적
|
||||
|
||||
### 4.1 중복·동시 요청 — sample `POST /posters/{id}/imagePublications` 같은 키 재전송
|
||||
|
||||
```text
|
||||
브라우저 --Idempotency-Key--> WebMvcRequestIdFilter(요청 ID) -> JsonBodyLimitFilter(multipart라 통과)
|
||||
-> Spring Security(JWT) -> RequestLoggingFilter -> RateLimitInterceptor(켜졌을 때)
|
||||
-> PosterImagePublicationController(키 blank·길이 검사)
|
||||
-> PublishPosterImageUseCase: transactions.inWrite( IdempotencyExecutor.execute(scope, fingerprint, attempt, action) )
|
||||
-> 결과: 202 / replay 202 / 409 IN_FLIGHT / 422 MISMATCH / 503 UNAVAILABLE / 500 RECOVERY_REQUIRED
|
||||
```
|
||||
|
||||
| 항목 | 기록 |
|
||||
| --- | --- |
|
||||
| 입력 신뢰 | 키는 호출자 값. 길이만 본다(02-12). scope는 tenant·principal·키를 digest한 값이라 원문 키는 저장소에 가지 않는다 |
|
||||
| 인가 | 보안 체인이 인증. 권한은 use case 쪽(sample 정책). principal이 없으면 `IllegalArgumentException` → 400(401이 아님 — 보안 체인이 먼저 막으므로 도달 불가) |
|
||||
| 규칙 소유 | 같은 요청 판정은 `IdempotencyExecutor`와 use case의 fingerprint(`PosterImagePublicationFingerprint`) |
|
||||
| 트랜잭션 | `execute`가 `inWrite` 안에서 돈다. PostgreSQL 저장소면 claim이 같은 트랜잭션에 묶이고, Redis면 밖에 있다. 두 경우의 동시 요청 동작 차이는 application·persistence 영역(이 리뷰 범위 밖, 미검증) |
|
||||
| 외부 부작용 | object storage staging은 트랜잭션 뒤(`stageAndPrepare`) |
|
||||
| 성공의 의미 | 202는 "예약됨". 상태는 `GET .../{operationId}`로 본다 |
|
||||
| 오류 변환 | carrier 한 분기. in-flight 409의 클라이언트 행동이 정해지지 않았다(02-01). complete 단계의 503은 "action 전"이라는 문서와 다르다(P6-new-2) |
|
||||
| 진단 | 응답 `meta.requestId`·`traceId`. scope digest는 로그에만 |
|
||||
|
||||
### 4.2 다른 사용자 리소스 접근 — `GET /operations/{id}`
|
||||
|
||||
`DurableOperationController.get`은 principal·tenant를 query에 담아 `GetDurableOperationUseCase`로 넘기고, 없음과 남의 것을 같은 404 `OPERATION_NOT_FOUND`로 답한다(`DurableOperationController.java:106-118`). 판정은 use case와 `DurableOperationAccessPolicy`가 소유한다(I-1a 해결 유지). ID를 바꿔도 존재 여부가 새지 않는다. 남은 점: `OperationErrorCode`가 web 패키지 안의 enum이라 GraphQL·gRPC가 같은 연산을 노출하면 코드가 따로 생긴다(관찰, 발견으로 올리지 않음).
|
||||
|
||||
### 4.3 큰 입력 — JSON 본문, 콜백 본문, 목록
|
||||
|
||||
JSON은 1 MiB 기본 상한(`WebMvcPlatformSettings`)으로 선언 길이·스트림 계수 두 단계로 막는다(테스트 공백은 02-09). 알림 콜백은 컨트롤러가 `readNBytes(max+1)`로 직접 막는다. fileserver admin의 `limit`·`maxItems`는 HTTP에서 상한 없이 받아 use case로 넘긴다(use case 쪽 상한은 fileserver 영역에서 확인). 페이지 파라미터는 `PageParams`가 막는다.
|
||||
|
||||
### 4.4 적용 제외
|
||||
|
||||
| 시나리오 | 사유 |
|
||||
| --- | --- |
|
||||
| 외부 응답 지연·유실, DB 오류·경쟁, 메시지 중복·역순, 여러 서버 작업 실행 | 이 영역은 변환만 한다. 원인 쪽은 httpclient·persistence·messaging 영역 |
|
||||
| 신·구 버전 공존 | web-advanced 버전 정책은 운영 소비자 0. 예외 변환 결함만 02-07에 적었다 |
|
||||
| 세션·토큰 갱신 경쟁 | JWT 기본 모드는 서버 세션이 없다. redis-session 모드는 실행하지 않았다(미검증) |
|
||||
| 종료·재시작 | `GracefulShutdownProbe`·`TomcatLoadAndShutdownIT`가 있으나 `performanceTest`는 게이트에서 컴파일만 됐다(미검증) |
|
||||
| 선택 어댑터 제거 | composition 영역 |
|
||||
|
||||
## 5. 41절 설계 선택 검토
|
||||
|
||||
### 5.1 HTTP 오류를 Envelope 하나로(소유자 결정 2)
|
||||
|
||||
| 질문 | 답 |
|
||||
| --- | --- |
|
||||
| 1. 무엇이 필요한가 | 모든 HTTP 오류가 한 모양이고 `error.code`가 안정적이어야 한다. 짝 프론트가 이 모양을 검증한다 |
|
||||
| 2. 지킬 성질 | 어떤 경로(MVC 예외, 보안 체인, 인터셉터, fileserver)에서도 같은 키 집합·같은 문구 표·같은 코드 규칙 |
|
||||
| 3. 현재 보장 | `ErrorResponseFactory`가 본문을 만들고 `ClientErrorMessages`가 문구를 정한다. problem+json 누수는 막혔다(I-3a). 보장하지 않는 것: null 필드 존재(02-02), 직접 쓰는 writer의 문자셋(02-04), 라이브러리 예외의 코드(02-07) |
|
||||
| 4. 대안 | 현상 유지 / RFC 9457 problem+json / Envelope + wire 계약 문서 |
|
||||
| 5. 득실 | problem+json은 표준 도구와 맞지만 결정 2를 뒤집는다. Envelope 유지는 비용이 작고, 대신 wire 규칙을 문서·테스트로 고정해야 한다 |
|
||||
| 6. 왜 이 선택 | 결정 2를 유지한다. 부족한 것은 선택이 아니라 "키 집합을 단언하는 테스트와 소비자용 문서"다 |
|
||||
| 7. 재검토 조건 | 외부 공개 API로 쓰여 표준 도구 연동이 요구되면 problem+json을 다시 비교한다 |
|
||||
|
||||
### 5.2 멱등성 in-flight는 기다리지 않고 409, retryable=false
|
||||
|
||||
| 질문 | 답 |
|
||||
| --- | --- |
|
||||
| 1. 필요 | 결과 불명 쓰기를 같은 키로 안전하게 다시 보낼 수 있어야 한다 |
|
||||
| 2. 성질 | 같은 키는 한 번만 실행. 처리 중인 동안 다른 시도는 실행하지 않는다. 클라이언트는 "새 키로 다시"를 하지 않는다 |
|
||||
| 3. 현재 보장 | 앞 두 성질은 executor가 보장한다. 세 번째는 응답이 오히려 반대로 말한다(02-01) |
|
||||
| 4. 대안 | 409 + retryable=true + `Retry-After` / 서버 대기 후 replay / 키 조회 엔드포인트 / 202 + 상태 URL |
|
||||
| 5. 득실 | 02-01 표 참고. 202 + 상태 URL은 모든 KEYED 엔드포인트를 비동기 모양으로 바꿔야 해 비용이 크다 |
|
||||
| 6. 선택 | 기다리지 않는 409는 스레드를 잡지 않아 유지할 가치가 있다. retryable 값과 문서를 고친다 |
|
||||
| 7. 재검토 | 처리 시간이 대부분 lease보다 짧다는 측정이 나오면 짧은 대기 + replay가 더 단순할 수 있다 |
|
||||
|
||||
### 5.3 rate limit·인증 거부는 컨버터 밖에서 본문을 직접 쓴다
|
||||
|
||||
| 질문 | 답 |
|
||||
| --- | --- |
|
||||
| 1. 필요 | 컨트롤러 전에 거부한 요청도 Envelope로 답한다 |
|
||||
| 2. 성질 | 본문·문자셋·헤더가 컨트롤러 응답과 같다 |
|
||||
| 3. 현재 보장 | 세 writer(`AuthErrorResponseWriter`, `RateLimitInterceptor.reject`, GraphQL body limit)가 각자 `setContentType`·`writeValue`를 한다. 하나가 문자셋을 빠뜨렸다(02-04) |
|
||||
| 4. 대안 | 현상 유지 / 공용 `EnvelopeResponseWriter` / 인터셉터가 예외를 던져 `GlobalExceptionHandler`가 쓰게 함 |
|
||||
| 5. 득실 | 공용 writer는 파일 하나로 세 경로가 같아진다. 예외 방식은 보안 체인 안에서는 쓸 수 없다(MVC 밖) |
|
||||
| 6. 선택 | 공용 writer(리팩토링 R-1) |
|
||||
| 7. 재검토 | 보안 체인 거부를 MVC로 넘기는 구조로 바뀌면 예외 방식으로 합칠 수 있다 |
|
||||
|
||||
## 6. 리팩토링 후보
|
||||
|
||||
| ID | 무엇을 | 왜 | 보존 조건 |
|
||||
| --- | --- | --- | --- |
|
||||
| R-1 | `AuthErrorResponseWriter`·`RateLimitInterceptor.reject`의 본문 쓰기를 web의 `EnvelopeResponseWriter` 하나로 | 문자셋·content type·`Retry-After` 규칙이 한 곳에 있게(02-04) | 401의 `WWW-Authenticate`, 429의 `X-RateLimit-*`, 문구는 `ClientErrorMessages` |
|
||||
| R-2 | web-advanced 예외 10종 → `ApiErrorCarrier` + `WebAdvancedError` enum | 변환이 `handleCarrier` 한 분기로(02-07) | 예외 타입 이름(공개 API surface), 메시지의 서버 전용 정보는 본문에 안 나감 |
|
||||
| R-3 | profile-name record 5개 → `ProfileName` 하나(S5-#12) | 같은 정규식 다섯 벌 | 각 타입이 서로 대입되지 않게 하려면 래퍼 타입은 유지하고 검증만 공용 |
|
||||
| R-4 | `GlobalExceptionHandler` 등록 경로 하나로(02-10) | 스위치 의미가 코드와 같게 | 사용자가 같은 타입 bean을 주면 그것이 쓰인다 |
|
||||
| R-5 | `FileserverRequestContextFactory.java:63` 주석 "set by the request-logging filter" → `WebMvcRequestIdFilter` | 주석이 옛 구조를 말함 | 없음 |
|
||||
| R-6 | web `build.gradle`의 `testImplementation project(':adapter:inbound:web-fileserver')` | 부모 leaf 테스트가 자식 leaf를 안다(방향 역전, 테스트 범위). `PresentationWebConfigTest`의 예시를 web 안 fixture로 바꾸면 끊을 수 있다 | prefix가 절대 경로 컨트롤러를 건드리지 않는다는 단언 |
|
||||
|
||||
## 7. 기능 개발 패턴과 판단 지점
|
||||
|
||||
### 7.1 템플릿이 주는 틀
|
||||
|
||||
- 새 HTTP 엔드포인트: 컨트롤러는 DTO를 반환하고 `EnvelopeBodyAdvice`가 감싼다. 예시는 sample-portfolio 컨트롤러와 `DurableOperationController`.
|
||||
- 도메인 오류: `ApiErrorCarrier` + 자기 `ApiErrorCode` enum이면 `GlobalExceptionHandler`가 한 분기로 처리한다(`OperationErrorCode`가 예).
|
||||
- 인가: use case의 `@RequiresPermission` + 소유자·tenant 검사는 use case 안. 관리 경로는 `RestrictedPathRule` bean으로 보안 체인에서 한 번 더.
|
||||
- 입력: `PageParams`·`SortParam`, `ETags`·`PreconditionFailedException`.
|
||||
- 테스트: `WebContractAssertions`, `ContractFixtureApplication`, `WebArchitectureRules`(ArchUnit), 장애 fixture(`IdempotencyResponseLossContract`, `CommitThenConnectionResetIT`).
|
||||
|
||||
### 7.2 빠진 것
|
||||
|
||||
- 소비자용 HTTP 계약 문서(Envelope 키 규칙, 상태·코드·retryable·헤더·클라이언트 행동 표). 지금은 README 예외 표가 유일하다(02-01, 02-02).
|
||||
- `Idempotency-Key` 공용 parse(02-12).
|
||||
- CORS 노출 헤더 기본값(02-05).
|
||||
- `String` 반환 금지 규칙(02-06).
|
||||
- web-fileserver·web-notification README(S5-#14c).
|
||||
|
||||
### 7.3 개발자가 내려야 하는 판단(매뉴얼 재료)
|
||||
|
||||
1. **응답 모양**: DTO를 반환할지 `Envelope`를 직접 만들지. `String`은 반환하지 않는다. 202·Location이 필요하면 `ResponseEntity<Envelope<…>>`.
|
||||
2. **오류 코드 설계**: 새 실패마다 status·category·retryable을 정한다. retryable은 "같은 요청을 그대로 다시 보내면 성공할 수 있는가"로 판단한다(02-01이 이 기준을 어긴 예).
|
||||
3. **404와 403**: 남의 리소스는 "없음"과 같은 404로 답할지(operation이 이 방식), 403으로 답할지.
|
||||
4. **KEYED 여부**: 중복 실행이 피해인지. 그렇다면 키를 필수로 받고, fingerprint에 넣을 필드를 use case에서 정하고, in-flight·mismatch 응답을 클라이언트에 어떻게 설명할지.
|
||||
5. **입력 상한**: JSON 1 MiB 밖의 media type을 받으면 자체 상한을 둔다.
|
||||
6. **공개 경로·관리 경로**: `public-paths`에 넣을지, `RestrictedPathRule`로 막을지.
|
||||
7. **브라우저 노출 헤더**: 클라이언트가 읽어야 하는 응답 헤더면 CORS 노출 목록에 넣는다.
|
||||
|
||||
## 8. 28개 관점 판정표
|
||||
|
||||
| # | 관점 | 판정 | 이유 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 코드 성숙도 | P | 대부분 명확하다. 문자셋 누락(02-04), String 함정(02-06) |
|
||||
| 2 | 구조적 성숙도 | O | leaf 분리와 의존 방향이 registry대로. 인가·멱등 판정이 use case에 있다 |
|
||||
| 3 | 변경 용이성 | P | 오류 코드 추가는 enum 한 곳. 멱등 키 처리는 엔드포인트마다(02-12) |
|
||||
| 4 | 인지 부하 | P | 등록 경로 이중(02-10), in-flight 의미를 다섯 곳에서 맞춰 읽어야 함(02-01) |
|
||||
| 5 | 위험 가시성 | X | audience 기본 off(02-03), String 함정(02-06), null 필드(02-02)가 코드에 드러나지 않음 |
|
||||
| 6 | 실패 성숙도 | P | 실패 변환은 한 분기. 503→500, 라이브러리 예외 500(02-07, 02-08) |
|
||||
| 7 | 운영 성숙도 | P | 런북 있음. in-flight 런북 문장이 틀림(02-01) |
|
||||
| 8 | 디버깅 가능성 | O | 요청·trace ID가 보안 체인 앞에서 한 번 발급되고 모든 응답 `meta`에 실림. correlation ID 규칙만 다름(02-11) |
|
||||
| 9 | 유지보수 성숙도 | P | 남은 Nit(S5-#12, I-7), 낡은 주석(R-5) |
|
||||
| 10 | 테스트 성숙도 | P | 테스트 600건 13초대. 그러나 `doesNotExist`가 null을 못 가림(02-02), 본문 상한 변이 2건 생존(02-09), 문구 미단언(02-04) |
|
||||
| 11 | 데이터 성숙도 | - | 이 영역은 저장하지 않는다 |
|
||||
| 12 | 동시성 성숙도 | P | in-flight 판정은 저장소가 함. HTTP 계약이 클라이언트 행동을 틀리게 말함(02-01) |
|
||||
| 13 | 확장성 | ? | 부하를 걸지 않았다 |
|
||||
| 14 | 성능 성숙도 | ? | 필터 4개·HMAC 한 번 정도로 요청당 비용은 작다고 추정. 측정 안 함. 비JSON 본문 상한 없음(02-09) |
|
||||
| 15 | 보안 성숙도 | X | audience·role 범위(02-03). 그 밖의 경계(XFF 불신, 요청 ID 불신, 중복 키 JSON 거부, 콜백 별도 체인)는 좋음 |
|
||||
| 16 | 의존성 성숙도 | O | 방향 위반 없음. 테스트 범위 역방향 하나(R-6) |
|
||||
| 17 | API / Contract 성숙도 | X | 짝 계약과 3곳 불일치(02-01, 02-02, 02-11), 소비자용 계약 문서 없음 |
|
||||
| 18 | 배포 성숙도 | > | 13 build/CI 영역 |
|
||||
| 19 | 설정 성숙도 | P | 대부분 fail-closed. audience만 fail-open(02-03), CORS 노출 설정 없음(02-05) |
|
||||
| 20 | 개발자 경험 | P | 예시·testkit은 충분. 함정 2개(02-06, 02-12) |
|
||||
| 21 | Guardrail 성숙도 | P | ArchUnit 규칙 있음. String 반환·audience는 막지 않음 |
|
||||
| 22 | 추상화 성숙도 | O | `ApiErrorCarrier` 한 분기, `RestrictedPathRule` 기여 방식이 적절. web-advanced 예외만 빠짐(02-07) |
|
||||
| 23 | 일관성 | P | 같은 위반이 경로에 따라 다른 코드(02-08), writer 문자셋(02-04) |
|
||||
| 24 | 네이밍 / 의미 성숙도 | P | `retryable=false`가 실제 권장 행동과 반대(02-01), 스위치 이름과 동작 불일치(02-10) |
|
||||
| 25 | 조직 확장성 | P | KEYED 엔드포인트가 늘면 키 처리 갈라짐(02-12) |
|
||||
| 26 | Ownership 성숙도 | P | web-fileserver·web-notification에 README·CLAUDE.md 없음(S5-#14c) |
|
||||
| 27 | 삭제 가능성 | O | web-notification·web-fileserver·web-advanced가 한 줄로 빠진다. 스위치 의미만 02-10 |
|
||||
| 28 | 회복 가능성 | P | 결과 불명 쓰기의 복구 경로(같은 키 재전송)가 문서에 없다(02-01, P6-new-2) |
|
||||
@@ -0,0 +1,434 @@
|
||||
# 03 — inbound 실시간·GraphQL·gRPC (websocket · graphql · grpc 어댑터, vendored `grpc:*`·`grpc-advanced:*`)
|
||||
|
||||
2026-11-01 백엔드 성숙도 리뷰, 영역 03. 기준 커밋 `01a8a2a70`(main).
|
||||
|
||||
## 1. 범위 (36.1)
|
||||
|
||||
| 항목 | 기록 |
|
||||
| --- | --- |
|
||||
| 대상 | `src/adapter/inbound/websocket`, `src/adapter/inbound/graphql`, `src/adapter/inbound/grpc`, `src/grpc/*`(registry의 `optional-grpc` leaf 7개), `src/grpc-advanced/*`(2개), `src/optional-platforms` |
|
||||
| 커밋·시점 | `main` @ `01a8a2a70`, 2026-11-01 |
|
||||
| 목적·실행 구성 | 템플릿. 세 어댑터 모두 기본 bootJar에 없고 `runtimeOnly` 한 줄로 고르는 opt-in. gRPC 플랫폼은 별도 Gradle build(`-p optional-platforms`)이고 어떤 composition도 쓰지 않는다. qualification 이미지(`COMPOSITION=qualification`)만 세 어댑터를 모두 싣는다 |
|
||||
| 규모·운영 목표 | 문서에 없음. "대규모 운영 준비" 판정은 하지 않는다 |
|
||||
| 읽은 코드 | 세 어댑터 main 전부(websocket 1,557줄, grpc 어댑터 약 900줄), graphql은 `cost/`·`runtime/`·`dataloader/`·`policy/`·`autoconfigure/`·`context/`·`execution/` 전부와 나머지 목록, gRPC 플랫폼은 `grpc-core-api/ledger`·`grpc-runtime/idempotency`·`grpc-spring-boot-starter` 전부·`grpc-operation-ledger-jpa` 전부·`grpc-testkit/netty/GrpcNettyTestServer`, advanced는 지난 발견 재확인 범위만. 각 leaf `CLAUDE.md`·`README.md`, `src/grpc/CLAUDE.md`, `src/grpc-advanced/CLAUDE.md`, `.github/workflows/{integration-main,ci-quality-gates,release,pr-adapters}.yml`. Spring 소스 `spring-messaging-7.0.9` `SimpleBrokerMessageHandler` |
|
||||
| 실행한 명령 | 아래 표 |
|
||||
| 확인 못 한 것 | `-p optional-platforms ci`(grpc-runtime·testkit·advanced 단위 테스트, Netty·fault lane) 이번 커밋에서 미실행. `websocketNginxTest`는 오늘 미실행(결과 파일이 2026-09-28). 실부하·다중 노드·실 TLS 없음. GitHub Actions에서 `grpc-optional-platform-integration` job이 실제로 green인지는 확인하지 않음(외부 조회 금지) |
|
||||
| 이전 리뷰와 비교 | `docs/reviews/2026-09-18-techlead-review/{03,04,11}-*.md`, `docs/reviews/2026-09-25-review-followup-status.md`의 J·K·N·S5·S6·S7·NEW·P*-new 행, `docs/reviews/2026-08-14-graphql-module-code-review.md` |
|
||||
|
||||
실행 기록(모두 scratchpad worktree `wt-03`, `flock heavy.lock`으로 감쌈, 끝나고 worktree 제거):
|
||||
|
||||
| 명령 | 부하(uptime) | 결과 |
|
||||
| --- | --- | --- |
|
||||
| 오케스트레이터 게이트 `ci` | 9.15 | rc=0(7분 9초). 세 어댑터 `check`(test·spotless·checkstyle·Error Prone·API surface) 통과 |
|
||||
| 오케스트레이터 게이트 `mainCheck` | 20.68 | rc=1. 실패는 objectstorage MinIO 이미지 pull 404 두 건뿐. 이 영역의 `systemTest`(websocket·graphql), `websocketJettyTest`, `*TransportQualificationTest` 3개, `graphqlStableTest`, `conditionalTransportQualification`은 실행됐고 실패 없음 |
|
||||
| `:adapter:inbound:graphql:test --tests '*Review03ComplexityProbeTest'` (리뷰용 임시 테스트) | 8.65 | 통과 = 결함 재현. `REVIEW03 explicit20=410 omitted=40 nested4=100 variableDefault100000=40` (03-01) |
|
||||
| `:adapter:inbound:websocket:test --tests '*Review03WebSocketProbeTest'` (임시) | 8.65 | 통과 = 결함 재현. `leakedGlobalBytes=500`(03-07), `openAfterStop=1 running=false`(03-08) |
|
||||
| `-p optional-platforms :grpc:grpc-operation-ledger-jpa:integrationTest` | 7.89 | 통과. `GrpcOperationLedgerPostgresIT` 2건 + `JpaGrpcOperationLedgerContractIT` 16건, skip 0, `postgres:16-alpine`, V001 SQL을 그대로 적용. 벽시계 77초(잠금 대기 포함) |
|
||||
| 변이 1: `GraphQlCostBudgetHandler`의 `structuralLimits.verify(shape)` 무력화 → `:adapter:inbound:graphql:systemTest` | 6.13 | 잡힘. 25건 중 2건 실패(`aDocumentDeeperThanTheStructuralLimit…`, `anAliasBomb…`) |
|
||||
| 변이 2: STOMP SUBSCRIBE destination 검사 무력화 → `:adapter:inbound:websocket:test` | 6.13 | 잡힘. `WebSocketInboundAuthorizationInterceptorTest.permitsAuthenticatedSubscribeOnlyToConfiguredTopic` 실패 |
|
||||
|
||||
임시 테스트 원본은 scratchpad `src03/Review03*.java`에 남겼다. 메인 repo에는 이 문서 말고 바꾼 파일이 없다.
|
||||
|
||||
## 2. 지난 발견 재확인
|
||||
|
||||
상태: 해결 / 남음 / 바뀜. followup-status에서 이미 `완료`이고 이번에 다시 볼 이유가 없던 행은 생략했다. 아래는 남음·보류였거나 이번 주제(연결 상한·깊이·N+1·deadline·ledger)에 걸린 행이다.
|
||||
|
||||
| ID | 상태 | 근거 |
|
||||
| --- | --- | --- |
|
||||
| J-3b (Javadoc "detail은 로그에") | 해결 | `graphql/.../error/GraphQlWireErrorMapper.java:35`가 실제로 로그하는 `GraphQlExceptionResolver`를 가리킨다(J-3a에서 ERROR 로그 추가) |
|
||||
| J-4c (DataLoader 실패 테스트가 `isNotEmpty()`만) | 남음 | `graphql/src/test/.../runtime/GraphQlBatchLoaderRegistrationTest.java:133,146,162,198` |
|
||||
| J-9b (chunked 본문 경로 테스트 없음) | 해결 | `graphql/src/systemTest/.../runtime/GraphQlPlatformExecutionPathTest.java:263` `aChunkedBodyOverTheRawCapIsRefusedWith413` |
|
||||
| J-11b (README가 없는 resolver 설명) | 해결 | `graphql/README.md`에 `GraphqlExceptionResolver` 0건 |
|
||||
| J-12 / X2-P2-6b | 보류(소유자 결정 35) | 결정대로 유지. 다시 열지 않음 |
|
||||
| S5-#7c (autoconfig 주석이 사실과 다름) | 남음 | `graphql/.../autoconfigure/GraphQlRootAutoConfiguration.java:39` "component scan excludes by regex" 문장이 아직 있다 |
|
||||
| S5-#14d (graphql 주석 과다·"design §") | 남음 | graphql main에 `design §` 46곳 |
|
||||
| S5-#14e (interceptor 생성자 인자 과다) | 남음 | `graphql/.../runtime/GraphQlPlatformWebInterceptor.java:70-80` 인자 10개(9 → 10) |
|
||||
| K-5b (종료 IT가 context를 안 닫음) | 해결 | `websocket/src/systemTest/.../runtime/TomcatWebSocketShutdownIT.java:29-58`이 context를 닫고 1001을 단언. 단 `TomcatWebSocketAbuseIT.java:69`는 여전히 `handler.stop()` 직접 호출(중복 테스트) |
|
||||
| P25-new-1 (shutdown 테스트 시간 경계 flaky) | 남음 | `TomcatWebSocketAbuseIT.java:73-77` `took < 20s`와 `await(20s)`가 같은 경계 |
|
||||
| K-12c (CLAUDE.md "Boot 4.0.0") | 남음 | `adapter/inbound/grpc/CLAUDE.md:8`, `adapter/inbound/graphql/CLAUDE.md:8` |
|
||||
| techlead 03-H3 (`CONNECTION_MUST_CLOSE` 무시) | 해결 | `websocket/.../servlet/PlatformWebSocketHandler.java:176-180` 1013으로 닫음 |
|
||||
| techlead 03-H7 (gRPC loopback 전용) | 남음(의도·문서화) | `adapter/inbound/grpc/CLAUDE.md` "Current transport limit". TLS는 P2로 미룸 |
|
||||
| techlead 03-M4 (글로벌 예산을 poll 때 반납) | 해결 | `OutboundQueue.java:119-124` `releaseInFlight`가 write 뒤 반납. 다만 close 경합은 새 결함 03-07 |
|
||||
| techlead 03-M5 (모든 `BindableService` 노출) | 해결 | `GrpcServerConfig` `@GrpcExposedService` 한정 |
|
||||
| techlead 04-M5 (parser 한계 미설치) | 바뀜 | parse 전 `maxDocumentBytes` 16 KiB 검사(`GraphQlPlatformWebInterceptor.java:125-133`) + graphql-java 기본 parser 한계. 별도 설치는 여전히 없음 |
|
||||
| techlead 04-L2 (전역 `Clock` 빈) | 해결 | `GraphQlRequestContextConfiguration.java:35-37` `@ConditionalOnMissingBean(Clock.class)` |
|
||||
| techlead 11-C1 / N-1 / N-11a (ledger claim 원자성) | 해결 | `JpaGrpcOperationLedger.java:39-65`(native `INSERT … ON CONFLICT DO NOTHING`), 이번 PG lane 18건 통과 |
|
||||
| techlead 11-H1 (startup validator 미호출) | 해결 | `GrpcPlatformAutoConfiguration` `grpcPlatformStartupCheck`(`SmartInitializingSingleton`) |
|
||||
| techlead 11-M9 (starter가 JPA를 끌어옴) | 해결 | starter `build.gradle`에 ledger 의존 없음, `src/grpc/CLAUDE.md` "Durable operation ledger adoption" |
|
||||
| N-12a (`GrpcClientMessageDeduplicator` "constant space") | 남음 | `grpc-advanced/.../streaming/GrpcClientMessageDeduplicator.java:13,112` |
|
||||
| N-12b (`ReactiveGrpcClient.serverStream`) | 남음 | `grpc-advanced-compat/.../reactor/ReactiveGrpcClient.java:50` |
|
||||
| P5-new-1 (Envoy `VirtualHost.cors` deprecated) | 남음 | `grpc-advanced-compat/src/test/resources/envoy/envoy.yaml:37` |
|
||||
| P15-new-4 (status description 변경 이행 안내) | 바뀜(부분) | `adapter/inbound/grpc/README.md:79-81`에 trailer 안내 추가. 그러나 `:87`은 여전히 "code 문자열만 status description/trailer로 노출"이라 적어 설명이 엇갈린다 |
|
||||
| S7-lead-2 (root family 표에 gRPC 행 없음) | 남음 | root `CLAUDE.md` 「Module families」 표에 `messaging:*` 행만 있고 `grpc:*`·`grpc-advanced:*` 행이 없다 |
|
||||
|
||||
이번 커밋에서 남은 High/P1은 지난 발견 쪽에는 없다. High는 아래 새 발견 두 건이다.
|
||||
|
||||
## 3. 새 발견
|
||||
|
||||
심각도별: High 2 · Medium 7 · Low 3. 우선순위별: P1 2 · P2 7 · P3 3. Critical·P0 없음.
|
||||
|
||||
### 03-01 GraphQL 복잡도 점수가 목록 크기를 놓친다 — 페이지 인자 생략·변수 기본값·일반 list 필드
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 1, 5, 6, 10, 13, 14, 15, 17 |
|
||||
| 근거 | `graphql/.../cost/GraphQlDocumentComplexityScorer.java:217-222` — `first`/`last` 인자가 **값으로 읽힐 때만** `connectionCost`(자식 비용 × 페이지 크기)를 쓰고, 아니면 `fieldCost`(자식 비용 × 1). `:242-249` 변수 참조는 요청 `variables` 맵에 없으면 `null`. `GraphQlCostBudgetHandler.java:78`이 넘기는 맵은 클라이언트가 보낸 원본이라 연산의 변수 기본값(`$n: Int = 100000`)이 없다. `:206` `unwrap`이 `GraphQLList`를 벗겨 버려 일반 list 필드의 개수 정보가 사라진다. 반면 `GraphQlComplexityCalculator.java:9-11` Javadoc은 "first를 생략하면 기본 페이지로 계산해야 한다, 1로 계산하면 예산 우회"라고 적고 있다. 페이지 상한 검사(`GraphQlComplexityCalculator.java:51`)도 `connectionCost`에만 있다. 임시 테스트 결과: `items(first: 20){name}` = 410, `items{name}` = 40, `items{children{children{children{name}}}}` = 100(4단 중첩 list가 선형 합), `query($n:Int=100000){items(first:$n){name}}` = 40으로 통과(같은 값을 리터럴로 쓰면 `GraphQlComplexityRejectedException`) |
|
||||
| 발생 조건 | adopter 스키마에 list 반환 필드가 있으면 항상. 공격자는 `first`를 빼거나, 변수 기본값으로 숨기거나, 변수를 아예 안 보낸다 |
|
||||
| 영향 | 복잡도 예산(기본 10,000)과 페이지 상한(기본 100)이 사실상 꺼진다. 중첩 list는 실제 작업이 곱으로 늘어나는데 점수는 합으로만 는다. resolver가 플랫폼 밖 라이브러리 `GraphQlConnectionPolicy`를 직접 부르지 않으면 `first: 100000`이 그대로 DB까지 간다 |
|
||||
| 심각도·우선순위 | High · P1. GraphQL은 opt-in이지만 이 플랫폼이 판매하는 핵심 보호(`CLAUDE.md` 등급표 "depth/complexity 제한 `wired`")가 list 필드가 생기는 순간 무력하다. 템플릿을 복사한 서비스로 그대로 퍼진다 |
|
||||
| 확실성 | 직접 확인(E2 임시 테스트). systemTest 스키마(`src/systemTest/resources/graphql-platform/platform.graphqls`)에 list·connection 필드가 하나도 없어서 기존 테스트가 이 경로를 밟지 않는다. `GraphQlDocumentComplexityScorer` 전용 단위 테스트도 없다 |
|
||||
| 통제 수준 | 깊이·필드·alias 상한은 M3(변이 1로 확인). 목록 크기 반영은 M0 |
|
||||
| 결정의 근거 | 적용 제외 — 문서화된 계약(Javadoc)과 코드가 어긋난 단순 결함 |
|
||||
| 최소 개선 방향 | (1) 필드 정의가 list(또는 connection 규약 타입)면 `first`/`last`가 없거나 `null`일 때 `defaultPageSize`를 곱한다. (2) 변수 값은 `ExecutionInput`이 아니라 graphql-java가 기본값을 적용한 `CoercedVariables`(`ValuesResolver.coerceVariableValues`)로 읽는다. (3) 페이지 인자가 없는 일반 list는 기본 배수(`defaultPageSize`)로 곱하고, adopter가 `GraphQlFieldCostDescriptor`로 필드별 배수를 줄 수 있게 한다. 버린 대안: graphql-java 기본 `MaxQueryComplexityInstrumentation` 도입 — 이 역시 list 배수를 모르는 필드 개수 합이라 같은 구멍이 남고, 플랫폼 점수와 두 벌이 된다 |
|
||||
| 완료 기준 | 위 네 쿼리의 점수가 각각 페이지 크기만큼 곱해지고, 변수 기본값 100000은 `page size exceeds maximum`으로 거부된다 |
|
||||
| 검증 방법 | `cost/`에 scorer 단위 테스트(위 네 케이스) + systemTest 스키마에 list 필드 하나와 "first 생략 + 중첩" 거부 케이스 |
|
||||
|
||||
### 03-02 GraphQL 요청 deadline(10초)이 실행 중에는 강제되지 않는다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(문서와 동작 불일치) + 구조적 위험 |
|
||||
| 관련 관점 | 5, 6, 9, 14, 22 |
|
||||
| 근거 | `policy/GraphQlClientPolicy.java:90` `maxExecutionTime` 10초 → `GraphQlPlatformWebInterceptor.java:147` deadline 생성. 읽는 곳은 `GraphQlCostBudgetHandler.java:62`(실행 **전** 한 번)과 `dataloader/GraphQlBatchExecutor.java:110`(platform registrar로 등록한 batch만)뿐. resolver 실행 자체를 끊는 장치(Spring GraphQL `TimeoutWebGraphQlInterceptor`, `DataFetcher` timeout)는 없다. `execution/GraphQlTimeoutPolicy.java`는 main 호출자 0(테스트만). `context/GraphQlDeadline.java:9-12` Javadoc은 "resolver, DataLoader batch, JPA/Mongo/HTTP client deadline으로 같은 budget을 내려준다"고 적는다 |
|
||||
| 발생 조건 | 느린 resolver·외부 호출이 있는 adopter 쿼리 |
|
||||
| 영향 | 요청이 10초 뒤에도 servlet 스레드를 잡고 계속 돈다. 클라이언트는 이미 끊었는데 DB 커넥션·스레드가 묶인다. 운영자는 설정만 보고 10초 상한이 있다고 믿는다 |
|
||||
| 심각도·우선순위 | Medium · P2. 기본 composition에 없고 피해는 자원 점유로 제한된다 |
|
||||
| 통제 수준 | M1(설정·Javadoc만), 실행 강제 M0 |
|
||||
| 결정의 근거 | 적용 제외 — 이미 정한 계약(`maxExecutionTime`)을 실행에 연결하는 문제 |
|
||||
| 최소 개선 방향 | 고른 방법: Spring GraphQL의 `TimeoutWebGraphQlInterceptor`(또는 같은 일을 하는 interceptor)를 `maxExecutionTime`으로 auto-config에 넣고, 시간 초과를 `REQUEST_TIMEOUT`으로 매핑한다. 쓰지 않는 `GraphQlTimeoutPolicy`는 지우거나 하위 호출이 쓰도록 연결한다. 버린 대안: resolver마다 deadline을 검사 — adopter가 기억해야 하는 숨은 규칙이 된다 |
|
||||
| 완료 기준 | 11초 걸리는 resolver를 가진 systemTest 쿼리가 10초 근처에서 `REQUEST_TIMEOUT`으로 끝난다 |
|
||||
| 검증 방법 | systemTest에 느린 resolver 케이스 하나(주입 시계 대신 짧은 `maxExecutionTime` 설정) |
|
||||
|
||||
### 03-03 N+1을 막는 길이 adopter 기억에만 있다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 4, 5, 14, 20, 21 |
|
||||
| 근거 | 플랫폼 batch 보호(chunk·deadline·tenant scope)는 `runtime/GraphQlBatchLoaderRegistrar.java:58-82`로 **명시 등록한** loader에만 붙는다. Spring 표준 `@BatchMapping`이나 per-parent `@SchemaMapping`은 이 경로를 거치지 않는다. 템플릿에는 feature GraphQL 예시가 없고(`graphql/README.md` 「아직 구현하지 않은 범위」), README는 registrar 사용법을 한 줄도 적지 않는다. 비용 카탈로그는 기본이 비어 있어(`GraphQlExecutionChainConfiguration` `GraphQlCostCatalog.of()`) 모든 필드가 같은 가중치 10이다. `EXTERNAL_PER_OBJECT(20)`과 `BATCHED_RELATION(3)` 구분은 adopter가 등록해야만 의미가 있다 |
|
||||
| 발생 조건 | adopter가 list 부모 아래 자식 필드를 일반 `@SchemaMapping`으로 구현 |
|
||||
| 영향 | 부모 N개마다 하위 호출 N번. 03-01과 겹치면 점수도 낮게 나와 거부되지 않는다 |
|
||||
| 심각도·우선순위 | Medium · P2 |
|
||||
| 통제 수준 | M2(registrar 경로는 `GraphQlBatchLoaderRegistrationTest`로 50 parent → 3 호출 확인), 그 밖 경로 M0 |
|
||||
| 결정의 근거 | 현재 선택: 플랫폼은 feature-agnostic이고 resolver를 모른다(사실, `CLAUDE.md`). 대안 (a) 문서·예시만 추가, (b) graphql-java instrumentation으로 같은 필드의 per-parent fetch 횟수를 세어 임계값 넘으면 WARN/metric, (c) 카탈로그 미등록 list 자식 필드를 기동 때 경고. 고른 방향: (a)+(b). (c)는 스키마 전체를 adopter가 등록해야 해서 비용 대비 효과가 작다. 재검토 조건: sample에 GraphQL feature가 들어오면 그 예시가 (a)를 대신한다 |
|
||||
| 최소 개선 방향 | README에 "자식 필드는 `GraphQlBatchLoaderRegistrar.register`로" 조립 예와 `@BatchMapping`과의 차이(플랫폼 budget 미적용)를 적고, 요청당 같은 좌표 fetch 횟수 metric을 추가 |
|
||||
| 완료 기준 | README 예시가 컴파일되는 테스트로 고정되고, per-parent fetch가 임계값을 넘는 systemTest에서 WARN/metric이 관찰된다 |
|
||||
| 검증 방법 | systemTest에 list 부모 + 일반 `@SchemaMapping` 자식 쿼리 하나 |
|
||||
|
||||
### 03-04 `GraphQlDataLoaderRequestRegistry`는 도달 불가인데 README가 요청 스코프 장치로 설명한다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(갈라진 중복 복사본) |
|
||||
| 관련 관점 | 4, 9, 22, 27 |
|
||||
| 근거 | `dataloader/GraphQlDataLoaderFactory.java:37` `newRequestRegistry()`의 호출자는 테스트 하나(`GraphQlDataLoaderRequestRegistryTest.java:84`)뿐. 실제 요청 스코프는 Spring이 실행마다 새로 만드는 `DataLoaderRegistry`다(`GraphQlBatchLoaderRegistrar.java:19-23,48-50` Javadoc이 스스로 "아무것도 연결하지 않던 registry"라고 적음). 그런데 `graphql/README.md:204-208`은 이 registry가 요청마다 새로 만들어져 tenant 누출을 막는다고 설명한다 |
|
||||
| 영향 | 읽는 사람이 죽은 타입을 보호 장치로 믿는다. public 타입이라 API surface에도 남는다 |
|
||||
| 심각도·우선순위 | Low · P3 |
|
||||
| 결정의 근거 | 적용 제외 — 두 번째 경로가 이미 대체된 상태라 비교할 선택이 없다 |
|
||||
| 단순화의 보존 조건 | `GraphQlBatchLoaderRegistrar`의 요청 스코프(실행마다 새 `DataLoaderRegistry`)와 `GraphQlBatchContext.cacheScope()` 지문 동작은 유지 |
|
||||
| 최소 개선 방향 | `GraphQlDataLoaderRequestRegistry`와 `newRequestRegistry()` 삭제, API surface 재승인, README 절을 registrar 기준으로 다시 쓴다 |
|
||||
| 완료 기준 | main·test grep 0건, `verifyGraphQlApiSurface` 통과 |
|
||||
| 검증 방법 | `:adapter:inbound:graphql:check` |
|
||||
|
||||
### 03-05 batch loader가 플랫폼 context 없이 불리면 `REQUEST_TIMEOUT`으로 나간다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 6, 8, 17 |
|
||||
| 근거 | `runtime/GraphQlBatchLoaderRegistrar.java:73-76` context가 없으면 `GraphQlBatchTimeoutException` → mapper가 `REQUEST_TIMEOUT`/TIMEOUT(J-4a 매핑). 원인은 interceptor 미배선 같은 조립 오류인데 클라이언트·운영자는 시간 초과로 본다. 같은 조립 오류를 instrumentation은 WARN과 `PLATFORM_CONTEXT`로 따로 다룬다(P8-new-2) |
|
||||
| 영향 | 잘못 조립된 배포가 "느리다"로 오진된다. retryable 시간 초과로 보이면 클라이언트가 재시도한다 |
|
||||
| 심각도·우선순위 | Low · P3 |
|
||||
| 결정의 근거 | 적용 제외 — 이미 있는 `PLATFORM_CONTEXT` 처리와 맞추는 일 |
|
||||
| 최소 개선 방향 | 전용 플랫폼 거부(예: `GraphQlPlatformContextMissingException`, INTERNAL + WARN 한 번)로 바꾼다 |
|
||||
| 완료 기준·검증 | context 없는 batch 호출 테스트가 `INTERNAL_ERROR`와 WARN 한 줄을 단언 |
|
||||
|
||||
### 03-06 WebSocket 연결 수·구독 수·연결 수명 상한이 없고, STOMP 전송 한도가 코드에 드러나지 않는다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 5, 6, 13, 14, 15, 19 |
|
||||
| 근거 | (1) STOMP: `stomp/WebSocketConfig.java:62-68`은 `configureWebSocketTransport`를 두지 않아 메시지 크기 64 KiB·send buffer 512 KiB·send time 10초·첫 메시지 60초가 Spring 기본값으로만 정해진다. 노드·principal당 연결 수 상한이 없다. (2) 구독 수: `WebSocketInboundAuthorizationInterceptor.java:34-36`은 destination만 보고 개수를 세지 않는다. Spring `SimpleBrokerMessageHandler`(7.0.9 소스 `:397-402`)는 세션 하나의 subscription id마다 메시지를 한 번씩 보낸다. 같은 `/topic/events`를 id만 바꿔 N번 SUBSCRIBE하면 broadcast 한 건이 그 세션에 N번 나가고, 구독 registry가 N만큼 커진다. (3) 라이브러리 handler: `servlet/PlatformWebSocketHandler.java:110` `openConnections()`는 세기만 하고 거부하지 않는다. `README.md` 「서비스가 챙길 것」은 인증·origin·크기·idle만 적고 연결 수는 적지 않는다. (4) 연결 수명: 인증은 handshake 한 번이고 토큰 만료·폐기 뒤에도 연결이 유지된다. 이 한계도 문서에 없다 |
|
||||
| 발생 조건 | 인증된 사용자 한 명(또는 탈취된 토큰)이 연결을 많이 열거나 SUBSCRIBE를 반복 |
|
||||
| 영향 | 노드 메모리·broker 채널 큐(기본 10,000)를 한 사용자가 채운다. broker 큐가 차면 다른 사용자의 live event가 drop된다(R1 best-effort라 오류 없이) |
|
||||
| 심각도·우선순위 | Medium · P2. opt-in이고 인증된 사용자만 가능 |
|
||||
| 통제 수준 | destination allowlist M3(변이 2로 확인). 연결·구독 수 M0 |
|
||||
| 결정의 근거 | 현재: 노드 내 simple broker, 연결 관리는 컨테이너·프록시 몫(README). 대안 (a) 문서로만 "프록시에서 연결 수 제한", (b) STOMP inbound interceptor에서 세션당 구독 수 1개(이 채널은 destination이 하나뿐)와 노드 연결 수 상한을 설정 키로, (c) principal별 연결 수 제한(분산 카운터 필요). 고른 방향: (b) — destination이 하나뿐이라 "세션당 구독 1"은 비용이 거의 없고, 노드 상한은 지역 카운터로 충분. (c)는 다중 노드에서 Redis가 필요해 이 leaf 범위를 넘으므로 문서로 남긴다. 재검토 조건: broker relay·다중 노드 전달을 도입할 때 |
|
||||
| 최소 개선 방향 | `configureWebSocketTransport`로 Spring 기본값을 명시 설정 키로 꺼내고, 세션당 중복 SUBSCRIBE 거부, 노드 연결 상한(`app.websocket.max-connections`) 추가. 라이브러리 handler는 생성자에 연결 상한을 받거나 README에 필수 항목으로 적는다 |
|
||||
| 완료 기준 | 같은 세션의 두 번째 SUBSCRIBE가 ERROR 프레임으로 거부되고, 상한+1번째 연결이 거부되는 systemTest |
|
||||
| 검증 방법 | `WebSocketBoundaryQualificationTest`에 두 케이스 |
|
||||
|
||||
### 03-07 `SerializedOutboundWriter`의 offer와 close가 겹치면 노드 버퍼 예산이 영구히 샌다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 1, 6, 12, 14 |
|
||||
| 근거 | `outbound/SerializedOutboundWriter.java:86`에서 `closed`를 본 뒤 `:93` queue lock을 잡기 전에 `close()`(`:179-192`)가 끼어들면, close가 빈 큐를 비운 다음 offer가 메시지를 넣고 `GlobalBufferBudget`에 바이트를 예약한다. 이어지는 `drain()`(`:112`)은 `closed`라 아무것도 쓰지 않는다. writer는 handler map에서 이미 빠졌으므로 그 예약을 돌려줄 주체가 없다. 임시 테스트(queue lock을 잡고 producer를 그 앞에 세운 뒤 close)로 `leakedGlobalBytes=500` 재현 |
|
||||
| 발생 조건 | 응답 enqueue(`PlatformWebSocketHandler.writeReply`)와 연결 종료(`afterConnectionClosed`·`stop`)가 다른 스레드에서 동시에. 연결이 많고 끊김이 잦을수록 누적 |
|
||||
| 영향 | 노드 예산이 조금씩 줄어 결국 모든 연결의 GUARANTEED 응답이 1013으로 닫힌다. 코드 주석(`PlatformWebSocketHandler.java:94-96`)이 막는다고 적은 바로 그 누수다. 재시작 전까지 회복되지 않는다 |
|
||||
| 심각도·우선순위 | Medium · P2. 라이브러리형이라 조립한 서비스에만 해당 |
|
||||
| 통제 수준 | M2(정상 경로), 경합 경로 M0 |
|
||||
| 결정의 근거 | 적용 제외 — 동시성 결함 수정 |
|
||||
| 최소 개선 방향 | `queue.offer`를 queue lock 안에서 `closed`를 다시 확인한 뒤에만 하고, 닫힌 뒤면 `CONNECTION_MUST_CLOSE` 반환. 또는 `close()`의 `discardAll`을 offer와 같은 lock 아래 마지막 단계로 두고 offer도 lock 안에서 closed를 본다 |
|
||||
| 완료 기준 | 위 경합 테스트에서 `global.buffered() == 0` |
|
||||
| 검증 방법 | 결정적 경합 테스트를 `SerializedOutboundWriterTest`에 추가(테스트용 hook 대신 queue를 감싼 latch fake로) |
|
||||
|
||||
### 03-08 `PlatformWebSocketHandler.stop()` 뒤에 들어온 연결은 1001을 받지 못한다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 6, 7, 18, 28 |
|
||||
| 근거 | `servlet/PlatformWebSocketHandler.java:63-71` `afterConnectionEstablished`가 `running`을 보지 않는다. `stop()`(`:133-148`)은 그 시점의 세션만 닫는다. handler 단계(`DEFAULT_PHASE`)와 web server graceful 단계(`DEFAULT_PHASE - 1024`) 사이에 서버는 아직 upgrade를 받는다. 임시 테스트: `stop()` 뒤 연결 → `openAfterStop=1`, `close` 호출 0회 |
|
||||
| 발생 조건 | 롤링 재시작. 1001을 받은 클라이언트가 바로 재접속하고, 로드밸런서 endpoint 제거가 늦어 같은 pod로 다시 붙는 경우 |
|
||||
| 영향 | 그 연결은 서버 종료 때 1006으로 끊긴다. stop()이 막으려던 "공격적 재접속"이 바로 그 창에서 생긴다 |
|
||||
| 심각도·우선순위 | Medium · P2 |
|
||||
| 결정의 근거 | 적용 제외 — 이미 정한 종료 계약(1001)의 빈틈 |
|
||||
| 최소 개선 방향 | `afterConnectionEstablished`에서 `!running`이면 즉시 1001(또는 1012)로 닫는다 |
|
||||
| 완료 기준 | stop 뒤 연결이 즉시 1001로 닫히는 단위 테스트, `TomcatWebSocketShutdownIT`에 "stop 직후 재접속" 케이스 |
|
||||
| 검증 방법 | `PlatformWebSocketHandlerTest`, systemTest |
|
||||
|
||||
### 03-09 gRPC 어댑터 서버가 io.grpc 기본값으로 뜬다 — deadline·동시 호출·executor·메시지 크기 상한이 없고, 플랫폼 한도는 testkit 서버에만 적용된다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 5, 6, 13, 14, 19, 23 |
|
||||
| 근거 | `adapter/inbound/grpc/.../GrpcServerRunner.java:75` `NettyServerBuilder.forAddress(...)`에 `maxInboundMessageSize`, `maxConcurrentCallsPerConnection`, `executor`, keepalive·`maxConnectionAge` 설정이 없다. io.grpc 기본은 메시지 4 MiB, 연결당 동시 호출 무제한, 스레드 수 제한 없는 cached executor다. 서버 쪽 기본 deadline(클라이언트가 deadline 없이 부른 호출을 끊는 장치)도 없다. 플랫폼은 `GrpcTransportLimits`(1 MiB/8 KiB), `GrpcServerProfile`, `GrpcAdmissionController`를 갖지만 이를 `NettyServerBuilder`에 적용하는 코드는 `grpc-testkit/.../netty/GrpcNettyTestServer.java:69-70` 하나뿐이고, starter(`GrpcPlatformAutoConfiguration`)는 profile bean만 만들고 서버를 만들지 않는다. 종료는 `stop()`(`:112-130`)이 health를 NOT_SERVING으로 바꾸자마자 `shutdown()`해 LB가 상태를 볼 시간이 없다 |
|
||||
| 발생 조건 | adopter가 어댑터로 feature 서비스를 노출하고 호출이 몰릴 때. 현재 P1은 loopback 전용이라 같은 Pod sidecar 정도만 해당 |
|
||||
| 영향 | 느린 handler가 스레드를 무한정 늘린다. Netty lane이 인증한 한도(1 MiB 등)는 실제 production 서버와 다른 서버에 대한 증거다 |
|
||||
| 심각도·우선순위 | Medium · P2. loopback 제한이 노출을 줄인다. TLS·외부 bind(P2)를 열기 전에는 해결해야 한다 |
|
||||
| 통제 수준 | 어댑터 M0, 플랫폼 M2(testkit 한정) |
|
||||
| 결정의 근거 | 현재: 두 스택 공존은 X1-#10·techlead 11-K6에서 의도로 수용됐다(다시 열지 않는다). 대안 (a) 어댑터가 `GrpcTransportLimits`와 같은 값을 자기 `GrpcServerSettings`로 노출해 builder에 설정, (b) 어댑터가 플랫폼 `GrpcServerProfile`을 받는다(registry edge 추가 = "배선은 별도 결정"), (c) 현상 유지 + README에 기본값 명시. 고른 방향: (a). 두 스택 분리 결정을 건드리지 않고 기본값을 코드에 드러낸다. (b)는 소유자가 플랫폼 배선을 결정할 때 다시 본다 |
|
||||
| 최소 개선 방향 | `GrpcServerSettings`에 `maxInboundMessageBytes`(1 MiB), `maxConcurrentCallsPerConnection`, bounded executor 크기, 기본 deadline을 두고 builder에 적용. stop에 짧은 drain 대기(`shutdownGraceSeconds` 안에서) |
|
||||
| 완료 기준 | `GrpcP1BoundaryWireTest`에 1 MiB 초과 메시지 `RESOURCE_EXHAUSTED`, deadline 없는 느린 호출이 기본 deadline에 `DEADLINE_EXCEEDED` 케이스 |
|
||||
| 검증 방법 | `:adapter:inbound:grpc:grpcTransportQualificationTest` |
|
||||
|
||||
### 03-10 operation ledger의 `IN_PROGRESS` claim에 만료·회수가 없다 — 소유자가 죽으면 그 key는 영구히 막힌다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 1, 6, 11, 12, 28 |
|
||||
| 근거 | `grpc-runtime/.../idempotency/GrpcIdempotencyInterceptor.java:118-121`: claim이 `IN_PROGRESS`면 `waitAndPoll` 또는 `rejectInProgress`. 만료 판단이 없다. `GrpcOperationLedger` port와 `JpaGrpcOperationLedger`에 stale claim 회수 메서드가 없다. `V001__create_grpc_operation_ledger.sql:35-37`은 "owner가 죽은 IN_PROGRESS 행을 찾아 release하기 위한 인덱스"라고 적지만 그 회수 코드는 main 어디에도 없다. COMMITTED 행 보존 기간·정리도 없다 |
|
||||
| 발생 조건 | claim 뒤 commit/fail 전에 프로세스가 죽거나 트랜잭션 밖에서 claim이 커밋된 경우(`tryInsertClaim`은 `@Transactional`이라 호출자 트랜잭션이 없으면 즉시 커밋) |
|
||||
| 영향 | 같은 key의 재시도가 영원히 대기하거나 거부된다. 클라이언트가 key를 바꾸면 중복 실행 방지가 깨진다. 테이블은 끝없이 자란다 |
|
||||
| 심각도·우선순위 | High · P1(ledger 채택 전 차단). 현재는 어떤 서버 경로도 이 판단 함수를 쓰지 않아(03-11) 노출은 없다. 채택하는 순간 pod 재시작 한 번으로 발생하는 일반 장애다 |
|
||||
| 확실성 | E1(코드 경로 확인). PG lane 18건은 claim 원자성만 다루고 stale claim 케이스는 없다 |
|
||||
| 통제 수준 | claim 유일성 M4(DB 제약 + PG lane E3). stale 회수 M0 |
|
||||
| 결정의 근거 | 현재: claim이 소유를 정하는 lease 없는 lock이다. 대안 (a) `claimed_at` + TTL로 stale `IN_PROGRESS`를 조건부 UPDATE로 재claim(`tryReclaimStale`, 기존 `tryReclaimFailed`와 같은 모양), (b) owner token + heartbeat lease(outbox lease와 같은 방식), (c) stale 행을 지우는 sweeper job. 고른 방향: (a). 인덱스가 이미 있고 SQL 한 문장으로 끝나며 회수 시 "결과 불명"을 `GrpcCompletionReconciler`로 넘길 수 있다. (b)는 장시간 작업에만 필요하다. 재검토 조건: 처리 시간이 TTL보다 길 수 있는 method가 생기면 (b) |
|
||||
| 최소 개선 방향 | port에 `reclaimStale(identity, fingerprint, olderThan, now)` 추가, JPA는 `UPDATE … WHERE state='IN_PROGRESS' AND claimed_at < :cutoff`, interceptor가 stale이면 재claim. 보존 기간 정리 쿼리와 문서 |
|
||||
| 완료 기준 | 계약 테스트 `GrpcOperationLedgerContract`에 "TTL이 지난 IN_PROGRESS는 같은 요청이 한 번만 재claim" 추가, fake와 JPA(PG lane) 모두 통과 |
|
||||
| 검증 방법 | `-p optional-platforms :grpc:grpc-operation-ledger-jpa:integrationTest`, `grpc-core-api:test` |
|
||||
|
||||
### 03-11 `app.grpc.platform.operation-ledger-enabled`는 검증만 통과시키고 실제로 key를 처리하는 코드가 없다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(설정 키가 하지 않는 일을 약속) |
|
||||
| 관련 관점 | 5, 17, 19, 21 |
|
||||
| 근거 | `grpc-spring-boot-starter/.../GrpcPlatformProperties.java:53` 플래그, `GrpcPlatformStartupValidator.java:149-155` "key would be accepted and never honoured"를 막는 검사. 하지만 starter(`GrpcPlatformAutoConfiguration`)는 ledger bean도 `GrpcIdempotencyInterceptor`도 만들지 않고, `GrpcIdempotencyInterceptor`의 호출자는 테스트(`GrpcIdempotencyInterceptorTest`)뿐이다. 플래그를 `true`로 두면 검증은 통과하고 key는 여전히 처리되지 않는다. `adapter/inbound/websocket/CLAUDE.md` 「Forbidden」의 "하지 않는 동작에 대한 설정 키 금지"와 같은 원칙을 이 family는 어긴다 |
|
||||
| 영향 | 운영자가 멱등 처리가 켜졌다고 믿는다 |
|
||||
| 심각도·우선순위 | Medium · P2(optional build, 채택 시 문제) |
|
||||
| 결정의 근거 | 대안 (a) 플래그를 지우고 validator는 `GrpcOperationLedger` bean 존재로 판단, (b) 플래그가 true면 ledger bean + 서버 interceptor를 조립. 고른 방향: (a). 서버 interceptor 조립은 "플랫폼 배선은 별도 결정"(`src/grpc/CLAUDE.md`)에 속하므로, 그 전까지는 거짓 약속만 없앤다 |
|
||||
| 완료 기준 | 플래그 삭제, ledger bean이 없으면 `IDEMPOTENCY_KEY_REQUIRED` method가 기동 거부되는 context test |
|
||||
| 검증 방법 | `GrpcPlatformAutoConfigurationContextTest` |
|
||||
|
||||
### 03-12 ledger PG lane은 main push·nightly에서만 돌고 PR·릴리스 게이트에 없다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험(게이트 범위) |
|
||||
| 관련 관점 | 10, 18, 21 |
|
||||
| 근거 | `.github/workflows/integration-main.yml:329-345` job `grpc-optional-platform-integration`이 `-p optional-platforms integrationCheck`를 push(main)와 nightly cron에 실행한다. PR 게이트(`ci-quality-gates.yml:66-73`)는 `-p optional-platforms ci`만, 릴리스(`release.yml:128-147` `grpc-stable-release-gate`)는 testkit lane 3개만 부른다. integration-main은 머지 뒤 알리는 단계라 tag 릴리스가 이 lane 결과를 보지 않는다. 오늘 로컬 실행은 18건 통과 |
|
||||
| 영향 | ledger SQL을 깨는 변경이 PR에서 통과하고, main이 빨간 상태로 tag가 나갈 수 있다 |
|
||||
| 심각도·우선순위 | Low · P3. 플랫폼이 아직 채택되지 않았고, 다음 main push에서 드러난다 |
|
||||
| 결정의 근거 | 적용 제외 — 기존 단계 설계(container lane은 stage 2) 안에서 릴리스 needs 한 줄 문제 |
|
||||
| 최소 개선 방향 | `release.yml` gRPC gate에 `-p optional-platforms integrationCheck` 추가(PR 예산은 그대로) |
|
||||
| 완료 기준·검증 | `release.yml` needs와 실행 목록에 포함, 릴리스 dry-run에서 lane 실행 확인 |
|
||||
|
||||
## 4. 31절 시나리오 추적
|
||||
|
||||
### 4.1 큰 입력·목록 조회 — GraphQL `POST /graphql`
|
||||
|
||||
```text
|
||||
HTTP body ─> GraphQlRequestBodyLimitFilter(raw cap, 413)
|
||||
─> Spring GraphQL decode ─> GraphQlPlatformWebInterceptor
|
||||
├─ document bytes ≤ 16 KiB, variables bytes ≤ 64 KiB, JSON 구조·extension allowlist
|
||||
├─ principal resolver → GraphQlRequestContext(deadline = now + 10s)
|
||||
─> parse/validate(BoundedPreparsedDocumentProvider 캐시)
|
||||
─> GraphQlPlatformInstrumentation → GraphQlExecutionChain
|
||||
├─ OperationSelection(named 필요 여부)
|
||||
├─ DocumentAuthorization(좌표 규칙, fragment 1회 전개)
|
||||
└─ CostBudget: deadline 1회 확인 → 깊이·필드·alias·fragment 상한 → 복잡도 점수
|
||||
─> resolver 실행 (시간 상한 없음)
|
||||
─> 오류는 GraphQlWireErrorMapper 하나
|
||||
```
|
||||
|
||||
| 항목 | 결과 |
|
||||
| --- | --- |
|
||||
| 입력 신뢰 수준 | 신뢰하지 않음. 바이트·구조 상한은 parse 전에 걸린다(M3) |
|
||||
| 인가 위치 | 문서 단위 좌표 인가는 실행 전(`GraphQlDocumentAuthorizationHandler`). 객체 단위 인가는 `modelled`(요청 경로 없음) — adopter resolver 책임 |
|
||||
| 규칙 소유 | 상한 값은 `GraphQlClientPolicy` 하나 |
|
||||
| 트랜잭션 | 이 leaf는 열지 않는다. use case 몫 |
|
||||
| 외부 부작용 | 없음(health 표면만) |
|
||||
| 성공의 의미 | 상한·인가·예산을 통과하고 resolver가 응답 |
|
||||
| 오류 변환 | 플랫폼 거부 → `ApiErrorCarrier` → 등록 매핑 → `IllegalArgumentException`=`BAD_PARAMETER` → 나머지 `INTERNAL_ERROR` + ERROR 로그(executionId) |
|
||||
| 진단 정보 | executionId, MDC requestId, operation name은 allowlist일 때만 metric label |
|
||||
| 판정 | 깊이·alias·문서 크기는 막힌다(변이 1). **목록 크기는 막히지 않는다(03-01). 실행 시간도 막히지 않는다(03-02)** |
|
||||
|
||||
### 4.2 종료·재시작 — WebSocket
|
||||
|
||||
| 경로 | 결과 |
|
||||
| --- | --- |
|
||||
| STOMP 채널 | Spring `SubProtocolWebSocketHandler`의 lifecycle stop이 세션을 GOING_AWAY로 닫는다(Spring 동작, 이 leaf 테스트 없음). broker 큐에 남은 live event는 버려진다(R1 문서화) |
|
||||
| 라이브러리 handler | context close → `stop()`(DEFAULT_PHASE)이 열린 연결에 1001 → web server graceful 종료. `TomcatWebSocketShutdownIT`로 E2. stop 뒤 새 연결은 빠진다(03-08) |
|
||||
| gRPC 어댑터 | `GrpcServerRunner.stop()`이 health terminal → `shutdown()` → `shutdownGraceSeconds`(5초) 대기 → `shutdownNow()`. drain 대기 없음(03-09) |
|
||||
|
||||
### 4.3 중복·동시 요청 — gRPC operation ledger
|
||||
|
||||
| 항목 | 결과 |
|
||||
| --- | --- |
|
||||
| 요청 식별 | `GrpcOperationIdentity`(caller 지문, method, key 해시). 컬럼 폭 검증(N-11b) |
|
||||
| DB 제약 | PK `storage_key` + UNIQUE(caller, method, key hash). `INSERT … ON CONFLICT DO NOTHING`의 affected row로 승자 결정. PG lane `concurrentClaimsHaveExactlyOneOwner` 통과(E3, 로컬) |
|
||||
| 실패 뒤 재시도 | FAILED_TERMINAL은 같은 fingerprint 한 번만 재claim(`tryReclaimFailed`) |
|
||||
| 결과 불명 | 소유자가 죽은 IN_PROGRESS는 회수 경로가 없다(03-10) |
|
||||
| 실제 요청 경로 | 없음. 판단 함수만 있고 서버 interceptor가 없다(03-11) |
|
||||
|
||||
### 4.4 외부 응답 지연 — gRPC deadline
|
||||
|
||||
| 항목 | 결과 |
|
||||
| --- | --- |
|
||||
| 플랫폼 | `GrpcDeadlineBudget`이 단조 시계 절대 deadline으로 바뀜(N-2 해결). 하위 호출 budget 계산 라이브러리 |
|
||||
| 어댑터 | 클라이언트 deadline은 io.grpc가 취소로 전달하지만, deadline 없는 호출에 서버 기본값이 없고 executor도 무제한(03-09) |
|
||||
|
||||
### 적용 제외
|
||||
|
||||
| 시나리오 | 사유 |
|
||||
| --- | --- |
|
||||
| 정상 쓰기 요청 | 세 어댑터 모두 feature mutation이 없다(health 표면만) |
|
||||
| DB 오류·경쟁 | ledger 외 DB 접근 없음. ledger는 4.3에서 다룸 |
|
||||
| 메시지 중복·역순 | 영역 10(messaging) |
|
||||
| 신·구 버전 공존 | gRPC proto 호환은 Buf breaking(CI job `grpc-proto-buf`)이 맡는다. 이번에 미실행 — 다른 영역(13 빌드·CI)과 겹침 |
|
||||
| 여러 서버의 작업 실행 | 이 영역에 scheduler 없음 |
|
||||
| 세션·토큰 갱신 경쟁 | 인증은 HTTP 계층·adopter resolver 몫. WebSocket 연결 수명 동안 토큰 재확인이 없다는 점만 03-06에 기록 |
|
||||
| 다른 사용자 리소스 접근 | GraphQL 객체 인가는 `modelled`(요청 경로 없음), 결정 35로 보류. feature resolver가 없어 따라갈 요청이 없다 |
|
||||
| 선택 어댑터 제거 | `conditionalTransportQualification`·`conditionalTransportBuildContractTest`가 mainCheck에서 통과(오늘). 영역 12(bootstrap)와 겹쳐 상세는 생략 |
|
||||
|
||||
## 5. 41절 설계 선택 검토
|
||||
|
||||
### 5.1 GraphQL 비용 제한을 플랫폼 자체 scorer로 둔 것
|
||||
|
||||
1. **필요한 것**: 실행 전에 비싼 문서를 거절. 대상은 adopter가 나중에 붙일 임의 스키마.
|
||||
2. **지킬 성질**: 거절 판단이 실제 작업량의 상한이어야 한다. 특히 list 크기에 비례해야 한다.
|
||||
3. **현재 보장**: 깊이·필드·alias·fragment 상한은 지켜진다(변이 1). 복잡도는 페이지 인자가 값으로 보일 때만 곱한다. list 기본 배수·변수 기본값은 반영하지 않는다(03-01, E2).
|
||||
4. **대안**: (a) graphql-java `MaxQueryComplexityInstrumentation` + `FieldComplexityCalculator`, (b) 현재 scorer를 고친다, (c) 깊이·필드 상한만 남기고 복잡도는 버린다.
|
||||
5. **얻고 지불하는 것**: (a)는 graphql-java가 coerced 변수·기본값을 계산해 준다. 대신 플랫폼의 페이지 상한 거부·카탈로그 가중치를 calculator로 다시 써야 하고, 테스트가 바뀐다. (b)는 코드 변경이 작지만 변수 coercion을 직접 맞춰야 한다. (c)는 가장 단순하지만 `first: 100`을 12단 중첩하는 문서를 막지 못한다.
|
||||
6. **현재 조건의 선택**: (b). 기존 카탈로그·거부 코드와 테스트를 유지하면서 구멍만 막는다. 변수는 graphql-java `ValuesResolver`로 coercion하면 (a)의 장점을 가져온다.
|
||||
7. **바뀌는 조건**: adopter가 federation·persisted query처럼 graphql-java 표준 계측을 함께 쓰게 되면 (a)로 옮기는 편이 두 벌 유지를 줄인다.
|
||||
|
||||
### 5.2 gRPC를 두 스택(어댑터 서버 + vendored 플랫폼)으로 둔 것
|
||||
|
||||
1. **필요한 것**: 지금은 loopback unary 하나. 나중에 TLS·streaming·멱등성이 필요할 수 있다.
|
||||
2. **지킬 성질**: production 서버가 문서가 말하는 한도로 동작한다.
|
||||
3. **현재 보장**: 어댑터 서버는 io.grpc 기본값. 플랫폼 한도는 testkit 서버에만 적용(03-09). 멱등성은 판단 함수와 ledger만 있고 서버 경로가 없다(03-11).
|
||||
4. **대안**: (a) 현상 유지 + 어댑터에 한도 명시, (b) 어댑터가 플랫폼 `grpc-runtime`을 받는다(registry edge 추가), (c) 플랫폼을 템플릿에서 빼고 필요할 때 가져온다.
|
||||
5. **얻고 지불하는 것**: (a)는 작고 두 스택 결정을 건드리지 않는다. 같은 한도 값을 두 곳이 갖는 중복은 남는다. (b)는 증거(Netty lane)가 production 서버를 가리키게 되지만 플랫폼 143개 파일이 어댑터 의존에 들어온다. (c)는 유지비를 없애지만 소유자가 만든 플랫폼을 버린다.
|
||||
6. **선택**: 소유자 결정(X1-#10 수용, "배선은 별도 결정")을 존중해 (a). 중복 값은 `GrpcTransportLimits` 값을 어댑터 문서에 인용해 두 곳이 같다는 사실을 테스트로 고정한다.
|
||||
7. **바뀌는 조건**: TLS·외부 bind(P2)를 열거나 streaming이 필요해지면 (b)를 다시 본다. 그때 03-10·03-11이 먼저 닫혀야 한다.
|
||||
|
||||
### 5.3 WebSocket live push를 simple broker + best-effort로 둔 것
|
||||
|
||||
1. **필요한 것**: 단일 노드에서 도메인 이벤트 알림.
|
||||
2. **지킬 성질**: 발행 스레드를 느리게 하지 않는다. 한 사용자가 다른 사용자의 수신을 막지 않는다.
|
||||
3. **현재 보장**: broker 채널 bounded executor(K-11b, 테스트 있음), 꽉 차면 drop. 구독·연결 수 상한이 없어 한 사용자가 큐를 채울 수 있다(03-06).
|
||||
4. **대안**: (a) 현상 + 세션당 구독 1·연결 상한, (b) broker relay(RabbitMQ·ActiveMQ), (c) SSE로 전환.
|
||||
5. **비용**: (a)는 interceptor 몇 줄. (b)는 운영 인프라 추가. (c)는 STOMP 클라이언트 계약을 깨고 servlet 스레드 점유 모델이 다르다.
|
||||
6. **선택**: (a). README가 이미 단일 노드 best-effort라고 선언했고, 그 범위 안에서 공정성만 막으면 된다.
|
||||
7. **바뀌는 조건**: 다중 노드 전달이나 재전송이 요구되면 (b).
|
||||
|
||||
## 6. 리팩토링 후보
|
||||
|
||||
| 대상 | 무엇을 왜 | 보존 조건 |
|
||||
| --- | --- | --- |
|
||||
| `GraphQlDataLoaderRequestRegistry` + `GraphQlDataLoaderFactory.newRequestRegistry()` | 도달 불가 중복 경로 삭제(03-04) | registrar 요청 스코프, `cacheScope()` 지문, API surface 재승인 |
|
||||
| `GraphQlTimeoutPolicy` | main 호출자 0. 03-02에서 쓰거나 삭제 | `REQUEST_TIMEOUT` wire code 유지 |
|
||||
| `GraphQlPlatformWebInterceptor` 생성자 10개 | anonymous 3값을 record 하나로(S5-#14e) | 거부 순서·오류 코드·`GraphQlRequestStageErrorMappingTest` |
|
||||
| `TomcatWebSocketAbuseIT.shutdownClosesLiveConnections` | `TomcatWebSocketShutdownIT`와 중복, 시간 경계 flaky(P25-new-1). 삭제하거나 "close code만" 단언으로 축소 | 1001 단언은 ShutdownIT가 계속 가진다 |
|
||||
| `TomcatWebSocketAbuseIT` inline FQN 9곳 | import로 | 없음(형식만) |
|
||||
| `GrpcClientMessageDeduplicator` | 세션별 map으로 나눠 `endSession` O(1)(N-12a) | 중복 판정 결과, 세션 종료 후 outcome 미보존 |
|
||||
| gRPC 어댑터 `GrpcServerSettings` | 한도 값을 `GrpcTransportLimits`와 같은 이름·값으로(03-09) | `ignoreUnknownFields=false` 바인딩, loopback 강제 |
|
||||
|
||||
## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료)
|
||||
|
||||
### 7.1 템플릿이 주는 틀
|
||||
|
||||
| 기능 | 주는 것 | 빠진 것 |
|
||||
| --- | --- | --- |
|
||||
| GraphQL 필드 추가 | `classpath:graphql/*.graphqls` 병합, `@Controller` 자동 바인딩, 플랫폼 상한·인가·비용·오류 매핑, `GraphQlBatchLoaderRegistrar`, 전송 경계 ArchUnit | feature 예시(sample에 GraphQL 없음), 목록 필드 비용 규약(03-01), DataLoader 조립 예(03-03), 실행 시간 상한(03-02) |
|
||||
| WebSocket 서버 push | `LiveEventProjector<T>` 하나 등록하면 broadcast, bounded 채널 | projector 예시(sample 0), 연결·구독 상한(03-06) |
|
||||
| WebSocket 요청/응답 | `PlatformWebSocketHandler` + budget, README 조립 예 | 연결 수 상한, stop 뒤 연결 처리(03-08) |
|
||||
| gRPC 서비스 | `@GrpcExposedService` + `GrpcAuthenticationPolicy` 하나, 오류 매핑, health | `.proto` 예시, 서버 한도(03-09), TLS(P2) |
|
||||
| gRPC 멱등 mutation | ledger 테이블·JPA 어댑터·판단 함수 | 서버 interceptor, stale claim 회수(03-10·03-11) |
|
||||
|
||||
### 7.2 개발자가 내려야 하는 판단
|
||||
|
||||
1. **어느 전송인가.** 요청/응답이면 web. 서버가 먼저 알려야 하면 STOMP 채널. 연결 하나에서 명령을 주고받으면 라이브러리 handler. 내부 서비스 간이면 gRPC(지금은 같은 Pod만).
|
||||
2. **GraphQL list 필드를 만들 때.** connection(`first`/`last`)으로 둘지 일반 list로 둘지 정한다. 지금 scorer는 인자가 값으로 보일 때만 곱한다. 03-01 수정 전까지는 모든 list에 `first` 인자를 필수(non-null)로 두는 것이 안전하다.
|
||||
3. **자식 필드를 어떻게 가져오나.** 부모가 list면 `GraphQlBatchLoaderRegistrar.register`로 batch loader를 쓴다. `@BatchMapping`은 플랫폼 chunk·deadline이 붙지 않는다.
|
||||
4. **비용 가중치.** 외부 호출이 있는 필드는 `GraphQlCostCatalog`에 `EXTERNAL_PER_OBJECT`로 등록한다. 등록하지 않으면 모두 10이다.
|
||||
5. **오류 코드.** product 오류는 `ApiErrorCode`를 가진 예외(`ApiErrorCarrier`)로 던진다. GraphQL 전용 코드는 `GraphQlErrorCode.platform`에 `GRAPHQL_` 접두로만.
|
||||
6. **WebSocket 연결 상한.** 프록시(Nginx `limit_conn`)에서 둘지 앱에서 둘지 정한다. 지금 앱에는 없다.
|
||||
7. **gRPC 멱등성.** `IDEMPOTENCY_KEY_REQUIRED` method는 03-10·03-11이 닫히기 전에는 application `IdempotencyExecutor`를 use case 안에서 쓰는 쪽이 안전하다(websocket `CLAUDE.md`와 같은 권고).
|
||||
8. **opt-in 절차.** `runtimeOnly` 한 줄 + registry edge + env key 등록 + `conditionalTransportQualification` 실행. 세 leaf `CLAUDE.md` 「Adopting」 절이 순서를 준다.
|
||||
|
||||
## 8. 28개 관점 판정표
|
||||
|
||||
기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역.
|
||||
|
||||
| # | 관점 | 판정 | 이유 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 코드 성숙도 | P | 대부분 정돈. 동시성 누수(03-07)·비용 계산 구멍(03-01) |
|
||||
| 2 | 구조적 성숙도 | P | inbound→outbound 금지·전송 경계 ArchUnit은 M3. gRPC 두 스택이 같은 한도를 따로 가진다(03-09) |
|
||||
| 3 | 변경 용이성 | P | GraphQL auto-config가 기능별 8개로 나뉨(S5-#7a). 비용 규칙을 바꾸려면 scorer·calculator·policy 세 곳을 같이 봐야 한다 |
|
||||
| 4 | 인지 부하 | P | 등급표·README가 잘 돼 있음. 죽은 registry를 장치로 설명(03-04), graphql 주석 32% |
|
||||
| 5 | 위험 가시성 | X | 실행 시간 상한(03-02)·ledger 플래그(03-11)·STOMP 전송 한도(03-06)가 코드에 없거나 약속과 다르다 |
|
||||
| 6 | 실패 성숙도 | P | 오류 매핑 단일화·마스킹+로그는 O. stale claim·종료 창·deadline 미강제 |
|
||||
| 7 | 운영 성숙도 | P | 1001 종료·health terminal 있음. gRPC drain 대기 없음 |
|
||||
| 8 | 디버깅 가능성 | P | executionId·requestId 연결 O. batch context 누락이 timeout으로 보임(03-05) |
|
||||
| 9 | 유지보수 성숙도 | P | 남은 W5 nit 다수(S5-#14d·#14e, K-12c, N-12) |
|
||||
| 10 | 테스트 성숙도 | P | 변이 2개 모두 잡힘. list 필드·scorer 단위 테스트 없음(03-01). shutdown 테스트 시간 경계 flaky(P25-new-1) |
|
||||
| 11 | 데이터 성숙도 | P | ledger DB 제약·마이그레이션 PG 검증 O. 보존·정리 없음(03-10) |
|
||||
| 12 | 동시성 성숙도 | P | claim 원자성 E3, gRPC admission·rotation 경합 수정(N-5). writer close 경합(03-07) |
|
||||
| 13 | 확장성 | X | 연결·구독 수 상한 없음(03-06), gRPC executor 무제한(03-09) |
|
||||
| 14 | 성능 성숙도 | P | 문서 캐시·bounded 채널 O. 비용 점수가 실제 작업과 비례하지 않음(03-01). 실부하 증거 없음 |
|
||||
| 15 | 보안 성숙도 | P | handshake principal·origin allowlist·introspection off·좌표 인가 O. 목록 크기 DoS(03-01), 구독 증폭(03-06) |
|
||||
| 16 | 의존성 성숙도 | O | grpc BOM·lockfile, 플랫폼 별도 build, registry edge 최소 |
|
||||
| 17 | API / Contract 성숙도 | P | wire 오류 코드 카탈로그·API surface 스냅샷 O. 설정 키가 약속만 함(03-11), README 설명 엇갈림(P15-new-4) |
|
||||
| 18 | 배포 성숙도 | P | build-time opt-in 명확. ledger lane이 릴리스 게이트 밖(03-12) |
|
||||
| 19 | 설정 성숙도 | P | `ignoreUnknownFields=false`, `@Validated`, 필수 deployment-mode O. 숨은 기본값(STOMP·gRPC) |
|
||||
| 20 | 개발자 경험 | P | 「Adopting」 절차 O. GraphQL·WebSocket feature 예시 없음 |
|
||||
| 21 | Guardrail 성숙도 | P | strict lane(no-skip)·전송 경계 ArchUnit·production 인가 정책 강제 O. 비용·deadline 가드 부재 |
|
||||
| 22 | 추상화 성숙도 | P | 판단 함수 + port 구조는 적절. 쓰이지 않는 `GraphQlTimeoutPolicy`·registry |
|
||||
| 23 | 일관성 | P | 오류 문구 shared 표 통일 O. 같은 한도가 두 gRPC 스택에 따로 |
|
||||
| 24 | 네이밍 / 의미 성숙도 | P | 대체로 명확. `operation-ledger-enabled`가 실제 의미와 다름 |
|
||||
| 25 | 조직 확장성 | - | 이 영역 단독으로 판단할 근거 없음(팀·소유 정보 없음) |
|
||||
| 26 | Ownership 성숙도 | P | leaf별 `CLAUDE.md`가 소유 규칙을 가짐. root family 표에 gRPC 행 없음(S7-lead-2) |
|
||||
| 27 | 삭제 가능성 | O | 세 어댑터 모두 한 줄 제거로 빠지고 `conditionalTransportQualification`이 확인(오늘 통과) |
|
||||
| 28 | 회복 가능성 | X | stale `IN_PROGRESS` 회수 불가(03-10), 예산 누수는 재시작 전 회복 불가(03-07) |
|
||||
|
||||
### 성능·테스트 시간 메모
|
||||
|
||||
오늘 게이트의 테스트 결과 XML(testsuite time 합, JVM·Spring 기동 시간 제외):
|
||||
|
||||
| lane | 건수 | 시간 |
|
||||
| --- | --- | --- |
|
||||
| websocket `test` / `systemTest` / `websocketJettyTest` / `websocketTransportQualificationTest` | 74 / 18 / 8 / 5 | 3.6초 / 1.8초 / 0.9초 / 1.9초 |
|
||||
| graphql `test` / `systemTest` / `graphqlStableTest` / `graphqlTransportQualificationTest` | 377 / 25 / 4 / 8 | 9.7초 / 2.1초 / 0.3초 / 1.9초 |
|
||||
| grpc 어댑터 `test` / `grpcTransportQualificationTest` | 48 / 20 | 2.7초 / 2.3초 |
|
||||
| ledger `integrationTest`(로컬) | 18 | 0.55초(+ container 기동) |
|
||||
|
||||
실행 시간은 과하지 않다. 비용은 기동 쪽에 있다(graphql systemTest가 random-port 서버를 띄움). 요청당 복잡도 계산 비용은 측정하지 않았다(scorer 방문 노드 상한 200,000이 상한).
|
||||
@@ -0,0 +1,480 @@
|
||||
# 04 Persistence — 성숙도 리뷰 (2026-11-01)
|
||||
|
||||
영역: `adapter:outbound:persistence-jpa`, `adapter:outbound:persistence-mongo`,
|
||||
`adapter:outbound:persistence-fileserver`, `adapter:outbound:persistence-notification`, Flyway 마이그레이션과 스키마.
|
||||
|
||||
## 1. 범위
|
||||
|
||||
| 항목 | 기록 |
|
||||
| --- | --- |
|
||||
| 대상 | `clean-architecture-backend-template`, Gradle 루트 `src/` |
|
||||
| 커밋 | `main` @ `01a8a2a70` (리뷰 후속 Wave 1–3 머지 직후). 작업 트리 깨끗함 |
|
||||
| 목적·지원 구성 | 템플릿(reference implementation). 파생 서비스가 복사해 쓴다. JPA·Mongo는 `runtimeOnly` 한 줄로 켜는 capability다. 다중 인스턴스를 전제로 한 장치(outbox lease fencing, `FOR UPDATE SKIP LOCKED` claim)가 있으므로 다중 인스턴스를 지원 구성으로 본다 |
|
||||
| 규모·운영 목표 | 문서에 합의된 수치 없음. 그래서 "대규모 운영 준비" 판정은 하지 않는다 |
|
||||
| 읽은 코드 | 네 leaf의 `src/main`(JPA 193개·Mongo 278개·notification 48개·fileserver 27개 파일)의 트랜잭션·예외 변환·엔티티·쿼리·claim 경로, `src/test`·`postgresqlIntegrationTest`·`testFixtures`의 관련 부분, 각 `build.gradle`, 루트 `src/build.gradle` lifecycle, `.github/workflows/*.yml`, `config/module-defaults/persistence-jpa.yml`, 마이그레이션 디렉터리 9곳, `docs/jpa/*.md`, ADR-JPA-003. sample의 WorkLog 영속 경로(참조 패턴으로서) |
|
||||
| 위임 조사 | Mongo leaf, notification·fileserver leaf는 읽기 전용 하위 조사로 나눠 읽었다. High로 올린 항목과 핵심 근거는 내가 코드를 다시 열어 확인했다 |
|
||||
| 실행한 명령 | 아래 표 |
|
||||
| 확인 못 한 것 | Mongo 컨테이너 lane(현재 커밋 미실행. 결과 XML은 09-28 것), JPA platform 태그 lane(`jpaPlatformContractTest` 등, 현재 커밋 미실행), 04-05의 실제 중복 처리 재현, 04-11의 실제 WriteConflict 재현, 쿼리 수 실측(04-09는 계산값) |
|
||||
| 이전 리뷰와 비교 | techlead `05`·`06`, followup-status E·F·S2 행과 persistence 관련 TEST·X1·S6·S7·P*·ORCH 행 |
|
||||
|
||||
실행한 명령 (모두 scratchpad worktree `wt-04`에서, `flock heavy.lock` 안에서 실행. 끝난 뒤 worktree 삭제):
|
||||
|
||||
| 명령 | 부하(uptime 1분) | 결과 |
|
||||
| --- | --- | --- |
|
||||
| `./gradlew :adapter:outbound:persistence-jpa:test` (+ 실험 테스트 1개 파일 추가) | 26.38 | 통과. 503개, 테스트 시간 합 8.6초, wall 2분 29초(컴파일 포함, 고부하) |
|
||||
| `./gradlew :adapter:outbound:persistence-jpa:postgresql{FileserverMetadata,FileserverReclamation,Idempotency,Migration}IntegrationTest --continue` | 14.03 | 4개 lane 모두 통과. 16/15/8/5개, 테스트 시간 4.9/0.6/4.5/8.1초, Gradle 56초(lock 대기 포함 wall 181초) |
|
||||
| `./gradlew :adapter:outbound:persistence-jpa:test --tests '*ScratchReview*'` | 7.92 | 실험 3개 통과(04-01·04-02·04-03 근거) |
|
||||
|
||||
게이트 결과(오케스트레이터 실행, `scratchpad/gates`): `ci rc=0`(434초). `mainCheck rc=1` — 원인은 objectstorage MinIO 이미지 pull 실패 2건이고 이 영역과 무관하다. 이 영역에서 `ci`가 돌린 것은 `persistence-jpa:test`(502개, 16.6초), `persistence-notification:test`(19개, 1.1초), `persistence-mongo:test`(79개, 6.1초)·`mongoStableContractTest`(465개, 6.1초)다. `persistence-fileserver:test`는 `NO-SOURCE`다. `mainCheck`에서 이 영역이 실제로 돌린 테스트는 `mongoDocumentContractTest`(2개)뿐이다. 실 DB lane은 두 게이트 어디에도 없다.
|
||||
|
||||
### 0.1 전제
|
||||
|
||||
| 전제 | 기록 |
|
||||
| --- | --- |
|
||||
| 사용 목적 | 사내 서비스 시작점 템플릿. 파생 서비스(tech-log-backend 등)가 복사한다 |
|
||||
| 지원 실행 형태 | 다중 인스턴스 서버(근거: outbox·durable operation·recipient lease의 fencing 설계) |
|
||||
| 데이터와 권한 | 알림 수신 거부·연락처(개인정보 해시), 파일 메타데이터·쿼터, 멱등성 기록 |
|
||||
| 의존 시스템 | PostgreSQL(주), H2(로컬 전용), MongoDB(선택, 소비자 0) |
|
||||
| 운영 목표 | 미정. 허용 지연·데이터 손실·복구 시간 수치 없음 |
|
||||
| 지원·비지원 | JPA: PostgreSQL만 운영 대상. Mongo: imperative만, outbox·멱등성·lock 미지원 |
|
||||
|
||||
## 2. 지난 발견 재확인
|
||||
|
||||
경로 약어: `PJ` = `src/adapter/outbound/persistence-jpa`, `PM` = `src/adapter/outbound/persistence-mongo`, `PN` = `src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform`, `PF` = `src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver`.
|
||||
|
||||
| ID | 상태 | 근거 |
|
||||
| --- | --- | --- |
|
||||
| E-3c canonical append ownership 테스트 | 해결 | 테스트가 `PJ/src/test/.../outbox/jpa/JpaOutboxStoreTest.java:157-174`(append·claim·mark의 트랜잭션 없는 호출 거부)로 옮겨졌다 |
|
||||
| E-4c inbox 테스트가 운영 쿼리 복사본 실행 | 바뀜 | 이제 `@Query` 어노테이션에서 SQL을 읽어 실행한다(`PJ/src/postgresqlIntegrationTest/.../PostgreSqlInboxCutoffIntegrationTest.java:122-147`). 아직 adapter(`JpaNotificationInbox.markAllRead`)를 거치지 않는다. `'UNREAD'`는 fixture INSERT(`:165`)에만 남았다 |
|
||||
| E-5c README "aggregate당 최대 한 row" | 남음 | `PJ/README.md:255` 문장 그대로 |
|
||||
| E-6a tenant 규칙이 필드 이름 `tenantId`로만 판정 | 남음 | `PJ/src/testFixtures/.../testkit/arch/TenantScopedRepositoryPredicate.java:19,49-51` |
|
||||
| E-12 CLAUDE.md 벤더 표에 `55P03` 누락 | 남음 | `PJ/CLAUDE.md:273-279`에 없음. 코드는 `PJ/src/main/.../postgresql/PostgreSqlSqlStateErrorMapping.java:20`에서 매핑 |
|
||||
| F-1d security lane "injection" 과장 | 바뀜 | 단위 테스트에 `$ne`·`$gt` 거부가 생겼다(`PM/src/test/.../query/PolicyAwareMongoQueryBuilderTest.java:121-161`). lane 설명(`PM/build.gradle:209`)은 여전히 injection을 주장하지만 lane 테스트(`MongoSecurityIntegrationLaneTest.java:93-165`)에는 없다 |
|
||||
| F-5d CSFLE 테스트·호출자 없음 | 바뀜 | 테스트 5개 추가(`MongoCsfleClientFactoryTest.java:59-124`). leaf 밖 호출자는 0. README "테스트 없는 진입점"(`PM/README.md:165-167`)에 5개가 남음 |
|
||||
| F-9a inline FQN | 남음 | `PM/src/main/.../autoconfigure/MongoPlatformAutoConfiguration.java` 37줄(:62, :69, :129-166 외). 규칙 `PM/CLAUDE.md:70` |
|
||||
| S2-#8b "두 조립 루트가 adapter를 스캔" 서술 | 남음 | `PJ/src/test/.../CandidateAdapterCompositionTest.java:6-14`, `PJ/src/main/.../idempotency/postgresql/PostgreSqlIdempotencyStore.java:52` |
|
||||
| S2-#12 이력 서술 Javadoc | 남음 | 네 문구("used to" 등) JPA main 16줄, Mongo main 41개 파일 51회 |
|
||||
| S2-#14a JPA CLAUDE.md의 "NoSQL은 미래 모듈"·MapStruct 절 | 남음 | `PJ/CLAUDE.md:17-19, 317-340` |
|
||||
| S2-#14b API surface에 옮겨간 타입 | 해결 | `docs/architecture/jpa-adopter-api-surface.txt`에 `FileserverSchemaActivation` 없음 |
|
||||
| S2-lead-2 / X1-#3b 멱등성 공통 계약 | 남음 | testFixtures 어디에도 `IdempotencyStoreContract` 없음 |
|
||||
| TEST-F-2a claim 순서 단언 없음 | 남음 | `PJ/src/postgresqlIntegrationTest/.../platform/PostgreSqlWorkClaimContractTest.java:78-86` `isNotEmpty()`만 |
|
||||
| TEST-FAKE-DeliveryProjectionStorePort | 남음 | fake 3개, 공통 계약 없음 |
|
||||
| S7-lead-4 / X1-#6d recipient lease 공통 fencing 계약 | 남음 | PG IT 하나뿐(`PostgreSqlRecipientLeaseFencingIntegrationTest`) |
|
||||
| ORCH-new-2 `NotificationPayloadAtRestContractTest` inputs 미선언 | 남음 | `src/adapter/outbound/notification/src/test/.../NotificationPayloadAtRestContractTest.java:155-163`가 다른 leaf의 V10 SQL을 읽는데 `notification/build.gradle`에 `inputs` 없음 |
|
||||
| P4-new-1 fileserver migration 불변성 테스트 없음 | 해결 | `PJ/src/test/.../migration/AppliedMigrationImmutabilityTest.java:39-43`이 notification·fileserver 디렉터리도 검사. inputs 선언 `PJ/build.gradle:267-271` |
|
||||
| P20-new-5 / 결정 36 JPA 설정 prefix | 남음 | 플랫폼 키가 아직 `app.persistence.vendor`, `app.runtime.migration-on-startup`에 있다(`PJ/src/main/resources/config/module-defaults/persistence-jpa.yml:160-164`, `PostgreSqlIdempotencyStoreConfig.java:38`). 결정 36은 이것을 `app.persistence-jpa.*`로 모으라고 했다(Wave 4 P33 예정) |
|
||||
| S6-#16c hikari 이력 주석 | 남음 | `persistence-jpa.yml:33-37` |
|
||||
| S6-#16e OSIV 예외 메시지의 문서 ID | 남음 | `PJ/src/main/.../startup/OpenInViewSafetyValidator.java:29` |
|
||||
|
||||
남은 High/P1급 지난 발견: 없음. 남은 항목은 모두 W4(테스트)·W5(문서) 성격이다.
|
||||
|
||||
## 3. 새 발견
|
||||
|
||||
심각도 순. 단순 결함은 설계 선택 필드를 `적용 제외`로 둔다.
|
||||
|
||||
### 04-01 커밋 중 연결이 끊기면 "재시도 가능(DB_UNAVAILABLE)"으로 답한다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 6 실패, 12 동시성, 17 계약, 11 데이터, 5 위험 가시성 |
|
||||
| 근거 | `PJ/src/main/.../failure/PersistenceExceptionTranslator.java:24,97` — SQLState가 `08`로 시작하면 무조건 `DB_UNAVAILABLE`. `OperationalError.DB_UNAVAILABLE`은 `retryable=true`(`src/shared-contract/.../OperationalError.java:54`). `SpringTransaction.execute`(`PJ/src/main/.../transaction/SpringTransaction.java:98-105`)는 커밋 실패도 같은 번역기로 보낸다. `TransactionCompletionUnknownException`은 main 어디에서도 생성되지 않는다(생성자 호출 0건). 실험: `TransactionSystemException(SQLException "08006")`을 커밋에서 던지는 `PlatformTransactionManager`로 `inWrite`를 호출 → `DB_UNAVAILABLE retryable=true`(E2). web은 retryable 코드에 `Retry-After`를 붙인다(`src/adapter/inbound/web/.../observability/RetryAfterAdvisor.java:29`) |
|
||||
| 발생 조건 | 커밋 요청을 보낸 뒤 응답 전에 DB 연결이 끊김(장애 조치, 네트워크 단절, `pg_terminate_backend`) |
|
||||
| 영향 | 서버는 커밋했을 수 있다. 클라이언트는 "일시 장애, 다시 시도"를 받고 같은 쓰기를 다시 보낸다. 멱등성 키가 없는 쓰기는 중복된다. ADR-JPA-003("completion unknown은 자동이든 아니든 재시도하지 않는다")과 반대다 |
|
||||
| 심각도·우선순위 | High / P1. 데이터 중복으로 이어지는 도달 가능한 경로이고, 기본 조립의 모든 쓰기 유스케이스가 지난다. 템플릿을 복사하면 그대로 퍼진다 |
|
||||
| 확실성 | 분류 결과는 실험으로 확인. 실제 PG에서 같은 SQLState가 나오는지는 `PostgreSqlTransactionIntegrationTest:147-197`이 연결 종료를 재현하지만 결과 코드를 단언하지 않아 미확인 |
|
||||
| 결정의 근거 | 적용 제외 — 기대 계약(ADR-JPA-003)이 이미 정해져 있다 |
|
||||
| 이해 비용 | 쓰기 유스케이스 작성자는 "503+Retry-After면 재시도해도 안전한가"를 코드에서 알 수 없다 |
|
||||
| 최소 개선 방향 | `SpringTransaction`이 커밋 단계에서 난 예외를 따로 잡는다. `TransactionTemplate.execute` 대신 `getTransaction`/`commit`을 직접 부르거나, 액션 완료 여부를 플래그로 기록한다. 액션이 끝난 뒤 난 `08*`·`40003`·전송 단절은 `DB_COMPLETION_UNKNOWN`(retryable=false)로 바꾼다 |
|
||||
| 완료 기준 | 커밋 중 연결 종료 시 호출자가 `DB_COMPLETION_UNKNOWN`을 받는다. 커밋 전 연결 실패는 여전히 `DB_UNAVAILABLE`이다 |
|
||||
| 검증 방법 | `PostgreSqlTransactionIntegrationTest#connectionLossDuringCommit…`에 결과 코드·retryable 단언 추가. 커밋 전 실패와 구분하는 단위 테스트 1개 |
|
||||
|
||||
### 04-02 다중 인스턴스에서 알림 정산 job이 중복 처리된다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(정적). 중복 처리의 업무 영향 범위는 일부 미확인 |
|
||||
| 관련 관점 | 12 동시성, 13 확장성, 6 실패, 5 위험 가시성 |
|
||||
| 근거 | `PN/JdbcReconciliationJobStore.java:43-52` claim은 `SELECT … FOR UPDATE SKIP LOCKED`다. `:117-123`은 이것을 트랜잭션 없이 `JdbcOperations.query`로 실행한다. 호출자 `src/adapter/outbound/notification/.../dispatch/ReconciliationJobWorker.java:81`과 스케줄러 `NotificationBackgroundWorkers.java:79-104`에도 트랜잭션이 없다. autocommit이라 행 잠금은 SELECT가 끝나는 순간 풀린다. lease·owner 컬럼도 없다. 같은 leaf의 다른 쓰기는 모두 `CallerTransaction.require`를 부르는데 이 store의 네 메서드(`:93-143`)만 부르지 않는다 |
|
||||
| 발생 조건 | 인스턴스 2개 이상, 정산 대기 job이 있을 때 |
|
||||
| 영향 | 같은 job을 여러 인스턴스가 동시에 가져간다. 공급자 상태 조회가 중복되고 `attempts`가 두 번 오른다(최대 시도 도달이 빨라짐). 결과 기록이 두 번 일어날 때의 업무 영향은 reconciler 구현의 멱등성에 달려 있고 확인하지 않았다 |
|
||||
| 심각도·우선순위 | High / P1. 코드가 "잠근다"는 의도를 보이지만 실제로 잠그지 않는다. 다중 서버 업무 중복 실행에 해당한다 |
|
||||
| 결정의 근거 | 적용 제외 — 같은 leaf의 recipient claim(`RecipientClaimSql`)이 이미 lease+fence 방식을 쓴다. 그 방식을 따르면 된다 |
|
||||
| 최소 개선 방향 | claim을 `UPDATE … SET claimed_by, claimed_until … WHERE id IN (SELECT … FOR UPDATE SKIP LOCKED) RETURNING`으로 바꾸고, reschedule·complete는 owner+token 조건 UPDATE로 바꾼다. 마이그레이션으로 컬럼 추가 |
|
||||
| 완료 기준 | 두 연결에서 동시에 claim하면 겹치는 job이 0개. lease가 지난 job만 다른 인스턴스가 가져간다 |
|
||||
| 검증 방법 | 실 PG 동시 claim 테스트(두 스레드, 교집합 0 단언). 가능하면 X1-#6d의 범용 `ClaimFencingContract`를 상속 |
|
||||
|
||||
### 04-03 JPA 연관관계 원칙(양방향 금지)을 막는 장치가 없고, 템플릿 문서와 fixture는 반대로 가르친다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 5 위험 가시성, 21 guardrail, 20 개발자 경험, 23 일관성, 4 인지 부하 |
|
||||
| 근거 | 전수 확인 결과 production 엔티티 28개(JPA 4, notification 12, fileserver 6, sample 5, gRPC ledger 1)에 `@ManyToOne`·`@OneToMany`·`@OneToOne`·`@ManyToMany`가 하나도 없다. 모두 UUID 컬럼으로 서로를 가리킨다. sample `WorkLogEntity.java:52-58`만 `@ElementCollection`(LAZY) 2개. 그러나 (1) ArchUnit 규칙 묶음 `JpaArchitectureRules`(`PJ/src/testFixtures/.../testkit/arch/JpaArchitectureRules.java:34-102`)와 `JpaProductionArchitectureTest`(`src/app-bootstrap/src/architectureTest/.../JpaProductionArchitectureTest.java`)에 연관관계 규칙이 없다. (2) `docs/jpa/entity-mapping-guide.md:50-57`은 "inverse collection + 양쪽을 맞추는 association helper"를 권장한다. (3) testFixtures `PagedParent.java:41-46`·`LifecycleParent.java:46-51`이 `@OneToMany(mappedBy, cascade=ALL, orphanRemoval)` + `@ManyToOne` 양방향 예시다. (4) sample 엔티티는 `JpaProductionArchitectureTest`의 import 대상이 아니다(app-bootstrap이 sample에 의존하지 않음) |
|
||||
| 발생 조건 | 파생 서비스 개발자가 가이드나 fixture를 따라 첫 연관관계를 만들 때 |
|
||||
| 영향 | 양방향 매핑이 아무 경고 없이 들어온다. 그러면 한쪽만 바꿔 FK가 비는 실수, `cascade=ALL`이 다른 aggregate 행을 지우는 실수, 직렬화·toString 순환, 컬렉션 로딩 N+1이 개발자 기억에 맡겨진다. 사용자가 정한 "위험은 코드에 드러나야 한다" 원칙과 반대다 |
|
||||
| 심각도·우선순위 | Medium / P1. 지금 production에 위반은 없다. 그러나 템플릿이 반대 패턴을 문서와 예제로 배포하므로 복제 범위가 크다 |
|
||||
| 결정의 근거 | 확인한 사실: 현재 코드는 이미 "ID 참조만" 방식으로 일관된다. 기록된 의도: 가이드는 양방향 helper를 권장한다. 둘이 어긋난다. 추론: 현재 코드의 일관성은 의도된 규칙이 아니라 결과일 가능성이 있다 |
|
||||
| 최소 개선 방향 | `JpaArchitectureRules`에 "필드에 `@OneToMany(mappedBy=…)`가 있으면 위반"(또는 "`@OneToMany`·`@ManyToMany` 금지, `@ManyToOne`은 LAZY 필수") 규칙을 추가하고 `JpaProductionArchitectureTest`와 sample 아키텍처 테스트에서 호출한다. 가이드 50-57행을 "aggregate 사이는 ID 참조, aggregate 안 자식은 단방향 `@ManyToOne` 또는 `@ElementCollection`"으로 바꾼다. fixture는 단방향으로 바꾸거나 "규칙의 위반 예시"로 이름과 위치를 옮긴다 |
|
||||
| 대안 비교 | (a) 문서만 고침: 비용 최소, 강제 없음(M1). (b) ArchUnit 규칙(선택): 빌드에서 막힘(M3), 규칙 1개·테스트 1개. (c) 컴파일 단계 annotation processor: 강제 강도는 같고 비용 큼. (d) 현상 유지: 원칙과 문서가 계속 충돌. (b)를 고른다. (c)는 얻는 것 대비 비용이 크다 |
|
||||
| 단순화의 보존 조건 | pagination·lifecycle 계약 테스트가 쓰는 fixture 동작(LAZY 컬렉션 페이지 경고, orphan 삭제)은 단방향 매핑이나 별도 위반 fixture로 유지해야 한다 |
|
||||
| 재검토 조건 | aggregate 안 자식 컬렉션을 엔티티로 다뤄야 하는 실제 요구(예: 자식 단독 조회·수정)가 생기면 `@OneToMany` 단방향(+`@JoinColumn`) 허용 범위를 다시 정한다 |
|
||||
| 완료 기준 | 양방향 fixture를 production 패키지에 넣으면 `architectureCheck`가 실패한다. 가이드와 fixture가 원칙과 같은 말을 한다 |
|
||||
| 검증 방법 | 위반 fixture로 규칙이 실패하는지 보는 red/green 테스트 |
|
||||
|
||||
### 04-04 실 PostgreSQL lane 9개(57개 테스트)가 어떤 게이트·workflow에서도 돌지 않는다. persistence-fileserver는 자기 테스트가 0개다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(게이트 누락) |
|
||||
| 관련 관점 | 10 테스트, 21 guardrail, 26 ownership, 18 배포 |
|
||||
| 근거 | readiness lane 16개(`PJ/build.gradle:166-183`) 중 workflow가 이름으로 부르는 것은 5개뿐이다(`.github/workflows/integration-main.yml:305-317`). `postgresql{Lifecycle,SecurityBaseline,Migration,Aggregate,Query,Idempotency,FileserverMigration,FileserverMetadata,FileserverReclamation}IntegrationTest`는 workflow·`release-registry.json` 어디에도 없다. 이 클래스들에는 `@Tag`가 없어 태그 lane(`jpaPlatformContractTest` 등)에도 안 잡힌다. 루트 `integrationCheck`(`src/build.gradle:100-105`)가 유일한 집계인데 `ci`·`mainCheck`에 들어 있지 않고, workflow는 `--dry-run`만 한다(`integration-main.yml:96-99`). 게이트 로그: `persistence-fileserver:test NO-SOURCE`, `mainCheck`는 JPA 실 DB lane을 하나도 실행하지 않음. 실행 확인: 4개 lane을 직접 돌려 44개 모두 통과(E2) — 지금은 깨져 있지 않다 |
|
||||
| 발생 조건 | fileserver·멱등성·마이그레이션 영속 코드를 바꾸는 PR |
|
||||
| 영향 | 파일 메타데이터·쿼터 회수·멱등성 저장소의 실제 SQL 동작이 바뀌어도 아무 게이트가 실패하지 않는다. `PJ/CLAUDE.md:97`("Contracts run against real PostgreSQL")과 `:119-121`("fail closed")의 주장이 실행으로 뒷받침되지 않는다 |
|
||||
| 심각도·우선순위 | Medium / P1. 결함 자체가 아니라 검출 공백이지만, persistence-fileserver는 다른 검증 경로가 없다 |
|
||||
| 결정의 근거 | 적용 제외 — 원하는 계약(실 DB 계약 실행)이 이미 문서에 있다 |
|
||||
| 최소 개선 방향 | `integration-main.yml`에 `./gradlew :adapter:outbound:persistence-jpa:integrationTestLaneCheck` 한 step을 추가하거나, fileserver·idempotency lane을 `fileserver-pr.yml`·`pr-adapters.yml`의 해당 path filter job에 넣는다. 장기적으로는 fileserver IT를 `persistence-fileserver` leaf로 옮긴다(04-13 참고) |
|
||||
| 완료 기준 | 16개 readiness lane이 모두 하나 이상의 workflow에서 실행된다. lane 목록과 workflow를 대조하는 테스트가 있으면 더 좋다 |
|
||||
| 검증 방법 | workflow 실행 기록, 또는 lane 이름 ↔ workflow 텍스트 대조 테스트 |
|
||||
|
||||
### 04-05 `@Version` 충돌이 변환되지 않고 500 INTERNAL_ERROR로 나간다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 6 실패, 17 계약, 12 동시성, 8 디버깅 |
|
||||
| 근거 | `SpringTransaction`의 번역기는 SQLState만 본다(`PersistenceExceptionTranslator.java:73-84`). `ObjectOptimisticLockingFailureException`은 SQLException이 없어 `Optional.empty()` → `.orElse(failure)`(`SpringTransaction.java:105`)로 원래 예외가 나간다. web은 이것을 `INTERNAL_ERROR` 500으로 답한다(`src/adapter/inbound/web/.../error/GlobalExceptionHandler.java:189-196`). 실험으로 확인(E2). `DB_OPTIMISTIC_CONFLICT`(409)는 정의돼 있고 `LockFailureClassificationContractTest`가 enum 값만 확인한다(`src/app-bootstrap/src/test/.../LockFailureClassificationContractTest.java:38-60`). 이 코드를 만드는 곳은 라이브러리 API인 `PostgreSqlExceptionTranslator`뿐이고, 기본 조립은 이것을 쓰지 않는다 |
|
||||
| 발생 조건 | 같은 aggregate를 두 요청이 동시에 수정. sample `UpdateWorkLogUseCase.java:32-73`은 읽은 뒤 버전을 비교하지만, 비교와 커밋 사이 경쟁은 커밋 시점 `@Version` 충돌로만 잡힌다 |
|
||||
| 영향 | 클라이언트는 "다시 읽고 고쳐라"(409) 대신 "서버 오류"(500)를 받는다. 운영 로그에는 정상 경쟁이 error로 남는다 |
|
||||
| 심각도·우선순위 | Medium / P2 |
|
||||
| 결정의 근거 | 적용 제외 — 기대 코드(`DB_OPTIMISTIC_CONFLICT`)가 이미 정해져 있다 |
|
||||
| 최소 개선 방향 | `SpringTransaction.execute`(또는 `PersistenceExceptionTranslator`)에서 Spring `OptimisticLockingFailureException`을 `DB_OPTIMISTIC_CONFLICT`로 바꾼다. 04-06의 표 통합과 같이 하면 한 곳만 고친다 |
|
||||
| 완료 기준 | 커밋 시점 버전 충돌 시 호출자가 `PersistenceFailureException(DB_OPTIMISTIC_CONFLICT)`를 받고 web은 409를 답한다 |
|
||||
| 검증 방법 | 단위 테스트(실험과 같은 형태) + 실 PG 두 트랜잭션 경쟁 테스트 1개 |
|
||||
|
||||
### 04-06 SQLState 분류표가 두 벌이고 이미 갈라졌다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(갈라진 중복) |
|
||||
| 관련 관점 | 23 일관성, 9 유지보수, 17 계약, 22 추상화 |
|
||||
| 근거 | 표 1: `failure/StandardSqlStateErrorMapping` + `postgresql/PostgreSqlSqlStateErrorMapping.java:17-23`(SQLState → `OperationalError`). `TransactionPort` 경로가 쓴다. 표 2: `postgresql/error/PostgreSqlFailureClassifier.java:50-61`(SQLState → `FailureCategory`) + `api/error/JpaPersistenceException.java:59-75`(`FailureCategory` → `OperationalError`). 라이브러리 API 경로가 쓴다. 실험: `25P03`이 표 1에서는 `DB_IDLE_IN_TX_TIMEOUT`(retryable=true), 표 2에서는 `TRANSACTION_TIMEOUT` → `DB_QUERY_CANCELED`(retryable=false)(E2). `40003`은 표 2에만 있다(completion unknown). `@Version` 충돌은 표 2에만 있다(04-05) |
|
||||
| 발생 조건 | 같은 DB 오류가 어느 경로로 올라오느냐에 따라 |
|
||||
| 영향 | 같은 장애에 클라이언트가 받는 retryable 값이 경로마다 다르다. SQLState를 하나 추가할 때 두 곳을 고쳐야 하고, 하나만 고쳐도 아무 테스트가 실패하지 않는다 |
|
||||
| 심각도·우선순위 | Medium / P2 |
|
||||
| 결정의 근거 | 확인한 사실: 두 표 모두 `PersistenceFailureException`을 만든다(`JpaPersistenceException extends PersistenceFailureException`). 기록된 의도: 표 2 Javadoc은 "세 갈래 병렬 분류 대신 같은 코드"를 말한다(`JpaPersistenceException.java:19`). 의도는 하나로 모으는 것이었고 끝나지 않았다 |
|
||||
| 최소 개선 방향 | 표 2(`PostgreSqlFailureClassifier` → `FailureCategory`)를 정본으로 하고, `PostgreSqlSqlStateErrorMapping`은 그 결과로부터 파생한다. 또는 반대로 표 1에 `FailureCategory`를 얹는다 |
|
||||
| 대안 비교 | (a) 표 2 정본(선택): 범주가 더 풍부(completion unknown, optimistic, schema mismatch). 표 1의 SPI(`SqlStateErrorMapping`)는 vendor 확장점이라 어댑터 하나로 남긴다. (b) 표 1 정본: 기본 경로라 영향 범위 작음, 그러나 completion-unknown·optimistic 표현이 없다. (c) 두 표 유지 + 일치 테스트: 가장 싸지만 중복이 남는다. (a)를 고르고, 이행 중에는 (c)의 일치 테스트로 보호한다 |
|
||||
| 단순화의 보존 조건 | `SqlStateErrorMapping` SPI(H2 행 기여)와 중복 SQLState 기여 시 기동 실패(`PersistenceExceptionTranslator.java:43-56`)는 유지 |
|
||||
| 재검토 조건 | 두 번째 RDBMS 벤더가 운영 대상이 되면 vendor별 표 구조를 다시 정한다 |
|
||||
| 완료 기준 | 모든 SQLState에 대해 두 경로의 결과 코드가 같다(또는 표가 하나다) |
|
||||
| 검증 방법 | `PostgreSqlState` 전 값에 대한 parameterized 일치 테스트 |
|
||||
|
||||
### 04-07 bulk UPDATE가 `@Version`을 올리지 않는다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 12 동시성, 11 데이터, 21 guardrail |
|
||||
| 근거 | `PN/inbox/InboxItemJpaRepository.java:82-108` `markAllRead`는 `state`·`read_at`을 바꾸지만 `version`을 올리지 않고 `clearAutomatically`도 없다. 엔티티는 `@Version`(`PN/inbox/InboxItemEntity.java:72-74`). `PN/RecipientClaimSql.java:53-64` `EXPIRE_OVERDUE`도 같다. 같은 leaf의 claim SQL은 이미 version을 올린다(`RecipientClaimSql.java:42-46`). `JpaAuditMechanismRule.bulkUpdatesOfAuditedEntitiesStampAudit`는 audit 컬럼만 본다 |
|
||||
| 발생 조건 | 같은 트랜잭션이나 다른 요청이 그 전에 읽은 엔티티를 수정·flush |
|
||||
| 영향 | 낙관적 락이 충돌을 못 잡고 `read_at`이나 EXPIRED 상태를 되돌린다(lost update) |
|
||||
| 심각도·우선순위 | Medium / P2 |
|
||||
| 결정의 근거 | 적용 제외 |
|
||||
| 최소 개선 방향 | 두 쿼리에 `version = version + 1`, `@Modifying(clearAutomatically = true, flushAutomatically = true)`. 그리고 audit 규칙과 같은 방식으로 "`@Version` 엔티티 테이블을 바꾸는 native/JPQL UPDATE는 version을 올린다" ArchUnit/문자열 규칙을 추가 |
|
||||
| 완료 기준 | 두 쿼리 뒤에 이전 버전으로 flush하면 낙관적 락 충돌이 난다 |
|
||||
| 검증 방법 | 실 PG 테스트 1개(읽기 → bulk → 이전 엔티티 수정 → 충돌 단언) |
|
||||
|
||||
### 04-08 upsert가 "찾고 없으면 넣기"라 동시 요청에서 깨진다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 12 동시성, 11 데이터, 6 실패 |
|
||||
| 근거 | 수신 거부: `PN/JpaSuppressionStore.java:47-64` find → save. DDL에 unique 제약이 없고 일반 인덱스뿐이다(`persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V2__notification_platform_contact_template_policy.sql:77-93`). finder는 단건 `Optional`(`PN/SuppressionJpaRepository.java:33`). 선호 설정: `PN/JpaPolicyStores.java:50-72` 같은 구조, 제약 `uk_notification_preference`는 있음(V2:102) |
|
||||
| 발생 조건 | 같은 대상의 bounce webhook 두 개가 동시에 도착, 또는 첫 선호 저장이 동시에 두 번 |
|
||||
| 영향 | 수신 거부: 행이 2개 생기고, 그 뒤 같은 키의 upsert는 매번 `IncorrectResultSizeDataAccessException`(500)으로 실패한다. 수동 정리 전까지 회복되지 않는다. 선호 설정: 한쪽이 `DB_UNIQUE_VIOLATION`(409)을 받는다. 멱등해야 할 동작이 충돌 오류가 된다 |
|
||||
| 심각도·우선순위 | Medium / P2 |
|
||||
| 결정의 근거 | 적용 제외 — 같은 클래스의 dedup 경로가 이미 `ON CONFLICT`로 고쳐져 있다 |
|
||||
| 최소 개선 방향 | 새 마이그레이션 `UNIQUE (tenant_id, normalized_target_hmac, reason)`(기존 중복 정리 포함), 두 store를 `INSERT … ON CONFLICT … DO UPDATE` native upsert로 |
|
||||
| 완료 기준 | 동시 upsert 두 개 후 행 1개, 두 호출 모두 성공 |
|
||||
| 검증 방법 | 실 PG 동시 upsert 테스트 |
|
||||
|
||||
### 04-09 sample 목록 조회가 N+1이다(페이지당 최대 202쿼리)
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(정적 계산, 실측 안 함) |
|
||||
| 관련 관점 | 14 성능, 10 테스트, 20 개발자 경험, 21 guardrail. sample 영역과 겹침(>) |
|
||||
| 근거 | `WorkLogEntity.java:52-58` LAZY `@ElementCollection` 2개. `WorkLogRepositoryAdapter.java:77-80` `findAll(pageRequest)` 뒤 행마다 `toDomain` → `WorkLog.rehydrate`가 `List.copyOf(techStack)`, `List.copyOf(links)`(`domain/worklog/WorkLog.java:51-52`)로 두 컬렉션을 초기화. `default_batch_fetch_size` 기본 0(`persistence-jpa.yml:150`). 페이지 크기 상한 100(`PageParams.java:20`). 쿼리 수 = 1(page) + 1(count) + 2×N → N=20이면 42, N=100이면 202. testkit에 `JpaQueryAssertions`(`PJ/src/testFixtures/.../testkit/query/`)가 있지만 sample은 persistence-jpa testFixtures를 쓰지 않는다 |
|
||||
| 발생 조건 | `GET` 목록 요청마다 |
|
||||
| 영향 | 요청당 DB 왕복이 행 수에 비례한다. 템플릿의 "참조 구현"이 N+1을 보여 주므로 파생 서비스가 그대로 복사한다 |
|
||||
| 심각도·우선순위 | Medium / P2 |
|
||||
| 결정의 근거 | 대안: (a) `default_batch_fetch_size`를 100 정도로 기본 설정(선택: 한 줄, 모든 LAZY 컬렉션에 효과, 쿼리 수 4로 고정). (b) 목록은 이미 있는 `WorkLogSummaryQueryPort`(컬렉션 없는 projection)로 돌림: 목록 화면 요구가 요약뿐이면 가장 싸다. (c) `@EntityGraph` fetch join: 컬렉션 2개 동시 join은 카테시안 곱과 페이지 메모리 처리 경고를 만든다 → 기각 |
|
||||
| 최소 개선 방향 | (a)와 함께, sample 목록 테스트에 `JpaQueryAssertions`로 "쿼리 수 ≤ 4" 단언을 넣는다 |
|
||||
| 완료 기준 | 목록 요청의 쿼리 수가 N과 무관하다 |
|
||||
| 검증 방법 | statement 수 단언 테스트(실 PG lane) |
|
||||
|
||||
### 04-10 기본 쓰기·읽기 트랜잭션에 시간 제한이 없다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 6 실패, 7 운영, 14 성능 |
|
||||
| 근거 | `SpringTransaction.java:58`은 `inNew`에만 30초를 건다. `inWrite`·`inRootWrite`·`inRead`는 timeout 없음. `statement_timeout`·`lock_timeout`·`idle_in_transaction_session_timeout`을 설정하는 코드·설정이 없다(`set_config`는 COPY loader·실험 패키지에만). Hikari `leak-detection-threshold: 30000`(`persistence-jpa.yml`)은 경고만 한다 |
|
||||
| 발생 조건 | 느린 쿼리, 행 잠금 대기, 트랜잭션 안의 외부 호출 |
|
||||
| 영향 | 커넥션 10개(기본 pool) 풀이 오래 붙잡혀 다른 요청이 `connection-timeout` 5초 뒤 실패한다. 원인 쿼리는 끝나지 않는다 |
|
||||
| 심각도·우선순위 | Medium / P2 |
|
||||
| 결정의 근거 | 대안: (a) `TransactionTemplate.setTimeout`을 모드별로(선택: JPA query hint로 전파, 코드 한 곳). (b) DB role 수준 `ALTER ROLE … SET statement_timeout`: 앱 밖이라 템플릿이 보장 못 함, runbook에 병기. (c) 매 트랜잭션 `set_config('statement_timeout', …, true)`: 왕복 1회 추가 → (a)로 충분할 때 기각 |
|
||||
| 최소 개선 방향 | `app.persistence-jpa.transaction.write-timeout`/`read-timeout` 설정(기본 예: 10초/5초)을 두고 템플릿에 적용 |
|
||||
| 완료 기준 | 기본 설정에서 `pg_sleep(실제보다 긴 값)`이 든 `inWrite`가 정해진 시간 안에 실패한다 |
|
||||
| 검증 방법 | 실 PG 테스트 1개 |
|
||||
|
||||
### 04-11 Mongo 트랜잭션 본문의 일시 오류가 재시도되지 않는다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(정적, 실 서버 미재현) |
|
||||
| 관련 관점 | 6 실패, 12 동시성, 10 테스트 |
|
||||
| 근거 | 본문에 넘기는 것은 `template.withSession(session)`(`PM/src/main/.../transaction/SpringMongoTransactionSessionFactory.java:92`)이다. `MongoTemplate`은 드라이버 예외를 Spring `DataAccessException`으로 바꿔 던진다. 그런데 `runBody`는 `MongoException`만 잡는다(`:141-142`). 그래서 WriteConflict(TransientTransactionError)는 `MongoTransactionTransientException`이 되지 않고, `MongoTransactionRetryCoordinator.execute`(`retry/MongoTransactionRetryCoordinator.java:85-92`)의 본문 재시도 분기에 걸리지 않는다. coordinator를 실 서버에서 검증하는 테스트는 없다 |
|
||||
| 영향 | `PM/CLAUDE.md:137-139`가 보장하는 "본문 재시도"가 템플릿 경로에서는 동작하지 않는다. 쓰기 경쟁이 그대로 실패로 나간다. 소비자가 0이라 현재 피해는 없다 |
|
||||
| 심각도·우선순위 | Medium / P2 |
|
||||
| 결정의 근거 | 적용 제외 |
|
||||
| 최소 개선 방향 | `runBody`에서 `DataAccessException`의 cause 사슬에서 `MongoException`을 찾아 분류한다 |
|
||||
| 완료 기준 | replica set lane에서 강제 WriteConflict 후 본문이 한 번 더 실행되고 성공한다 |
|
||||
| 검증 방법 | `mongoReplicaSetTest`에 테스트 추가 |
|
||||
|
||||
같은 파일의 관련 소항목(Low): commit 재시도 대기 중 인터럽트가 `IllegalStateException`으로 바뀌어 "commit 결과 모름" 표시가 사라진다(`MongoTransactionRetryCoordinator.java:150,186`). `MongoTransactionCommitUnknownException`으로 감싸야 한다.
|
||||
|
||||
### 04-12 Mongo 기본 경로(URI만 준 배포)에 timeout·pool 제한이 없다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 19 설정, 6 실패, 7 운영 |
|
||||
| 근거 | typed profile이 없으면 설정 적용을 건너뛴다(`PM/src/main/.../client/MongoProfileClientSettingsAutoConfiguration.java:82-83`). 그러면 드라이버 기본값(pool 100, server selection 30초, socket timeout 무제한)을 쓴다. `PM/src/main/resources/config/mongo.yml:11` 주석은 "active-profile이 비면 안 된다"고 하지만 `MongoPlatformSettings.java:84-86`은 profile이 있을 때만 검사한다 |
|
||||
| 심각도·우선순위 | Medium / P2 |
|
||||
| 최소 개선 방향 | `mongo.yml`에 `spring.mongodb` timeout·pool 기본값을 두거나, 주석을 실제 동작에 맞춘다 |
|
||||
| 결정의 근거 | 적용 제외 — 문서와 코드 불일치 정리 |
|
||||
| 완료 기준·검증 | URI만 준 기동에서 `MongoClientSettings`의 socket·selection timeout이 유한값임을 단위 테스트로 확인 |
|
||||
|
||||
### 04-13 persistence adapter가 정책을 소유하고, claim 토큰을 프로세스 메모리에 둔다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 2 구조, 5 위험 가시성, 12 동시성, 22 추상화 |
|
||||
| 근거 | `PF/JpaCleanupQueue.java:36` `MAXIMUM_ATTEMPTS = 8`, `:151-160` 소진 시 ABANDONED 판정, `:67` lease 10분 상수. `:100-116` claim은 행마다 UPDATE를 따로 보내고 `SKIP LOCKED`가 없다. claim 토큰은 `heldClaims` 맵(`:77`)에 두고 `CleanupItem`으로 돌려주지 않는다. 다른 인스턴스가 reclaim하거나 트랜잭션이 롤백되면 항목이 남는다. inbox 상태 전이(seen/read/archive 단조성)는 엔티티 메서드에 있다(`PN/inbox/InboxItemEntity.java:106-151`) |
|
||||
| 영향 | 재시도 한도·lease 길이를 바꾸려면 persistence 코드를 고쳐야 한다(HARD-STOP 4 "비즈니스 규칙이 mapper·설정으로 이동"과 같은 방향의 위험). 토큰이 프로세스에 있어 fencing 정보가 포트 계약에 드러나지 않는다 |
|
||||
| 심각도·우선순위 | Medium / P2 |
|
||||
| 결정의 근거 | 기록된 의도: 주석(`:110-113`)은 "재시작하면 토큰을 잃는 것이 목적"이라 한다. 그 목적은 토큰을 `CleanupItem`에 실어 호출자가 들고 있어도 똑같이 지켜진다 |
|
||||
| 최소 개선 방향 | 토큰과 시도 횟수를 `CleanupItem`에 싣고, `markFailed`의 소진 판정은 application(`application-fileserver`)으로, 한도·lease는 포트 인자나 설정으로. claim은 notification의 CTE + `SKIP LOCKED` + `RETURNING` 한 문장 패턴으로 |
|
||||
| 대안 비교 | (a) 현상 유지 + 문서화: 비용 0, 숨은 위험 유지. (b) 위 방향(선택). (c) 범용 lease 모듈로 통합(X1-#6): 범위가 커서 이번 항목과 분리 |
|
||||
| 단순화의 보존 조건 | "늦게 깬 worker의 완료는 적용되지 않는다"(토큰 불일치 시 0행)는 유지 |
|
||||
| 완료 기준 | adapter에 정책 상수 없음, claim 한 문장, 토큰이 포트 타입에 있음 |
|
||||
| 검증 방법 | `PostgreSqlFileserverReclamationIntegrationTest` 확장 |
|
||||
|
||||
### 04-14 notification·fileserver 영속 leaf가 테스트 규칙(공유 계약)을 따르지 않는다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(규칙 위반) |
|
||||
| 관련 관점 | 10 테스트, 26 ownership, 23 일관성 |
|
||||
| 근거 | `application-notification`, `application-fileserver`에 `testFixtures` source set이 없다. fileserver fake는 `application-fileserver/src/test/.../testkit/InMemory*.java`에 있고, `MetadataPortContractTest`는 abstract가 아니다. PG IT는 fake와 별개로 작성됐다. AGENTS.md 테스트 규칙 6("fake와 adapter가 같은 추상 계약을 통과")과 capability 완료 기준 5 위반. fileserver IT 37개는 `persistence-jpa`의 source set에 있다(`PJ/build.gradle:102-115`) |
|
||||
| 영향 | fake로 통과한 유스케이스 테스트가 실제 저장소 동작과 다를 수 있다. leaf 소유자와 테스트 소유자가 다르다 |
|
||||
| 심각도·우선순위 | Medium / P2 (지난 W4 항목 TEST-FAKE-*·X1-#3b·S7-lead-4와 같은 묶음) |
|
||||
| 결정의 근거 | 적용 제외 — 규칙이 이미 정해져 있다 |
|
||||
| 최소 개선 방향 | 포트별 abstract `XxxContract`를 각 application leaf testFixtures로, fake 테스트와 PG IT가 상속. fileserver IT는 `persistence-fileserver`의 integration lane으로 이동 |
|
||||
| 완료 기준·검증 | 포트마다 계약 1개, 구현 2개 이상이 상속. `persistence-fileserver:test`가 NO-SOURCE가 아님 |
|
||||
|
||||
### 04-15 Mongo 라이브러리를 파생 서비스가 쓸 경로와 예시가 없다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 / 개선 제안 |
|
||||
| 관련 관점 | 20 개발자 경험, 22 추상화, 27 삭제 가능성, 13 확장성 |
|
||||
| 근거 | 레지스트리에서 mongo leaf에 의존할 수 있는 모듈은 `app-bootstrap`뿐이고 그 줄도 주석이다(`src/app-bootstrap/build.gradle:164`). README는 "서비스 어댑터 leaf가 `implementation`으로 받는다"(`PM/README.md:140-142`)고 하지만 등록 절차 안내가 없다. `@Document`·`MongoRepository` 예시가 0개. main 278개 파일·18,939줄, 공개 타입 271개(`docs/architecture/mongo-api-surface.txt`), leaf 밖 production 소비자 0 |
|
||||
| 영향 | 파생 서비스는 레지스트리 edge, 예외 변환(`MongoDuplicateKeyException` 등), 정책 적용 범위(repository 직접 사용 시 `MongoQueryPolicy` 우회)를 추측해야 한다 |
|
||||
| 심각도·우선순위 | Medium / P2 |
|
||||
| 결정의 근거 | 사용자 원칙상 소비자 없는 코드는 확장 지점이지 죽은 코드가 아니다. 다만 확장 지점이면 "어떻게 꽂는지"가 있어야 한다. 그 부분이 빠졌다 |
|
||||
| 최소 개선 방향 | testFixtures에 document·repository·mapper·port 구현 예시 한 벌, `docs/mongodb`에 "소비 leaf 등록" 절차(레지스트리 edge 추가 예) |
|
||||
| 대안 비교 | (a) 예시+절차(선택). (b) advanced 패키지를 별도 leaf로 분리해 표면 축소: 효과 크지만 이동 범위 큼(CLAUDE.md가 이미 별도 커밋으로 미룸). (c) 소비자 생길 때까지 삭제: 소유자 결정(capability 유지)과 충돌 → 기각 |
|
||||
| 완료 기준·검증 | 예시가 `mongoStableContractTest`에서 컴파일·실행된다 |
|
||||
|
||||
### 04-16 notification·fileserver leaf에 가까운 안내 문서가 없고 패키지가 평평하다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 개선 제안 |
|
||||
| 관련 관점 | 4 인지 부하, 9 유지보수, 26 ownership |
|
||||
| 근거 | 두 leaf에 `CLAUDE.md`·`README.md`가 없다(루트 CLAUDE.md는 "nearest guidance가 local rules를 소유"한다고 말한다). notification은 엔티티·repository·adapter·SQL 상수 약 37개가 `platform` 한 패키지에 있고 하위는 `inbox`뿐. fileserver는 `entity/`·`repository/`로 나눴고 adapter는 루트에 있어 두 leaf 규칙이 다르다 |
|
||||
| 심각도·우선순위 | Low / P3 |
|
||||
| 최소 개선 방향 | 두 leaf에 짧은 CLAUDE.md(테스트 위치, 트랜잭션 guard 규칙, 마이그레이션 위치·불변성 테스트). notification을 기능별 하위 패키지로 |
|
||||
| 결정의 근거·완료 기준 | 적용 제외 — 문서·배치 정리. 완료: 두 leaf에 안내 문서, 같은 패키지 규칙 |
|
||||
|
||||
### 04-17 미리 정한 UUID + primitive `long` version이라 `save()`가 merge로 동작한다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(작음) |
|
||||
| 관련 관점 | 14 성능, 11 데이터 |
|
||||
| 근거 | `PF/entity/FileEntity.java:78` 외 fileserver 엔티티의 `@Version long`. Spring Data는 primitive version이면 id null 여부로 새 엔티티를 판단하는데 id가 미리 정해져 있어 merge가 된다. `save` 호출: `PF/JpaFileMetadata.java:76`, `JpaFileQuota.java:50`, `JpaUploadSession.java:58` 등 |
|
||||
| 영향 | insert마다 SELECT 1회 추가. id가 겹치면 unique 오류 대신 낙관적 락 오류나 덮어쓰기 |
|
||||
| 심각도·우선순위 | Low / P3 |
|
||||
| 최소 개선 방향 | `Persistable<UUID>` 구현 또는 `Long version`(null = 새 엔티티) |
|
||||
| 결정의 근거·검증 | 적용 제외. 검증: statement 수 단언 테스트 |
|
||||
|
||||
## 4. 31절 시나리오 추적
|
||||
|
||||
### 선택 1 — DB 오류·경쟁: sample WorkLog 동시 수정
|
||||
|
||||
```
|
||||
WorkLog 수정 요청 (expectedVersion 선택)
|
||||
→ WorkLogController (입력 검증, inbound DTO → command)
|
||||
→ UpdateWorkLogUseCase.handle ── tx.inWrite 시작 (REQUIRED, READ_COMMITTED, timeout 없음)
|
||||
→ repository.findById → 버전 비교(있으면) → 도메인 메서드로 규칙 적용
|
||||
→ WorkLogRepositoryAdapter.save → findById(audit created_* 이월) → jpa.save = merge
|
||||
── 커밋: flush 시 UPDATE … WHERE version=?
|
||||
→ 응답
|
||||
```
|
||||
|
||||
| 항목 | 결과 |
|
||||
| --- | --- |
|
||||
| 입력 신뢰 수준 | 인증된 사용자 입력. 크기·형식은 web에서 검증 |
|
||||
| 권한 판단 위치 | 이 영역 밖(> 인증 영역). 영속 계층은 소유자 조건 없이 id로만 조회한다 |
|
||||
| 규칙 소유 객체 | `WorkLog` 도메인(상태 전이). 버전 비교는 유스케이스. audit 스탬프는 adapter(`WorkLogRepositoryAdapter.java:42-56`) — 인프라 관심사라 적절 |
|
||||
| 트랜잭션 | 유스케이스가 `TransactionPort.inWrite`로 연다. adapter는 열지 않는다. 시간 제한 없음(04-10) |
|
||||
| 외부 부작용 | 없음(outbox 미사용 경로) |
|
||||
| 성공의 의미 | 커밋 후 반환. `@Version`이 경쟁을 막는다 |
|
||||
| 오류 변환 | 버전 비교 실패 → `WorkLogVersionMismatchException`(sample 핸들러가 409). 비교 통과 후 커밋 경쟁 → `ObjectOptimisticLockingFailureException` 원본 → 500(04-05). 커밋 중 연결 끊김 → `DB_UNAVAILABLE` retryable(04-01) |
|
||||
| 진단 정보 | 500 경로는 스택 포함 error 로그. persistence carrier는 SQLState만 로그(파라미터 없음) — 민감정보 보호는 지켜진다 |
|
||||
|
||||
### 선택 2 — 여러 서버의 작업 실행: 알림 정산 job
|
||||
|
||||
`NotificationBackgroundWorkers`(인스턴스마다 스케줄러 1개) → `ReconciliationJobWorker.reconcileOnce` → `JdbcReconciliationJobStore.claimDue`(autocommit `FOR UPDATE SKIP LOCKED`) → 공급자 조회 → `reschedule`/`complete`. 소유권 표시가 없어 중복 실행된다(04-02). 같은 leaf의 recipient claim, JPA outbox claim은 owner+token fencing으로 올바르게 처리한다(`PJ/README.md` outbox 절, V17).
|
||||
|
||||
### 선택 3 — 큰 입력·목록 조회
|
||||
|
||||
web `PageParams.MAX_SIZE=100` → 유스케이스 → adapter `PageRequest`. 크기 상한은 web에만 있고 adapter는 `size<=0`만 보정한다(`WorkLogRepositoryAdapter.java:69`). 쿼리 수는 N에 비례(04-09). 라이브러리 keyset은 상한 500(`api/query/KeysetPageRequest.java:19`), Mongo keyset 1,000·skip 상한 있음. notification의 limit 없는 List 조회 4곳(`ConsentJpaRepository.java:23`, `ProviderEventJpaRepository.java:32`, `RecipientDeliveryJpaRepository.java:28`, `SuppressionJpaRepository.java:24`)은 누적 데이터에 비례해 커진다(Low, 04-14 작업 때 같이).
|
||||
|
||||
### 적용 제외
|
||||
|
||||
| 시나리오 | 사유 |
|
||||
| --- | --- |
|
||||
| 정상 쓰기 요청 | 선택 1이 같은 경로를 포함 |
|
||||
| 중복·동시 요청 | 멱등성 executor는 composition·application 영역. 영속 측 공통 계약 부재는 S2-lead-2로 재확인 |
|
||||
| 외부 응답 지연·유실 | 영속 영역에 외부 호출 없음 |
|
||||
| 메시지 중복·역순 | outbox 발행·소비는 messaging 영역. 영속 측 fencing은 V17·`OutboxLeaseFencingContract`로 확인 |
|
||||
| 신·구 버전 공존 | 마이그레이션 불변성 테스트(해시 고정)로 적용된 파일 변경은 막힌다. expand/contract 지침은 `docs/jpa/migration-guide.md`. 실제 무중단 전환 실험은 범위 밖 |
|
||||
| 세션·토큰 갱신 경쟁, 다른 사용자 리소스 접근 | 인증·인가 영역 |
|
||||
| 종료·재시작 | 스케줄러 종료는 notification adapter 영역 |
|
||||
| 선택 어댑터 제거 | `JpaActivationEnvironmentPostProcessor`(enabled=false → Boot 자동설정 제외)와 Mongo `MongoCapabilityActivationTest`가 다룬다. composition 영역에서 확인 |
|
||||
|
||||
## 5. 41절 설계 선택 검토
|
||||
|
||||
### 5.1 엔티티 사이를 연관관계 없이 ID로만 잇는다(현재 코드의 선택)
|
||||
|
||||
1. 필요한 것: aggregate 경계 유지, 의도치 않은 로딩·cascade 방지, 사용자 원칙(양방향 금지).
|
||||
2. 지킬 성질: 한 aggregate의 저장이 다른 aggregate 행을 바꾸지 않는다. 로딩 범위가 쿼리에서 보인다.
|
||||
3. 현재 보장: production 엔티티 전부가 UUID 컬럼으로 참조한다(전수 확인). 강제 장치는 없다(M2, 04-03).
|
||||
4. 대안: (a) 단방향 `@ManyToOne` LAZY 허용, (b) 가이드대로 양방향 + helper, (c) ID 참조만.
|
||||
5. 대가: (a) 조인 쿼리 작성이 편하다. 프록시·LAZY 예외를 알아야 한다. (b) 양쪽 동기화를 기억해야 한다. cascade 오용 위험이 크다. (c) 조인이 필요하면 JPQL/projection을 직접 쓴다. 로딩이 늘 명시적이다.
|
||||
6. 현재 조건에서의 선택: (c)가 원칙과 aggregate 경계에 맞는다. aggregate 안 자식은 `@ElementCollection` 또는 단방향 `@ManyToOne`까지 허용하는 것이 현실적이다.
|
||||
7. 바뀌는 조건: aggregate 안 자식을 독립 엔티티로 조회·수정해야 하는 요구가 생기면 단방향 `@OneToMany(@JoinColumn)` 허용 여부를 다시 본다.
|
||||
|
||||
판정: 선택은 타당하지만 코드에 강제되지 않고 문서가 반대로 말한다. 그래서 설명 검증은 "부분 통과"다.
|
||||
|
||||
### 5.2 예외 변환을 TransactionPort 경계에서 SQLState로 한 번만 한다
|
||||
|
||||
1. 필요한 것: DB 세부(SQL, 제약 이름)가 클라이언트로 새지 않게, 그리고 재시도 가능 여부를 정확히 알린다.
|
||||
2. 지킬 성질: 결과 불명은 재시도 불가로, 경쟁은 409로, 장애는 503으로.
|
||||
3. 현재 보장: 누출 방지는 지켜진다(carrier는 코드만, 로그도 코드만). 재시도 판단은 두 곳에서 틀린다(04-01 커밋 단계 구분 없음, 04-05 SQLState 없는 Spring 예외 미처리). 분류표가 두 벌이다(04-06).
|
||||
4. 대안: (a) adapter마다 변환, (b) 경계에서 한 번(현재), (c) 경계에서 한 번 + 단계(액션/커밋) 인지 + Spring 예외 타입 인지.
|
||||
5. 대가: (a) 누락이 쉽고 중복된다. (b) 단순하지만 단계 정보를 잃는다. (c) `SpringTransaction`에 수십 줄 추가.
|
||||
6. 선택: (b)의 위치는 맞다. (c)로 보강해야 ADR-JPA-003을 지킨다.
|
||||
7. 바뀌는 조건: 트랜잭션 엔진이 둘이 되거나 reactive 트랜잭션이 들어오면 다시 본다.
|
||||
|
||||
### 5.3 실 PostgreSQL 계약 lane을 `ci`·`mainCheck` 밖에 둔다
|
||||
|
||||
1. 필요한 것: PR이 빨라야 하고(ci 7분), 실 DB 동작은 검증돼야 한다.
|
||||
2. 지킬 성질: 실 DB lane마다 적어도 한 workflow가 실행한다.
|
||||
3. 현재 보장: 태그 lane 5개와 readiness 5개는 workflow가 돈다. readiness 9개는 아무도 돌리지 않는다(04-04).
|
||||
4. 대안: (a) 전부 `mainCheck`로, (b) path filter workflow로(현재 일부), (c) `integrationCheck`를 nightly에 통째로.
|
||||
5. 대가: (a) main 단계가 수 분 늘어난다(이번 측정: 4개 lane Gradle 56초). (b) 필터 누락이 생긴다(지금 상태). (c) 반나절 늦게 발견.
|
||||
6. 선택: (c)를 기본 안전망으로 두고 (b)를 유지하는 것이 비용 대비 낫다. 지금은 안전망이 없다.
|
||||
7. 바뀌는 조건: lane 수가 늘어 nightly 시간이 문제가 되면 matrix로 나눈다.
|
||||
|
||||
## 6. 리팩토링 후보
|
||||
|
||||
| 무엇 | 왜 | 보존할 동작·타입·실패 계약 |
|
||||
| --- | --- | --- |
|
||||
| SQLState 분류표 두 벌 → 한 벌(04-06) | 갈라진 중복, retryable 값 불일치 | `SqlStateErrorMapping` SPI, 중복 기여 시 기동 실패, `PersistenceFailureException` 타입과 web의 carrier 처리, 로그에 SQL 미포함 |
|
||||
| `SpringTransaction.execute`에 커밋 단계 구분(04-01·04-05) | ADR-JPA-003 준수, 409 정상화 | 모드별 propagation·isolation·readOnly 표(`PJ/CLAUDE.md:221-226`), `inRootWrite`의 중첩 거부, 재시도 0회 |
|
||||
| `JpaCleanupQueue` 정책·토큰 이동(04-13) | 정책이 adapter에, 토큰이 메모리에 | 토큰 불일치 시 완료 무시, lease 만료 후 reaper 인수 |
|
||||
| notification `platform` 패키지 분할(04-16) | 37개 파일 평면 | 공개 타입 이름, Spring bean 이름(조립 코드가 참조) |
|
||||
| Mongo `internal` 패키지 이동(CLAUDE.md 보류 항목) | 공개 타입 271개 | `verifyMongoApiSurface` 스냅샷이 줄어드는 것으로 증명, Stable 패키지가 advanced를 참조하지 않는 규칙 |
|
||||
|
||||
## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료)
|
||||
|
||||
새 aggregate 하나를 JPA로 저장할 때 템플릿이 주는 것:
|
||||
|
||||
- 따라 할 예시: sample `WorkLogEntity`·`WorkLogPersistenceMapper`·`WorkLogRepositoryAdapter`·`WorkLogJpaRepository`, 계약 테스트 `WorkLogRepositoryContract`(fake와 adapter 공용).
|
||||
- 기반: `AuditableEntity`(audit 컬럼), `AuditContextPort`, `TransactionPort`, `CallerTransaction.require`(adapter가 호출자 트랜잭션을 요구), `PersistenceExceptionTranslator`.
|
||||
- 검사: `JpaProductionArchitectureTest`(엔티티 노출·final·generic repository·audit·tenant), `AppliedMigrationImmutabilityTest`(마이그레이션 해시 고정).
|
||||
- 문서: `docs/jpa/entity-mapping-guide.md`, `query-fetch-guide.md`, `migration-guide.md`, `transaction-guide.md`.
|
||||
|
||||
빠진 것:
|
||||
|
||||
- 연관관계 규칙과 그 검사(04-03). 지금 가이드는 원칙과 반대다.
|
||||
- 목록 조회의 쿼리 수 검사 예시(04-09). testkit 도구는 있는데 sample이 쓰지 않는다.
|
||||
- 낙관적 락 충돌의 표준 처리(04-05).
|
||||
- notification·fileserver처럼 "application leaf가 따로 있는 capability"의 영속 leaf 템플릿: testFixtures 계약, 테스트 위치, CLAUDE.md(04-14, 04-16).
|
||||
- Mongo로 aggregate를 저장하는 예시 한 벌(04-15).
|
||||
|
||||
개발자가 여기서 내려야 하는 판단:
|
||||
|
||||
1. 이 데이터는 독립 aggregate인가, 다른 aggregate의 자식인가. → 독립이면 ID 컬럼, 자식이면 `@ElementCollection` 또는 단방향 `@ManyToOne`(LAZY). 양방향은 쓰지 않는다.
|
||||
2. 같은 행을 동시에 바꿀 수 있는가. → 그렇다면 `@Version`(wrapper `Long`, null = 새 행)을 둔다. bulk UPDATE를 쓰면 version도 올린다.
|
||||
3. "같은 것이 두 번 생기면 안 되는가". → 애플리케이션 조회가 아니라 DB unique 제약으로 막고, upsert는 `ON CONFLICT`로 쓴다.
|
||||
4. 여러 인스턴스가 같은 행을 처리하는가(큐·스케줄러). → claim은 `UPDATE … WHERE id IN (SELECT … FOR UPDATE SKIP LOCKED) RETURNING`, 완료는 owner+token 조건 UPDATE. autocommit SELECT FOR UPDATE는 잠그지 않는다.
|
||||
5. 트랜잭션은 누가 여는가. → 유스케이스가 `TransactionPort`로 연다. adapter는 `CallerTransaction.require`만 부른다. 예외는 포트 자체가 원자 단위인 저장 프로토콜뿐이다.
|
||||
6. 목록 조회는 몇 번 쿼리하는가. → 컬렉션을 가진 엔티티를 페이지로 읽으면 N+1이다. projection 포트나 batch fetch를 쓰고 쿼리 수를 테스트로 고정한다.
|
||||
7. 스키마 변경은 새 파일인가. → 적용된 `V*` 파일은 고치지 않는다. 새 버전을 추가하고 `applied-migrations.sha256`에 해시를 추가한다.
|
||||
8. 오류를 클라이언트에 어떻게 알리는가. → adapter에서 잡지 말고 `TransactionPort` 경계 변환에 맡긴다. 업무 의미가 있는 충돌(버전 불일치 등)만 유스케이스가 자기 예외로 바꾼다.
|
||||
|
||||
## 8. 28개 관점 판정표
|
||||
|
||||
기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역.
|
||||
|
||||
| 번호 | 관점 | 판정 | 한 줄 이유 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 코드 성숙도 | P | 트랜잭션·fencing 코드는 의도가 드러난다. 갈라진 분류표(04-06)와 adapter 안 정책(04-13)이 남음 |
|
||||
| 2 | 구조적 성숙도 | P | leaf 방향은 레지스트리로 강제됨. adapter가 정책을 소유(04-13), JPA leaf가 플랫폼 라이브러리와 capability 저장소를 함께 가짐 |
|
||||
| 3 | 변경 용이성 | P | SQLState 하나 추가에 두 표 수정(04-06). 마이그레이션은 해시 고정으로 안전 |
|
||||
| 4 | 인지 부하 | P | JPA CLAUDE.md는 상세하나 길고 일부 낡음(S2-#14a). 분리 leaf 2개에 안내 없음(04-16) |
|
||||
| 5 | 위험 가시성 | X | 양방향 금지·bulk version·claim 잠금이 모두 개발자 기억에 의존(04-02·04-03·04-07) |
|
||||
| 6 | 실패 성숙도 | X | 커밋 결과 불명이 재시도 가능으로 나감(04-01), 버전 충돌 500(04-05), 시간 제한 없음(04-10) |
|
||||
| 7 | 운영 성숙도 | P | Hikari·OSIV·DDL·Flyway 위험 설정을 기동 시 거부. timeout 기본값 없음(04-10, 04-12) |
|
||||
| 8 | 디버깅 가능성 | P | 오류 로그에 SQL·파라미터 없음(보호 O). 정상 경쟁이 error 로그(04-05) |
|
||||
| 9 | 유지보수 성숙도 | P | 이력 서술 Javadoc(S2-#12), 중복 표(04-06) |
|
||||
| 10 | 테스트 성숙도 | P | unit 503개·실 PG lane 다수, 그러나 9개 lane 미실행(04-04), 공유 계약 부재(04-14), 쿼리 수 검사 미사용(04-09) |
|
||||
| 11 | 데이터 성숙도 | P | 마이그레이션 불변성 O, unique 제약 누락(04-08), bulk version 누락(04-07) |
|
||||
| 12 | 동시성 성숙도 | P | outbox·recipient·durable operation fencing O. 정산 job 무잠금(04-02), upsert 경합(04-08) |
|
||||
| 13 | 확장성 | P | 다중 인스턴스 claim 패턴 존재, 한 곳 누락(04-02). Mongo 소비 경로 없음(04-15) |
|
||||
| 14 | 성능 성숙도 | P | keyset·상한 제공. sample N+1(04-09), merge 추가 SELECT(04-17). 실측은 안 함 |
|
||||
| 15 | 보안 성숙도 | O | SQL·파라미터 비노출, runtime role 권한 lane, RLS `set_config(…, true)`(트랜잭션 범위), schema provider는 반환 시 search_path 초기화·실패 시 abort |
|
||||
| 16 | 의존성 성숙도 | O | vendor 드라이버 격리 ArchUnit, Mongo 레지스트리 parity 테스트 |
|
||||
| 17 | API / Contract | P | `DB_*` 코드 표 존재. 실제 도달 코드가 계약과 다름(04-01, 04-05) |
|
||||
| 18 | 배포 성숙도 | ? | 마이그레이션 기동 순서·readiness 연계는 코드로 확인. 실제 무중단 배포 실험 없음 |
|
||||
| 19 | 설정 성숙도 | P | 위험 값 기동 거부 O. prefix 분산(P20-new-5 남음), Mongo 주석·코드 불일치(04-12) |
|
||||
| 20 | 개발자 경험 | P | 예시·testkit 풍부. 원칙과 반대인 가이드(04-03), Mongo 예시 없음(04-15) |
|
||||
| 21 | Guardrail | P | 엔티티·노출·audit·마이그레이션 규칙 M3. 연관관계·bulk version 규칙 없음 |
|
||||
| 22 | 추상화 성숙도 | P | `TransactionPort`·`CallerTransaction`은 적절. Mongo 공개 타입 271개 대비 소비자 0 |
|
||||
| 23 | 일관성 | P | 두 분류표(04-06), 두 분리 leaf의 패키지 규칙 상이(04-16), claim 패턴 3종 |
|
||||
| 24 | 네이밍 / 의미 | P | `claimDue`가 잠그지 않음(04-02), `QUOTA_EXCEEDED`를 상태 충돌에 사용(`PF/JpaFileQuota.java:94-96`) |
|
||||
| 25 | 조직 확장성 | P | fileserver 테스트가 JPA leaf에 있어 소유가 섞임(04-14) |
|
||||
| 26 | Ownership | P | 분리 leaf 2개 안내 문서 없음(04-16) |
|
||||
| 27 | 삭제 가능성 | O | `enabled=false`가 Boot 자동설정까지 제외, runtimeOnly 한 줄로 제거 |
|
||||
| 28 | 회복 가능성 | P | completion-unknown 회복 경로가 커밋 단계에서 끊김(04-01). 수신 거부 중복은 수동 정리 필요(04-08) |
|
||||
|
||||
미검증: 18(무중단 배포), 04-02의 업무 중복 효과, 04-11 실 서버 재현, 04-09 실측, JPA 태그 lane과 Mongo 컨테이너 lane의 현재 커밋 실행 결과.
|
||||
@@ -0,0 +1,566 @@
|
||||
# 05. Outbound capability 영역 성숙도 리뷰
|
||||
|
||||
대상 leaf: `adapter:outbound:redis-runtime`, `redis-sdk`, `cache-redis`, `httpclient`, `objectstorage`,
|
||||
`notification`, `fileserver`, `identifier`, `support`, `application-notification`, `application-fileserver`,
|
||||
`application-objectstorage`, `composition:fileserver-platform`, `composition:notification-platform`.
|
||||
|
||||
경로는 `src/`를 생략한다. 패키지 앞부분이 긴 경로는 파일 이름만 적고, 처음 나올 때 leaf를 밝힌다.
|
||||
|
||||
## 1. 범위
|
||||
|
||||
| 항목 | 기록 |
|
||||
| --- | --- |
|
||||
| 대상 | `clean-architecture-backend-template`, 브랜치 `main`, 커밋 `01a8a2a70` |
|
||||
| 확인 시점 | 2026-11-01 |
|
||||
| 목적과 실행 구성 | 템플릿(파생 서비스의 시작점). 기본 조립은 web·support·identifier뿐이고, 이 영역의 나머지는 `app-bootstrap/build.gradle`에 `runtimeOnly` 한 줄로 켜는 선택 모듈이다(`app-bootstrap/build.gradle:162-171`). 다중 인스턴스 배포를 전제로 한 설정(lease, `FOR UPDATE SKIP LOCKED`, Redis 공유 상태)이 있다. |
|
||||
| 규모·운영 목표 | 합의된 SLO·처리량 없음. 그래서 "운영 준비 완료" 판정은 하지 않는다. |
|
||||
| 읽은 범위 | 14개 leaf의 main 코드(약 9.5만 줄) 중 위험 경로: 알림 제출·dispatch·recovery·SES/SMTP·SNS 콜백, 파일 업로드(tus)·복사·다운로드·권한·쿼터, 객체 저장소 S3/local-dev 오류 분류, Redis 캐시·멱등성·rate-limit Lua·연결 lane, HTTP client retry·deadline·circuit breaker·SSRF, support의 module-defaults 로더, identifier. 각 leaf의 README·CLAUDE.md·`config/module-defaults/*.yml`, `AutoConfiguration.imports`, `app-bootstrap`의 관련 설정. 하위 조사 4개(알림, 파일·객체 저장소, Redis, HTTP client·support·identifier)가 코드를 읽었고, High 판정 항목은 리뷰어가 해당 줄을 직접 다시 읽어 확인했다. |
|
||||
| 실행한 것 | ① 오케스트레이터 게이트 결과 읽기: `ci` rc=0(이 영역 14개 leaf `test` 전부 실행·통과), `mainCheck` rc=1(objectstorage MinIO lane 2개 실패, 원인은 이미지 pull 404). ② 변이 실험 2회(별도 worktree, `flock` 잠금): 아래 표. ③ 현재 `build/test-results` XML 집계(ci가 11-01 20:38~20:40에 만든 결과). |
|
||||
| 확인 못 한 것 | Redis 실제 서버 lane(`ca.redis-topology-lane`, explicit-only라 게이트에 없음), HTTP client Toxiproxy lane(`httpClientFailureInjectionTest`, `integrationCheck`에만 있음), MinIO lane(이미지 소멸로 실행 불가), SES/SMTP 실제 발송, 다중 인스턴스 경쟁 실험, 부하 측정. 지난 리뷰의 실행 결과는 증거로 쓰지 않았다. |
|
||||
| 비교 가능한 범위 | techlead 07·08·09, followup-status B·C·D·G·H·S3·S4 그룹과 후속 발견(P·ORCH), 2026-08-14 notification 모듈 리뷰. |
|
||||
|
||||
변이 실험(worktree `wt-05`, 실행 후 원복·삭제):
|
||||
|
||||
| # | 바꾼 코드 | 돌린 테스트 | 결과 |
|
||||
| --- | --- | --- | --- |
|
||||
| M1 | `AppendUploadApplicationUseCase.java:165` 클라이언트 offset 불일치 검사 무력화 | `:application-fileserver:test` (부하 15.7) | 잡힘 — `ResumableUploadUseCasesTest.anOffsetTheClientGuessedWrongIsRejectedWithoutWriting` 실패 |
|
||||
| M2 | `CopyFileApplicationUseCase.java:70-71`, `PrepareDownloadApplicationUseCase.java:53-54`에서 권한 검사에 넘기는 descriptor를 `Optional.empty()`로 (소유자 검사가 사라짐) | `:application-fileserver:test`, `:composition:fileserver-platform:test`, `:adapter:inbound:web-fileserver:test` (부하 8.0) | **살아남음** — 442개 전부 통과 (05-08) |
|
||||
|
||||
테스트 실행 시간(현재 결과, ci 실행분): 14개 leaf 합계 테스트 약 1,790개, 클래스 시간 합 약 63초. 가장 긴 것은 objectstorage 19.4초(`ObjectStorageArchitectureTest`가 대부분), cache-redis 6.5초, httpclient 8.3초. 과하지 않다.
|
||||
|
||||
## 2. 지난 발견 재확인
|
||||
|
||||
상태: 해결 / 남음 / 바뀜(형태가 달라짐) / 일부.
|
||||
|
||||
| ID | 상태 | 근거 |
|
||||
| --- | --- | --- |
|
||||
| B-7d tenant 거부를 SUPPRESS로 보고 | 해결 | `AdminAuthorizationGuard.java:41-49`가 호출 연산의 authority를 인자로 받음 |
|
||||
| B-10a 알림 README·CLAUDE.md "R0 legacy" | 남음 | `adapter/outbound/notification/README.md:1,3`, `CLAUDE.md:15,23` |
|
||||
| B-10b application-notification CLAUDE.md 없음 | 남음 | `application-notification/`에 `build.gradle`·`src`만 |
|
||||
| B-10c / C-12c / D-11c / G-12b CLAUDE.md "Boot 4.0.0" | 남음 | notification `CLAUDE.md:8`, fileserver `CLAUDE.md:8`, objectstorage `CLAUDE.md:8`, cache-redis `CLAUDE.md:8`, identifier `CLAUDE.md:8`(새로 확인) |
|
||||
| B-10d / S1-#19 / S3-#11 / S4-#16a·b inline FQN·이력 주석 | 남음(줄어듦) | notification main FQN 약 93줄, objectstorage 약 60줄, httpclient 약 59줄. 예: `LeaseRecoveryService.java:103-104`, `RedisCacheRegionAdapter.java:262-266` |
|
||||
| S1-#20 notification `dispatch/` 46파일 | 남음 | 제출·템플릿·ContactPoint·reconciliation이 한 패키지 |
|
||||
| S4-#3a 미조립 provider 5종 삭제 | 일부 | adapter는 삭제(`ProviderType`은 SES·SMTP만). `ApnsDeviceToken`, `FcmInstallationId`, `WebPushContent` 같은 contact/content 타입은 남음 |
|
||||
| S4-#3b SES projector 연결 | 해결 | `NotificationPlatformRegistriesConfig.java:39` `StandardDeliveryProjector` |
|
||||
| S4-#17b `*ProviderProperties` 이름 | 남음 | `SesProviderProperties`·`SmtpProviderProperties`는 바인딩 대상이 아닌 record |
|
||||
| SesSuppressionUpdater dead code | 해결(삭제) | suppression은 `ProviderEventProjectionService.java:84-88` |
|
||||
| ORCH-new-2 알림 계약 테스트 inputs 미선언 | 남음(범위 넓어짐) | `NotificationPayloadAtRestContractTest`와 ReleaseGate·LegacyNamespaceRetirement·ModeSsot 테스트가 저장소 파일을 읽지만 `notification/build.gradle`에 `inputs` 없음 |
|
||||
| 결정 13 category 생략 → 400 | 해결(위치 다름) | 유스케이스가 아니라 `AcceptNotificationCommand.java:71-72`에서 거부 |
|
||||
| 결정 21 provider profile 소실 → 일반 재시도 후 FAILED | 해결 | `NotificationDispatchService.java:170-176, 249-286` |
|
||||
| C-10 / S2-#11 fileserver 경쟁 SQL leaf 테스트 0 | 바뀜 | leaf 안에는 여전히 없음. 실제 SQL은 `persistence-jpa`의 `PostgreSqlFileserverMetadataStoreIntegrationTest:107,258,283,313`(Testcontainers)이 검증 |
|
||||
| C-12b composition 주석 drift | 남음 | `composition/fileserver-platform/build.gradle:8-10` |
|
||||
| C-12c fileserver "default off" | 남음 | `adapter/outbound/fileserver/CLAUDE.md:19`, `README.md:17` vs `fileserver.yml`의 `enabled: true` |
|
||||
| D-4 staged kernel·handoff 동작 테스트 | 대부분 해결 | `StagedObjectPublicationLifecycleTest`(666줄), `ObjectPublicationHandoffRaceTest`. `StagedObjectPublicationKernelTest`는 이름과 달리 verdict policy만 봄 |
|
||||
| D-7a direct·multipart 업로드 코드 | 해결(삭제) | 해당 클래스 없음 |
|
||||
| D-11a~e objectstorage 문서 drift | 남음 | `objectstorage/CLAUDE.md:8,19,21`, `README.md:18-19`, `LocalDevObjectDataStore.java:77` |
|
||||
| P4-new-1 fileserver migration 불변성 테스트 | 해결 | `AppliedMigrationImmutabilityTest.java:43-45` manifest에 V1~V5 |
|
||||
| P14-new-5 application-objectstorage testFixtures 없음 | 남음 | testFixtures 디렉터리 없음, `PosterImagePublicationWorkflowTest.java:253` 자체 fake |
|
||||
| P30-new-3 local-dev create-only가 JVM 단위 | 일부 | `LocalObjectPathGuard.java:37-39,157-170`에 범위가 적힘. 동시 생성 테스트 없음 |
|
||||
| S5-#14c web-fileserver README·CLAUDE.md 없음 | 남음 | 디렉터리에 `*.md` 0개 |
|
||||
| S3AsyncResponseBodyBridgeTest 간헐 실패 | 개선, 위험 남음 | sleep 제거·1분 상한. `:40-41` await 없는 `shutdownNow`, `:84` 비동기화 `ByteArrayOutputStream` |
|
||||
| G-2b fake가 rate-limit HDEL/PEXPIRE 미흉내 | 일부 | 고정 필드 구조로 HDEL 불필요, 실제 Redis 필드 수 단언 추가(`LiveRedisSemanticPortsTest.java:242-255`). fake는 여전히 PEXPIRE 무시(`InMemorySemanticRedisCommands.java:395-475`) |
|
||||
| G-4j env-keys "Replaced by"가 없는 키 | 남음 | `docs/registries/env-keys.yaml:1428, 1460` |
|
||||
| G-5b redis-runtime README·CLAUDE.md 없음 | 남음 | 디렉터리에 `build.gradle`·`src`만 |
|
||||
| G-12c `src/README.md` orphan Redis 키 | 남음 | `src/README.md:312-320`(`external` client-mode는 존재하지 않음) |
|
||||
| G-12d cache-redis README 테스트 명령 | 해결 | `cache-redis/README.md:230-234` |
|
||||
| G-12e runtime 키의 owner_module | 일부 | runtime이 바인딩하는 22개 키의 owner가 아직 cache-redis |
|
||||
| S1-#3b lease 호출자 0 / 결정 8 공통 계약 | 일부 | `DistributedLeaseContract`(testFixtures)를 in-memory·Redis·live Redis가 상속. lock+lease 공통 계약은 없음 |
|
||||
| S2-lead-2 멱등성 공통 계약 테스트 | 남음 | `application-core/src/testFixtures/.../idempotency/testkit/`에 `InMemoryIdempotencyStore`뿐 |
|
||||
| S3-#12a `CacheKeys` 가변 generation, `KeyDigest` 위치 | 남음 | `RedisCacheRegionAdapter.java:352-354`, `capability/RedisKeys.java` |
|
||||
| S3-#12b CLAUDE.md "legacy cache router" | 남음 | `cache-redis/CLAUDE.md:22` |
|
||||
| S3-#13c Redis health indicator 중복 | 남음 | `RedisRuntimeAutoConfiguration.java:276-288`, `:308-331` |
|
||||
| ORCH-new-4 redis-sdk 테스트 경로·inputs | 일부 | 경로 수정됨(`RedisSdkModuleBoundaryTest:181`). `inputs` 미선언, `RedisSupportMatrixTest`에 document-contract 태그 없음 |
|
||||
| P13-new-2 local-redis lane 기동 WARN | 남음 | `RedisRuntimeSettings.java:207,215` WARN 2줄과 `run-compose-runtime-smoke.sh:520-522` 무음 검사 충돌 |
|
||||
| P20-new-3 sample 죽은 키 | 남음 | `sample-portfolio/src/main/resources/application.yml:254-273`(`app.cache.redis.*`), `:286-287`(`app.outbound.http.*`) |
|
||||
| H-3d `DefaultDynamicTargetGateway.exchange` 테스트 0 | 해결, 공백 남음 | `DefaultDynamicTargetGatewayTest` exchange 7건. 사설 IP로 resolve되는 hop 거부는 exchange 경로로 미검증 |
|
||||
| H-10a / P20-new-4 README httpclient 절 | 남음 | `src/README.md:337-365`가 `app.capabilities.http-client`·`bindLegacy`를 설명(코드에 0건) |
|
||||
| S3-#1 / H-5 / H-7 reactive 스택 (결정 9) | 해결 | src·build.gradle·lockfile에 webflux·reactor 0건 |
|
||||
| S3-#13a Jackson 2 사용 | 남음 | `RemoteProblemDecoder.java:3-4`, `httpclient/build.gradle:56,64` |
|
||||
| P11-new-2 `verify-httpclient-docs.py` 경로 | 남음 | `scripts/verify-httpclient-docs.py:22,64`. `.github/workflows/release.yml:188`에서 실행되므로 release 작업이 실패한다 |
|
||||
| P11-new-3 FailureInjection lane이 docker-proxy에 의존 | 수정됨, 미실행 | `FailureInjectionContractTest.java:53-68` 루프백 거부 방식. 이번 게이트에 이 lane 없음 |
|
||||
| S3-#6 `HttpClientTagPolicy` | 해결 | `HttpClientTagPolicy.java:32` |
|
||||
|
||||
지난 발견 중 남은 High/P1은 없다. 남은 것은 대부분 W5(문서·Nit)와 W4(테스트 규칙)다. 다만 W4 중 "공통 포트 계약 테스트 없음"(S2-lead-2, P14-new-5)은 이번 새 발견 05-02·05-16과 직접 연결된다.
|
||||
|
||||
## 3. 새 발견
|
||||
|
||||
심각도 분포는 문서 끝 「발견 요약」에 있다. High는 전체 양식으로, Medium·Low는 필요한 필드만 쓴다. 설계 선택이 아닌 단순 결함은 "대안 비교: 적용 제외 — 이유"로 둔다.
|
||||
|
||||
### 05-01 알림 attempt를 "요청 시작 안 함(확정)"으로 저장한 채 provider를 호출한다 — 워커가 발송 중 죽으면 같은 알림이 다시 나간다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 1, 5, 6, 10, 11, 12, 28 |
|
||||
| 근거 | ① `application-notification/.../dispatch/DeliveryAttemptFactory.java:54-56` — attempt 행을 처음 만들 때 `ProviderExecutionEvidence.notStarted()`(값 false, 확실성 PROVEN). ② `NotificationDispatchService.java:189-199` 이 행을 insert하고, `:201` lease 확인 뒤 `:215` `submitOutsideTransaction`이 provider를 부른다. 그 사이에 evidence를 바꾸는 쓰기가 없다(`requestStarted`를 쓰는 곳은 insert `JpaDeliveryAttemptStore.java:80-83`과 완료 기록 `:288-291`뿐). ③ `LeaseRecoveryService.java:101-106` `provablyNeverStarted`가 PROVEN+false면 true, `:134-136`이 그 경우 reconcile 없이 `READY_TO_DISPATCH`로 되돌린다. 리뷰어가 세 곳 모두 직접 읽었다. |
|
||||
| 발생 조건 | SES/SMTP 호출 중 pod가 SIGKILL·OOM으로 죽는다. 또는 shutdown-grace(20s)를 넘긴다. 또는 워커가 lease 만료(`lease-duration` 2m, `NotificationDeliveryConfiguration.java:131`에서 staleAfter로도 쓰임)를 넘겨 멈춘다. |
|
||||
| 영향 | recovery가 그 수신자를 다시 큐에 넣고 다른 워커가 같은 메일을 다시 보낸다. 늦게 깨어난 첫 워커의 결과 기록은 fence로 버려진다. 이 경로는 `LeaseRecoveryService` 주석과 `allow-ambiguous-fallback: false` 설정이 막겠다고 한 바로 그 경우다. |
|
||||
| 심각도·우선순위 | High / P1. 가이드 35.2의 "결과 불명 작업의 무방비 재실행"에 해당한다. 기본 구성(SERVING, 다중 인스턴스)에서 프로세스 중단만으로 도달한다. 금전 피해는 아니므로 Critical은 아니다. 템플릿 기본값이라 파생 서비스로 그대로 복제된다. |
|
||||
| 확실성 | 코드 경로는 확인(E1). 실제 crash 재현은 하지 않았다. |
|
||||
| 테스트가 못 잡는 이유 | `LeaseRecoveryServiceTest.java:241-247`과 `PostgreSqlNotificationBackgroundPassIntegrationTest.java:370`이 attempt를 factory가 아니라 직접 만들어 넣는다. factory → crash → recovery를 잇는 테스트가 없다. |
|
||||
| 결정의 근거 | 코드 주석은 "호출 전에는 아무것도 시작 안 됨이 증명된 사실"이라고 적는다. 행을 insert한 순간에는 맞지만, 그 행이 호출이 끝날 때까지 그대로 남는다는 점이 빠졌다. "증명"은 insert 시점에만 참이다. |
|
||||
| 최소 개선 방향 | factory가 `requestStarted = UNKNOWN`으로 행을 만든다. "확정 미시작"은 `closedBeforeSubmission`(`:205-211`)이나 adapter가 돌려준 `ProviderCallNotStartedException` 결과로만 기록한다. |
|
||||
| 대안 비교 | (a) 위 방법: 쓰기 추가 없음, crash 시 항상 reconcile. SMTP처럼 상태 조회가 없는 provider는 운영자 대기로 간다. (b) insert는 미시작 확정으로 두고 호출 직전에 UNKNOWN으로 갱신하는 쓰기를 추가: 트랜잭션 한 번 더, insert~갱신 사이 crash만 안전 requeue. (c) 현상 유지: 중복 발송 허용. (a)를 고른다. (b)가 얻는 것은 "insert 직후 crash" 한 구간의 requeue뿐이고 쓰기가 늘어난다. |
|
||||
| 단순화의 보존 조건 | 행이 없을 때의 requeue(`:117-122`)와 완료된 attempt의 requeue(`:124-133`)는 유지한다. |
|
||||
| 완료 기준 | factory로 만든 attempt를 recovery에 넣으면 reconcile 경로를 탄다. |
|
||||
| 검증 방법 | `LeaseRecoveryServiceTest`에 `DeliveryAttemptFactory.create(...)`로 만든 미완료 attempt → `recoverOnce()` → `reconciled`에 포함, `transitions` 비어 있음. Postgres lane에서 같은 흐름 1건. |
|
||||
|
||||
### 05-02 Redis 멱등성 `renew()`가 처리 lease를 연장하지 못한다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(현재 호출자 없음 — 잠복) |
|
||||
| 관련 관점 | 1, 10, 12, 17 |
|
||||
| 근거 | `cache-redis/.../idempotency/RedisIdempotencyStoreAdapter.java:183-190` renew를 `Transition("EXECUTING", "EXECUTING", …, leaseMillis, …)`로 보낸다. `IdempotencyScripts.java:101-108`은 revision·from 상태를 보기 전에 `state == ARGV[5]`(목표 상태)면 `ALREADY`를 반환한다. 현재 상태가 EXECUTING이면 renew는 항상 이 분기에 걸리고 `leaseUntil` 갱신(`:122-126`)에 닿지 않는다. fake도 같은 순서라 버그를 따라 한다(`InMemorySemanticRedisCommands.java:258-263`). main 코드에 `renew(` 호출자는 없다(grep). 리뷰어가 Lua를 직접 읽었다. |
|
||||
| 발생 조건 | 파생 서비스가 30초(기본 processing lease)보다 긴 작업에서 renew로 lease를 늘린다. |
|
||||
| 영향 | renew는 `ALREADY_RENEWED_SAME_OPERATION`(성공처럼 보이는 값)을 돌려주고 lease는 그대로 만료된다. 다른 요청이 `TAKEN_OVER`로 가져가 같은 부작용을 두 번 실행한다. |
|
||||
| 심각도·우선순위 | High / P1. 공개 포트의 계약이 조용히 깨져 있고 성공 값으로 숨는다. 템플릿 안에 호출자가 없어 지금 피해는 없지만, 쓰는 순간 중복 실행이다. |
|
||||
| 결정의 근거 | 적용 제외 — "같은 상태로의 전이"를 재시도 응답으로 해석한 Lua 분기 순서의 단순 결함이다. |
|
||||
| 최소 개선 방향 | Lua에서 `ARGV[4] ~= ARGV[5]`일 때만 ALREADY 분기를 탄다. fake도 같이 고친다. |
|
||||
| 완료 기준 | renew 후 lease가 연장되고, 다른 owner의 claim이 `IN_PROGRESS`를 받는다. |
|
||||
| 검증 방법 | application-core testFixtures에 멱등성 공통 계약(`IdempotencyStoreContract`)을 만들고 in-memory·Redis fake·live Redis·PostgreSQL store가 상속한다(S2-lead-2와 같은 작업). renew 정상 경로 케이스를 넣는다. |
|
||||
|
||||
### 05-03 캐시 `ONLY_IF_SOURCE_REVISION_NEWER`가 조건 없이 덮어쓴다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 1, 5, 11, 17 |
|
||||
| 근거 | `application-core/.../cache/CacheRecordIntent.java:8`이 이 intent를 공개한다. `cache-redis/.../cache/RedisCacheRegionAdapter.java:238-253`은 `ONLY_IF_OBSERVED`만 Lua CAS로 보내고, 나머지는 `presenceOf`(`:262-266`)로 보낸다. `presenceOf`는 `ONLY_IF_ABSENT`가 아니면 `ALWAYS`다. `sourceRevision`은 envelope에 저장만 하고(`:229`) 비교하지 않는다. 이 intent를 쓰는 테스트는 없다. 리뷰어가 직접 읽었다. |
|
||||
| 발생 조건 | 호출자가 "원본 revision이 더 새로울 때만 기록"을 요청했는데, 늦게 끝난 loader가 옛 revision으로 기록한다. |
|
||||
| 영향 | 새 값이 옛 값으로 덮인다. 결과는 `RECORDED`라 호출자는 조건이 지켜졌다고 믿는다. hard TTL(5분) 동안 옛 값을 읽는다. |
|
||||
| 심각도·우선순위 | High / P1. 호출자가 명시한 일관성 조건을 성공 응답으로 무시한다. 지원하지 않으면 거부해야 할 계약이다. |
|
||||
| 결정의 근거 | 적용 제외 — enum 값 하나의 구현 누락이다. |
|
||||
| 최소 개선 방향 | `ONLY_IF_OBSERVED`처럼 Lua로 envelope의 revision을 비교하고 교체한다. 당장 구현하지 않으면 이 intent에 `NOT_RECORDED_CONDITION`이 아니라 명시적 미지원 예외를 던진다. |
|
||||
| 완료 기준 | 더 작은 revision의 기록은 `NOT_RECORDED_CONDITION`, 큰 revision은 `RECORDED`. |
|
||||
| 검증 방법 | application-core testFixtures에 `CacheRegionContract`를 만들고 fake와 Redis adapter가 같은 표를 통과한다. |
|
||||
|
||||
### 05-04 캐시 무효화와 느린 loader의 경합, stampede 보호 없음, 문서는 jitter를 주장
|
||||
|
||||
- 성격: 구조적 위험(경합 결과는 추론). 관점 1, 5, 12, 14.
|
||||
- 근거: Miss는 항상 `CacheWriteCondition.unavailable()`을 돌려준다(`RedisCacheRegionAdapter.java:135,169,173`). `invalidate`는 `GETDEL` 하나다(`:277`). single-flight, early refresh, TTL jitter 구현은 없다(grep 0건). 그런데 `cache-redis/CLAUDE.md:17-18`은 "deterministic bounded jitter"를 구현했다고 적는다. region 무효화 반영은 generation 재확인 주기가 softTtl(30s)과 같아 인스턴스 간에 최대 30초 늦는다(`:316`, 테스트가 이 지연을 고정: `RedisCacheRegionAdapterTest.java:237-240`).
|
||||
- 발생 조건: 미스 → 원본에서 옛 값 로드 중 → 다른 요청이 invalidate → `UPSERT`/`ONLY_IF_ABSENT`로 옛 값 재기록. 인기 키 만료 순간 동시 미스.
|
||||
- 영향: 무효화 직후 옛 값이 최대 hard TTL(5분) 남는다. 동시 미스가 모두 원본을 친다.
|
||||
- 심각도·우선순위: Medium / P2. 캐시 사용처가 템플릿에 없고, 05-03을 고치면 revision 비교로 첫 시나리오를 막을 수단이 생긴다.
|
||||
- 최소 개선 방향: 고른 방법 — invalidate를 key 단위 tombstone(짧은 TTL, 이전 revision 기록 거부)으로 바꾸고 Miss에도 observation token을 돌려준다. 버린 대안 — 분산 lock 기반 single-flight: Redis 왕복과 lock 만료 처리가 늘고, 대부분의 캐시에는 tombstone+CAS로 충분하다. stampede는 문서에 "보호 없음, 호출자가 single-flight 책임"을 적거나 로컬 single-flight를 붙인다. CLAUDE.md의 jitter 문장은 지운다.
|
||||
- 완료 기준: "invalidate 후 옛 loader의 기록이 거부된다" 계약 케이스 통과.
|
||||
|
||||
### 05-05 HTTP client: 4xx 응답이 circuit breaker 실패로 집계된다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 6, 7, 17, 19 |
|
||||
| 근거 | `httpclient/.../restclient/BlockingResponseMapper.java:72-76` THROW_ON_ERROR(기본)에서 2xx가 아니면 `HttpRemoteErrorException`. `BlockingAttemptExecutor.java:95-100`이 이를 `REMOTE_STATUS`로 만들고, `:111-114`가 REMOTE_STATUS면 breaker에 실패로 넘긴다. `resilience/AttemptResiliencePipeline.java:104-106` `circuitBreaker.onError`. breaker는 `ResilienceRegistry.java:37-41` `CircuitBreakerRegistry.ofDefaults()`라 모든 예외를 실패로 센다. breaker 임계값·창·대기 시간을 바꾸는 설정 키는 없다. 리뷰어가 직접 읽었다. |
|
||||
| 발생 조건 | 조회 API가 정상적으로 404/409/422를 많이 돌려준다(라이브러리 기본: 최소 100회 중 50% 실패). |
|
||||
| 영향 | breaker가 열리고 그 profile의 모든 호출이 기본 60초 동안 `HttpCircuitOpenException`으로 거부된다. 상대 서버는 건강하다. |
|
||||
| 심각도·우선순위 | High / P1. 상대가 정상인데 기능 전체가 멈춘다. 프로젝트가 고칠 설정 키도 없다. |
|
||||
| 결정의 근거 | 적용 제외 — 실패 분류 기준의 누락이다. 업계 관행(5xx·timeout만 실패)과 다를 이유가 코드·문서에 없다. |
|
||||
| 최소 개선 방향 | 5xx·408·429와 전송 실패만 `onError`, 그 밖의 4xx는 `onSuccess`(또는 ignore)로 기록한다. profile별 breaker 설정(임계값·최소 호출 수·대기 시간)을 `app.httpclient.clients[n].circuit-breaker.*`로 노출한다. |
|
||||
| 완료 기준 | 404 응답 200회 뒤에도 breaker가 CLOSED. |
|
||||
| 검증 방법 | `AttemptResiliencePipeline` 단위 테스트에 상태 코드 표(`@ParameterizedTest`). |
|
||||
|
||||
### 05-06 HTTP client: 전체 시간 예산이 진행 중인 attempt를 끊지 못한다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 6, 7, 14, 17 |
|
||||
| 근거 | transport timeout은 profile 고정값(connect 0.5s, 응답 헤더 2s, read idle 3s)이고 남은 deadline으로 줄이지 않는다(`apache/ApacheClientFactory.java:74,79-80,129`). main에 `cancel(`/`abort(` 호출이 없다. deadline 검사는 attempt 시작 전에만 있다(`DefaultGenericHttpGateway.java` `attempt()`). JDK transport는 read idle을 쓰지 않는다(`jdk/JdkBlockingTransportProvider.java:66`). README는 "One effective deadline covers … read"라고 적는다. |
|
||||
| 발생 조건 | 상대가 바이트를 3초보다 짧은 간격으로 조금씩 보낸다(slow drip). 또는 JDK transport로 body가 멈춘다. |
|
||||
| 영향 | `totalCall` 4초를 무제한 넘긴다. 호출 스레드(virtual thread)와 pool 연결(기본 50)이 묶인다. 호출자의 요청 deadline이 깨진다. |
|
||||
| 심각도·우선순위 | High / P1. 31절 "외부 응답 지연" 시나리오의 핵심 계약(대기 제한)이 문서와 다르다. |
|
||||
| 결정의 근거 | 적용 제외 — 문서가 약속한 성질의 구현 누락. |
|
||||
| 최소 개선 방향 | attempt마다 `min(stage timeout, 남은 deadline)`으로 RequestConfig를 만들고, 남은 시간이 끝나면 요청을 취소(Apache `cancel`, JDK `CompletableFuture` timeout)한다. |
|
||||
| 완료 기준 | slow-drip 서버에 대해 호출이 `totalCall + 작은 오차` 안에 끝난다. |
|
||||
| 검증 방법 | Toxiproxy `slicer`/`latency` toxic으로 `httpClientFailureInjectionTest`에 케이스 추가, 이 lane을 `mainCheck`에 포함(05-16). |
|
||||
|
||||
### 05-07 파일 서버: copy가 디스크 수위 검사를 우회하고, 쿼터는 기록만 한다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 6, 13, 14, 15, 28 |
|
||||
| 근거 | `application-fileserver/.../lifecycle/CopyFileApplicationUseCase.java:66-103`에 admission(디스크 high-water)도 quota도 없다. 대상 namespace는 요청 본문에서 온다(`web-fileserver/.../FileLifecycleController.java:88,109`). 업로드 쪽 쿼터도 상한을 비교하지 않는다(`persistence-fileserver/.../JpaFileQuota.java:21-30`), 범위는 namespace 단위(`CreateUploadApplicationUseCase.java:100-102`)이고 commit은 예약보다 큰 값을 받는다(`JpaQuotaCommit.java:37-52`). 리뷰어가 copy 경로를 직접 읽었다. |
|
||||
| 발생 조건 | `file:copy` 권한을 가진 사용자가 큰 파일을 반복 복사한다. |
|
||||
| 영향 | 업로드는 high-water(0.85)에서 멈추지만 copy는 그 선을 넘어 볼륨을 끝까지 채운다. 그 뒤 모든 사용자의 업로드·복사가 실패한다. 같은 볼륨을 쓰는 다른 프로세스도 영향을 받을 수 있다. |
|
||||
| 심각도·우선순위 | High / P1. 인증된 사용자 하나로 서비스 전체 쓰기가 멈춘다. 기본 역할 `ROLE_FILE_WRITE`가 `file:copy`를 포함한다(`app-bootstrap/.../config/security.yml:58`). |
|
||||
| 결정의 근거 | 사용자별 쿼터를 둘지는 서비스 정책이다(0.2절). 하지만 "디스크를 다 채우지 않는다"는 템플릿이 지켜야 할 안전한 기본값이고, 업로드 경로는 이미 지킨다. copy만 빠졌다. |
|
||||
| 최소 개선 방향 | copy에 `admissionController.acquireUpload`와 `quotaService.reserve`를 넣는다. 대상 namespace는 policy 허용 목록으로 제한한다. 쿼터 상한 강제(principal/tenant 범위)는 별도 결정으로 분리한다. |
|
||||
| 대안 비교 | (a) copy에 admission만 추가: 볼륨 고갈은 막고 사용자 간 공정성은 남는다. (b) (a) + 쿼터 상한: 공정성까지, 쿼터 정책 결정 필요. (c) copy 기능을 서버 측 링크(참조 카운트)로: 바이트가 늘지 않지만 삭제·정리 모델이 바뀐다. 최소 변경은 (a), 템플릿 기본값으로는 (b)를 권장. |
|
||||
| 완료 기준 | high-water 이상에서 copy가 거절된다. |
|
||||
| 검증 방법 | `FileLifecycleUseCasesTest`에 수위 초과 fake admission으로 copy 거절 케이스. |
|
||||
|
||||
### 05-08 파일 서버: 소유자 검사를 지워도 테스트가 하나도 실패하지 않는다
|
||||
|
||||
- 성격: 확인된 결함(테스트 공백). 관점 10, 15, 21.
|
||||
- 근거: 변이 M2. `CopyFileApplicationUseCase.java:70-71`과 `PrepareDownloadApplicationUseCase.java:53-54`에서 descriptor를 `Optional.empty()`로 바꾸면 `RoleBasedFileAccessPolicy.java:65`(`descriptor.isPresent() && …`)가 소유자 검사를 건너뛴다. application-fileserver·composition·web-fileserver 테스트 442개가 모두 통과했다(E2). 원인은 `application-fileserver/src/test/.../testkit/FakeFileAccessPolicy.java:22-28`이 descriptor를 무시하고 연산만 기록하는 것이다. 소유자·tenant 판정은 `RoleBasedFileAccessPolicyTest:133,164,187`에만 있다.
|
||||
- 발생 조건: 누군가 use case를 고치다 descriptor를 빼먹는다. `DownloadDescriptor`는 public record라 새 inbound 경로가 권한 검사 없이 `OpenDownloadContent`를 부를 수도 있다(`OpenDownloadContentApplicationUseCase.java:38-40`).
|
||||
- 영향: 다른 사용자의 파일 다운로드(31절 "다른 사용자 리소스 접근")가 회귀해도 게이트가 통과한다.
|
||||
- 심각도·우선순위: Medium / P1. 지금 코드는 안전하지만 인가 회귀를 막는 장치가 없다.
|
||||
- 최소 개선 방향: fake가 받은 descriptor를 기록하고, use case 테스트마다 "descriptor.owner == record owner"를 단언한다. COPY·MOVE·READ_METADATA 거부 테스트를 추가한다.
|
||||
- 완료 기준: M2 변이가 죽는다.
|
||||
|
||||
### 05-09 객체 저장소: MinIO 이미지 공급원이 사라져 mainCheck가 빨갛다
|
||||
|
||||
- 성격: 확인된 결함(외부 공급원 의존). 관점 7, 10, 16, 18, 28.
|
||||
- 근거: `mainCheck` rc=1. `objectStorageMinioContractTest`, `objectStorageMinioFaultTest`가 `ContainerFetchException`(pull 404, "repository does not exist"). 같은 머신에서 `alpine:3`은 받아졌다(오케스트레이터 확인). 이미지 고정이 네 곳에 복사돼 있다: `MinioManagedObjectContractTest.java:52`, `MinioManagedObjectFaultTest.java:37-39`, `minio-provider-evidence.json:5`(test·integrationTest 두 벌, 내용 동일), 그리고 compose가 다른 태그를 쓴다(`docker-compose.infra.yml:183,425` `minio/minio:RELEASE.2024-09-13…`). 고정된 버전(2024-01-16)의 evidence는 `status: UNSUPPORTED`이고 create-only 계열 5개 프로필을 제외한다(`minio-provider-evidence.json`의 `excludedProfiles`, `limitations`). lane은 `rejectSkipped = true`로 fail-closed다(`objectstorage/build.gradle:85-103`), `mainCheck`가 둘 다 요구한다(`:123-125`).
|
||||
- 발생 조건: Docker Hub 저장소 삭제·비공개 전환·rate limit. 이번이 실제 사례다.
|
||||
- 영향: main 브랜치 게이트가 코드와 무관하게 실패한다. 이 영역의 유일한 실제 S3 벤더 증거(완료 기준 5)가 사라진다. local compose 개발 환경도 같은 공급원을 쓴다.
|
||||
- 심각도·우선순위: Medium / P1. 데이터 피해는 없지만 main 게이트가 막혀 있어 다른 회귀를 가린다.
|
||||
- 게이트가 어떻게 반응해야 하는가: 지금처럼 skip하지 않고 실패하는 것은 맞다(조용히 skip하면 벤더 증거가 없는데 초록이 된다). 부족한 것은 두 가지다. ① 실패 이유가 "코드 결함"인지 "공급원 소멸"인지 메시지로 구분되지 않는다. lane 시작 전에 이미지 pull을 별도 단계로 두고, 실패하면 "pinned image unavailable: <digest>"로 실패시킨다. ② 공급원이 사라졌을 때 바꿀 곳이 네 군데다. 이미지 참조를 `minio-provider-evidence.json` 하나에서 읽게 하고 compose도 같은 값을 쓰게 한다.
|
||||
- 대안 비교:
|
||||
|
||||
| 후보 | 얻는 것 | 비용·위험 | 판단 |
|
||||
| --- | --- | --- | --- |
|
||||
| (a) 같은 digest를 조직 레지스트리(GHCR/ECR)에 미러하고 거기서 받기 | 공급원 소멸에 영향받지 않음, digest 그대로라 evidence 유효 | 미러 운영(최초 push, 보존 정책), 원본 digest를 아직 가진 곳이 있어야 함(로컬 캐시·CI 캐시) | 1순위. 원본 digest를 확보할 수 있으면 증거 연속성을 지킨다 |
|
||||
| (b) 같은 제작사의 다른 레지스트리(예: `quay.io/minio/minio`) | 코드 변경 최소 | 그 레지스트리도 같은 이유로 사라질 수 있음. digest가 같은지 확인 필요. 이번 리뷰에서 가용성 미확인 | (a)가 불가능할 때 임시 |
|
||||
| (c) 커뮤니티 fork·재배포 이미지(예: Chainguard 등) | 계속 유지되는 공급원 | 다른 빌드라 evidence 재작성 필요, S3 조건부 쓰기 동작이 다를 수 있음 | evidence 재측정을 감수할 때 |
|
||||
| (d) 다른 S3 호환 구현(SeaweedFS, Garage, LocalStack S3, Ceph RGW) | MinIO 의존 제거 | `If-None-Match`·`If-Match` 의미가 구현마다 다름. 계약 lane의 판정 기준(create-only 지원 여부)을 다시 정해야 함 | 장기 선택지. 단기 복구 수단은 아님 |
|
||||
| (e) lane을 explicit-only로 내리고 mainCheck에서 빼기 | 게이트 즉시 초록 | 실제 벤더 증거 0개가 됨(기준 5 위반) | 기각 |
|
||||
|
||||
후보의 현재 가용성은 외부 접속 금지 규칙 때문에 확인하지 않았다.
|
||||
- 완료 기준: 이미지 참조 한 곳, 미러 또는 대체 공급원에서 두 lane 통과, 공급원 실패 시 이유가 구분되는 메시지.
|
||||
|
||||
### 05-10 알림: collapse 미지원 예외가 try 밖에서 터져 끝없이 재시도된다
|
||||
|
||||
- 성격: 확인된 결함. 관점 6, 7, 11.
|
||||
- 근거: `NotificationDispatchService.java:331` `requireCollapseSupported`가 `new ProviderSubmission(...)` 인자를 만드는 중에 실행되고, `try`(`:334`)보다 앞이다. 던진 `ProviderCallNotStartedException`(`:355-359`)이 dispatch 밖으로 나가고 attempt는 DISPATCHING으로 남는다. 05-01 때문에 recovery가 이 행을 "확정 미시작"으로 보고 다시 큐에 넣는다. collapse는 HTTP 요청으로 들어온다(`web-notification/.../SubmitNotificationHttpRequest.java`). 템플릿의 provider(SES·SMTP)는 둘 다 collapse를 지원하지 않는다.
|
||||
- 영향: collapse를 지정한 요청은 약 lease 주기마다 같은 실패를 반복한다. attempt 행이 계속 늘고 재시도 한도도, FAILED 종료도 없다.
|
||||
- 심각도·우선순위: Medium / P2. 발송은 일어나지 않는다. 대신 독이 든 요청 하나가 영구히 워커를 쓴다.
|
||||
- 최소 개선 방향: collapse 확인을 attempt insert 전, `failBeforeAttempt` 경로(`:167-187`)로 옮긴다. 05-01을 고치면 루프는 reconcile로 바뀌지만 원인은 여기서 고쳐야 한다.
|
||||
|
||||
### 05-11 알림: SMTP 실패가 전부 "결과 불명"이 되어 재시도 없이 운영자 대기로 멈춘다
|
||||
|
||||
- 성격: 확인된 결함. 관점 6, 7, 8.
|
||||
- 근거: `adapter/outbound/notification/.../provider/smtp/JavaMailSenderSmtpDispatch.java:44-52`가 모든 `MailException`을 `replyCode=empty, dataCommitted=true`로 감싼다. 그래서 `SmtpFailureClassifier.java:49-75`의 4xx/550 분기는 운영 경로에서 실행되지 않는다. SMTP는 상태 조회가 없어 reconcile은 `Unsupported` → `RECONCILIATION_REQUIRED`(`ReconciliationService.java:122-127,148-159`).
|
||||
- 영향: 릴레이 다운·인증 실패·잘못된 수신자처럼 "보내지 않은 것이 확실한" 실패도 재시도되지 않고 운영자가 하나씩 처리해야 한다.
|
||||
- 심각도·우선순위: Medium / P2.
|
||||
- 최소 개선 방향: nested `SMTPSendFailedException`·`SMTPAddressFailedException`의 return code를 꺼낸다. `MailAuthenticationException`과 connect 실패는 `dataCommitted=false`. 같은 성격으로 SES 사전 오류(`SesNotificationProviderAdapter.java:107-138`, `SesRequestMapper.java:99`)를 `ProviderCallNotStartedException`으로 감싼다.
|
||||
- 검증: 실제 `JavaMailSender` 예외를 넣는 분류 테스트, GreenMail 같은 실제 SMTP 컨테이너 테스트 1건(기준 5).
|
||||
|
||||
### 05-12 파일 서버: tus PATCH가 쓰기를 커밋한 뒤 `file:read`를 요구한다
|
||||
|
||||
- 성격: 확인된 결함. 관점 1, 15, 17.
|
||||
- 근거: `web-fileserver/.../TusController.java:171-181` append(`file:upload`) 커밋 후 `:183` `status.handle(...)` 호출. `GetUploadStatusApplicationUseCase.java:28` `@RequiresPermission("file:read")`. 기본 역할은 상속하지 않는다(`security.yml:51-59`, "a writer that also reads holds both roles"). 리뷰어가 직접 읽었다.
|
||||
- 영향: write 역할만 가진 클라이언트는 바이트·offset이 커밋됐는데 403을 받는다. 자동 finalize(`:184-191`)가 실행되지 않고 HEAD로 이어받기도 못 한다.
|
||||
- 심각도·우선순위: Medium / P2. 두 역할을 함께 주면 피할 수 있지만 문서가 권하는 최소 권한 구성에서 깨진다.
|
||||
- 최소 개선 방향: `AppendUploadResult`에 `expectedLength`·`expiresAt`을 실어 status 재조회를 없앤다. 버린 대안 — `ROLE_FILE_WRITE`에 `file:read`를 더함: 최소 권한 원칙과 security.yml의 의도에 어긋난다.
|
||||
|
||||
### 05-13 파일 서버: 정리 worker가 기본으로 꺼져 있다
|
||||
|
||||
- 성격: 확인된 결함(위험한 기본값). 관점 7, 19, 28.
|
||||
- 근거: `composition/fileserver-platform/.../config/module-defaults/fileserver.yml:79` `admin.enabled: false`, `:82` `cleanup.enabled: false`. `FileserverCleanupConfiguration.java:24-28`은 true일 때만 켜진다. 만료 세션을 정리 작업으로 바꾸는 곳은 `DefaultCleanupService.java:126`뿐이다. 기동 검증에 cleanup 관련 검사가 없다.
|
||||
- 영향: 기본 구성에서 staging `.part`, 거절·삭제된 콘텐츠가 쌓여 결국 high-water에 걸린다. 05-07과 합쳐지면 디스크 문제가 더 빨리 온다.
|
||||
- 심각도·우선순위: Medium / P2.
|
||||
- 최소 개선 방향: cleanup을 기본 on으로 한다. 끄려면 운영 프로필에서 명시적 이유 키를 요구하거나 기동 경고를 낸다.
|
||||
|
||||
### 05-14 HTTP client: 기본 설정에서 결과 불명 분류가 틀린 경로로 나간다
|
||||
|
||||
- 성격: 확인된 결함. 관점 6, 8, 17.
|
||||
- 근거: ① `resilience/DefaultRetryEligibilityEngine.java:19-21`의 maxAttempts 거부가 `:47-49`의 ambiguity 판정보다 먼저다. 기본 maxAttempts=1이면 SENT_NO_RESPONSE인 비멱등 요청이 `HttpAmbiguousExecutionException`이 아니라 일반 timeout 예외로 나간다. README는 ambiguous 예외를 약속한다. ② `restclient/BlockingAttemptExecutor.java:222-234`가 transport 호출 전에 단계를 REQUEST_BODY로 올려, `ApacheFailureClassifier`의 "보내기 전 실패" 분기가 실행될 수 없다. TLS handshake timeout이 SENT_NO_RESPONSE가 된다. ③ `:136`에서 계산한 evidence를 `StableBlockingExceptionMapper.java:26-27`이 덮어써 HTTP/2 REFUSED_STREAM → NOT_SENT 보정이 사라진다.
|
||||
- 영향: 호출자가 "보냈는지 모름"과 "안 보냄"을 구분하지 못한다. POST를 정산해야 할 때 일반 실패로 보고 다시 보내거나, 안 보낸 요청을 운영자 대기로 보낸다.
|
||||
- 심각도·우선순위: Medium / P2. retry는 idempotency 선언으로 막혀 있어(`RetryContext.java:71-75`) 클라이언트 자체가 중복 POST를 만들지는 않는다. 오류 계약이 틀린 것이다.
|
||||
- 최소 개선 방향: ambiguity 판정을 먼저 한다. 단계는 연결 이벤트나 엔진 예외 타입으로 정한다. evidence는 더 구체적인 쪽을 유지한다. gateway 수준의 ambiguous 테스트를 추가한다.
|
||||
|
||||
### 05-15 HTTP client: 바인딩되지만 동작하지 않는 설정 키, 0 timeout 허용
|
||||
|
||||
- 성격: 확인된 결함. 관점 5, 19, 21. capability 기준 3 위반.
|
||||
- 근거: `timeout.request-write-idle`, `timeout.proxy-connect`, `proxy.connect-timeout`, `pool.eviction-interval`, `pool.shutdown-timeout`, `observability.operation-name-required` 6개는 profile factory 밖 소비처가 0이다. `profile/ClientProfileValidator.java:94-107`은 비슷한 미지원 키를 거부하면서 이 6개는 받는다. `:109-118`은 totalCall만 0을 거부한다(Apache에서 0은 무한). maxAttempts 상한이 없고, budget 이름이 없으면 retry budget이 무제한이다(`RestClientRuntimeFactory.java:90`).
|
||||
- 영향: 운영자가 timeout을 설정했다고 믿지만 적용되지 않는다. 0을 넣으면 무한 대기.
|
||||
- 심각도·우선순위: Medium / P2.
|
||||
- 최소 개선 방향: 6개 키를 지우거나 `*_UNSUPPORTED` 위반으로 거부한다. 모든 timeout에 `> 0`, maxAttempts에 상한.
|
||||
|
||||
### 05-16 capability 완료 기준 5가 영역 전체에서 지켜지지 않는다
|
||||
|
||||
- 성격: 확인된 결함(규칙과 구조의 불일치). 관점 10, 21, 23, 27.
|
||||
- 근거:
|
||||
- 포트 계약 테스트가 포트 소유 모듈 testFixtures가 아니라 adapter의 `src/test`에 있다: `notification/.../testkit/ProviderAdapterContract.java`, `CallbackContract.java`, `fileserver/.../testkit/ContentStoreContract.java`, `objectstorage/.../contract/ObjectStorageProviderContract.java`. `application-notification`, `application-fileserver`, `application-objectstorage`에는 testFixtures 디렉터리가 없다.
|
||||
- cache·idempotency·rate-limit 포트에는 공통 계약이 없다. testFixtures에 있는 것은 `DistributedLeaseContract`, `DurableOperationStoreContract`, `OutboxLeaseFencingContract`뿐이다(`application-core/src/testFixtures`). 그래서 05-02·05-03이 fake와 adapter 양쪽에서 같은 버그로 숨었다.
|
||||
- `ObjectStorageProviderContract`는 local-dev provider만 상속하고 MinIO 테스트는 상속하지 않는다.
|
||||
- 실제 벤더 테스트: Redis는 Testcontainers가 아니라 외부 topology lane이고 `-Predis.topology.mode` 없이는 explicit-only다. HTTP client Toxiproxy lane은 `integrationCheck`에만 있다. 알림 SES/SMTP 실제 테스트는 없다(`ProviderSandboxSmokeTest`는 env로만 켜짐). 이번 게이트에서 돈 실제 벤더 lane은 MinIO 2개뿐이었고 둘 다 실패했다(05-09).
|
||||
- 영향: 파생 서비스가 새 adapter(예: 다른 캐시, 다른 메일 provider)를 만들 때 상속할 계약이 없다. AGENTS.md 규칙 6과 기준 5가 문서에만 있다.
|
||||
- 심각도·우선순위: Medium / P2.
|
||||
- 최소 개선 방향: 포트 소유 leaf에 `java-test-fixtures`를 붙이고 계약 클래스를 옮긴다. cache·idempotency 계약을 새로 만든다(05-02·05-03의 검증 수단). Redis·HTTP client 실제 lane 하나씩을 `mainCheck`에 넣는다.
|
||||
- 버린 대안: 기준 5를 완화해 "adapter test에 계약이 있으면 충분"으로 바꾸기 — 파생 서비스가 계약을 재사용할 수 없어 기준의 목적(갈아끼울 수 있는 포트)이 사라진다.
|
||||
|
||||
### 05-17 Redis: 연결 실패를 "결과 불명"으로 보고하고, 시간 초과된 연결을 pool에 돌려준다
|
||||
|
||||
- 성격: 확인된 결함. 관점 6, 12, 14.
|
||||
- 근거: `redis-runtime/.../RedisRuntimeOwner.java:201` `openLane` 예외가 `RedisLaneUnavailableException`이 아니어서 `SemanticRedisCall`(`:73,109-111`)이 unknown으로 분류한다. Redis가 완전히 내려가면 멱등성 claim은 `Indeterminate`(→ reconcile 경로), rate-limit은 `NO_MUTATION_CONFIRMED`가 된다. 명령은 하나도 보내지 않았다. 또 `SemanticRedisCall`은 실패·시간 초과 뒤 `invalidate()`를 부르지 않는다(`:98-112`). 로컬 await 200ms, Lettuce timeout 2초(`RedisTopologyClientFactory.java:295`)라 큐에 명령이 남은 연결이 다음 사용자에게 간다. 최악 지연: lane 대기 2s + 연결 2s + 명령 0.2s ≈ 4.2s, health probe는 두 lane에서 약 9.5s(`RedisHealthContributor.java:86-104`).
|
||||
- 영향: Redis 장애 때 "안 보냈음"이 확실한 경우도 reconcile·불명 처리로 간다. 시간 초과 직후 다음 명령이 앞 명령의 응답을 기다린다.
|
||||
- 심각도·우선순위: Medium / P2. 결정 24(포화 시 UNAVAILABLE)는 lane 포화 경우만 충족한다.
|
||||
- 최소 개선 방향: 연결 열기 실패를 lane unavailable로 분류한다. 실패·시간 초과 lease는 invalidate한다. rate-limit은 남은 caller deadline을 borrow·connect에도 적용한다.
|
||||
|
||||
### 05-18 설정 prefix·바인딩 방식이 capability 기준 4와 다르다
|
||||
|
||||
- 성격: 확인된 결함(규칙 불일치). 관점 19, 23.
|
||||
- 근거: redis-runtime은 `@ConfigurationProperties("app.redis")`(`RedisRuntimeAutoConfiguration.java:85`)와 setter+`validate()` 방식이다. cache-redis는 `app.capabilities.*`와 `app.rate-limit.*`를 쓴다. 알림은 `@Value` 두 곳에 기본값을 중복한다(`NotificationCallbackMvcController.java:58`, `NotificationSubmissionConfiguration.java:91`). 같은 auto-configuration이 R0 legacy prefix(`app.notification.slack-webhook`, `google-email`)를 함께 import한다(`NotificationPlatformAutoConfiguration.java:29-31`).
|
||||
- 영향: 모르는 키 거부(StrictSettingsBinder)가 일부 모듈에서 동작하지 않는다. 운영자가 한 모듈의 설정을 여러 트리에서 찾아야 한다.
|
||||
- 심각도·우선순위: Low / P3. 결정 36처럼 예외로 인정할지 정하고, 인정하면 AGENTS.md 규칙 4에 적는다.
|
||||
|
||||
### 05-19 bootstrap이 알림·파일 서버 권한 이름을 안다
|
||||
|
||||
- 성격: 확인된 결함(기준 7). 관점 3, 27.
|
||||
- 근거: `app-bootstrap/src/main/resources/config/security.yml:40-45`(notification 권한 2개), `:50-59`(`ROLE_FILE_*` → `file:*`). 모듈을 빼도 이 매핑이 남고, 모듈을 넣는 서비스는 bootstrap 파일을 알아야 한다.
|
||||
- 심각도·우선순위: Low / P3. 남은 매핑은 동작하지 않는 문자열일 뿐이다.
|
||||
- 최소 개선 방향: 각 composition 모듈의 `module-defaults/*.yml`이 `app.security.authz.role-permissions.<role>` 항목을 싣는다. Spring Binder는 여러 property source의 Map 항목을 합치므로 bootstrap은 이 줄들을 지울 수 있다. 버린 대안 — 모듈별 `RolePermissionContributor` bean: 코드가 늘고 설정 한 곳에서 보이지 않는다.
|
||||
- 완료 기준: 모듈 한 줄을 지우면 security 설정에서 해당 권한이 사라진다.
|
||||
|
||||
### 05-20 SES 콜백: replay 창 5분이 장애 뒤 SNS 재전송을 버린다
|
||||
|
||||
- 성격: 구조적 위험(SNS 재전송 시 Timestamp가 유지된다는 점은 AWS 동작에 대한 추론). 관점 6, 11, 28.
|
||||
- 근거: `SesCallbackAdapter.java:79-81,101-111`이 메시지 `Timestamp`와 수신 시각 차이가 5분(`notification.yml` replay-skew)을 넘으면 거부한다. 중복 방지는 이미 ledger unique 제약이 한다(`persistence-notification` `V1__…sql:174-178`). 또 `SnsSignatureVerifier.java:80`은 cert fetch 실패(`IllegalStateException`, `NotificationCallbackProviderConfig.java:74-86`)를 잡지 않아 500이 된다.
|
||||
- 영향: 서버가 5분 넘게 내려가 있었다면 그동안의 bounce·complaint가 영구 손실되고 suppression이 누락된다. 반송 주소로 계속 보내 발신 평판이 떨어질 수 있다.
|
||||
- 심각도·우선순위: Medium / P2.
|
||||
- 최소 개선 방향: 중복은 unique 제약에 맡기고 창을 SNS 재시도 기간에 맞춰 늘린다(설정 키는 이미 있다 — 기본값 변경). cert fetch 실패는 일시 장애(503)로 명시 매핑한다.
|
||||
|
||||
### 05-21 identifier leaf: 이름·문서가 내용과 맞지 않는다
|
||||
|
||||
- 성격: 개선 제안. 관점 4, 24, 26.
|
||||
- 근거: main 코드는 `HmacUserPrincipalPseudonymizer` 한 클래스(53줄)다. README·CLAUDE.md·`package-info.java`는 "식별자 생성/인코딩(UUIDv7), clock, crypto/random"을 말한다. README `:3`의 패키지 루트(`dev.caskeleton.adapter.identifier`)는 실제(`…adapter.outbound.identifier`)와 다르다. README는 `app-bootstrap`이 조립한다고 적지만 실제는 `composition/service-runtime/.../PseudonymizationConfig.java:26`이다. `composition:fileserver-platform`의 registry edge(`adapter-outbound-identifier`)는 build.gradle에서 쓰이지 않는다. 테스트에 알려진 정답 벡터(RFC 4231)가 없어 charset·알고리즘을 바꾸는 변이가 살아남을 수 있다(추론).
|
||||
- 심각도·우선순위: Low / P3.
|
||||
- 최소 개선 방향: leaf 이름은 유지하고(소비자 영향) 문서를 실제 내용으로 고친다. 정답 벡터 테스트 1건. 쓰지 않는 registry edge 삭제.
|
||||
|
||||
### 05-22 파일 서버: finalize가 writer lease 없이 돈다
|
||||
|
||||
- 성격: 구조적 위험(결과는 추론). 관점 12.
|
||||
- 근거: `FinalizeUploadApplicationUseCase.java:118-148`은 lease를 잡지 않는다. `AtomicMoveContentPublisher.java:32-39`는 hash 계산과 move 사이에 틈이 있다. `LocalUploadContent.java:83-105`의 lease 해제는 노드 단위 `instanceId`가 같으면 해제한다.
|
||||
- 영향: 길이를 미루는 Draft-12 업로드에서 append와 finalize가 겹치면 INTEGRITY_MISMATCH 후 고아 파일, 레코드는 VERIFYING에 멈춘다.
|
||||
- 심각도·우선순위: Low / P3(Draft-12 경로에서만 도달, 켜면 Medium).
|
||||
- 최소 개선 방향: finalize도 lease·fence로 감싸고 해제는 lease token 기준으로.
|
||||
|
||||
### 05-23 작은 결함 묶음 (각각 독립, Low / P3)
|
||||
|
||||
| ID | 내용 | 근거 |
|
||||
| --- | --- | --- |
|
||||
| 05-23a | 0바이트로 선언한 업로드에 1바이트를 쓸 수 있고, 그 세션은 만료까지 finalize 불가 | `UploadSessions.java:67`, `LocalUploadContent.java:108` `Math.max(expected, 1)` |
|
||||
| 05-23b | S3 mutation의 500/503을 "확정 미반영"으로 분류. 요청 본문 bridge가 재구독 불가라 `maxAttempts>1`이어도 PUT 재시도는 항상 실패 | `S3ProviderErrorMapper.java:45,63`, `S3AsyncRequestBodyBridge.java:60-63`, `S3AsyncClientFactory.java:28-32`. kernel이 다음 시도에서 `resolveCreate`로 확인해 손상은 없음 |
|
||||
| 05-23c | 알림 dedup DROP 결과를 저장하지 않아 같은 idempotency key의 응답이 시간에 따라 바뀜 | `NotificationSubmissionService.java:135-138` |
|
||||
| 05-23d | module-defaults 파일 간 같은 키·같은 파일명을 검출하지 않음(지금 7개 파일 사이 충돌 0건) | `support/.../ModuleDefaultsEnvironmentPostProcessor.java:43-49` |
|
||||
| 05-23e | Redis `DEGRADED` 상태가 health status order에 없음 — 전체 health가 DOWN 대신 DEGRADED로 보일 수 있음(추론, 미검증) | `RedisRuntimeAutoConfiguration.java:70-71`, yml에 `status.order` 없음 |
|
||||
| 05-23f | rate-limit dedup 정책이 기본으로 켜져 있지만 adapter·Lua 어디서도 쓰지 않음. `evaluationId`도 무시 → INDETERMINATE 뒤 재시도가 두 번 차감 | `RateLimitPolicy.java:36`, `EdgeRateLimitTransportBridge.java:69` |
|
||||
| 05-23g | HTTP client 401마다 retry 가능 여부와 상관없이 토큰을 다시 받음 | `DefaultGenericHttpGateway.java:194` |
|
||||
|
||||
다른 영역으로 넘기는 것(>): `AuthenticationMode.REDIS_SESSION`이 요구하는 `redisVersionedSessionRepository` bean을 main 코드 어디서도 만들지 않는다(`app-bootstrap/.../AuthenticationModeSettings.java:50-53`) — 인증 영역.
|
||||
|
||||
## 4. 31절 시나리오 추적
|
||||
|
||||
### 4.1 외부 응답 지연·유실 — 알림 1건 발송 (적용)
|
||||
|
||||
`POST /v1/notifications` → 제출 → dispatch → SES 호출을 따라갔다.
|
||||
|
||||
```text
|
||||
HTTP 요청 → web-notification 컨트롤러(DTO 검증, @RequiresPermission notification:submit)
|
||||
→ NotificationSubmissionService: tx { (tenant, idempotency_key) UNIQUE insert, 지문 비교 }
|
||||
→ (스케줄러) RecipientClaimSql: FOR UPDATE SKIP LOCKED, lease 2m
|
||||
→ tx { attempt insert (evidence = 미시작 확정) } ← 05-01
|
||||
→ lease 재확인 → [tx 밖] SES 호출 (connect 2s, apiCallTimeout 10s, SDK 재시도 꺼짐)
|
||||
→ tx { recorder.record (owner + fence 조건) } → retryPolicy → lease 해제
|
||||
```
|
||||
|
||||
| 항목 | 결과 |
|
||||
| --- | --- |
|
||||
| 입력 신뢰 수준 | HTTP 본문은 비신뢰. DTO 검증 후 `AcceptNotificationCommand` 생성자가 category를 강제(`:71-72`) |
|
||||
| 인가 위치 | use case 메서드의 `@RequiresPermission`, 관리자 연산은 `AdminAuthorizationGuard` |
|
||||
| 규칙 소유 객체 | 중복 제출: DB unique 제약 + 지문. 발송 상태: `RecipientDeliveryRecord`, 재시도: `RetryPolicy` |
|
||||
| 트랜잭션 | insert·claim·attempt insert·결과 기록이 각각 짧은 트랜잭션. provider 호출은 트랜잭션 밖(`NotificationDispatchService.java:215`) — 맞다 |
|
||||
| 외부 부작용 | SES·SMTP 발송. provider 쪽 idempotency key는 없다(SES API가 지원하지 않음) |
|
||||
| 성공의 의미 | 제출 응답은 "접수", 발송 성공은 provider 수락(`SubmissionOutcome`)과 콜백 기반 delivery 결과가 따로다 |
|
||||
| 오류 변환 | timeout → AMBIGUOUS → reconcile(SES), SMTP는 전부 AMBIGUOUS(05-11) |
|
||||
| 진단 정보 | attempt 행에 evidence·failure code, health endpoint의 backlog·stuck lease 임계값 |
|
||||
| 결론 | 정상 경로와 timeout 분류는 계약대로다. 프로세스 중단 시 결과 불명이 "확정 미시작"으로 바뀌는 구멍(05-01)과 독 요청 루프(05-10)가 남는다. |
|
||||
|
||||
### 4.2 큰 입력 — tus 업로드 (적용)
|
||||
|
||||
`POST /v1/uploads`(Upload-Length) → `PATCH`(Upload-Offset, body) → finalize.
|
||||
|
||||
| 항목 | 결과 |
|
||||
| --- | --- |
|
||||
| 입력 신뢰 | `Upload-Length` 상한(`TusRequestParser.java:75`)과 policy 상한(`CreateUploadApplicationUseCase.java:171-177`). PATCH body는 쓰기 전 상한 검사(`LocalAppendEngine.java:221`), 선언 초과 거절(`:249-268`), 실패 시 truncate(`:82-101`), 고정 버퍼 스트리밍 |
|
||||
| 경로 | 서버가 만든 키만 경로가 된다. normalize 후 `startsWith` 검사(`DefaultPhysicalPathResolver.java:26-27,115-133`), NOFOLLOW로 한 단계씩 내려감. 클라이언트 파일명은 경로에 쓰이지 않는다 |
|
||||
| 콘텐츠 타입 | magic byte 판별 6종 또는 octet-stream(`MediaTypeVerifier.java:23-30`), 다운로드에 `nosniff`, 기본 `attachment`(`HttpContentDispositionFactory.java:41-86`) |
|
||||
| 인가 | 역할(`@RequiresPermission file:*`) + `FileAccessPolicyPort`(소유자·tenant) 둘 다(결정 32 반영). 테스트 공백은 05-08 |
|
||||
| 동시성 | offset·lease·terminal 전이가 조건부 UPDATE(`UploadLeaseRepository.java:26-148`). offset 검사는 변이 M1로 테스트가 잡음을 확인 |
|
||||
| 결론 | 크기·경로·타입 방어는 잘 돼 있다. 남은 것은 디스크 상한(05-07), 권한 조합(05-12), 정리 기본값(05-13) |
|
||||
|
||||
### 4.3 다른 사용자 리소스 접근 — 파일 다운로드 (적용)
|
||||
|
||||
`GET /v1/files/{id}/content` → `PrepareDownloadApplicationUseCase`가 `authorize(DOWNLOAD, subject, descriptor)` → `RoleBasedFileAccessPolicy`가 소유자·tenant 비교. 현재 코드는 다른 사용자의 id로 요청하면 거부한다. 하지만 이 검사를 지워도 게이트가 통과한다(변이 M2, 05-08). 콘텐츠를 여는 use case는 descriptor를 그대로 신뢰한다(`OpenDownloadContentApplicationUseCase.java:38-40`).
|
||||
|
||||
### 4.4 중복·동시 요청 — 멱등성 claim (부분 적용)
|
||||
|
||||
Redis 멱등성 store는 Lua 단일 키 원자 실행과 Redis `TIME`을 쓴다. 같은 owner의 재시도는 `ALREADY`로 처리한다. renew가 그 분기에 먹혀 lease를 늘리지 못한다(05-02). executor 조립은 `composition:idempotency`(다른 영역)다.
|
||||
|
||||
### 4.5 선택 어댑터 제거 (적용)
|
||||
|
||||
`app-bootstrap/build.gradle:162-171`에서 이 영역의 선택 모듈은 모두 주석 처리돼 있고 기본 조립은 support·identifier만 `implementation`으로 받는다(`:211-212`). `ci`의 `:app-bootstrap` 테스트가 이 기본 조립으로 통과했다. 모듈을 빼도 남는 흔적은 `security.yml`의 권한 매핑(05-19)과 Redis readiness 관련 주석·session bean 이름(`observability.yml:51-77`, `AuthenticationModeSettings.java`)이다. 각 모듈 기준 충족 여부는 7절 표에 있다.
|
||||
|
||||
### 4.6 적용 제외
|
||||
|
||||
| 시나리오 | 사유 |
|
||||
| --- | --- |
|
||||
| 정상 쓰기 요청(일반 도메인) | 이 영역은 도메인 쓰기가 아니라 capability. 4.1·4.2가 같은 경계를 다룬다 |
|
||||
| DB 오류·경쟁 | 영역의 SQL은 persistence leaf(다른 영역). 조건부 UPDATE 사용만 확인 |
|
||||
| 메시지 중복·역순 | messaging은 다른 영역. SNS 콜백 중복은 ledger unique로 처리됨을 확인(05-20) |
|
||||
| 신·구 버전 공존 | 캐시 envelope schema version(`CacheEnvelope.CURRENT_SCHEMA_VERSION`)만 확인, 실험 안 함 |
|
||||
| 여러 서버의 작업 실행 | 4.1의 lease·SKIP LOCKED로 대신함. 다중 인스턴스 실험은 미실행 |
|
||||
| 세션·토큰 갱신 경쟁 | HTTP client 토큰 single-flight(`SingleFlightTokenLoaderTest`)만 확인. 세션은 인증 영역 |
|
||||
| 종료·재시작 | 알림 shutdown-grace 20s 설정 확인. 05-01이 이 시나리오의 결함이다. 실제 종료 실험은 안 함 |
|
||||
|
||||
## 5. 41절 설계 선택 검토
|
||||
|
||||
### 5.1 알림 attempt의 "요청 시작 증거"로 recovery 경로를 고르는 설계
|
||||
|
||||
1. 필요한 것: 워커가 죽은 뒤 남은 DISPATCHING 건을 처리해야 한다. 상태 조회가 없는 provider(SMTP)도 있다.
|
||||
2. 지킬 성질: provider가 받았을 수 있는 요청은 다시 보내지 않는다. 확실히 안 보낸 것만 다시 큐에 넣는다.
|
||||
3. 현재 보장: `provablyNeverStarted`가 PROVEN+false만 requeue한다(`LeaseRecoveryService.java:101-106`). 규칙 자체는 맞다. 하지만 그 증거를 insert 시점에 "확정"으로 쓰고 갱신하지 않아 보장이 깨진다(05-01).
|
||||
4. 대안: (a) 모든 미완료 attempt를 reconcile(이전 방식). (b) 증거 기반 분기 + insert는 UNKNOWN. (c) 호출 직전 증거 갱신 쓰기 추가.
|
||||
5. 비용: (a) 단순하지만 상태 조회 없는 provider는 전부 운영자 대기. (b) 쓰기 추가 없음, "확정 미시작"이 생기는 곳이 명확(adapter 결과·lease 상실 종료). (c) 쓰기 1회 추가로 insert 직후 crash만 자동 requeue.
|
||||
6. 선택: (b). 현재 설계의 의도(증거로 분기)를 유지하면서 증거가 참인 시점에만 기록한다.
|
||||
7. 다시 볼 조건: 상태 조회를 지원하는 provider가 대부분이 되면 (a)로 단순화할 수 있다. insert 직후 crash 비율이 측정상 의미 있으면 (c).
|
||||
|
||||
### 5.2 캐시 무효화 모델: region generation + 키 GETDEL
|
||||
|
||||
1. 필요한 것: 키 단위·region 단위 무효화, Redis 장애 시 원본으로 우회.
|
||||
2. 지킬 성질: 무효화 뒤 옛 값이 다시 보이지 않는다(적어도 정해진 시간 안에).
|
||||
3. 현재 보장: region은 generation 카운터, 인스턴스는 softTtl(30s)마다 재확인. 키는 `GETDEL`. 느린 loader가 무효화 뒤 옛 값을 다시 쓰는 것은 막지 못한다(05-04). revision 조건은 구현되지 않았다(05-03).
|
||||
4. 대안: (a) 현상 유지 + 문서에 "최대 hard TTL 동안 옛 값 가능" 명시. (b) 키 tombstone + revision CAS. (c) pub/sub로 무효화 전파(로컬 캐시가 있을 때만 의미). (d) 분산 lock single-flight.
|
||||
5. 비용: (a) 0, 일관성 약함. (b) Lua 하나, tombstone TTL 관리. (c) pub/sub 전송이 아직 없다(G-4i). (d) 왕복 증가, lock 만료 처리.
|
||||
6. 선택: (b). 이미 `ONLY_IF_OBSERVED`용 Lua CAS가 있어 같은 모양으로 확장된다.
|
||||
7. 다시 볼 조건: 로컬(L1) 캐시를 추가하면 (c)가 필요하다. 쓰기 빈도가 높아 CAS 충돌이 측정되면 재검토.
|
||||
|
||||
### 5.3 MinIO 하나에 기대는 실제 S3 벤더 증거
|
||||
|
||||
1. 필요한 것: S3 호환 저장소에서 adapter 계약이 맞다는 실행 증거(기준 5).
|
||||
2. 지킬 성질: 게이트가 초록이면 실제 벤더로 계약을 확인했다는 뜻이어야 한다.
|
||||
3. 현재 보장: digest 고정 + `rejectSkipped`로 fail-closed. 공급원이 사라지자 실패했다 — 성질은 지켰다. 대신 복구 수단이 없고, 고정 버전 자체도 create-only를 지원하지 않는다(`UNSUPPORTED`).
|
||||
4~6. 대안과 선택은 05-09 표. 조직 레지스트리 미러를 고른다.
|
||||
7. 다시 볼 조건: 운영 대상이 AWS S3로 정해지면 `objectStorageAwsQualificationTest`(현재 explicit-only)를 정기 실행하고 MinIO는 보조로 내린다.
|
||||
|
||||
## 6. 리팩토링 후보
|
||||
|
||||
| 대상 | 무엇을, 왜 | 보존 조건 |
|
||||
| --- | --- | --- |
|
||||
| notification `dispatch/` 46파일 | `submission/`, `dispatch/`, `reconciliation/`, `contact/`로 나눈다. 한 패키지에 기능 4개 | public 타입 이름·api surface 스냅샷(`docs/notification/api-surface-snapshot.txt`) 갱신, 테스트 패키지 동기 이동 |
|
||||
| notification adapter의 R0 legacy(`core/`, `slack/`, `email/google/`) | platform과 한 auto-config에 있음. 별도 leaf로 떼거나 삭제 결정 | `app.notification.slack-webhook`·`google-email` 키 동작, 해당 env 키 |
|
||||
| 포트 계약 테스트 위치 | adapter `src/test` → 포트 소유 leaf testFixtures(05-16) | 상속하는 구현 목록이 줄지 않을 것 |
|
||||
| `RedisCacheRegionAdapter`의 `CacheKeys` 가변 generation | `RegionGeneration` 객체로 분리(S3-#12a) | softTtl 재확인 주기, generation 0 처리 |
|
||||
| Redis health indicator 2개 | 상태 값만 인자로 받는 하나로(S3-#13c) | readiness 그룹 멤버 이름 `redisRequired`/`redisOptional` |
|
||||
| httpclient 단계 추적 | 연결 이벤트로 단계를 올리게(05-14) | `ExecutionEvidence` 값의 의미, 기존 분류 테스트 |
|
||||
| support의 `messaging/` encoder | support는 module-defaults·startup 규칙이 책임. messaging encoder는 messaging bridge 쪽이 맞다 | `IntegrationEventEncoderAutoConfiguration` bean 이름, 조립 순서 |
|
||||
| `NotificationPlatformSettings.ProviderProfile` | provider마다 전용 필드(`Ses ses`)를 추가하는 구조 → provider별 설정 record를 sealed 하위 타입으로 | 기존 키 경로 `…profiles[n].ses.*`, 검증 메시지 |
|
||||
|
||||
## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료)
|
||||
|
||||
### 7.1 capability 모듈별 완료 기준 현황
|
||||
|
||||
| 기준 | redis(runtime+cache) | httpclient | objectstorage | notification | fileserver |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 1 포트만 호출 | O | X — 호출 surface가 모듈 타입(`GenericHttpGateway`, `@HttpClientProfile`). 라이브러리형이라 `implementation`이 필요한데 README는 runtimeOnly 한 줄이라고만 함 | O | O | O |
|
||||
| 2 imports·enabled·순서 | O | O(순서 의존 없음) | O | P — adapter 쪽 순서 지정 없음 | P — `beforeName`만 |
|
||||
| 3 동작하지 않는 키 없음 | P — sample 죽은 키(P20-new-3) | X — 05-15 | O | P — R0 키 동거 | O |
|
||||
| 4 prefix 하나·StrictSettingsBinder | X — 05-18 | O | O | X — `@Value` 중복 | O |
|
||||
| 5 계약 테스트·실제 벤더 | P — lease만, 실제 lane은 explicit-only | P — 계약 위치, 실제 lane은 integrationCheck만 | P — 계약 위치, MinIO 실패(05-09) | X — testFixtures 없음, 실제 벤더 없음 | P — 계약 위치, Postgres는 다른 leaf |
|
||||
| 6 README 3가지 | P — redis-runtime README 없음 | O | O | O(composition README) | P — web-fileserver README 없음 |
|
||||
| 7 모듈만 안다 | O(주석 외) | O | O | P — security.yml | P — security.yml |
|
||||
|
||||
### 7.2 새 기능을 추가할 때 개발자가 내려야 하는 판단
|
||||
|
||||
**외부 API client 추가 (httpclient)**
|
||||
1. profile 설정(`APP_HTTPCLIENT_CLIENTS_N_*`): base-url, allowed-hosts·ports, body 상한, prod TLS profile.
|
||||
2. `@HttpExchange` 인터페이스 + 메서드마다 `@HttpOperationPolicy(name, idempotency)`.
|
||||
3. application-core에 포트를 정의하고 adapter leaf가 httpclient를 `implementation`으로 받는다.
|
||||
- 판단 지점: 이 연산은 멱등한가(아니면 idempotency key를 보낼 수 있는가)? 결과 불명(`SENT_NO_RESPONSE`)을 어떻게 정산하는가? 4xx 중 무엇이 업무상 정상인가(05-05가 고쳐지기 전에는 breaker에 주의)? 전체 deadline이 transport timeout 합보다 큰가(05-06)?
|
||||
|
||||
**알림 provider·채널 추가**
|
||||
1. `ProviderType`, adapter·failure classifier, `ProviderRuntimeAssembler`, `Notification<X>ProviderConfig`, `ProviderProfile` 필드, `NotificationSecretRequirements`, `notification.yml`, api surface 스냅샷·evidence manifest.
|
||||
2. 채널이면 `Channel`, sealed `NotificationContent`, `ContactPointType`, renderer·slot policy, persistence 매핑, web DTO까지.
|
||||
- 판단 지점: provider가 상태 조회를 지원하는가(없으면 결과 불명이 전부 운영자 대기)? 어떤 예외가 "확실히 안 보냄"인가? 콜백 서명 방식과 replay 창은? collapse·priority 같은 선택 기능을 지원하는가?
|
||||
|
||||
**파일 연산 추가**
|
||||
1. `FileOperation` 값과 `RoleBasedFileAccessPolicy.tierOf` 매핑, `@RequiresPermission`, security 매핑.
|
||||
2. use case 안에서 `authorize(op, subject, Optional.of(record.toDescriptor()))` — descriptor를 빠뜨리면 소유자 검사가 조용히 꺼진다(05-08).
|
||||
3. 바이트를 새로 만드는 연산이면 admission·quota(05-07). 실패 시 cleanup·recovery 큐에 넣을 것.
|
||||
- 판단 지점: 이 연산은 디스크를 늘리는가? 대상 namespace를 누가 정하는가? 중간 실패 시 고아 파일을 누가 회수하는가?
|
||||
|
||||
**캐시 region·rate-limit 정책 추가**
|
||||
1. cache region은 지금 `CacheRegionPort<String, byte[]>` bean 하나(`RedisCacheConfig.java:281`). 새 region은 cache-redis 안에 bean 추가가 필요하다 — 템플릿이 확장 지점을 주지 않는다.
|
||||
2. rate-limit 정책은 `app.capabilities.rate-limit.policies.<id>` yml 블록. 라우트별 정책은 inbound 코드를 고쳐야 한다.
|
||||
- 판단 지점: 키에 tenant·사용자 범위를 넣었는가(호출자 책임)? 무효화 뒤 옛 값이 얼마나 허용되는가(05-04)? Redis 장애 시 원본으로 갈 것인가 거부할 것인가? rate-limit revision을 바꾸면 카운터가 초기화된다.
|
||||
|
||||
### 7.3 템플릿이 주는 틀과 빠진 것
|
||||
|
||||
- 주는 것: capability별 auto-configuration·module-defaults·README 모양, StrictSettingsBinder, lease 공통 계약, 알림·파일 서버의 완성된 참조 구현.
|
||||
- 빠진 것: 포트별 공통 계약 테스트(cache·idempotency·rate-limit·알림 provider·파일 콘텐츠 store)를 testFixtures에서 상속하는 틀, 새 cache region을 서비스가 선언하는 확장 지점, httpclient를 포트 뒤로 숨기는 예제 adapter, application-* leaf의 CLAUDE.md(B-10b와 같은 성격, fileserver·objectstorage도 없음).
|
||||
|
||||
### 7.4 폴더 구조
|
||||
|
||||
- 찾기 쉬운 것: composition 모듈이 조립을, application-* 가 유스케이스를, adapter가 벤더 코드를 갖는 3단 구조는 알림·파일 서버에서 일관된다.
|
||||
- 찾기 어려운 것: Redis는 runtime·sdk·cache 세 leaf인데 runtime에 README가 없고 규칙이 cache-redis CLAUDE.md에 섞여 있다(G-5b). `redis-sdk`(main 24,506줄)는 소비자가 0인 라이브러리형 모듈이다 — 사용자 원칙상 확장 지점이지만, 무엇을 위해 남기는지 README에 소비 예제가 없다. identifier leaf는 이름과 내용이 다르다(05-21). 알림 adapter는 R0 legacy와 platform이 한 leaf에 있다.
|
||||
|
||||
### 7.5 성능 (코드에서 읽은 값, 측정 아님)
|
||||
|
||||
| 항목 | 값 |
|
||||
| --- | --- |
|
||||
| Redis lane 연결 수 | REGULAR 64, SCRIPT 8(rate-limit·멱등성·lease 공유) — `RedisRuntimeSettings.java:457-458` |
|
||||
| Redis 대기·timeout | lane 대기 2s, connect 2s, 명령 500ms/1s/2s, capability 명령 200ms. 최악 약 4.2s(05-17) |
|
||||
| SCRIPT lane 처리량(추정) | 왕복 1ms면 pod당 약 8k ops/s, Redis가 200ms로 느려지면 약 40 ops/s |
|
||||
| HTTP client pool | 전체 50, route당 25, pending 100(200ms 대기) |
|
||||
| HTTP client timeout | connect 0.5s, TLS 1s, 응답 헤더 2s, read idle 3s, 전체 4s |
|
||||
| HTTP 응답 버퍼링 | 응답 전체를 메모리에, profile당 최악 50 × 5MB = 250MB |
|
||||
| 알림 dispatch | claim 50건, 동시 64(virtual thread + semaphore), lease 2m, poll 1s |
|
||||
| 캐시 TTL | soft 30s, hard 5m, negative 10s |
|
||||
| 테스트 시간 | 14 leaf 합 약 63s, 1,790개 |
|
||||
|
||||
## 8. 28개 관점 판정표
|
||||
|
||||
기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역.
|
||||
|
||||
| # | 관점 | 판정 | 한 줄 이유 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 코드 성숙도 | P | 경로·크기 방어는 견고하나 공개 계약이 조용히 깨진 곳이 있다(05-02, 05-03) |
|
||||
| 2 | 구조적 성숙도 | O | application-*/adapter/composition 분리와 registry edge가 지켜진다. ci의 architectureCheck 통과 |
|
||||
| 3 | 변경 용이성 | P | provider 추가 시 일반 profile record 수정 필요, bootstrap security.yml 수정 필요(05-19) |
|
||||
| 4 | 인지 부하 | P | 알림·파일 서버는 개념이 많고 문서 drift(W5 항목 다수)가 읽는 비용을 올린다 |
|
||||
| 5 | 위험 가시성 | P | 결과 불명·lease 의도가 주석에 잘 드러나지만, 그 주석이 틀린 곳(05-01)과 문서가 jitter를 주장하는 곳(05-04)이 있다 |
|
||||
| 6 | 실패 성숙도 | P | 결과 불명 분류 체계는 있으나 SMTP·HTTP 기본 경로·Redis 연결 실패에서 분류가 틀린다(05-11, 05-14, 05-17) |
|
||||
| 7 | 운영 성숙도 | P | health·backlog 임계값은 있음. 정리 worker 기본 꺼짐(05-13), breaker 설정 키 없음(05-05) |
|
||||
| 8 | 디버깅 가능성 | P | attempt evidence·failure code가 남는다. MinIO 실패가 공급원 문제로 구분되지 않는다(05-09) |
|
||||
| 9 | 유지보수 성숙도 | P | 이력 주석·FQN·CLAUDE.md 버전 drift가 남아 있음(2절) |
|
||||
| 10 | 테스트 성숙도 | P | offset 검사는 테스트가 잡음(M1). 소유자 검사 제거는 못 잡음(M2), fake가 adapter 버그를 따라 함(05-02) |
|
||||
| 11 | 데이터 성숙도 | P | 제출 중복은 DB unique로 강제. 재발송(05-01), 캐시 옛 값(05-03), bounce 손실(05-20) |
|
||||
| 12 | 동시성 성숙도 | P | SKIP LOCKED·fence·조건부 UPDATE는 좋다. lease 만료 후 재발송, finalize lease 없음(05-22) |
|
||||
| 13 | 확장성 | ? | 다중 인스턴스·부하 실험 없음. SCRIPT lane 8개가 병목 후보(추정) |
|
||||
| 14 | 성능 성숙도 | P | 상한(pool·body·lane)은 정해져 있음. deadline이 진행 중 요청을 끊지 못함(05-06) |
|
||||
| 15 | 보안 성숙도 | P | 경로 탐색·SSRF·SNS 서명·nosniff 방어 확인. copy로 디스크 고갈(05-07), 인가 회귀 미검출(05-08) |
|
||||
| 16 | 의존성 성숙도 | P | reactive 스택 제거(결정 9), SES는 AWS SDK. MinIO 공급원 소멸(05-09), Jackson 2 잔존(S3-#13a) |
|
||||
| 17 | API / Contract 성숙도 | P | 포트 계약이 공개돼 있으나 구현이 일부 intent·renew를 지키지 않는다 |
|
||||
| 18 | 배포 성숙도 | > | 배포 파이프라인은 다른 영역. 이 영역은 release 스크립트 경로 오류(P11-new-2)만 기록 |
|
||||
| 19 | 설정 성숙도 | P | module-defaults 구조는 일관. 동작 안 하는 키·0 timeout 허용(05-15), prefix 여러 개(05-18) |
|
||||
| 20 | 개발자 경험 | P | 모듈 한 줄로 켜지는 경험은 좋다. 새 adapter가 상속할 계약·확장 지점이 없다(7.3) |
|
||||
| 21 | Guardrail 성숙도 | P | StrictSettingsBinder, fail-closed lane. 기준 5를 강제하는 장치는 없다(05-16) |
|
||||
| 22 | 추상화 성숙도 | P | 포트 경계는 적절. httpclient는 포트 없이 모듈 타입을 노출(7.1 기준 1) |
|
||||
| 23 | 일관성 | P | 계약 테스트 위치·설정 바인딩 방식이 모듈마다 다르다 |
|
||||
| 24 | 네이밍 / 의미 성숙도 | P | identifier leaf 이름 불일치(05-21), `*ProviderProperties`(S4-#17b) |
|
||||
| 25 | 조직 확장성 | ? | 담당자·소유 표기 없음. 판단할 자료 없음 |
|
||||
| 26 | Ownership 성숙도 | P | env-keys owner_module 오기(G-12e), application-* CLAUDE.md 없음 |
|
||||
| 27 | 삭제 가능성 | P | 한 줄 제거로 대부분 사라짐(`ci`의 기본 조립 통과). security.yml 잔여(05-19) |
|
||||
| 28 | 회복 가능성 | P | reconcile·recovery 경로가 있다. 증거 오기로 회복이 재발송이 됨(05-01), 정리 기본 꺼짐(05-13) |
|
||||
|
||||
## 발견 요약
|
||||
|
||||
| 심각도 | 개수 | ID |
|
||||
| --- | --- | --- |
|
||||
| Critical | 0 | |
|
||||
| High | 6 | 05-01, 05-02, 05-03, 05-05, 05-06, 05-07 |
|
||||
| Medium | 12 | 05-04, 05-08, 05-09, 05-10, 05-11, 05-12, 05-13, 05-14, 05-15, 05-16, 05-17, 05-20 |
|
||||
| Low | 11 | 05-18, 05-19, 05-21, 05-22, 05-23a~g |
|
||||
|
||||
| 우선순위 | 개수 | ID |
|
||||
| --- | --- | --- |
|
||||
| P1 | 8 | 05-01, 05-02, 05-03, 05-05, 05-06, 05-07, 05-08, 05-09 |
|
||||
| P2 | 10 | 05-04, 05-10, 05-11, 05-12, 05-13, 05-14, 05-15, 05-16, 05-17, 05-20 |
|
||||
| P3 | 11 | 05-18, 05-19, 05-21, 05-22, 05-23a~g |
|
||||
|
||||
사용 결정: **조건부 사용 가능.** 파일 서버의 크기·경로·타입 방어와 알림의 제출 중복 방지는 그대로 써도 된다. 알림 발송(05-01), Redis 멱등성 renew·캐시 revision 조건(05-02, 05-03), HTTP client(05-05, 05-06), 파일 copy(05-07)는 고치기 전에는 파생 서비스에서 쓰지 않거나 우회 조건을 문서로 정해야 한다.
|
||||
@@ -0,0 +1,495 @@
|
||||
# 06 — messaging 영역 성숙도 리뷰
|
||||
|
||||
- 대상: vendored `messaging:*`(`src/messaging`), `adapter:outbound:messaging`(anti-corruption bridge),
|
||||
`adapter:outbound:messaging-kafka`, `composition:outbox-relay`
|
||||
- 기준 커밋: `main` `01a8a2a70`
|
||||
- 작성일: 2026-11-01
|
||||
- 소유자 결정 유지: vendored 플랫폼은 Clean Architecture 레이어가 아니다(MSG-023 §6.2). messaging outbox도
|
||||
유지한다(followup `X1-지도-Outbox`). 이 문서는 그 결정을 뒤집지 않고 그 안의 품질과 결정의 반영 상태를 본다.
|
||||
|
||||
## 1. 범위
|
||||
|
||||
| 항목 | 기록 |
|
||||
| --- | --- |
|
||||
| 대상 저장소 | `clean-architecture-backend-template`, Gradle 루트 `src/` |
|
||||
| 커밋·확인 시점 | `01a8a2a70`, 2026-11-01 20:30–21:10 KST |
|
||||
| 목적과 지원 실행 구성 | 서비스 시작점 템플릿. 다중 인스턴스 배포를 전제한다(relay가 `SKIP LOCKED` + lease fencing을 쓴다). broker는 Kafka 하나 |
|
||||
| 규모·운영 목표 | 합의된 수치 없음. 그래서 처리량·복구 시간은 "현재 기본값으로 계산한 값"으로만 적는다 |
|
||||
| 읽은 코드 | `composition/outbox-relay/src/main/**` 전부, `adapter/outbound/messaging/src/main/**` 전부, `adapter/outbound/messaging-kafka`(코드 없음, `module-defaults/messaging.yml`), `application-core/.../application/outbox/**`(relay 동작 확인용), `persistence-jpa/.../outbox/**`(claim SQL·완료 확인용), `messaging-runtime-core` `DefaultMessagePublisher`, `messaging-transport-spi` `DefaultMessagingRuntimeRegistry`, `messaging-policy` `MessagingAdmissionController`, `messaging-kafka` `KafkaMessagingTransport`·`KafkaPublishFailureClassifier`, starter의 `MessagingShutdownLifecycle`·`MessagingOutboxRelayLifecycle`·`MessagingReliabilityAutoConfiguration`·`MessagingConsumeConfiguration`·`MessagingPublishConfiguration`, starter-kafka `KafkaMessagingAutoConfiguration`·`KafkaDeadLetterQuarantine`, sample `PortfolioEventOutbox`, `SubmitDurableOperationUseCase`, runbook `outbox-dead-letter`·`outbox-publish-failed`, `docs/messaging/*`. Spring Framework 7.0.9 소스(`ExecutorConfigurationSupport`, `ScheduledAnnotationBeanPostProcessor`)로 종료 순서 확인 |
|
||||
| 읽지 않은 코드 | vendored admin·claim-check·cloudevents·schema-avro/protobuf·observability 내부, `KafkaConsumerRegistrar` 786줄 중 settlement 세부 |
|
||||
| 수행한 테스트·실험 | 아래 "실행" 참고 |
|
||||
| 확인 못 한 것 | 실제 Kafka·PostgreSQL로 앱 relay를 끝까지 돌리는 실험(그런 테스트가 저장소에 없고 이번에 만들지도 않음), 실제 SIGTERM 종료 순서 실측, 처리량 실측 |
|
||||
| 이전 리뷰와 비교 범위 | techlead `10-messaging.md`, followup-status M·H 그룹, 모듈 리뷰 `2026-08-14-messaging-module-code-review.md`(MSG-015·MSG-023) |
|
||||
|
||||
### 실행
|
||||
|
||||
| 명령 | 결과 |
|
||||
| --- | --- |
|
||||
| 오케스트레이터 `ci` 게이트 로그(`gates/ci.log`) | rc=0. 이 영역 leaf의 `test` 전부 통과 |
|
||||
| 오케스트레이터 `mainCheck` 게이트 로그 | rc=1. 원인은 `objectstorage`의 MinIO 이미지 pull 404(이 영역 밖). 이 영역의 broker 실연 lane(`integrationTest`)은 `mainCheck`에 들어 있지 않아 컴파일만 됐다 |
|
||||
| 실험 1 (worktree `wt-06`, 부하 load avg 13.3): `./gradlew :messaging:messaging-runtime-core:test --tests '*DefaultMessagePublisherTest.reviewExperiment*' :adapter:outbound:messaging:test --tests '*PlatformIntegrationEventPublishAdapterTest.reviewExperiment*'` | 통과. 출력: `completion=REJECTED transmission=NOT_TRANSMITTED code=SHUTTING_DOWN retryable=true`, 이어서 bridge `outcome=REJECTED_BEFORE_SEND retryable=false`. 06-01 근거 |
|
||||
| 실험 2 (변이, worktree, load avg 7.6): `OutboxRelayScheduler`에서 `metrics.recordRelayResult`·`metrics.refresh` 호출을 사실상 제거하고 `./gradlew :composition:outbox-relay:test` | 18개 전부 통과(변이 생존). 06-05 근거 |
|
||||
| 테스트 시간(`build/test-results` XML 합계) | `adapter:outbound:messaging` 36개 2.8s, `messaging-kafka` adapter 4개 3.5s, `composition:outbox-relay` 18개 2.2s, `messaging-spring-boot-starter` 72개 4.9s, 나머지 messaging leaf는 각 1.5s 이하. 실행 시간은 문제 아님 |
|
||||
|
||||
실험용 테스트 편집은 worktree에만 했고 끝나고 worktree를 지웠다.
|
||||
|
||||
## 2. 지난 발견 재확인
|
||||
|
||||
| ID | 지난 내용(요약) | 상태 | 근거 |
|
||||
| --- | --- | --- | --- |
|
||||
| techlead H10 | 자동조립 publisher가 관측을 기록하지 않음 | 해결 | `messaging-spring-boot-starter/.../MessagingPublishConfiguration.java:224-231` observation 주입 |
|
||||
| techlead H3 | consumer가 배선되지 않음 | 바뀜 | starter-kafka가 `MessageHandler` bean마다 consumer를 연다(`MessagingConsumeConfiguration.java:60-68`). 다만 application leaf 쪽 경로가 없다 → 06-08 |
|
||||
| techlead M4 | 실행 경로에 스키마 호환성 검사 없음 | 바뀜 | 문서가 "선언만 하고 강제하지 않음"으로 표시(`docs/messaging/configuration-reference.md:123`). 앱 payload 버전에는 여전히 없음 → NN-10 |
|
||||
| techlead M5 | outbox 두 개 공존 | 남음(소유자 결정으로 유지) | vendored `MessagingReliabilityAutoConfiguration`·`JdbcOutboxRepository`가 runtime classpath에 있음. 문서·종료 순서 비용 → 06-02, NN-11 |
|
||||
| techlead M7 / H-1b | producer-id 키 부재, 빈 값 통과 | 해결 | `messaging-kafka/src/main/resources/config/module-defaults/messaging.yml` `producer-id`, `MessagingBridgeRootAutoConfiguration.java:77-87` |
|
||||
| H-1a | bridge 조건이 platform보다 먼저 평가 | 해결 | `MessagingBridgeRootAutoConfiguration.java:32-33` `afterName` |
|
||||
| H-8 | bridge `prepare`가 모든 예외를 REJECTED로 | 해결 | `PlatformIntegrationEventPublishAdapter.java:59-67`, 테스트 `aFailureOtherThanAnIncompatibleValueIsNotTurnedIntoARefusal` |
|
||||
| H-9, H-10b, H-10c | `KafkaSender` seam 관련 | 해당 없음(코드 삭제) | `adapter/outbound/messaging-kafka/src/main` 아래 Java 없음 |
|
||||
| M-1 | 이미 인코딩된 payload 재인코딩 | 해결 | `DefaultMessagePublisher.java:314-322` |
|
||||
| M-2a~f | Kafka 보안 설정 미적용 | 해결 | `KafkaMessagingAutoConfiguration.java:154-209`, followup의 테스트 존재 확인 |
|
||||
| M-3, M-7 | handler timeout 중복, poison 무한 재시도 | 해결 | `KafkaConsumerRegistrarTest.java:160,191,219` |
|
||||
| M-4a | admission 거부를 동기 예외로 던짐 | 해결 | `DefaultMessagePublisher.java:228-233` (결과로 반환). 단, 그 결과의 의미가 bridge에서 뒤집힌다 → 06-01 |
|
||||
| M-4b, M-4c, M-6, M-11 | vendored relay·cleanup | 해결 | `OutboxRelayTest.java:90`, `MessagingOutboxRelayLifecycleTest.java:77`, `OutboxOperationsTest.java:114`, `OutboxPostgresIT.java:226`. 이 relay는 앱이 쓰지 않는다 |
|
||||
| M-5a | publish가 최대 65초 막힘 | 해결 | `KafkaMessagingAutoConfiguration.java:203-206` `max.block.ms` = 5s |
|
||||
| M-8a | 옛 prefix `backend.messaging` fixture yml 2개 | 남음 | `messaging-spring-boot-starter/src/test/resources/application-valid.yml:2-3`, `application-invalid-ordering.yml`. 참조 0건 |
|
||||
| TEST-FAKE-MessagePublisher | fake와 `DefaultMessagePublisher`의 공통 계약 없음 | 남음 | `messaging-core-api`에 `testFixtures` 없음. `implements EncodedMessagePublisher`는 test fake 3곳과 본체뿐 |
|
||||
| A-2 그룹 밖(followup:173) | `MessagingAdminDurabilityValidator`의 profile 대소문자 판정 | 남음 | `MessagingAdminDurabilityValidator.java:25,53-54` `Set.of("prod","production")::contains`. `Prod`면 검사를 건너뛴다 |
|
||||
|
||||
남은 High/P1 지난 항목은 없다. 남은 것은 Low/Nit(M-8a, admin profile 판정)와 테스트 계약(TEST-FAKE)이다.
|
||||
|
||||
## 3. 새 발견
|
||||
|
||||
심각도별: High 2 · Medium 10 · Low 2. 우선순위별: P1 2 · P2 8 · P3 4.
|
||||
|
||||
### 06-01 — 다시 시도하면 될 거부를 relay가 즉시 DEAD로 보낸다
|
||||
|
||||
- 성격: 확인된 결함
|
||||
- 관련 관점: 6, 1, 17, 28, 5
|
||||
- 근거
|
||||
- platform은 일시적 거부를 `REJECTED` + `retryable=true`로 돌려준다.
|
||||
- 종료 중 admission 거부: `MessagingAdmissionController`가 `MessageBackpressureException("SHUTTING_DOWN")`(category `TRANSIENT_INFRASTRUCTURE`, retryable true)을 던지고 `DefaultMessagePublisher.java:228-233`이 `PublishResult.rejected`로 바꾼다.
|
||||
- permit 대기 초과: 같은 경로. 기존 테스트 `DefaultMessagePublisherTest.aSaturatedPermitPoolRejectsAsRetryableWithinTheCallersDeadline`이 `(REJECTED, retryable=true)`를 단언한다.
|
||||
- runtime 없음(종료 후 registry close): `DefaultMessagingRuntimeRegistry.java:86-90` → `DefaultMessagePublisher.java:261-267` `PUBLISH_RUNTIME_UNAVAILABLE` REJECTED.
|
||||
- transport 닫힘: `KafkaMessagingTransport.java:121-123` `KAFKA_TRANSPORT_CLOSED` REJECTED.
|
||||
- Kafka 인증·인가 오류: `KafkaPublishFailureClassifier.java:51-58`가 `AuthenticationException`·`AuthorizationException`을 확정 거부로 본다. credential 교체 중 실패나 ACL 배포 순서 문제도 여기로 온다.
|
||||
- bridge는 `retryable`을 보지 않는다. `PlatformIntegrationEventPublishAdapter.java:140-151`은 completion과 transmission만 보고 `REJECTED_BEFORE_SEND`/`REJECTED_AFTER_BROKER`를 만든다.
|
||||
- relay는 그 둘을 "같은 payload는 또 거부된다"로 보고 시도 예산을 쓰지 않고 바로 DEAD로 보낸다(`PublishPendingOutboxEventsUseCase.java:149-153`, `OutboxPublishOutcome.java` `retryable()`은 `AMBIGUOUS`만 true).
|
||||
- DEAD row는 같은 aggregate의 뒤 row를 모두 막는다(`PostgreSqlOutboxClaimRepository.java:27-36`, `p.status <> 'PUBLISHED'`).
|
||||
- 실험 1: `SHUTTING_DOWN` 거부가 `REJECTED/NOT_TRANSMITTED/retryable=true`로 나오고, 같은 모양의 결과를 bridge가 `REJECTED_BEFORE_SEND`(retryable false)로 바꾸는 것을 실행으로 확인했다. 마지막 고리(`REJECTED_BEFORE_SEND` → DEAD)는 기존 `OutcomeAwareRelayTest.aRefusalBeforeTransmissionIsDeadLettered`가 단언한다.
|
||||
- platform 문서도 "REJECTED는 포기해도 안전"이라고 적는다(`docs/messaging/delivery-guarantees.md:21-22`). 같은 platform이 retryable REJECTED를 만든다.
|
||||
- 발생 조건: 배포 종료 중 relay가 돌고 있을 때(06-02), 다른 publisher와 permit을 다툴 때, Kafka 인증 정보 교체·ACL 변경 순간.
|
||||
- 영향: 이미 커밋된 비즈니스 이벤트가 DEAD가 되고 그 aggregate의 이후 이벤트가 전부 멈춘다. 자동 복구가 없다. runbook의 수동 SQL이 필요하다.
|
||||
- 심각도·우선순위: High / P1. 배포는 정상 운영 동작이다. 결과가 영구 정지라서 출시 전 차단 항목으로 본다.
|
||||
- 확실성: 각 고리는 코드와 테스트로 확인했다(E2). 실제 종료에서 몇 건이 걸리는지는 미측정이다.
|
||||
- 결정의 근거: 적용 제외 — 두 계약(platform `retryable`, application "확정 거부") 사이의 번역 누락이다. 선택 비교가 아니라 번역을 맞추는 문제다.
|
||||
- 통제 수준: M0(retryable 거부를 retryable로 다루는 수단 없음). 증거 E2.
|
||||
- 최소 개선 방향: bridge `mapOutcome`에서 `result.failure().retryable()`이 true인 REJECTED는 "다시 시도 가능, 전송 안 됨"으로 번역한다. application 어휘에 그 값이 없으므로 `OutboxPublishOutcome`에 `DEFERRED_NOT_SENT`(가칭) 하나를 추가하고, relay는 이 값에서 `markFailed`를 하되 시도 횟수를 늘리지 않는 쪽을 고른다. Kafka 인증·인가 오류는 classifier에서 retryable 거부로 분류한다.
|
||||
- 버린 대안 1: `AMBIGUOUS`로 번역. 동작은 비슷하지만 "전송됐을 수 있음"이라는 거짓 정보를 남기고 중복 경고를 오염시킨다.
|
||||
- 버린 대안 2: relay가 platform `FailureDescriptor`를 직접 본다. application-core가 platform 타입을 알게 돼 bridge의 존재 이유가 사라진다.
|
||||
- 완료 기준: retryable REJECTED가 relay에서 FAILED가 되고 DEAD가 되지 않는다. 인증 오류가 retryable로 분류된다.
|
||||
- 검증 방법: bridge 테스트에 retryable REJECTED → 새 값 케이스, relay 테스트에 새 값 → FAILED(시도 미소비) 케이스. 실험 1의 두 테스트를 정식 테스트로 옮긴다.
|
||||
|
||||
### 06-02 — platform 종료 순서가 앱 relay를 모른다
|
||||
|
||||
- 성격: 확인된 결함(정적)
|
||||
- 관련 관점: 6, 7, 12, 28, 23
|
||||
- 근거
|
||||
- 앱이 실제로 쓰는 relay는 `@Scheduled` 메서드다(`OutboxRelayScheduler.java:36`). SmartLifecycle이 아니다.
|
||||
- platform 종료 순서는 vendored relay(`MessagingOutboxRelayLifecycle`, phase `Integer.MAX_VALUE`)를 먼저 멈추고 그다음 admission을 닫도록 설계됐다(`MessagingShutdownLifecycle.java:109-123`, phase `MAX_VALUE - 1024`). 앱은 vendored relay를 만들지 않는다(`OutboxRepository` bean을 만드는 production 코드 없음).
|
||||
- Spring 7.0.9에서 `@Scheduled` 작업은 `ContextClosedEvent`에 `cancel(false)`로 취소된다(`ScheduledAnnotationBeanPostProcessor` 597·613행). 실행 중인 relay 회차는 계속 돈다. scheduler executor의 lifecycle phase는 `Integer.MAX_VALUE / 2`다(`ExecutorConfigurationSupport` 75행).
|
||||
- 그래서 종료 순서는 "admission 닫기(MAX-1024) → scheduler가 실행 중 회차를 기다림(MAX/2) → bean destroy(registry·transport close)"다. 실행 중 회차의 남은 row는 `SHUTTING_DOWN`, `RUNTIME_NOT_INSTALLED`, `KAFKA_TRANSPORT_CLOSED` 순으로 거부된다. 06-01 때문에 모두 DEAD가 된다.
|
||||
- `MessagingShutdownLifecycle` 주석은 이 상황을 "row가 ambiguous가 된다"고 설명한다(`:113-116`). 앱 경로에서는 DEAD가 된다. 주석과 실제가 다르다.
|
||||
- 발생 조건: SIGTERM 순간 relay 회차가 진행 중. 적체가 있거나 broker가 느리면 회차가 길어 확률이 커진다(배치 20 × publish 최대 약 10초).
|
||||
- 영향: 06-01이 있는 지금은 배포마다 일부 row가 DEAD가 될 수 있다. 06-01을 고쳐도 시도 예산을 쓰고 FAILED 경고를 남긴다.
|
||||
- 심각도·우선순위: Medium / P1. 단독 영향은 중간이지만 06-01과 같이 고쳐야 배포 경로가 안전해진다.
|
||||
- 확실성: 순서는 Spring 소스와 phase 값으로 확인했다(E1). 실제 종료 실측은 하지 않았다.
|
||||
- 결정의 근거: 확인된 사실은 위와 같다. 기록된 의도는 "relay가 먼저 멈춘다"(`MessagingOutboxRelayLifecycle.java:55-68`)이다. 리뷰어 추론: vendored relay를 기준으로 설계한 뒤 앱 relay가 composition으로 옮겨지면서(2026-09-28) 이 순서에 들어가지 않았다.
|
||||
- 이해 비용: 운영자가 배포 후 DEAD를 보면 원인을 broker에서 찾게 된다. 종료 순서를 알아야 원인을 찾는다.
|
||||
- 최소 개선 방향: `OutboxRelayScheduler`를 SmartLifecycle로 바꾸고 phase를 `MessagingShutdownLifecycle`보다 높게 둔다. stop에서 진행 중 회차를 끝내고 새 회차를 막는다. 남은 claim은 lease를 놓아(release) 다른 인스턴스가 바로 가져가게 한다.
|
||||
- 대안 비교: (a) 현상 유지 + 06-01만 수정 — 비용 최소, 배포마다 FAILED 잡음과 시도 소비가 남는다. (b) scheduler executor phase를 올리기 — 전역 설정이라 다른 `@Scheduled` 작업까지 바뀐다. (c) relay 전용 SmartLifecycle — 범위가 relay에 한정된다. (c)를 고른다.
|
||||
- 비용·부작용: relay 루프를 직접 소유하게 된다. `@Scheduled` 의존이 사라지므로 `@EnableScheduling` 결정(L-1)도 함께 다시 본다.
|
||||
- 재검토 조건: relay를 별도 프로세스(worker 배포 단위)로 분리하면 이 순서 문제는 그 프로세스의 종료 절차로 옮겨 간다.
|
||||
- 완료 기준: 종료 중에 claim된 row가 DEAD가 되지 않고, PUBLISHED 또는 lease 해제 상태로 남는다.
|
||||
- 검증 방법: 컨텍스트 테스트에서 relay 회차를 막아 둔 채 `context.close()`를 호출하고 row 상태를 단언한다.
|
||||
|
||||
### 06-03 — broker가 몇 분만 멈춰도 row가 대량으로 DEAD가 되고 복구는 수작업이다
|
||||
|
||||
- 성격: 구조적 위험
|
||||
- 관련 관점: 28, 6, 7, 19, 14
|
||||
- 근거
|
||||
- 시도 예산은 고정 3회, 기본 지연 30초다(`OutboxBackoffPolicy.java:24,27`). 실패 지연은 1회차 30–60초, 2회차 60–90초다.
|
||||
- 지연의 기준 시각은 회차 시작 시각이다(`PublishPendingOutboxEventsUseCase.java:99`의 `now`를 `:176`에서 사용). broker가 멈추면 publish 하나가 약 5초(`max.block.ms` 5s 또는 publish deadline 5s) 걸린다. 배치 20개면 회차 하나가 약 100초다. 그래서 뒤쪽 row는 FAILED로 표시되는 순간 이미 재시도 시각이 지나 있다. 다음 회차에 바로 다시 시도된다.
|
||||
- 계산(추론): 전면 장애에서 row 하나가 DEAD까지 가는 데 약 3회차, 대략 5분이다. 5분 넘는 broker 장애는 그동안 claim된 모든 head row를 DEAD로 만든다.
|
||||
- `AMBIGUOUS`(전송됐을 수 있음)도 시도를 쓴다(`:143-147`). 장애 동안 실제로는 저장된 메시지도 DEAD가 될 수 있다. 코드 주석은 "parking it loses a message that was delivered"라며 이 결과를 피하려 하지만 3회 뒤에는 결국 parking한다.
|
||||
- 복구 절차는 row마다 `UPDATE`다(`docs/runbooks/outbox-dead-letter.md:39-41`). runbook의 차단 범위 조회(`:27`)는 `aggregate_id`·`occurred_at` 기준이라 현재 FIFO 키 `(tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index)`와 다르다.
|
||||
- 상수를 바꾸면 registry와 runbook을 같이 바꿔야 한다는 결정(I10)이 있다(`application-core/README.md` OutboxBackoffPolicy 절).
|
||||
- 발생 조건: Kafka 장애·네트워크 단절이 약 5분 이상.
|
||||
- 영향: 장애가 끝나도 이벤트 발행이 자동으로 재개되지 않는다. 장애 동안 이벤트를 만든 모든 aggregate가 운영자 개입 전까지 멈춘다.
|
||||
- 심각도·우선순위: High / P2. 지원 장애 조건에서 중요한 기능이 멈춘다. 데이터는 남아 있고 경보(`outcome=DEAD`)와 수동 절차가 있어 P2로 둔다.
|
||||
- 통제 수준: M1(runbook·경보 문서), 자동 복구 M0. 증거 E1 + 계산.
|
||||
- 결정의 근거: 기록된 의도는 "상수를 runbook과 맞춘다"이다. 장애 길이와 예산의 관계는 기록되어 있지 않다.
|
||||
- 최소 개선 방향
|
||||
- (a) 재시도 시각을 실패 시점 `clock.instant()`로 계산한다. 비용이 가장 작고 예산이 의도한 시간만큼 유지된다.
|
||||
- (b) `AMBIGUOUS`와 broker 도달 불가류 실패는 시도 예산을 쓰지 않고 상한 있는 지연(예: 최대 5분)으로 계속 재시도한다. 예산은 payload 자체의 거부에만 쓴다.
|
||||
- (c) DEAD 일괄 재구동 절차(조건별 `UPDATE`와 차단 범위 조회)를 runbook에 현재 FIFO 키로 고친다.
|
||||
- 버린 대안: `MAX_ATTEMPTS`만 늘리기. 장애 길이에 비례해 숫자를 계속 키워야 하고, 진짜 poison row가 늦게 격리된다.
|
||||
- 재검토 조건: relay가 per-row 지연 대신 broker 상태(circuit)를 보고 회차를 건너뛰게 되면 (b)는 불필요할 수 있다.
|
||||
- 완료 기준: broker가 10분 멈췄다가 돌아오면 운영자 개입 없이 PENDING/FAILED가 PUBLISHED로 간다.
|
||||
- 검증 방법: 시계를 주입한 relay 테스트로 장애 10분을 흉내 낸다. 실제 확인은 Toxiproxy lane(이미 vendored 쪽에 있다)에 앱 relay를 올려서 한다(06-09).
|
||||
|
||||
### 06-04 — aggregate 하나의 발행 속도가 poll 주기당 1건으로 묶인다
|
||||
|
||||
- 성격: 구조적 위험(성능)
|
||||
- 관련 관점: 14, 13, 5
|
||||
- 근거
|
||||
- claim은 aggregate마다 가장 앞 row 하나만 고른다(`PostgreSqlOutboxClaimRepository.java:27-36`).
|
||||
- relay는 tick마다 한 번만 claim한다. 배치가 꽉 차도 바로 다음 claim을 하지 않는다(`OutboxRelayScheduler.java:36-39`, fixed-delay `PT5S`).
|
||||
- 그래서 e1이 이번 회차에 발행돼도 e2는 다음 tick까지 기다린다.
|
||||
- 계산(추론): aggregate 하나는 최대 0.2건/초다. 인스턴스 하나는 최대 20건/5초 ≈ 4건/초다. aggregate 하나에 이벤트 100건이 쌓이면 비우는 데 약 8분 이상 걸린다.
|
||||
- 한 회차의 DB 왕복은 claim 1 + row마다 UPDATE(claim flush) + row마다 완료 트랜잭션 1 + 지표 GROUP BY 2다. 배치 20이면 약 43문장이다.
|
||||
- 발생 조건: 한 aggregate가 초당 0.2건 넘게 이벤트를 만들거나, 백로그가 인스턴스당 초당 4건을 넘는다.
|
||||
- 영향: `outbox.publisher.lag`가 계속 늘어난다. 하류 소비가 분 단위로 늦어진다.
|
||||
- 심각도·우선순위: Medium / P2. 업무 부하에 따라 달라진다. 템플릿 기본값이 그대로 복제된다.
|
||||
- 통제 수준: 처리량 상한을 알리는 문서·검사 없음(M0). 증거 E1 + 계산. 실측 안 함.
|
||||
- 최소 개선 방향: 배치가 꽉 찼으면 다음 tick을 기다리지 않고 곧바로 다시 claim한다(상한 있는 반복). aggregate 안 처리량이 필요하면 claim에서 aggregate별로 "앞 row가 같은 lease에 잡힌 경우" 다음 row까지 함께 가져오는 방법을 비교한다.
|
||||
- 버린 대안: poll 주기만 줄이기. 빈 tick마다 DB 질의와 지표 질의가 늘어난다.
|
||||
- 재검토 조건: 목표 처리량을 합의하면 그 수치로 다시 판단한다.
|
||||
- 완료 기준: 백로그 상태에서 인스턴스 처리량이 poll 주기에 묶이지 않는다. 처리량 상한을 README에 숫자로 적는다.
|
||||
- 검증 방법: PostgreSQL 통합 테스트에서 같은 aggregate 이벤트 N건이 몇 번의 relay 호출로 비워지는지 센다.
|
||||
|
||||
### 06-05 — relay가 꺼져 있거나 실패하는 동안 outbox 지표가 갱신되지 않는다
|
||||
|
||||
- 성격: 확인된 결함
|
||||
- 관련 관점: 7, 8, 10, 5
|
||||
- 근거
|
||||
- relay 기본값은 꺼짐이다(`persistence-jpa.yml:190` `${APP_OUTBOX_RELAY_ENABLED:false}`, `OutboxSettings.java:39-43`).
|
||||
- `outbox.pending.size`·`outbox.publisher.lag` 갱신은 relay scheduler 안에서만 일어난다(`OutboxRelayScheduler.java:48-49`가 유일한 호출자).
|
||||
- relay 회차가 예외로 끝나면 catch로 가서 지표 갱신을 건너뛴다(`:39-58`). DB 장애 동안 게이지가 마지막 값에 멈춘다.
|
||||
- 실험 2: 지표 호출 두 줄을 막아도 `composition:outbox-relay` 테스트 18개가 모두 통과했다. `OutboxMetrics` 단위 테스트가 없다.
|
||||
- 대비: vendored relay는 "relay를 잊으면 조용히 실패한다"를 문제로 적고 lifecycle로 강제한다(`MessagingOutboxRelayLifecycle.java:11-13`).
|
||||
- 발생 조건: messaging을 고르고 `APP_OUTBOX_RELAY_ENABLED`를 빠뜨린 배포. 또는 relay가 매 회차 예외를 던지는 장애.
|
||||
- 영향: row가 쌓여도 `outbox_publisher_lag` 경보가 울리지 않는다. runbook의 감지 조건(`outbox-publish-failed.md:21-23`)이 성립하지 않는다.
|
||||
- 심각도·우선순위: Medium / P2.
|
||||
- 통제 수준: M0(감지 경로가 relay 실행에 종속). 증거 E2(변이 실험).
|
||||
- 결정의 근거: 적용 제외 — 지표 수집 위치를 relay에서 떼어 내는 단순 결함이다.
|
||||
- 최소 개선 방향: 게이지 갱신을 relay와 독립된 주기 작업(또는 Micrometer gauge의 지연 조회)으로 옮긴다. relay가 꺼져 있고 발행 포트가 있으면 기동 시 WARN 한 줄을 남긴다. `OutboxMetrics` 테스트를 추가한다.
|
||||
- 완료 기준: relay가 꺼진 상태에서도 `outbox.pending.size{status=PENDING}`가 실제 행 수를 보여 준다.
|
||||
- 검증 방법: relay를 끈 컨텍스트 테스트에서 PENDING row를 넣고 게이지 값을 단언한다. 실험 2 변이가 죽는지 확인한다.
|
||||
|
||||
### 06-06 — application EventId 문법과 platform MessageId(UUID)가 다르다
|
||||
|
||||
- 성격: 확인된 결함(잠재)
|
||||
- 관련 관점: 17, 1, 5, 22
|
||||
- 근거
|
||||
- application은 `[A-Za-z0-9][A-Za-z0-9._:-]*` 1–96자를 받는다(`EventId.java:6-12`).
|
||||
- bridge는 `UUID.fromString`으로 바꾼다. UUID가 아니면 `IllegalArgumentException` → `REJECTED_BEFORE_SEND` → DEAD다(`PlatformIntegrationEventPublishAdapter.java:62-67,132-134`). 기존 테스트도 `"event-1"`이 REJECTED가 됨을 단언한다.
|
||||
- `SubmitDurableOperationUseCase.canonicalIdentity`는 UUID가 아닌 operation id를 `"operation-" + sha256`으로 바꾼다(`SubmitDurableOperationUseCase.java:167-173`). 이 값은 UUID가 아니므로 이 경로로 들어온 이벤트는 항상 DEAD다. 지금은 HTTP adapter가 UUID만 만들어 도달하지 않는다(`DurableOperationController.java:86`).
|
||||
- 발생 조건: UUID가 아닌 operation id(새 inbound adapter, 클라이언트 지정 id) 또는 UUID가 아닌 event id를 만드는 use case.
|
||||
- 영향: append는 성공하고 비즈니스 트랜잭션은 커밋된다. 실패는 나중에 relay에서 DEAD로 나타나고 aggregate를 막는다. 원인이 호출 지점과 멀다.
|
||||
- 심각도·우선순위: Medium / P2.
|
||||
- 통제 수준: M0. 증거 E1(+ 기존 bridge 테스트).
|
||||
- 최소 개선 방향: 둘 중 하나로 계약을 맞춘다. (a) application `EventId`를 UUID로 좁힌다. 비용이 작고 실패가 append 시점으로 당겨진다. (b) bridge가 비 UUID id를 결정적 UUIDv5로 바꾼다. 소비자가 보는 id가 원래 값과 달라진다. 소비자 중복 제거 키가 event id라는 계약(`application-core/README.md`)을 지키려면 (a)가 낫다. `canonicalIdentity`의 digest 경로는 (a)에 맞춰 UUIDv5로 바꾼다.
|
||||
- 완료 기준: bridge가 거부할 id는 `IntegrationEventDraft` 생성 또는 encode 단계에서 거부된다.
|
||||
- 검증 방법: 비 UUID event id로 encode를 호출하면 예외가 나는 테스트.
|
||||
|
||||
### 06-07 — 샘플이 aggregate 순서 번호를 벽시계로 만든다
|
||||
|
||||
- 성격: 구조적 위험
|
||||
- 관련 관점: 12, 1, 11, 20
|
||||
- 근거
|
||||
- `PortfolioEventOutbox.java:92,98-105`가 `AggregateOrder(sequenceOf(occurredAt), 0)`으로 순서를 만든다. 값은 epoch 마이크로초다.
|
||||
- FIFO gate는 이 번호로 앞뒤를 정한다(`PostgreSqlOutboxClaimRepository.java:33-35`).
|
||||
- `(tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index)`에 유일 제약이 없다(V3·V13·V18·V19 확인, PK는 `event_id`뿐).
|
||||
- 설계 문서는 "strict aggregate ordering은 timestamp가 아니라 explicit aggregate sequence를 요구한다"고 적는다(`docs/superpowers/specs/2026-07-28-messaging-production-capability-design.md:595`).
|
||||
- 발생 조건: 같은 aggregate를 두 인스턴스가 연달아 바꾸고 두 서버 시계가 어긋남. 또는 NTP가 시계를 되돌림. 또는 같은 마이크로초에 두 이벤트.
|
||||
- 영향: 나중에 커밋된 변경의 이벤트가 먼저 나간다. 같은 번호 두 개는 서로를 막지 않아 순서가 정해지지 않는다. 소비자의 "마지막 상태" 판단이 틀린다.
|
||||
- 심각도·우선순위: Medium / P2. 샘플은 새 기능의 복사 원본이다.
|
||||
- 통제 수준: M1(설계 문서), 코드 M0. 증거 E1.
|
||||
- 최소 개선 방향: 샘플에서 aggregate의 버전(낙관적 락 version) 또는 DB 시퀀스를 순서 번호로 쓴다. outbox에 순서 키 유일 제약을 추가해 중복 번호를 append 시점에 거부한다.
|
||||
- 버린 대안: 순서를 `occurred_at`으로만 두기. 지금 바로 이 문제다.
|
||||
- 완료 기준: 샘플의 순서 번호가 aggregate 쓰기와 같은 트랜잭션에서 단조 증가한다. 같은 번호 두 번 append는 실패한다.
|
||||
- 검증 방법: 같은 aggregate에 같은 순서 번호 두 건 append → 제약 위반 테스트. 샘플 use case 테스트에서 연속 변경의 번호가 증가하는지 단언.
|
||||
- 비고: 소유 leaf는 `sample-portfolio`·`persistence-jpa`다. 계약은 이 영역의 FIFO 의미라서 여기 적는다.
|
||||
|
||||
### 06-08 — 소비(consume)를 지원한다는 결정이 application 쪽 경로로 이어지지 않는다
|
||||
|
||||
- 성격: 구조적 위험(기능 개발 경로 공백)
|
||||
- 관련 관점: 2, 20, 25, 17
|
||||
- 근거
|
||||
- 소유자 결정 10: "Kafka 소비 지원. `MessageHandler<T>` 하나 + starter-kafka가 consumer 조립"(followup-status:38).
|
||||
- inbox 중복 제거는 `IdempotentConsumer` bean이 있어야 한다(`MessagingConsumeConfiguration.java:137-144`, 문서 `docs/messaging/outbox-inbox.md:115-119`). 이 타입은 `messaging-reliability`에 있다.
|
||||
- registry에서 `messaging-reliability`·`messaging-reliability-jdbc-postgresql`로 가는 application leaf 간선이 없다. bridge leaf는 `messaging-core-api`만 볼 수 있다(`modules.json` `:adapter:outbound:messaging`). `adapter:inbound:*`에 messaging leaf가 없다.
|
||||
- 저장소 전체에서 application 쪽 `MessageHandler` 구현·예제가 0건이다.
|
||||
- 소비자 중복 제거 의무는 문서에만 있다(`adapter/outbound/messaging/README.md` "중복 가능 구간", runbook `outbox-dead-letter.md:40`).
|
||||
- 발생 조건: 파생 서비스가 이벤트 소비 기능을 처음 만든다.
|
||||
- 영향: 어디에 handler를 둘지, inbox를 어떻게 조립할지 템플릿이 답하지 않는다. 각 팀이 registry 간선을 임의로 늘리거나 중복 제거 없이 소비한다.
|
||||
- 심각도·우선순위: Medium / P2.
|
||||
- 통제 수준: M1(문서). 증거 E1.
|
||||
- 결정의 근거: 기록된 의도는 "지원"이다. 현재 코드는 platform 안에서만 지원한다. 리뷰어 추론: consumer 조립은 platform 조립 경계(starter)에서 끝났고 application 경계 설계가 남았다.
|
||||
- 최소 개선 방향: `adapter:inbound:messaging`(가칭) leaf를 registry에 추가하고 `messaging-core-api`와 inbox 조립용 edge를 준다. 그 leaf가 application 포트(예: `IntegrationEventHandlerPort`)를 platform `MessageHandler`로 감싸는 bridge를 소유한다. 예제 handler 하나와 INBOX_TRANSACTIONAL destination 예시를 둔다.
|
||||
- 버린 대안: app-bootstrap에서 직접 handler bean 등록. composition root에 업무 handler가 들어가 HARD-STOP 4에 가까워진다.
|
||||
- 완료 기준: 샘플 이벤트 하나를 소비하는 handler가 inbox로 중복을 거르고, registry gate를 통과한다.
|
||||
- 검증 방법: Kafka+PostgreSQL 통합 테스트로 같은 메시지 두 번 전달 시 부작용 1회.
|
||||
|
||||
### 06-09 — 실제로 쓰는 발행 경로에는 broker 실연 테스트가 없고, broker 실연 lane은 어떤 기본 게이트에도 없다
|
||||
|
||||
- 성격: 확인된 결함(검증 공백)
|
||||
- 관련 관점: 10, 21, 18
|
||||
- 근거
|
||||
- 앱 경로 `PublishPendingOutboxEventsUseCase → OutboxMessagePublishAdapter → PlatformIntegrationEventPublishAdapter → DefaultMessagePublisher → Kafka`를 한 번에 도는 테스트가 없다. `PublishPendingOutboxEventsUseCase`를 쓰는 통합 테스트는 PostgreSQL + fake publisher뿐이다(`persistence-jpa/src/postgresqlIntegrationTest/.../readiness/*`). 앱 leaf 쪽 Kafka Testcontainers 사용은 0건이다.
|
||||
- Kafka 실연 테스트(`KafkaBrokerIT`, `KafkaAmbiguityChaosIT`, `MessagingLiveRoundTripQualificationTest` 등)는 vendored relay나 publisher 직접 호출을 검증한다. 앱은 vendored relay를 쓰지 않는다.
|
||||
- 이 lane들은 `integrationCheck`에만 묶인다(`src/build.gradle:100-105`). `mainCheck` 로그에서 messaging `integrationTest`는 컴파일만 됐다(`mainCheck.log:246-292`).
|
||||
- 06-01은 각 고리의 단위 테스트가 서로 다른 가정(retryable REJECTED / REJECTED=확정)을 단언하면서 통과해서 숨어 있었다.
|
||||
- 영향: 앱 경로의 실패 분류·종료·재시도가 실제 broker와 맞는지 아무 게이트도 확인하지 않는다.
|
||||
- 심각도·우선순위: Medium / P2.
|
||||
- 통제 수준: M0(앱 경로). 증거 E1.
|
||||
- 최소 개선 방향: `adapter:outbound:messaging-kafka`에 Kafka+PostgreSQL 통합 lane 하나를 두고 앱 relay를 실제로 돌린다: 정상 발행, broker 정지 후 재개(06-03), 종료 중 회차(06-02). lane은 CI 방향 결정에 따라 `mainCheck` 단계에 지정한다.
|
||||
- 버린 대안: vendored relay 테스트를 앱 증거로 인용하기. 다른 코드다.
|
||||
- 완료 기준: 앱 relay가 실제 Kafka로 발행한 레코드를 테스트가 읽어 envelope 바이트를 비교한다. 이 lane이 이름 있는 게이트에 들어 있다.
|
||||
- 검증 방법: 그 lane의 실행 로그.
|
||||
|
||||
### NN-10 — 이벤트 payload 버전을 올리는 방법과 호환성 검사가 없다
|
||||
|
||||
- 성격: 구조적 위험
|
||||
- 관련 관점: 17, 11, 20
|
||||
- 근거
|
||||
- encoder catalog는 `(contractId, payloadVersion)`을 키로 여러 버전을 함께 둘 수 있다(`JsonIntegrationEventEncoder.java:98,157-161`).
|
||||
- 버전 사이 호환성 검사가 없다. 기동 시 검사는 선언 hash와 classpath schema 파일의 일치뿐이다(`src/messaging/CLAUDE.md` "IntegrationEventEncoderPort" 절).
|
||||
- platform의 `schema.compatibility`는 선언만 한다(`docs/messaging/configuration-reference.md:123`).
|
||||
- payload v2를 추가하는 절차 문서가 없다. `payloadVersion`을 설명하는 문서는 `application-core/README.md:28` 한 줄이다.
|
||||
- outbox에 이미 쌓인 v1 row는 저장된 바이트 그대로 나간다(`JpaOutboxStore.java:197-235`). 이 점은 옳다. 다만 소비자가 v1·v2를 함께 받는 기간이 생긴다는 사실이 적혀 있지 않다.
|
||||
- 발생 조건: 기존 이벤트에 필드를 바꾸거나 지우는 변경.
|
||||
- 영향: 깨지는 schema 변경이 게이트를 통과한다. 소비자가 배포 순서에 따라 실패한다.
|
||||
- 심각도·우선순위: Medium / P2.
|
||||
- 통제 수준: M0. 증거 E1.
|
||||
- 최소 개선 방향: 같은 contract의 직전 버전 schema와 새 schema를 비교하는 테스트 fixture를 `shared-contract` 또는 `adapter:outbound:support` testFixtures에 두고, contract를 추가할 때 그 테스트를 함께 만들게 한다. 버전 올리기 절차(새 버전 추가 → 소비자 배포 → 생산자 전환 → 옛 버전 제거)를 README에 적는다.
|
||||
- 버린 대안: 외부 schema registry 도입. 이 템플릿 범위에 비해 운영 비용이 크다.
|
||||
- 완료 기준: 필드 삭제 같은 깨지는 변경이 테스트에서 실패한다.
|
||||
- 검증 방법: 샘플 contract에 깨지는 v2를 넣는 변이 실험.
|
||||
|
||||
### NN-11 — outbox가 둘인데 문서와 주석은 하나처럼 말한다
|
||||
|
||||
- 성격: 개선 제안(이해 비용)
|
||||
- 관련 관점: 4, 5, 23, 24
|
||||
- 근거
|
||||
- `docs/messaging/configuration-reference.md:28-33`: "outbox는 canonical 하나다".
|
||||
- 같은 폴더 `docs/messaging/outbox-inbox.md:28-60`은 vendored `messaging_outbox`와 그 relay(`REJECTED → markFailed`, 종단)를 "Outbox"로 설명한다. 앱이 쓰는 `outbox_event`·`composition:outbox-relay`는 `docs/messaging`에 언급이 없다.
|
||||
- 두 모델은 같은 이름의 상태가 반대 뜻이다. `OutboxPublishOutcome.java` javadoc이 "naming trap between the two outbox models is real"이라고 직접 경고한다.
|
||||
- vendored relay·lifecycle·cleanup bean 정의와 DDL은 runtime classpath에 있다(`messaging-spring-boot-starter/build.gradle:41-42` `implementation`). 조건이 맞지 않아 bean은 안 생긴다.
|
||||
- `MessagingShutdownLifecycle.java:113-116`은 존재하지 않는 relay를 전제로 순서를 설명한다(06-02).
|
||||
- 영향: 새 개발자가 `docs/messaging`을 읽고 앱 outbox의 동작을 잘못 예측한다. DEAD/FAILED 의미를 반대로 읽는다.
|
||||
- 심각도·우선순위: Medium / P3.
|
||||
- 통제 수준: M1(경고 주석 한 곳). 증거 E1.
|
||||
- 결정의 근거: 소유자 결정은 "messaging outbox 유지"다. 이 항목은 유지 자체가 아니라 두 모델의 경계 표시를 다룬다.
|
||||
- 최소 개선 방향: `docs/messaging/outbox-inbox.md` 맨 앞에 "이 문서는 vendored platform outbox다. 이 템플릿의 application은 `outbox_event`와 `composition:outbox-relay`를 쓴다"를 적고 앱 outbox 문서로 연결한다. 두 상태 이름 대응표를 한 곳에 둔다. `configuration-reference.md`의 "하나다"를 "application 경로는 하나다"로 고친다.
|
||||
- 완료 기준: `docs/messaging`에서 앱 outbox 문서로 가는 링크가 있고, 상태 대응표가 하나 있다.
|
||||
- 검증 방법: 문서 리뷰.
|
||||
|
||||
### NN-12 — 배치 크기와 lease 시간의 관계를 검사하지 않는다
|
||||
|
||||
- 성격: 구조적 위험
|
||||
- 관련 관점: 12, 19, 21
|
||||
- 근거
|
||||
- 회차 하나의 최악 시간은 배치 크기 × (송신 전 대기 5s + 응답 대기 5s)다(`KafkaMessagingAutoConfiguration.java:203-206`, `PublishOptions` 기본 5s). 기본값 20이면 약 200초다.
|
||||
- lease는 `in-flight-timeout` 기본 5분이다(`persistence-jpa.yml:196`). 지금은 여유가 있다.
|
||||
- `OutboxSettings`는 각 값을 따로 검사한다(`OutboxSettings.java:35-53`). `batch-size: 40`이면 최악 약 400초로 lease를 넘는다. 그러면 다른 인스턴스가 row를 다시 claim해 같은 이벤트를 또 보낸다. 늦은 쪽은 STALE이 된다(fencing은 상태 덮어쓰기만 막는다).
|
||||
- 영향: 설정 하나로 다중 인스턴스 중복 발행이 정상 운영 중에 생긴다.
|
||||
- 심각도·우선순위: Medium / P3. 기본값에서는 발생하지 않는다.
|
||||
- 통제 수준: M0. 증거 E1 + 계산.
|
||||
- 최소 개선 방향: 기동 시 `batchSize × 2 × publishDeadline < inFlightTimeout`을 검사하고 어기면 기동을 거부한다. 또는 relay가 회차 중 남은 lease를 보고 남은 row를 놓는다.
|
||||
- 완료 기준: lease를 넘을 수 있는 설정 조합이 기동에서 거부된다.
|
||||
- 검증 방법: `OutboxSettings` 바인딩 테스트에 경계 조합 추가.
|
||||
|
||||
### NN-13 — 이 영역 문서·주석의 낡은 설명
|
||||
|
||||
- 성격: 개선 제안
|
||||
- 관련 관점: 24, 9, 26
|
||||
- 근거
|
||||
- `OutboxRelayScheduler.java:15` "Registered by `OutboxConfig`"(실제 `OutboxRelayAutoConfiguration`).
|
||||
- `PublishPendingOutboxEventsUseCase.java:27` "Wired manually by `app-bootstrap`"(실제 `composition:outbox-relay`).
|
||||
- `adapter/outbound/messaging/README.md:73-77` 검증이 "build-tools로 옮겼다", `VerifyMessagingEvidenceTask`(둘 다 없음. 실제는 루트 `src/build.gradle:140` `verifyMessagingContracts`).
|
||||
- `adapter/outbound/messaging/CLAUDE.md:8` "Spring Boot 4.0.0"(실제 4.0.8).
|
||||
- `docs/runbooks/outbox-dead-letter.md:27` 차단 범위 조회가 옛 FIFO 키 사용(06-03).
|
||||
- `OutboxLeaderElectionToken.java:4-5` "presence satisfies the multi-instance coordination requirement". 이 bean을 요구하는 검사가 없다. 리더 선출도 하지 않는다(row 단위 claim이다).
|
||||
- `composition:outbox-relay`, `adapter:outbound:messaging-kafka`에 `CLAUDE.md`가 없다(README만 있음).
|
||||
- 심각도·우선순위: Low / P3.
|
||||
- 최소 개선 방향: 위 문장을 현재 위치로 고친다. `OutboxLeaderElectionToken`은 지우거나 이름을 `OutboxClaimStrategy`처럼 실제 동작으로 바꾼다.
|
||||
- 완료 기준: 위 위치의 설명이 코드와 맞는다.
|
||||
- 검증 방법: 문서 리뷰.
|
||||
|
||||
### NN-14 — DLQ 격리 레코드가 모든 원인을 `POISON_MESSAGE`로 적는다
|
||||
|
||||
- 성격: 개선 제안
|
||||
- 관련 관점: 8, 28
|
||||
- 근거: `KafkaDeadLetterQuarantine.java:41-47`. 복원 불가 레코드와 "시도 예산 소진"(일시 장애로 handler가 계속 실패한 경우)을 같은 category로 적는다.
|
||||
- 영향: redrive 판단 때 원인을 구분하지 못한다. 일시 장애로 격리된 메시지를 poison으로 오해한다.
|
||||
- 심각도·우선순위: Low / P3.
|
||||
- 최소 개선 방향: 호출자가 사유 category를 넘기게 한다(`UNDECODABLE` / `ATTEMPTS_EXHAUSTED`).
|
||||
- 완료 기준: 두 경로가 다른 header 값을 남긴다.
|
||||
- 검증 방법: `KafkaConsumerRegistrarTest`에 header 단언 추가.
|
||||
|
||||
## 4. 31절 시나리오 추적
|
||||
|
||||
### 4.1 정상 쓰기 → 발행 (`POST` durable operation)
|
||||
|
||||
| 항목 | 내용 |
|
||||
| --- | --- |
|
||||
| 입력 신뢰 수준 | HTTP 본문은 외부 입력이다. operation id는 서버가 UUID로 만든다(`DurableOperationController.java:86`) |
|
||||
| 인가 위치 | web adapter(이 영역 밖). relay는 `@RequiresPermission("outbox:relay")`가 붙어 있지만 bean이 아니라 관례로만 지킨다 |
|
||||
| 규칙 소유 객체 | 이벤트 생성 규칙: `SubmitDurableOperationUseCase`. 봉투 규칙: `JsonIntegrationEventEncoder`. 순서 규칙: FIFO gate(SQL) |
|
||||
| 트랜잭션 | `transactions.inWrite` 하나 안에서 operation 저장과 `outbox.append`(`SubmitDurableOperationUseCase.java:106-140`). append는 caller 트랜잭션이 없으면 거부한다(`JpaOutboxStore.java:61`) |
|
||||
| 외부 부작용 | 요청 안에서는 없다. relay가 커밋 뒤 비동기로 Kafka에 보낸다 |
|
||||
| 성공의 의미 | 202 응답은 "operation과 발행 의도가 함께 커밋됨"이다. 발행 완료가 아니다 |
|
||||
| 오류 변환 | 발행 실패는 요청에 영향이 없다. relay에서 FAILED/DEAD로 남고 `Slf4jOutboxRelayFailureReportAdapter`가 ERROR 한 줄을 남긴다 |
|
||||
| 진단 정보 | `correlation_id`(= operation id), `event_id`, `outbox.*` 지표. 단 relay가 꺼져 있으면 지표가 안 움직인다(06-05) |
|
||||
|
||||
원자성 판정: outbox 기록과 비즈니스 쓰기는 같은 JPA 트랜잭션에서 커밋된다. `CallerTransaction.require`가 경계에서 강제한다(M4, 이 경로 한정). 비즈니스 저장소가 JPA가 아닌 경우(Mongo 등)의 원자성은 다른 영역에서 확인해야 한다(>).
|
||||
|
||||
### 4.2 메시지 중복·역순
|
||||
|
||||
- 중복: lease 만료 재claim, `markPublished` 실패, AMBIGUOUS 재시도에서 같은 event id로 다시 나간다. 소비자 중복 제거가 필요하지만 application 쪽 소비 경로가 없다(06-08).
|
||||
- 역순: FIFO gate는 aggregate마다 head 하나만 내보낸다. relay는 응답을 기다린 뒤 다음 row로 간다(`OutboxMessagePublishAdapter.java:43` `join`). Kafka producer는 idempotence를 켠다(`KafkaMessagingAutoConfiguration.java:184-190`). 그래서 순서 번호가 맞으면 역순은 없다. 순서 번호 자체가 벽시계면 역순이 생긴다(06-07).
|
||||
|
||||
### 4.3 여러 서버의 relay 실행
|
||||
|
||||
- claim은 `FOR UPDATE SKIP LOCKED`, 인스턴스마다 UUID owner, row마다 token 증가(`JpaOutboxStore.java:105-127`).
|
||||
- 완료는 owner·token이 맞을 때만 적용된다. 아니면 STALE(`:136-162`). `PostgreSqlOutboxConcurrentRelayIntegrationTest`가 있다.
|
||||
- 같은 aggregate의 두 row는 두 인스턴스가 동시에 가져갈 수 없다. 앞 row가 PUBLISHED가 아니면 뒤 row는 gate에 걸린다.
|
||||
- 남은 위험: 배치 시간이 lease를 넘는 설정(NN-12).
|
||||
|
||||
### 4.4 외부 응답 지연·유실 (Kafka 느림·정지)
|
||||
|
||||
- 송신 전 대기 5s(`max.block.ms`), 응답 대기 5s(publish deadline)로 묶인다. relay thread가 무한정 막히지 않는다.
|
||||
- deadline 초과는 AMBIGUOUS로 분류된다(`DefaultMessagePublisher.java:244-256`). 결과 불명을 "전송됐을 수 있음"으로 남기는 것은 옳다.
|
||||
- 장애가 약 5분을 넘으면 DEAD가 대량으로 생긴다(06-03).
|
||||
|
||||
### 4.5 종료·재시작
|
||||
|
||||
- 진행 중 relay 회차는 끝까지 돈다. 그러나 platform admission이 먼저 닫혀 남은 row가 DEAD가 된다(06-01, 06-02).
|
||||
- 프로세스가 강제 종료되면 IN_FLIGHT row는 5분 뒤 다른 인스턴스가 가져간다. 이 경로는 설계대로다.
|
||||
- consumer 쪽은 drain 마감 30s 뒤 미정산 메시지를 broker 재전달에 맡긴다(`MessagingShutdownLifecycle.java:21-28`). 앱 handler가 없어 앱 경로로는 확인 대상이 없다.
|
||||
|
||||
### 4.6 신·구 버전 공존
|
||||
|
||||
- outbox row는 append 때의 바이트를 그대로 내보낸다. 배포가 바뀌어도 옛 row의 봉투는 변하지 않는다.
|
||||
- destination 선언이 새 배포에서 빠지면 옛 row는 `PUBLISH_PREPARATION_FAILED` REJECTED → DEAD가 된다. 이것은 설정 오류라 확정 거부로 보는 것이 맞다.
|
||||
- payload 버전 호환성 검사와 절차가 없다(NN-10).
|
||||
|
||||
### 4.7 선택 어댑터 제거
|
||||
|
||||
- `app-bootstrap/build.gradle`에서 `messaging-kafka` 줄을 지우면 bridge·platform·Kafka client·기본 설정이 함께 빠진다(README 서술, `KafkaCapabilityActivationTest`).
|
||||
- 발행 포트가 없으면 relay scheduler가 생기지 않고 PENDING row가 그대로 남는다(`OutboxRelayAutoConfiguration.java:62-64`). 대역 publisher가 row를 DEAD로 소진하지 않는다. 설계대로다.
|
||||
- 이때 지표도 갱신되지 않아 적체가 보이지 않는다(06-05).
|
||||
|
||||
### 4.8 적용 제외
|
||||
|
||||
| 시나리오 | 사유 |
|
||||
| --- | --- |
|
||||
| 세션·토큰 갱신 경쟁 | 이 영역에 사용자 세션이 없다 |
|
||||
| 다른 사용자 리소스 접근 | 사용자 요청 경로가 없다. tenant는 봉투 필드로만 옮긴다 |
|
||||
| 큰 입력·목록 조회 | payload 상한은 platform이 검사한다(`KafkaMessagingTransport.java:124-130`, admission). 목록 조회 API는 없다 |
|
||||
| DB 오류·경쟁 | `markPublished` 실패 경로만 해당하며 4.3·README에 설명된 대로 IN_FLIGHT로 남아 재claim된다. 별도 추적 생략 |
|
||||
|
||||
## 5. 41절 설계 선택 검토
|
||||
|
||||
### 5.1 application outcome 어휘: "REJECTED = 확정 거부 → 즉시 DEAD"
|
||||
|
||||
1. 필요한 것: relay가 재시도할 실패와 재시도해도 소용없는 실패를 구분해야 한다.
|
||||
2. 지킬 성질: 다시 보내면 성공할 수 있는 이벤트는 DEAD가 되면 안 된다. 다시 보내도 실패할 이벤트는 예산을 낭비하지 않는다.
|
||||
3. 현재 보장: 4값 enum(`OutboxPublishOutcome`)과 bridge 번역. platform의 `retryable` 정보는 번역에서 버려진다. 성질 1을 지키지 못한다(06-01).
|
||||
4. 대안: (a) 현상 유지, (b) 5번째 값 "전송 안 됨 + 재시도 가능", (c) REJECTED는 전부 retryable로 보고 예산으로 제한, (d) relay가 platform 타입을 직접 본다.
|
||||
5. 비용: (a) 배포·장애마다 영구 정지 위험. (b) enum 값 하나와 relay 분기 하나. (c) 진짜 poison row가 3회 동안 aggregate를 막고 예산을 쓴다. (d) 경계가 깨진다.
|
||||
6. 선택: (b). 의미를 잃지 않는 가장 작은 변경이다.
|
||||
7. 재검토 조건: platform이 retryable REJECTED를 없애고 그 경우를 AMBIGUOUS가 아닌 별도 completion으로 바꾸면 (a)로 돌아가도 된다.
|
||||
|
||||
### 5.2 relay 실행 방식: `@Scheduled` fixed-delay, tick당 claim 1회, aggregate당 head 1건
|
||||
|
||||
1. 필요한 것: 커밋된 이벤트를 순서대로, 다중 인스턴스에서 겹치지 않게 내보낸다.
|
||||
2. 지킬 성질: aggregate 안 순서, 같은 row 동시 발행 금지, 종료 시 진행 중 row를 망가뜨리지 않음.
|
||||
3. 현재 보장: 순서와 동시성은 SQL gate와 fencing으로 M4에 가깝게 지킨다. 종료 조율은 없다(06-02). 처리량은 poll 주기에 묶인다(06-04).
|
||||
4. 대안: (a) 현상 유지, (b) relay 전용 SmartLifecycle 루프(배치가 차면 바로 다시 claim, stop에서 drain), (c) vendored `OutboxRelayWorker`로 교체, (d) CDC(Debezium).
|
||||
5. 비용: (a) 0, 종료·처리량 문제 유지. (b) 루프 코드 소유, 테스트 필요. (c) outbox 모델·DDL·상태 의미 전환이 필요하고 소유자 결정 7(앱 outbox 하나)과 충돌한다. (d) 운영 인프라 추가, 2026-09-25에 삭제한 방향.
|
||||
6. 선택: (b). 지금 결정과 충돌하지 않고 두 문제를 같이 줄인다.
|
||||
7. 재검토 조건: relay를 별도 worker 배포 단위로 떼면 lifecycle 대신 그 프로세스의 종료 절차로 판단한다. 목표 처리량이 수백 건/초를 넘으면 (d)를 다시 비교한다.
|
||||
|
||||
### 5.3 outbox 두 개 유지(소유자 결정)
|
||||
|
||||
1. 필요한 것: application은 검증된 봉투를 같은 트랜잭션에 기록하는 outbox가 필요하다. platform은 제품으로서 자기 outbox를 가진다.
|
||||
2. 지킬 성질: 개발자가 어느 outbox가 동작 중인지 헷갈리지 않는다. platform의 종료·지표 설계가 앱 경로에도 맞는다.
|
||||
3. 현재 보장: bean 조건으로 vendored relay가 앱에서 생기지 않는다. 문서·종료 순서는 vendored relay 기준이다(06-02, NN-11).
|
||||
4. 대안: (a) 결정 유지 + 경계 표시 보강, (b) vendored outbox를 starter `implementation`에서 빼서 opt-in 의존으로, (c) 하나로 합치기.
|
||||
5. 비용: (a) 문서·주석 수정. (b) starter 의존 정리와 vendored 테스트 classpath 조정. (c) 결정 번복.
|
||||
6. 선택: (a)를 먼저, (b)는 다음 단계 후보. 결정은 유지한다.
|
||||
7. 재검토 조건: 앱이 vendored relay의 기능(claim-check, ordering key 등)을 필요로 하면 다시 비교한다.
|
||||
|
||||
## 6. 리팩토링 후보
|
||||
|
||||
| 대상 | 무엇을 왜 | 단순화의 보존 조건 |
|
||||
| --- | --- | --- |
|
||||
| `OutboxRelayScheduler` + `OutboxRelayAutoConfiguration` | `@Scheduled`를 relay 전용 lifecycle 루프로 바꾼다(06-02, 06-04) | 발행 포트가 없으면 relay가 없다. `relay-enabled=false`면 relay가 없다. 예상 못 한 예외에도 루프가 산다. 같은 ERROR 필드(`retry.disposition=next-tick`)를 남긴다. 회차가 겹치지 않는다 |
|
||||
| `OutboxMetrics` | relay에서 떼어 내 독립 갱신(06-05) | PUBLISHED는 세지 않는다. `MeterRegistry`가 없으면 no-op. event type이 사라지면 series를 덮어쓴다 |
|
||||
| `OutboxLeaderElectionToken` | 소비자 없는 marker. 지우거나 실제 동작 이름으로 | `BootstrapCapabilityReachabilitySystemTest.java:30`의 단언을 함께 고친다 |
|
||||
| `PlatformIntegrationEventPublishAdapter.mapOutcome` | retryable 정보를 보존하는 번역(06-01) | CONFIRMED·AMBIGUOUS 번역은 그대로. transmission 근거로 before/after를 나누는 규칙 유지. 문자열 비교 금지(MSG-022) |
|
||||
| starter 테스트 리소스 2개 | 참조 없는 옛 prefix fixture 삭제(M-8a) | 없음 |
|
||||
|
||||
## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료)
|
||||
|
||||
### 템플릿이 주는 틀
|
||||
|
||||
- 새 이벤트 발행: `IntegrationEventContractContribution` bean 등록 → use case에서 `IntegrationEventDraft` 생성 → `IntegrationEventEncoderPort.encode` → 같은 `inWrite` 안에서 `OutboxAppendPort.append`. 예시는 `SubmitDurableOperationUseCase`(단건 aggregate)와 sample `PortfolioEventOutbox`(여러 이벤트).
|
||||
- destination 선언: `app.messaging.destinations.<logical>`(`docs/messaging/configuration-reference.md`).
|
||||
- 발행 켜기: `runtimeOnly project(':adapter:outbound:messaging-kafka')`, `APP_MESSAGING_PRODUCER_ID`, `APP_MESSAGING_KAFKA_BROKERS`, `APP_OUTBOX_ENABLED=true`, `APP_OUTBOX_RELAY_ENABLED=true`.
|
||||
- fake: application-core testFixtures `InMemoryOutboxStore`, 계약 `OutboxLeaseFencingContract`.
|
||||
|
||||
### 빠진 것
|
||||
|
||||
- 이벤트 소비(handler 위치, inbox 조립) 예제와 leaf(06-08).
|
||||
- aggregate 순서 번호를 만드는 올바른 예(06-07).
|
||||
- payload 버전 올리기 절차와 호환성 테스트(NN-10).
|
||||
- 앱 relay를 실제 Kafka로 돌리는 테스트 틀(06-09).
|
||||
- `MessagePublisher` fake와 본체의 공통 계약(TEST-FAKE-MessagePublisher).
|
||||
|
||||
### 개발자가 내려야 하는 판단
|
||||
|
||||
1. 이 이벤트의 aggregate는 무엇이고 순서 번호는 어디서 오는가? 벽시계가 아니라 aggregate version이나 DB 시퀀스를 쓴다.
|
||||
2. event id는 무엇으로 만드는가? 소비자 중복 제거 키가 되므로 재시도해도 같은 값이 나와야 한다. 지금 bridge는 UUID만 받는다(06-06).
|
||||
3. 이 이벤트는 발행 완료를 기다려야 하는 요청인가? 아니라면 202 + outbox. 기다려야 하면 outbox만으로는 요구를 못 채운다(가이드 41.6).
|
||||
4. payload를 바꾸는가? 바꾸면 새 `payloadVersion`을 추가하고 소비자가 먼저 두 버전을 읽게 한다.
|
||||
5. 이 destination의 소비자는 부작용이 있는가? 있으면 INBOX_TRANSACTIONAL을 쓴다.
|
||||
6. 한 aggregate가 초당 몇 건을 만드는가? 0.2건/초를 넘으면 현재 relay 기본값으로는 지연이 쌓인다(06-04).
|
||||
7. relay를 몇 개 인스턴스에서 켤 것인가? batch-size를 올리면 lease 시간과 함께 계산한다(NN-12).
|
||||
|
||||
## 8. 28개 관점 판정표
|
||||
|
||||
기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역.
|
||||
|
||||
| 번호 | 관점 | 판정 | 한 줄 이유 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 코드 성숙도 | P | 실패 경로를 의식한 코드가 많다. platform과 application 사이 실패 의미 번역에 결함(06-01, 06-06) |
|
||||
| 2 | 구조적 성숙도 | P | 발행 경로는 port → bridge → platform으로 깨끗하다. 소비 경로에 application leaf가 없다(06-08) |
|
||||
| 3 | 변경 용이성 | P | 새 이벤트 추가 경로는 짧다. payload 버전 변경 경로가 없다(NN-10) |
|
||||
| 4 | 인지 부하 | P | 두 outbox 모델과 반대 뜻의 상태 이름(NN-11) |
|
||||
| 5 | 위험 가시성 | P | 중복 가능 구간은 README에 있다. "REJECTED = 영구"라는 가정이 코드에서 보이지 않는다(06-01) |
|
||||
| 6 | 실패 성숙도 | X | 일시 거부·종료·짧은 장애가 영구 DEAD로 이어진다(06-01, 06-02, 06-03) |
|
||||
| 7 | 운영 성숙도 | P | runbook·경보·구조화 ERROR가 있다. relay 꺼짐·실패 중 지표 정지(06-05), runbook 조회가 옛 키 |
|
||||
| 8 | 디버깅 가능성 | P | failure report에 event·aggregate·correlation id가 있다. DLQ 사유가 한 값(NN-14) |
|
||||
| 9 | 유지보수 성숙도 | P | 주석·README에 낡은 위치 설명(NN-13) |
|
||||
| 10 | 테스트 성숙도 | P | 단위 테스트 촘촘하고 빠름(합계 수 초). 앱 경로 실연 테스트 없음(06-09), 지표 변이 생존(06-05) |
|
||||
| 11 | 데이터 성숙도 | P | 봉투 바이트·hash 보존이 좋다. 순서 키 유일 제약 없음(06-07) |
|
||||
| 12 | 동시성 성숙도 | P | SKIP LOCKED + fencing은 좋다. 배치·lease 관계 미검사(NN-12), 종료 순서(06-02) |
|
||||
| 13 | 확장성 | P | 인스턴스 수평 확장은 된다. aggregate당 처리량 상한(06-04) |
|
||||
| 14 | 성능 성숙도 | ? | 계산만 했다. 실측 없음. 회차당 약 43 DB 문장, 인스턴스당 최대 약 4건/초 |
|
||||
| 15 | 보안 성숙도 | O | Kafka TLS/SASL·ACL 적용 확인(M-2 해결). 실패 report에 payload를 싣지 못하게 타입으로 막음 |
|
||||
| 16 | 의존성 성숙도 | P | broker SDK는 선택 줄을 지우면 빠진다. starter가 쓰지 않는 vendored outbox 구현을 `implementation`으로 싣는다 |
|
||||
| 17 | API / Contract 성숙도 | P | 봉투 v1 schema와 hash 검사가 있다. EventId/MessageId 불일치(06-06), payload 호환성 없음(NN-10) |
|
||||
| 18 | 배포 성숙도 | X | 배포 종료 중 row가 DEAD가 될 수 있다(06-02). broker 실연 lane이 기본 게이트 밖(06-09) |
|
||||
| 19 | 설정 성숙도 | P | strict 바인딩, producer-id 필수. relay 기본 꺼짐의 결과가 안 보임(06-05), 값 사이 관계 미검사(NN-12) |
|
||||
| 20 | 개발자 경험 | P | 발행 한 줄 켜기가 쉽다. 소비·버전·순서 번호 안내가 없다(06-07, 06-08, NN-10) |
|
||||
| 21 | Guardrail 성숙도 | P | caller 트랜잭션 강제, 대역 publisher 금지, producer-id 필수가 좋다. 이벤트 id·순서 번호·설정 조합 가드 없음 |
|
||||
| 22 | 추상화 성숙도 | P | bridge는 필요한 만큼만 안다. outcome 어휘가 platform 의미 하나를 담지 못한다(06-01) |
|
||||
| 23 | 일관성 | P | platform 종료 설계와 앱 relay 방식이 다르다(06-02, NN-11) |
|
||||
| 24 | 네이밍 / 의미 성숙도 | P | `OutboxLeaderElectionToken`이 하지 않는 일을 이름으로 말한다. 두 outbox의 FAILED 의미 반대 |
|
||||
| 25 | 조직 확장성 | P | 발행은 팀별로 독립 추가 가능. 소비는 registry 간선을 각자 만들게 된다(06-08) |
|
||||
| 26 | Ownership 성숙도 | P | leaf README가 근거를 잘 남긴다. composition·messaging-kafka에 `CLAUDE.md` 없음 |
|
||||
| 27 | 삭제 가능성 | O | messaging 줄 하나로 bridge·platform·Kafka가 함께 빠지고, relay는 남은 row를 소진하지 않는다 |
|
||||
| 28 | 회복 가능성 | X | DEAD는 수동 SQL로만 풀리고 짧은 장애에도 대량 발생한다(06-03) |
|
||||
@@ -0,0 +1,422 @@
|
||||
# 07 — 조립 루트·공용 런타임·설정 계약·컨테이너 (bootstrap-composition-config)
|
||||
|
||||
- 기준: 브랜치 `main`, 커밋 `01a8a2a70`
|
||||
- 맡은 leaf: `app-bootstrap`, `composition:service-runtime`, `composition:idempotency`(조립 쪽), `sample-portfolio`
|
||||
- 맡은 비-leaf 범위: 설정·환경 계약(`app.*` prefix, env key, `verifyEnvKeys`), `src/Dockerfile`, `src/Dockerfile.sample`, 루트 compose 파일, 보안 기본값
|
||||
- 증거 표기: 가이드 35.5 — E1 정적 확인, E2 테스트 실행, E3 실험 확인
|
||||
|
||||
## 1. 범위
|
||||
|
||||
| 항목 | 기록 |
|
||||
| --- | --- |
|
||||
| 대상 | `clean-architecture-backend-template`, Gradle 루트 `src/` |
|
||||
| 커밋·시점 | `01a8a2a70`, 2026-11-01 20:30~20:50 KST. 메인 repo 작업 트리는 깨끗한 상태 |
|
||||
| 목적·실행 구성 | 템플릿. 기본 조합은 web + 관측 + cores + support/identifier. 단일 배포 단위, 다중 인스턴스는 `APP_MULTI_INSTANCE_ENABLED`로 선택 |
|
||||
| 규모·운영 목표 | 정해진 목표 없음. 그래서 "운영 준비 완료" 판정은 하지 않는다 |
|
||||
| 읽은 코드·구성 | `app-bootstrap/src/main` 전체(31 java, yml 8, logback), `build.gradle` 전체, `composition/service-runtime`·`composition/idempotency` main 전체, `sample-portfolio`의 조립(`SamplePortfolioApplication`, `bootstrap/**`), `WorkLogController`, WorkLog 유스케이스, `application.yml`, README·CLAUDE.md, `src/Dockerfile`, `src/Dockerfile.sample`, `src/.dockerignore`, `src/.env.example`, 루트 `docker-compose*.yml`, build-logic `ca.config-contract`, support `startup/*`, persistence-jpa `JpaStartupAutoConfiguration`·`MigrationStartupRunner`(타이밍 확인용), web `WebSecurityAutoConfiguration`·`MethodSecurityConfig`·`JwtDecoderConfig`·`SecuritySettings` |
|
||||
| 게이트(오케스트레이터 실행) | `ci` rc=0(434s, 잠금 대기 포함). `mainCheck` rc=1 — 실패는 `:adapter:outbound:objectstorage:objectStorageMinioContractTest`·`objectStorageMinioFaultTest`의 `ContainerFetchException`(MinIO 이미지 조회 실패, 08 영역). 같은 실행에서 `:app-bootstrap:verifyEnvKeys` OK(346 env keys, 249 APP_ 참조), `:app-bootstrap:systemTest` 4 suite 8 test 통과, `:app-bootstrap:publicPathSnapshotTest`, `:sample-portfolio:webSystemTest` 실행됨 |
|
||||
| 이 리뷰가 돌린 실험 | (1) worktree `wt-07`에서 `:app-bootstrap:systemTest --tests '*ExperimentProbeTest*'` — BUILD SUCCESSFUL 10s, 부하 7~15. 기본 조합을 실제로 띄워 트레이서·로깅·audience·지연 초기화를 관찰. (2) `Dockerfile.sample`과 `Dockerfile`의 builder 단계 COPY 집합을 그대로 재현한 디렉터리에서 `./gradlew help --offline` — sample 집합 rc=1, main 집합 rc=0. 둘 다 끝난 뒤 worktree·임시 디렉터리 삭제 |
|
||||
| 확인 못 한 것 | 실제 `docker build`(이미지 빌드·기동). JPA를 켠 조합에서 prod 검증 순서의 실측(PostgreSQL 필요). `:app-bootstrap:integrationTest`는 이번 게이트에 없음(결과 파일이 2026-09-28). sample `systemTest`·`integrationTest`도 이번 게이트에 없음. 부하·메모리 측정 |
|
||||
| 이전 리뷰와 비교 | techlead `12-bootstrap-sample.md`, followup-status L·S6 행, `2026-09-07-app-bootstrap-module-code-review.md`(BOOT-001~017, 2026-09-19 closure에서 전부 닫힘) |
|
||||
|
||||
## 2. 지난 발견 재확인
|
||||
|
||||
followup-status에서 `남음`이던 행과 이 영역의 핵심 행만 다시 봤다. BOOT-001~017은 closure 문서 이후 코드가 크게 바뀌어(바인더·startup 어휘가 support로 이동) 표본만 확인했다.
|
||||
|
||||
| ID | 상태 | 근거 |
|
||||
| --- | --- | --- |
|
||||
| L-2b runtime.yml multi-instance 주석 | 남음 | `src/app-bootstrap/src/main/resources/config/runtime.yml:11-13`이 여전히 "requires the 5 instance-coordination beans". 실제 검사는 `distributedLockProvider` 하나(`StartupSafetyValidator.java:18-19,48-57`) |
|
||||
| L-4a sample이 중앙 ArchUnit에서 빠짐 | 해결(바뀜) | `src/app-bootstrap/build.gradle:192` `architectureTestRuntimeOnly project(':sample-portfolio')`. `..application..`·`..domain..` 패턴 규칙이 sample 패키지에도 걸린다(`ApplicationBoundaryArchitectureTest.java:55-59`) |
|
||||
| L-4b 없는 ArchUnit 규칙 인용 | 남음 | `src/sample-portfolio/CLAUDE.md:43`, `src/app-bootstrap/README.md:478`, `src/domain-core/README.md:27`. 규칙 정의 0건 |
|
||||
| L-7b `ActuatorSecurityHttpTest`가 도달 불가 200 단언 | 해결 | `ActuatorSecurityHttpTest.java:95-97`이 이제 `loggers`가 404임을 단언 |
|
||||
| L-10f build.gradle 고아 주석 | 남음 | `src/app-bootstrap/build.gradle:280-281` "Kafka producer ownership…" 주석이 `jakarta.ws.rs-api` 줄 위에 있음 |
|
||||
| L-11a `ca-skeleton.rate-limit.*` | 해결 | `application-test.yml`·sample `application.yml`에 `ca-skeleton.` 키 0건. sample은 `app.rate-limit`(`sample-portfolio/.../application.yml:189`) |
|
||||
| L-11b test yml `api-base-path: ""` + `/api/healthcheck` | 남음 | `src/app-bootstrap/src/test/resources/application-test.yml:112,118` |
|
||||
| L-11c 참조 없는 `broken-readme.md` | 남음 | `src/app-bootstrap/src/test/resources/developer-experience/broken-readme.md` 존재 |
|
||||
| S6-#2d 멱등성 provider 기본값 | 해결(유지) | `composition/idempotency/.../module-defaults/idempotency.yml:12` `disabled`, `IdempotencySettings.java` `Provider.DISABLED` |
|
||||
| S6-#4 root 넓은 scan | 해결(유지) | `CaSkeletonApplication.java:19-26` 자기 패키지 scan + bootstrap 4개 패키지 properties scan |
|
||||
| S6-#7 sample이 bootstrap 인프라 복사 | 해결(유지) | sample이 `composition:service-runtime`·`composition:idempotency`를 `runtimeOnly`로 받음(`sample-portfolio/build.gradle` dependencies) |
|
||||
| S6-#9 sample yml의 읽는 코드 없는 블록 | 남음(범위 커짐) | `app.capabilities.cache`(`application.yml:150-177`), `app.bootstrap`(`:180-181`), `app.logging`(`:209-225`) 그대로. 추가로 sample이 `WebSecurityAutoConfiguration`을 제외해서 `app.security`·`app.authz`·`app.cors`(`:194-208`)도 읽히지 않는다(07-03) |
|
||||
| S6-#10e sample CLAUDE.md 경로 | 남음 | `src/sample-portfolio/CLAUDE.md:20-23` `adapter/web`, `adapter/persistence`, `adapter/identifier`(실제는 `adapter/inbound/web`, `adapter/outbound/persistence`, `adapter/outbound/identifier`) |
|
||||
| S6-#15 bootstrap `:test`의 저장소 governance 테스트 | 남음 | `app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/` 45파일 6,991줄. Wave 4 P33에 배정됨 |
|
||||
| S6-#16a 이력·리뷰 ID 주석 | 남음 | bootstrap·composition main에서 `BOOT-n`/`Dn`/`DRIFT-` 류 35줄 |
|
||||
| S6-#16d config yml 같은 3줄 헤더 | 남음 | `config/{server,observability,runtime,security}.yml` 4개가 같은 3줄 |
|
||||
| S6-#17 `TracingSettings.sampleRate`가 String | 남음(이동) | `composition/service-runtime/.../TracingSettings.java:13,56-63`, `TracingSampleRateResolver.java:18-29`, `TracingSamplingEnvironmentPostProcessor.java:30`에서 세 번 파싱 |
|
||||
| BOOT-005 startup 순서 | 해결(유지) | `StartupOrder` 상수, `RuntimeEnvironmentProfileValidator.java:90-92`, `TracingSamplingEnvironmentPostProcessor.getOrder()` |
|
||||
| BOOT-017 bootstrap이 어댑터 구현 소유 | 해결 | bootstrap main에 포트 구현 없음. 단 `DurableOperationConfig`가 유스케이스를 조립한다(07-08) |
|
||||
|
||||
지난 리뷰에서 남은 High/P1은 이 영역에 없다. 위 `남음`은 전부 W4·W5(테스트 규칙·문서)다.
|
||||
|
||||
## 3. 새 발견
|
||||
|
||||
### 07-01 트레이스가 어디로도 나가지 않는다 — OTLP endpoint를 설정해도 span을 만들지도 보내지도 않는다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 7, 8, 5, 16, 19 |
|
||||
| 근거 | `composition/service-runtime/.../tracing/TracingConfig.java:66-91` — 자체 `Tracer` bean이 `SdkTracerProvider.builder().setSampler(...).build()`로 만든다. span processor·exporter를 붙이는 줄이 없다. `TracingSettings.Exporter.isConfigured()`(`TracingSettings.java:35`)는 호출하는 곳이 없다. `app-bootstrap/gradle.lockfile`의 runtime classpath에 Boot의 tracing 자동 설정 모듈(`spring-boot-micrometer-tracing*`, `spring-boot-opentelemetry`)이 없다. 그래서 `TracingSamplingEnvironmentPostProcessor`가 넣는 `management.tracing.sampling.probability`(`:30-38`)를 읽는 코드도 없다. 문서는 반대로 말한다: `composition/service-runtime/README.md:72-75` "엔드포인트를 설정하면 export 가 시작된다", `config/observability.yml:153-158` |
|
||||
| 실행 결과 (E3) | 기본 조합을 `OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318`로 띄움 → Tracer bean은 `micrometerTracer` 하나, `SpanExporter` 0개, `SpanProcessor` 0개, `ObservationHandler`는 `defaultMeterObservationHandler` 하나(트레이싱 핸들러 없음). 즉 HTTP 요청 observation이 span을 만들지 않는다 |
|
||||
| 발생 조건 | 항상. 운영자가 OTLP collector 주소를 넣는 순간 문제가 드러나야 하지만 아무 오류도 경고도 없다 |
|
||||
| 영향 | "트레이스 기본 제공" 주장이 거짓이다. 로그의 `trace_id`는 web filter가 만든 W3C 값(`WebMvcRequestIdFilter.java:108-118`)이라 로그 상관은 된다. 그러나 서비스 간 span 트리, 지연 분해, 오류 span(`SpanErrorRecorder`)은 없다. 파생 서비스가 그대로 복제한다 |
|
||||
| 심각도·우선순위 | High / P1. 관측성은 이 템플릿이 기본 조합에 넣었다고 선언한 기능이다. 설정 옵션이 동작하지 않는데 조용하다(AGENTS.md capability 기준 3 "동작하지 않는 옵션은 설정 키 자체를 두지 않는다" 위반) |
|
||||
| 확실성 | 직접 확인: 빈 목록, lockfile. 추론: Boot 4의 tracing 자동 설정 모듈을 넣으면 `micrometerTracer`의 `@ConditionalOnMissingBean`과 순서 경쟁이 생길 수 있다 — 수정 때 확인할 것 |
|
||||
| 통제 수준 | M1(문서만 있음). 테스트 `TracingActivationContextTest`는 bean 존재만 본다 |
|
||||
| 결정의 근거 | 설계 선택 포함. 기록된 의도: "Plan A — seam activated"(`observability.yml:154`). 현재 효과: seam만 있고 출력이 없다 |
|
||||
| 최소 개선 방향 | 고른 방법: 자체 `Tracer` 조립을 지우고 Boot 4의 tracing 모듈(`spring-boot-micrometer-tracing-opentelemetry` 계열 starter)과 OTLP export 설정 키 하나로 바꾼다. `app.tracing.sample-rate`의 profile 기본값(prod 0.01)은 EPP로 Boot 키에 넣는 현재 방식을 유지한다. 버린 대안 1: 자체 `SdkTracerProvider`에 `BatchSpanProcessor`+`OtlpHttpSpanExporter`를 직접 붙인다 — observation→span 연결(`TracingObservationHandler`, propagator)까지 손으로 만들어야 해서 Boot가 이미 주는 것을 다시 짠다. 버린 대안 2: tracing 의존성과 설정을 지우고 "로그 상관만 제공"으로 범위를 줄인다 — 가능하지만 owner가 관측 기본 제공을 정했으므로 소유자 결정이 필요하다 |
|
||||
| 단순화의 보존 조건 | `app.tracing.enabled=false`면 Tracer 없음. `SpanErrorRecorder`는 Tracer가 없어도 NOOP bean으로 남음. prod 기본 sample rate 0.01, 그 밖 1.0. 응답 `meta.traceId`와 로그 `trace_id`가 같은 값 |
|
||||
| 완료 기준 | endpoint를 넣으면 span exporter bean이 생기고, 넣지 않으면 exporter가 없거나 비활성이다. HTTP 요청 하나가 span 하나를 만든다 |
|
||||
| 검증 방법 | systemTest에 in-memory span exporter를 주입해 HTTP 요청 1건 → span 1건, `trace_id`가 응답 meta·MDC와 같음을 단언 |
|
||||
|
||||
### 07-02 prod 기동 검사가 DB 연결과 Flyway 마이그레이션이 끝난 뒤에 돈다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험(실측은 미실행) |
|
||||
| 관련 관점 | 6, 15, 11, 5, 21 |
|
||||
| 근거 | 모든 `StartupRule`은 `StartupRuleRunner.afterSingletonsInstantiated()`(`adapter/outbound/support/.../startup/StartupRuleRunner.java:35`)에서 한 번에 돈다. 이 콜백은 모든 싱글턴이 만들어진 뒤에 불린다. JPA 모듈을 켜면 그 전에 이미 (a) `FlywayMigrationInitializer`가 `MigrationStartupRunner.migrate()`로 마이그레이션을 실행하고, (b) `jpaResolvedDataSourceCheck`(`JpaStartupAutoConfiguration.java:101-107`, `InitializingBean`)가 DB 연결을 연다. 그런데 prod를 지키는 `PostgreSqlTransportSecurityValidator`(sslmode=verify-full), `FlywayProdSafetyValidator`(baseline-on-migrate·out-of-order·clean), `RequiredEnvironmentValidator`는 모두 `StartupRule`이다. 주석은 반대로 적었다: `JpaStartupAutoConfiguration.java:59` "datasource connection env present **before migration runs**" |
|
||||
| 발생 조건 | JPA 모듈 선택 + prod + 금지 값 하나(예: `sslmode=disable`, `APP_…`로 `spring.flyway.out-of-order=true`) |
|
||||
| 영향 | 기동은 결국 실패한다. 그러나 실패 전에 (1) 평문 연결로 DB 비밀번호가 나간다, (2) out-of-order·baseline 옵션으로 마이그레이션이 이미 적용된다. (2)는 되돌릴 수 없는 스키마 변경이다. 검증기의 존재 이유가 "운영 DB에 위험한 옵션이 닿기 전에 막기"인데 순서가 그 뒤다 |
|
||||
| 심각도·우선순위 | High / P1. prod 안전 검사의 약속 자체가 순서 때문에 깨진다. 기본 조합에는 JPA가 없어서 P0은 아니다 |
|
||||
| 확실성 | 직접 확인: runner 호출 시점(Spring 계약), JPA 쪽 bean 종류. 실측하지 않음: PostgreSQL이 필요해 이 리뷰에서 재현하지 않았다. `lazy-initialization=true`에서도 `SmartInitializingSingleton` 기반 검사는 돈다는 것은 실험으로 확인했다(E3: `lazy-prod-no-salt => FAILED`, `lazy-prod-include-stacktrace => FAILED`). 단 `InitializingBean` 기반 JPA 검사(`jpaPlatformStartupCheck`, `jpaResolvedDataSourceCheck`)는 지연 초기화에서 건너뛸 수 있다 — 05 영역 확인 필요 |
|
||||
| 통제 수준 | M2(검사는 구현돼 있음), 순서는 M0 |
|
||||
| 결정의 근거 | 41절 D2 참조. 단일 runner로 모은 결정은 옳았다. 문제는 실행 시점이 phase 이름(`PROFILE_CHECK`, `ENV_VALIDATION`)과 맞지 않는 것이다 |
|
||||
| 최소 개선 방향 | 고른 방법: 환경만 읽는 rule(`violations(Environment)`만 쓰는 것 — 현재 전부 해당)은 `EnvironmentPostProcessor`나 `BeanFactoryPostProcessor` 단계에서 돌리는 두 번째 진입점을 support에 둔다. rule 인터페이스와 종료 코드는 그대로 둔다. 버린 대안 1: Flyway 전략(`MigrationStartupRunner`) 안에서 rule을 먼저 부른다 — JPA만 고치고 다른 모듈의 같은 문제를 남긴다. 버린 대안 2: DataSource bean에 `@DependsOn("startupRuleRunner")` — 그래도 runner 자체가 `afterSingletonsInstantiated`라 효과가 없다 |
|
||||
| 단순화의 보존 조건 | 위반 시 같은 종료 코드(71/72/78), 같은 `startup.phase`·`error.code` 로그 필드, 한 rule의 위반을 한 번에 보고 |
|
||||
| 완료 기준 | prod + `sslmode=disable`에서 DataSource가 연결을 열기 전에 기동이 실패한다 |
|
||||
| 검증 방법 | JPA systemTest에 연결 시도를 세는 DataSource 프록시를 두고, 금지 값에서 연결 횟수 0 + 종료 코드 71을 단언 |
|
||||
|
||||
### 07-03 실행 중인 샘플에서는 `@RequiresPermission`이 아무 일도 하지 않는다 — 익명 삭제 가능, 생성은 500
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(정적 확인) |
|
||||
| 관련 관점 | 15, 5, 20, 21, 10 |
|
||||
| 근거 | `SamplePortfolioApplication.java:31` `@EnableAutoConfiguration(exclude = WebSecurityAutoConfiguration.class)`. 제외한 클래스가 `MethodSecurityConfig`·`AuthorizationAdapter`·`RolePermissionRegistry`를 들여오는 유일한 곳이다(`adapter/inbound/web/.../WebSecurityAutoConfiguration.java:41-49`). 그 대신 들어오는 `SamplePublicAccessSecurityConfig.java:21-26`은 `/**` 전체 permitAll이고 인증 수단이 없다. 그런데 유스케이스는 권한을 선언한다: `DeleteWorkLogUseCase.java:14` `@RequiresPermission("worklog:close")`(주석 "admin-tier"), `CreateWorkLogUseCase.java:23` `worklog:write`. 컨트롤러는 인증 주체가 없으면 owner를 `null`로 넘기고(`WorkLogController.java:221-229`) 도메인은 `Objects.requireNonNull`로 거부한다(`WorkLogOwner.java`) — NPE라 `GlobalExceptionHandler`의 `Exception` 처리(500)로 간다. 권한 E2E 테스트는 보안 필터와 자동 설정을 끄고 advisor를 직접 넣는다(`WorkLogAuthorizationE2ETest`), 그래서 실행본의 상태를 보지 못한다 |
|
||||
| 발생 조건 | `:sample-portfolio:bootRun` 또는 sample 이미지로 띄운 앱 |
|
||||
| 영향 | 누구나 `DELETE /api/worklogs/{id}`로 아무 기록이나 지운다. 생성은 항상 500이다. README의 curl 예시(`sample-portfolio/README.md:33-58`)는 경로(`/work-logs`)도 틀렸다. 더 큰 문제는 복제 범위다. 샘플은 adopter가 가장 먼저 베끼는 코드이고, 여기서 "보안 자동 설정 하나 제외"가 메서드 보안 전체를 조용히 끈다는 사실이 어디에도 드러나지 않는다. `@RequiresPermission`이 붙은 bean이 있는데 advisor가 없으면 실패하는 장치도 없다 |
|
||||
| 심각도·우선순위 | High / P1. 데모라 데이터 가치는 낮지만, 인가 위치(유스케이스)라는 핵심 규칙이 예시에서 무력화되고 복제된다(35.2 "샘플을 통해 복제되는 범위") |
|
||||
| 확실성 | 정적 경로는 끝까지 확인했다. HTTP로 실제 삭제를 재현하지는 않았다(PostgreSQL 필요) |
|
||||
| 통제 수준 | M0(실행본에서). 단위 계층은 M3 |
|
||||
| 결정의 근거 | 기록된 의도: "IdP 없이 둘러볼 수 있는 공개 데모"(`sample-portfolio/README.md:410-412`). 의도는 URL 공개였지 권한 검사 제거가 아니었다고 읽힌다 — README도 "JWT 필터 체인·메서드 보안·권한 port만 뺀다"고 적어 메서드 보안 제거를 인정하면서 유스케이스 주석은 admin 전용이라고 말한다 |
|
||||
| 최소 개선 방향 | 고른 방법: `WebSecurityAutoConfiguration`을 제외하지 않고, 샘플은 JWT 대신 고정 데모 주체(예: `X-Demo-Role` 헤더나 local 전용 dev 토큰)를 넣는 인증 필터 하나만 둔다. 그러면 권한 검사는 production과 같은 경로로 돈다. 버린 대안 1: 지금 구조 유지 + README 경고 — 위험이 코드에 드러나지 않는다는 원칙에 어긋난다. 버린 대안 2: 샘플에서 `@RequiresPermission`을 지운다 — 인가 위치를 보여 주는 예시가 사라진다. 함께 할 것: `@RequiresPermission` bean이 있는데 `requiresPermissionAuthorizationAdvisor`가 없으면 기동 실패하는 rule을 web 모듈에 둔다 |
|
||||
| 완료 기준 | 실행 중인 샘플에서 권한 없는 주체의 DELETE가 403, 권한 있는 주체는 204. 생성은 주체가 있으면 201 |
|
||||
| 검증 방법 | sample `systemTest`(실제 컨텍스트, 보안 자동 설정 포함)에서 위 세 경우를 HTTP로 단언 |
|
||||
|
||||
### 07-04 `Dockerfile.sample`은 빌드되지 않는다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 18, 20, 10 |
|
||||
| 근거 | `src/Dockerfile.sample:50-53`은 `gradlew`, `gradle/`, `config/`, `settings.gradle build.gradle **/build.gradle **/gradle.lockfile`만 복사한다. `src/Dockerfile:46,53`이 따로 복사하는 `gradle.properties`와 `build-logic/` 전체가 없다. `settings.gradle:1-6`은 `includeBuild('build-logic')`로 convention plugin을 가져오므로 build-logic의 `settings.gradle`(version catalog)과 `src/main/groovy` 플러그인이 없으면 settings 단계에서 실패한다. main Dockerfile 주석(`:49-52`)이 같은 실패를 이미 설명하고 고쳤는데 sample은 따라가지 않았다. 이 파일을 빌드하는 CI lane도 없다(`git grep Dockerfile.sample` → 문서·계획서만) |
|
||||
| 실행 결과 (E3) | 두 COPY 집합을 그대로 재현한 디렉터리에서 `./gradlew help --offline`. sample 집합: rc=1, `settings.gradle line 9 … A problem occurred evaluating project ':build-logic' … unknown property 'libs'`. main 집합(+`build-logic/`, `gradle.properties`): rc=0. 실제 `docker build`는 하지 않았다 |
|
||||
| 발생 조건 | 문서대로 `docker build -f src/Dockerfile.sample src/`(`Dockerfile.sample:12`) |
|
||||
| 영향 | 샘플 이미지를 만들 수 없다. 07-03의 문제를 이미지로 배포하는 경로는 지금은 막혀 있지만, 고치면 그대로 드러난다 |
|
||||
| 심각도·우선순위 | Medium / P2. 운영 이미지가 아니라 데모 이미지다 |
|
||||
| 통제 수준 | M0(검증 lane 없음) |
|
||||
| 결정의 근거 | 적용 제외 — main Dockerfile이 이미 정답을 갖고 있어 선택 비교가 필요 없다 |
|
||||
| 최소 개선 방향 | builder 단계를 main과 같게 맞춘다. 더 나은 방법: 두 Dockerfile의 builder 단계를 하나로 두고 `ARG` 하나로 `:app-bootstrap`/`:sample-portfolio`를 고른다(main이 이미 `COMPOSITION` 인자로 같은 일을 함). 갈라진 복사본을 없애는 쪽이 원칙에 맞다 |
|
||||
| 완료 기준 | `docker build -f src/Dockerfile.sample src/` 성공, 이미지 HEALTHCHECK 통과 |
|
||||
| 검증 방법 | 두 Dockerfile을 모두 빌드하는 CI lane(또는 `DeveloperExperienceContractTest`에 builder COPY 집합 동일성 단언) |
|
||||
|
||||
### 07-05 prod에서 JWT audience를 비워도 기동하고, 경고도 없이 audience 검사를 끈다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 15, 19, 6 |
|
||||
| 근거 | `.env.example:97` `APP_SECURITY_JWT_AUDIENCE=`(빈 값). `SecuritySettings.java:35-41`은 값이 `null`일 때만 경고하고, 빈 문자열이면 경고 없이 `""`로 둔다. `JwtDecoderConfig.java:80-82`는 audience가 비면 검사기를 붙이지 않는다. prod secret guard(`SecretSourceValidator.REQUIRED_PROD_SECRETS`, `:34-35`)와 그 밖의 prod rule 어디에도 audience가 없다. `.env.example:12-15`는 "issuer와 audience는 기본값이 없다 — 아무도 고르지 않은 대상을 막기 위해"라고 말한다 |
|
||||
| 실행 결과 (E3) | prod + 빈 audience(두 경로 모두 빈 값)로 기본 조합 기동 → `BOOTED` |
|
||||
| 발생 조건 | `.env.example`을 복사하고 audience를 채우지 않은 prod 배포 |
|
||||
| 영향 | 같은 IdP realm에서 다른 클라이언트용으로 발급된 토큰을 이 API가 받는다(토큰 혼용). 문서의 약속과 반대로 동작한다 |
|
||||
| 심각도·우선순위 | Medium / P2. issuer 검사는 남아 있어 외부 토큰은 막힌다. 피해 범위가 같은 IdP의 다른 client로 제한된다 |
|
||||
| 통제 수준 | M0(prod 강제 없음) |
|
||||
| 결정의 근거 | 설계 선택 포함. 기록된 의도는 "blank disables the check"(`application.yml:45`)로, 로컬 편의 때문이다 |
|
||||
| 최소 개선 방향 | 고른 방법: prod에서 JWT 모드면 audience 필수인 `StartupRule`을 web 모듈에 둔다(local·dev는 지금처럼 허용, 대신 빈 값도 경고). 버린 대안: 모든 profile에서 필수 — 로컬 IdP 없이 띄우는 흐름을 깨고, 이 템플릿의 local 경험을 바꾼다 |
|
||||
| 완료 기준 | prod + JWT + 빈 audience → 기동 실패(ENV_VALIDATION). local은 경고 1줄 |
|
||||
| 검증 방법 | `DefaultCompositionBootTest`에 prod 빈 audience 거부 케이스 추가 |
|
||||
|
||||
### 07-06 로그 설정이 두 군데에서 읽힌다 — `LoggingSettings`는 아무도 쓰지 않고, logback은 env 키를 직접 읽는다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 19, 5, 8, 22 |
|
||||
| 근거 | `bootstrap/settings/LoggingSettings.java`는 `app.logging.*`를 바인딩하고 잘못된 값을 "경고 후 기본값"으로 고친다(예: 빈 경로 → `logs/app.json`, `:20-23`). main 코드에 이 record를 쓰는 곳이 없다(사용처는 `LoggingSettingsTest`뿐). 실제 로깅을 정하는 `logback-spring.xml:17-46`은 `springProperty source="APP_LOG_FILE_ENABLED"` 같은 env 키 이름을 직접 읽는다. 그래서 (1) `app.logging.*`를 yml이나 profile 파일로 바꾸면 반영되지 않고, (2) `LoggingSettings`의 경고는 실제로 적용되지 않는 대체값을 알린다(경로 대체값 `logs/app.json` vs logback 기본 `logs/ca-skeleton.json`) |
|
||||
| 실행 결과 (E3) | `--app.logging.file.enabled=true --app.logging.file.path=…`로 기동 → root appender `[ASYNC_CONSOLE]`만. 파일 appender가 붙지 않는다 |
|
||||
| 발생 조건 | 운영자가 env 대신 `application-prod.yml`이나 설정 서버로 `app.logging.*`를 바꿀 때 |
|
||||
| 영향 | 로그 파일·보관 기간이 설정과 다르게 동작한다. 경고 로그가 거짓 정보를 준다 |
|
||||
| 심각도·우선순위 | Medium / P2 |
|
||||
| 통제 수준 | M1 |
|
||||
| 결정의 근거 | 설계 선택 포함. logback은 Spring 바인딩보다 먼저 초기화돼 typed settings를 쓸 수 없다는 제약이 있다(`logback-spring.xml:5` 주석) |
|
||||
| 최소 개선 방향 | 고른 방법: `LoggingSettings`를 지우고, logback `springProperty`의 `source`를 `app.logging.*` 키로 바꾼다(`springProperty`는 Spring Environment를 읽으므로 env→yml placeholder 경로가 그대로 산다). 값 검증은 logback이 실패할 값(예: maxHistory<=0)만 `StartupRule` 하나로 fail-fast. 버린 대안: `LoggingSettings`를 유지하고 logback을 런타임에 재구성 — 초기 로그와 이후 로그가 다른 설정을 쓰는 구간이 생긴다 |
|
||||
| 단순화의 보존 조건 | env 키 이름(`APP_LOG_*`)과 기본값, JSON 필드, 마스킹 |
|
||||
| 완료 기준 | `app.logging.file.enabled=true`(yml)로 파일 appender가 붙는다. 같은 값이 한 곳에서만 정의된다 |
|
||||
| 검증 방법 | 위 실험을 systemTest로 고정 |
|
||||
|
||||
### 07-07 종료 시간 예산표에 async executor 대기 19초가 빠져 있다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 7, 18, 12, 9 |
|
||||
| 근거 | 루트 `docker-compose.yml:9-19,88-89`의 예산: 앱 30s(`timeout-per-shutdown-phase`) + preStop 5s + 여유 5s = `stop_grace_period: 40s`. 그런데 `AsyncExecutorConfig.java:27-28,53-54`는 `setWaitForTasksToCompleteOnShutdown(true)` + `awaitTermination 19s`이고 주석은 "container app-shutdown budget (20s)"라고 적는다. Spring은 lifecycle 단계(웹 서버 graceful 30s까지)를 끝낸 뒤 bean destroy에서 executor 대기를 한다. 최악은 30 + 19 = 49s로 40s를 넘는다 |
|
||||
| 발생 조건 | 종료 시점에 HTTP 요청 처리가 길고, 동시에 async 작업이 큐에 남아 있을 때 |
|
||||
| 영향 | 컨테이너가 SIGKILL로 끝나 async 작업이 중간에 끊긴다. 종료 로그가 남지 않는다 |
|
||||
| 심각도·우선순위 | Medium / P2. 최악 경로에서만 일어난다 |
|
||||
| 확실성 | lifecycle → destroy 순서는 Spring 계약으로 판단했다. 최악 시간은 측정하지 않았다. `AsyncGracefulShutdownBehaviorTest`(2 test, 통과)는 executor만 따로 본다 |
|
||||
| 통제 수준 | M1(표는 있음, 표가 틀림) |
|
||||
| 결정의 근거 | 적용 제외 — 숫자 정합성 문제다 |
|
||||
| 최소 개선 방향 | executor 대기를 `spring.lifecycle.timeout-per-shutdown-phase`에서 계산하거나, 예산표에 executor 대기를 넣어 `stop_grace_period`를 다시 잡는다. 숫자는 한 곳(env-keys)에만 두고 compose·주석은 그것을 가리킨다 |
|
||||
| 완료 기준 | 예산표의 합 ≤ `stop_grace_period`, 코드 상수와 주석이 같은 값 |
|
||||
| 검증 방법 | 종료 순서를 기록하는 systemTest(웹 요청 1개 + async 작업 1개를 걸고 close 시간 측정) |
|
||||
|
||||
### 07-08 기본 조립 루트가 아직 선택 capability를 안다 (capability 기준 7 위반)
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 2, 27, 26, 23, 19 |
|
||||
| 근거 | AGENTS.md capability 기준 7: "이 모듈을 아는 곳은 모듈 자신뿐". 현재 bootstrap·이미지·compose에 남은 것: (1) `config/security.yml:39-59` — notification·durable operation·fileserver 권한 매핑. (2) `src/Dockerfile:158-167` — fileserver 저장 경로 `VOLUME` (기본 이미지는 fileserver가 없다). (3) `docker-compose.yml:70-82,110-113` — `fileserver-data` 볼륨을 무조건 마운트. (4) `application-dev.yml:20-22`, `application-prod.yml:22-28` — persistence-jpa 키(`app.persistence.vendor`, `spring.flyway.enabled`)와 이미 삭제된 `JpaSchemaSafetyValidator` 설명(`application-prod.yml:11`). (5) `bootstrap/autoconfigure/operation/DurableOperationConfig.java:37-74` — 유스케이스 조립이 bootstrap에 남음. 소유자 결정 3은 같은 성격(outbox relay·멱등성 executor)을 `composition:*`으로 옮겼다. 그래서 sample은 이 조립을 재사용할 수 없다. (6) build-logic `ConfigContractPlugin.java` `dependsOn(':adapter:outbound:redis-runtime:compileJava')` — env 계약 태스크가 특정 leaf를 안다 |
|
||||
| 발생 조건 | capability를 지우거나 새 capability를 더할 때 |
|
||||
| 영향 | 한 줄 삭제로 기능이 "완전히" 사라지지 않는다. 지운 기능의 권한 문자열·볼륨·설정이 남아, 읽는 사람이 그 기능이 켜져 있다고 오해한다. 새 capability 작성자는 bootstrap 파일을 고쳐야 하는지 판단해야 한다 |
|
||||
| 심각도·우선순위 | Medium / P2 |
|
||||
| 통제 수준 | M1. `DefaultCompositionBootTest`는 bean만 보고 설정·이미지 자산은 보지 않는다 |
|
||||
| 결정의 근거 | 41절 D1 참조 |
|
||||
| 최소 개선 방향 | 고른 방법: 권한 매핑은 각 capability의 `config/module-defaults/<모듈>.yml`로, durable operation 조립은 `composition:durable-operation`(또는 기존 outbox-relay 모듈)로 옮긴다. fileserver 볼륨은 fileserver README의 "필요한 마운트"로 옮기고 기본 compose에서는 뺀다. 버린 대안: bootstrap에 두고 "선택 시 사용" 주석만 단다 — 기준 7을 문서로 대체하는 것이라 기각 |
|
||||
| 완료 기준 | bootstrap main·기본 compose·기본 Dockerfile에서 capability 이름(`fileserver`, `notification`, `operation`, `persistence`) grep 0건 |
|
||||
| 검증 방법 | 위 grep을 `DefaultCompositionBootTest` 옆 계약 테스트로 고정 |
|
||||
|
||||
### 07-09 새 기능을 만들 때 따라 할 예시가 세 갈래다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험(갈라진 복사본) |
|
||||
| 관련 관점 | 3, 4, 23, 20, 25 |
|
||||
| 근거 | (1) `sample-portfolio` — 한 Gradle 모듈 안에 `domain/`·`application/<기능>/`·`adapter/`를 두고 기능별 패키지(P30 결정). (2) `app-bootstrap/src/test/java/dev/caskeleton/onboarding/**` — `DomainFeatureOnboardingContractTest`가 쓰는 예시는 종류별 패키지(`application/usecase`, `application/port`, `application/query`, `application/command`). (3) AGENTS.md "기능 개발 프로토콜" — production 기능은 `domain-core` → `application-core` → `adapter:*` leaf로 여러 Gradle 모듈에 나눠 둔다. 셋이 서로 다른 배치를 가르친다. 또 sample의 posterimage 기능은 application 클래스만 45개라, 가장 단순한 WorkLog 흐름보다 먼저 눈에 띈다 |
|
||||
| 발생 조건 | 처음 기능을 추가하는 개발자·에이전트 |
|
||||
| 영향 | 어느 예시를 베끼느냐에 따라 패키지 규칙이 달라진다. ArchUnit은 `..application..` 같은 넓은 패턴이라 셋 다 통과시키므로, 일관성이 리뷰에만 의존한다 |
|
||||
| 심각도·우선순위 | Medium / P2 |
|
||||
| 통제 수준 | M1 |
|
||||
| 결정의 근거 | 41절 질문은 7절(매뉴얼 재료)과 함께 적었다 |
|
||||
| 최소 개선 방향 | 고른 방법: 패키지 규칙 하나를 정하고(P30이 고른 기능별 배치), onboarding fixture를 같은 배치로 바꾼다. AGENTS.md 프로토콜에 "sample은 한 모듈에 모든 계층을 두지만 실제 기능은 leaf별로 나눈다"는 차이를 한 줄로 적는다. sample README 첫 절을 WorkLog 한 흐름(생성 1건)으로 시작한다. 버린 대안: sample을 leaf 여러 개로 쪼갠다 — 템플릿 삭제 용이성(샘플 한 모듈 삭제)을 잃는다 |
|
||||
| 완료 기준 | 예시 패키지 배치가 하나. ArchUnit에 "application 하위는 기능 패키지" 규칙(선택) |
|
||||
| 검증 방법 | onboarding fixture와 sample에 같은 규칙 적용 |
|
||||
|
||||
### 07-10 설정 오타·죽은 키가 기동에서도 게이트에서도 안 잡히는 곳이 있다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 19, 21, 23 |
|
||||
| 근거 | (1) bootstrap 자기 설정은 `@ConfigurationProperties`(관대한 바인딩, 모르는 키 무시): `AsyncExecutorSettings.java:16-17`, `BootstrapSettings`, `RuntimeSafetySettings`, `SecretSourceSettings`, `AuthenticationModeSettings`. 모듈들은 `StrictSettingsBinder`(모르는 키면 실패)를 쓴다. 그래서 `app.async.executor.core-sise` 같은 오타는 조용히 기본값이 된다. (2) `verifyEnvKeys`는 yml·java만 본다(`ConfigContractPlugin.java` file trees). compose 파일·`logback-spring.xml`은 대상이 아니다. 실제로 `docker-compose.prod-smoke.yml:29` `APP_LOG_JSON_ENABLED`는 어디서도 읽지 않는 키다. (3) sample `application.yml`의 죽은 블록(S6-#9, 07-03) |
|
||||
| 영향 | 운영자가 값을 바꿨다고 믿지만 반영되지 않는다 |
|
||||
| 심각도·우선순위 | Low / P3. 기본값이 안전한 쪽이라 피해가 작다 |
|
||||
| 통제 수준 | 모듈 M3, bootstrap M1 |
|
||||
| 결정의 근거 | 적용 제외에 가깝다 — 기준 4가 이미 strict 바인딩으로 정했다 |
|
||||
| 최소 개선 방향 | bootstrap 설정 record도 `StrictSettingsBinder`로 묶는다(prefix `app.async`, `app.runtime`, `app.bootstrap`, `app.secret-source`). `verifyEnvKeys` 입력에 루트 compose 파일과 `logback-spring.xml`의 `source="APP_*"`를 넣는다 |
|
||||
| 완료 기준 | 오타 키로 기동 실패. compose의 미등록 `APP_*` 키로 `verifyEnvKeys` 실패 |
|
||||
| 검증 방법 | 각각 실패 테스트 1건 |
|
||||
|
||||
### 07-11 주석·문서가 현재 동작과 다르다 (이번에 새로 찾은 것)
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 개선 제안(문서 결함) |
|
||||
| 관련 관점 | 9, 5, 20 |
|
||||
| 근거 | `application-prod.yml:11` 삭제된 `JpaSchemaSafetyValidator`를 prod 규칙으로 나열. `src/Dockerfile:201-202` "readiness 그룹이 datasource를 포함한다" — 기본 조합의 readiness는 `readinessState`뿐(`config/observability.yml:79-80`), JPA를 켤 때만 `db`가 붙는다. `AsyncExecutorConfig.java:27` "budget (20s)"(07-07). `sample-portfolio/README.md:22-58` 엔드포인트 표·curl이 `/work-logs`, `/work-logs/import` — 실제는 `/worklogs`, `/worklogs:batchCreate`(`WorkLogController.java:89-165`). `SamplePortfolioApplication.java` Javadoc "The one exclusion is the web leaf's security root"는 맞지만 그 결과(메서드 보안 없음)를 말하지 않는다 |
|
||||
| 심각도·우선순위 | Low / P3 |
|
||||
| 결정의 근거 | 적용 제외 — 문서 수정 |
|
||||
| 최소 개선 방향 | 위 줄을 고친다. 샘플 curl은 sample webSystemTest의 실제 요청에서 생성하거나, 테스트가 README 경로를 읽어 대조한다 |
|
||||
| 완료 기준 | 위 위치가 코드와 같다 |
|
||||
| 검증 방법 | 리뷰 + README 경로 대조 테스트(선택) |
|
||||
|
||||
### 07-12 virtual thread를 켠 상태에서 `server.tomcat.threads.max`는 동시 처리 상한이 아니다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 미검증(구조적 위험 후보) |
|
||||
| 관련 관점 | 14, 13, 19 |
|
||||
| 근거 | `application.yml:54-57` virtual thread 기본 켜짐. `config/server.yml:15-17` `threads.max: 200`, `RuntimeNumericBoundsValidator.java:22`가 이 값을 검증한다. Boot는 virtual thread를 켜면 Tomcat 요청 처리에 virtual thread executor를 쓰고, 이때 `threads.max`는 동시 처리 상한으로 작동하지 않는다(Boot 동작, 이번에 실측 안 함). 실제 상한은 `max-connections: 8192` |
|
||||
| 영향 | 운영자가 `threads.max`로 부하를 제한한다고 믿으면, JPA를 켠 서비스에서 수천 요청이 커넥션 풀(기본 10)에서 대기한다 |
|
||||
| 심각도·우선순위 | Low / P3(미검증) |
|
||||
| 최소 개선 방향 | 설정 주석에 "virtual thread가 켜져 있으면 상한은 max-connections와 하위 자원(풀·rate limit)"이라고 적고, 필요하면 동시 요청 제한(semaphore filter)을 선택 항목으로 둔다 |
|
||||
| 검증 방법 | 기본 조합에서 지연 엔드포인트에 300 동시 요청 → 동시 처리 수 측정 |
|
||||
|
||||
### 07-13 기본 compose가 관리 포트 9001을 모든 인터페이스에 연다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 개선 제안(보안 기본값) |
|
||||
| 관련 관점 | 15, 18 |
|
||||
| 근거 | `docker-compose.yml:52` `"9001:9001"`. 관리 체인은 `health`·`info`·`prometheus`를 인증 없이 허용한다(`ManagementSecurityConfig.java` `permitAll`). `info.env.enabled: true`(`observability.yml:96-97`)라 `info.capabilities.*`와 build revision이 보인다. local override는 DB 포트를 loopback으로만 연다(`docker-compose.local.yml:14-16` 설명)와 대조된다 |
|
||||
| 영향 | compose로 띄운 개발 장비가 LAN에 메트릭·구성 정보를 노출한다. 운영(k8s)과는 무관하다 |
|
||||
| 심각도·우선순위 | Low / P3 |
|
||||
| 최소 개선 방향 | `"127.0.0.1:9001:9001"`. 앱 포트도 같은 원칙을 쓸지 결정 |
|
||||
| 검증 방법 | `docker compose config` 결과 대조(기존 compose 계약 테스트에 추가) |
|
||||
|
||||
### 07-14 프로필 검증기가 main class 이름을 문자열로 비교한다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 개선 제안 |
|
||||
| 관련 관점 | 21, 20 |
|
||||
| 근거 | `RuntimeEnvironmentProfileValidator.java:83-87` `"dev.caskeleton.bootstrap.CaSkeletonApplication".equals(...)`. AGENTS.md 템플릿 재사용 체크리스트 2·3단계가 바로 이 패키지와 클래스 이름을 바꾸라고 한다. 바꾸고 문자열을 놓치면 profile 없는 jar가 기동한다. 다만 `RuntimeEnvironmentProfileValidatorTest`가 class literal로 주입해 검사하므로, 이름만 바꾸면 그 테스트가 실패해 알려 준다(M3) |
|
||||
| 심각도·우선순위 | Low / P3 |
|
||||
| 최소 개선 방향 | `CaSkeletonApplication.class.getName()`을 쓴다. 같은 leaf라 의존 문제가 없다 |
|
||||
| 검증 방법 | 기존 단위 테스트 |
|
||||
|
||||
## 4. 31절 시나리오 추적
|
||||
|
||||
### 4.1 선택 어댑터 제거 — 기본 조합 기동 (적용)
|
||||
|
||||
- 입력 신뢰: 운영자 env. 필수는 `SPRING_PROFILES_ACTIVE`, `APP_NAME`, `APP_SECURITY_JWT_ISSUER`, `APP_SECURITY_JWT_AUDIENCE`(빈 값 허용 — 07-05), prod는 `APP_PRIVACY_PSEUDONYMIZATION_SALT`.
|
||||
- 흐름: `RuntimeEnvironmentProfileValidator`(EPP, profile 정확히 1개) → 모듈 기본값 EPP(support) → 컨텍스트 생성 → `SmartInitializingSingleton` 검사들(`SecretSourceValidator`, `StartupSafetyValidator`, `AuthenticationModeCompositionValidator`, `StartupRuleRunner`) → readiness UP.
|
||||
- 결과(E2): `DefaultCompositionBootTest`가 local·dev·prod에서 capability bean 0개, DataSource·Mongo·Kafka·Redis 연결 bean 0개로 기동함을 단언하고 이번 게이트에서 통과. prod에서 salt 없으면 실패하는 것도 단언. 이번 실험(E3)에서 `lazy-initialization=true`여도 secret·에러상세 검사가 돈다.
|
||||
- 잘못된 조합: `APP_IDEMPOTENCY_PROVIDER=redis`인데 모듈이 없으면 `IdempotencyAutoConfiguration.java:49-62`이 store 수를 세어 기동 실패. `APP_MULTI_INSTANCE_ENABLED=true`인데 lock provider가 없으면 `StartupSafetyValidator`가 종료 코드 72. 이해 가능한 오류로 거부된다.
|
||||
- 남는 것: 기본 조합이 선택 capability의 설정·볼륨·권한 문자열을 갖고 있다(07-08).
|
||||
|
||||
### 4.2 정상 쓰기 요청 — sample `POST /api/worklogs` (적용)
|
||||
|
||||
- 입력 신뢰: 외부 JSON. `@Valid` DTO, unknown field 거부(`spring.jackson…fail-on-unknown-properties: true`).
|
||||
- 인가 위치: 유스케이스 `@RequiresPermission("worklog:write")` — 실행본에서는 advisor가 없어 검사가 없다(07-03).
|
||||
- 규칙 소유: `WorkLog.create`(도메인), owner 필수는 `WorkLogOwner.of`.
|
||||
- 트랜잭션: `CreateWorkLogUseCase.handle` 안의 `tx.inWrite` 하나. 저장과 outbox append가 같은 트랜잭션(이중 쓰기 금지 예시로 적절).
|
||||
- 외부 부작용: 없음(outbox 행만). relay는 sample에서 꺼짐(`application.yml:234-237`).
|
||||
- 성공의 의미: 201 + ETag. 실행본에서는 주체가 없어 owner `null` → NPE → 500(07-03).
|
||||
- 오류 변환: 도메인 예외 → `DomainExceptionHandler`, 그 밖은 `GlobalExceptionHandler`.
|
||||
- 진단: `request_id`·`trace_id` MDC(web filter), JSON 로그(local·dev는 패턴 로그). span 없음(07-01).
|
||||
|
||||
### 4.3 다른 사용자 리소스 접근 — sample `DELETE /api/worklogs/{id}` (적용)
|
||||
|
||||
- 인증 없음 → 메서드 보안 없음 → `DeleteWorkLogUseCase`가 존재만 확인하고 삭제(07-03). 소유자 비교도 없다. 템플릿이 "객체 ID를 바꿔도 거부된다"를 보여 주는 예시는 fileserver(`FileAccessPolicyPort`, 다른 영역)에만 있고 sample에는 없다. 매뉴얼 재료로 7절에 적었다.
|
||||
|
||||
### 4.4 종료·재시작 (적용)
|
||||
|
||||
- 신호: Dockerfile `ENTRYPOINT ["java", …]` exec 형식이라 java가 PID 1로 SIGTERM을 받는다.
|
||||
- 신규 요청 차단: `server.shutdown: graceful`, `timeout-per-shutdown-phase: 30s`. 게이트 로그(mainCheck.log)에 "Graceful shutdown complete"가 찍힌다.
|
||||
- 진행 작업: async executor가 최대 19s 더 기다린다 → 예산표와 어긋남(07-07).
|
||||
- readiness: 종료 중 readiness 전환은 Boot 기본 동작에 맡긴다(별도 확인 안 함).
|
||||
- 메시지 확인: 기본 조합에 메시지 없음 — 적용 제외(10 영역).
|
||||
|
||||
### 4.5 적용 제외
|
||||
|
||||
| 시나리오 | 사유 |
|
||||
| --- | --- |
|
||||
| 중복·동시 요청 | 멱등성 실행 경로는 web·persistence·Redis 영역. 이 영역은 조립만: provider≠disabled면 store가 정확히 1개여야 기동(`IdempotencyAutoConfiguration.java:49-62`) — 충족 |
|
||||
| 외부 응답 지연·유실 | 기본 조합에 외부 호출 없음(08 영역) |
|
||||
| DB 오류·경쟁 | 기본 조합에 DB 없음(05 영역). 단 prod 검사 순서는 07-02 |
|
||||
| 메시지 중복·역순 | 10 영역 |
|
||||
| 신·구 버전 공존 | API·스키마는 02·05 영역 |
|
||||
| 여러 서버의 작업 실행 | 다중 인스턴스 검사는 lock provider 존재만 본다(`StartupSafetyValidator`). 스케줄러 소유권은 05·10 영역 |
|
||||
| 세션·토큰 갱신 경쟁 | 02 영역(redis-session 모드) |
|
||||
| 큰 입력·목록 조회 | 02 영역. sample batch 상한 1000은 `@Size`로 강제(`WorkLogController.java:177-183`) |
|
||||
|
||||
## 5. 41절 설계 선택 검토
|
||||
|
||||
### D1. capability = `runtimeOnly` 한 줄 + 모듈 자체 `AutoConfiguration.imports`, 기본 조합은 web-only
|
||||
|
||||
1. 필요: 파생 서비스가 쓰지 않는 기능(JPA·Redis·Kafka…)의 연결·설정·의존성을 지지 않고 시작해야 한다.
|
||||
2. 지킬 성질: 줄을 지우면 bean·설정·의존성이 함께 사라진다. 기본 조합은 외부 연결 없이 기동한다. 선택한 기능이 덜 설정되면 기동 실패.
|
||||
3. 현재 보장: `app-bootstrap/build.gradle:157-171` 주석 처리된 선택 줄, `DefaultCompositionBootTest`(E2, 이번 게이트 통과), `qualificationBootJar`로 전부 켠 조합을 compose lane에서 검증. 보장하지 않는 것: 설정 파일·이미지·compose의 capability 흔적(07-08), 권한 문자열.
|
||||
4. 대안: (a) 모든 모듈을 `implementation`으로 싣고 `enabled` 스위치로 끄기(이전 방식). (b) Gradle feature variant/플랫폼별 bootJar 여러 개. (c) 현재 방식.
|
||||
5. 득실: (a)는 끄는 것을 잊으면 연결을 시도하고, 의존성 표면이 크다 — 이전 리뷰가 이 이유로 기각. (b)는 조합 수만큼 산출물이 생겨 검증 비용이 커진다. (c)는 한 줄로 고르지만, "모듈만 자기를 안다"를 지키려면 권한·볼륨·profile 파일까지 모듈로 옮겨야 한다.
|
||||
6. 왜 이 선택: 소유자 결정(B안·web-only)과 일치하고 검증이 이미 붙어 있다. 확인한 조건에서 타당하다.
|
||||
7. 다시 볼 조건: 파생 서비스 대부분이 같은 3~4개 capability를 항상 켠다면, "표준 조합" 플랫폼 하나를 두는 편이 싸다.
|
||||
|
||||
### D2. 기동 검증 = `StartupRule` bean + support의 runner 하나 (`afterSingletonsInstantiated`)
|
||||
|
||||
1. 필요: 잘못된 설정을 첫 요청이 아니라 기동에서 막고, 종료 코드·로그 필드를 일정하게 한다.
|
||||
2. 지킬 성질: 위험한 값이 외부 시스템(DB·브로커)에 닿기 전에 거부한다. 위반은 phase별 종료 코드로 보고한다.
|
||||
3. 현재 보장: 규칙 어휘와 보고는 하나로 모였다(`StartupRule`, `StartupValidationContext`). 실행 시점은 모든 싱글턴 생성 뒤라, "닿기 전" 성질은 보장하지 않는다(07-02). bootstrap의 다른 검사(`SecretSourceValidator` 등)도 같은 시점이다.
|
||||
4. 대안: (a) 현재. (b) 환경만 보는 rule을 EPP/BFPP에서 먼저 실행, bean 상태를 보는 rule만 현재 시점. (c) 각 모듈이 자기 연결 bean 생성 직전에 자기 rule을 부른다.
|
||||
5. 득실: (a) 단순하지만 순서 위험. (b) 진입점이 둘이 되지만 rule 인터페이스는 하나, 현재 rule 전부가 `violations(Environment)`라 이동 비용이 작다. (c) 모듈마다 호출 위치를 기억해야 한다 — 숨은 규칙이 늘어난다.
|
||||
6. 판단: (b)가 현재 요구에 맞다. (a)를 유지하려면 "PROFILE_CHECK"라는 이름이 약속하는 시점을 문서로 낮춰야 하는데, 그건 위험을 숨기는 쪽이다.
|
||||
7. 다시 볼 조건: bean 상태가 필요한 rule이 다수가 되면 두 단계 구분을 phase 속성으로 표현한다.
|
||||
|
||||
### D3. 공용 런타임 배선을 `composition:service-runtime`으로 분리하고, sample은 bean 이름으로 actuator chain을 바꾼다
|
||||
|
||||
1. 필요: bootstrap과 sample이 같은 tracing·metrics·가명화·actuator 보안을 쓰되 복사하지 않는다(S6-#7).
|
||||
2. 지킬 성질: 두 조립 루트가 같은 구현을 쓴다. sample의 공개 정책이 production 기본을 바꾸지 않는다.
|
||||
3. 현재 보장: 두 루트가 `runtimeOnly project(':composition:service-runtime')`. sample은 `actuatorSecurityFilterChain` 이름의 bean으로 공용 chain을 밀어낸다(`ManagementSecurityConfig`의 `@ConditionalOnMissingBean(name=…)`). 보장하지 않는 것: 공용 모듈 안의 tracing이 실제로 동작하는지(07-01) — 분리는 결함도 함께 공유한다.
|
||||
4. 대안: (a) 현재. (b) 공용 배선을 support에 넣기. (c) 각 루트가 복사.
|
||||
5. 득실: (b)는 support가 Spring Boot actuator·security·OTel에 의존하게 돼 모든 capability가 그 무게를 진다. (c)는 이미 갈라진 전례가 있다(S6-#7).
|
||||
6. 판단: (a)가 타당하다. bean 이름으로 대체하는 방식은 문자열 계약이라, 이름이 바뀌면 sample이 조용히 공용 chain과 자기 chain을 둘 다 갖게 된다 — 이름을 상수로 공개하는 정도의 보강이 맞다.
|
||||
7. 다시 볼 조건: 세 번째 조립 루트(예: 배치 전용 앱)가 생기면 web 의존 부분(actuator chain)과 비-web 부분을 나눈다.
|
||||
|
||||
## 6. 리팩토링 후보
|
||||
|
||||
| 대상 | 무엇을 왜 | 보존 조건 |
|
||||
| --- | --- | --- |
|
||||
| `TracingConfig` 자체 Tracer | Boot tracing 모듈로 교체(07-01). 출력 없는 seam 제거 | enabled=false → Tracer 없음, `SpanErrorRecorder` NOOP 대체, prod 0.01 기본 샘플률, `trace_id` 일치 |
|
||||
| `TracingSettings.sampleRate` String | `Double`(nullable)로 바꿔 파싱 1회(S6-#17) | 빈 값 = profile 기본값, [0,1] 밖이면 ENV_VALIDATION 실패 |
|
||||
| `LoggingSettings` + logback env 직접 참조 | 한 출처로(07-06) | `APP_LOG_*` 키 이름·기본값, 마스킹, JSON 필드 |
|
||||
| `StartupRuleRunner` 단일 시점 | 환경 rule은 EPP/BFPP 단계로(07-02) | 종료 코드 71/72/78, `startup.phase`·`error.code` 필드, rule 단위 일괄 보고 |
|
||||
| `DurableOperationConfig` | `composition:*` 모듈로(07-08) | `@ConditionalOnBean` 3종 조건, 유스케이스가 bean이라 메서드 보안 프록시 적용 |
|
||||
| bootstrap `security.yml` 권한 매핑 | 각 capability `module-defaults`로(07-08) | 키(역할명)·값(권한) 그대로, bracket 키 표기 |
|
||||
| `Dockerfile` / `Dockerfile.sample` builder 단계 | 한 파일 + `ARG`(07-04) | 잠금 검증 단계, 레이어 순서, 비루트·읽기전용 루트 |
|
||||
| bootstrap 설정 record 바인딩 | `StrictSettingsBinder`로(07-10) | 현재 기본값과 오류 메시지의 env 키 이름 |
|
||||
|
||||
## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료)
|
||||
|
||||
### 템플릿이 주는 틀
|
||||
|
||||
- 조립: capability는 `app-bootstrap/build.gradle`에서 한 줄. 새 capability는 자기 `AutoConfiguration.imports` + `config/module-defaults/<모듈>.yml` + README의 env 키.
|
||||
- 기동 검사: `StartupRule` bean 하나를 모듈에 둔다. 비밀값은 `RequiredProductionSecrets` bean.
|
||||
- 공용 런타임: tracing·metrics·가명화·actuator 보안은 `composition:service-runtime`이 준다. 파생 서비스는 손대지 않는다.
|
||||
- 예시: sample WorkLog(생성·조회·수정·삭제·batch, ETag, outbox). onboarding fixture(테스트 안).
|
||||
- 검증: `DefaultCompositionBootTest`(기본 조합), `qualificationBootJar`+compose lane(전부 켠 조합), `verifyEnvKeys`.
|
||||
|
||||
### 빠진 것
|
||||
|
||||
- 실행본에서 인가가 실제로 도는 예시(07-03)와 객체 소유자 검사 예시.
|
||||
- 트레이스가 실제로 나가는 경로(07-01).
|
||||
- 예시 배치 규칙 하나(07-09).
|
||||
- "새 설정 키를 추가할 때 고칠 곳" 목록: settings record, `module-defaults` yml, `docs/registries/env-keys.yaml`, `.env.example`(생성물), 모듈 README. 지금은 `verifyEnvKeys` 실패 메시지로 배운다.
|
||||
|
||||
### 개발자가 여기서 내려야 하는 판단
|
||||
|
||||
1. 이 기능은 production leaf에 둘 것인가, sample에 둘 것인가? (예시는 sample, 실제 기능은 `domain-core`/`application-core`/`adapter:*`.)
|
||||
2. 외부 연결이 필요한가? 필요하면 어떤 capability 줄을 켜는가, 그 capability README의 env 키를 채웠는가?
|
||||
3. 이 설정 값이 틀리면 언제 알아야 하는가? 기동 시점이면 settings record compact constructor 또는 `StartupRule`. prod에서만 금지면 `RuntimeProfileSnapshot.isProduction()` 분기.
|
||||
4. 그 검사가 외부 시스템에 닿기 전에 도는가? (07-02 — 지금은 개발자가 직접 확인해야 한다.)
|
||||
5. 이 유스케이스의 권한은 무엇이고, 객체 소유자 검사가 필요한가? 권한 문자열은 어느 설정 파일(모듈 기본값)에 매핑하는가?
|
||||
6. 응답·로그에 비밀·개인정보가 섞이는가? `user_principal`은 가명화되고, owner 원문은 응답에 넣지 않는다(sample 예시).
|
||||
7. 종료 중에 진행 작업이 끝나야 하는가? async executor 대기와 컨테이너 grace를 같이 본다(07-07).
|
||||
8. 기능을 지우면 무엇이 남는가? 권한 매핑·볼륨·compose 항목까지 모듈 안에 있는가(07-08)?
|
||||
|
||||
## 8. 28개 관점 판정표
|
||||
|
||||
기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역
|
||||
|
||||
| 번호 | 관점 | 판정 | 한 줄 이유 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 코드 성숙도 | P | 조립 코드는 작고 명확(main 31파일 1,505줄). 출력 없는 tracing 조립과 소비자 없는 `LoggingSettings`가 남음 |
|
||||
| 2 | 구조적 성숙도 | P | composition 모듈 분리·좁은 scan은 좋음. bootstrap이 capability 권한·볼륨·durable operation 조립을 가짐(07-08) |
|
||||
| 3 | 변경 용이성 | P | capability 추가·삭제는 한 줄. 새 기능 예시가 세 갈래(07-09) |
|
||||
| 4 | 인지 부하 | P | bootstrap `:test` 저장소 계약 테스트 45파일, sample posterimage 45클래스, 이력 주석 35줄 |
|
||||
| 5 | 위험 가시성 | X | 동작 안 하는 OTLP 설정(07-01), 실행본에서 꺼진 인가(07-03), 검사 순서(07-02)가 코드에서 안 보임 |
|
||||
| 6 | 실패 성숙도 | P | profile·secret·에러상세·멱등성 store 수·multi-instance 모두 fail-fast(E2·E3). prod audience 미검사(07-05), 검사 시점(07-02) |
|
||||
| 7 | 운영 성숙도 | P | health/liveness/readiness 분리, graceful shutdown, 관리 포트 분리. 종료 예산 불일치(07-07), 트레이스 없음 |
|
||||
| 8 | 디버깅 가능성 | P | `request_id`·`trace_id`·`user_principal` MDC, JSON 로그, 구조화 startup 실패 로그. 분산 span 없음 |
|
||||
| 9 | 유지보수 성숙도 | P | 주석·README drift 다수(07-11, L-2b, L-4b, S6-#10e) |
|
||||
| 10 | 테스트 성숙도 | P | 기본 조합 기동 테스트가 실제 위험을 잡음(E2). 트레이스 출력·sample 실행본 인가·Dockerfile.sample은 테스트 없음 |
|
||||
| 11 | 데이터 성숙도 | > | 05 영역. 단 prod 검사 순서가 마이그레이션 뒤인 문제는 07-02 |
|
||||
| 12 | 동시성 성숙도 | P | async executor는 큐 상한·거부 정책·MDC 전파가 있음. virtual thread 상한 의미 미검증(07-12) |
|
||||
| 13 | 확장성 | ? | 부하·다중 인스턴스 실측 없음 |
|
||||
| 14 | 성능 성숙도 | P | 기본 조합 기동 약 1.3s/회(`DefaultCompositionBootTest` 4회 5.4s, 부하 ~20), bootstrap `test` 321건 합 10.2s, systemTest 8건 14.2s. 메모리 512m·heap 75%. 부하 측정 없음 |
|
||||
| 15 | 보안 성숙도 | P | prod 에러상세 차단·secret 강제·관리 체인 분리·loggers 비노출. prod 빈 audience(07-05), sample 익명 삭제(07-03), 9001 전체 공개(07-13) |
|
||||
| 16 | 의존성 성숙도 | P | lockfile strict. `opentelemetry-exporter-otlp`가 실려 있으나 쓰이지 않음(07-01) |
|
||||
| 17 | API / Contract 성숙도 | > | 02 영역. sample README 엔드포인트 drift만 07-11 |
|
||||
| 18 | 배포 성숙도 | P | 비루트·읽기전용 루트·레이어 추출·HEALTHCHECK·digest 고정. `Dockerfile.sample` 빌드 불가(07-04) |
|
||||
| 19 | 설정 성숙도 | P | `app.*` 통일, 모듈 strict 바인딩, `verifyEnvKeys` OK(346 키). bootstrap 관대한 바인딩, 로그 설정 이중 출처, compose 미검사(07-06, 07-10) |
|
||||
| 20 | 개발자 경험 | P | 한 줄 선택·`bootRunH2`·`.env.example` 생성. sample 이미지·curl 예시가 동작 안 함 |
|
||||
| 21 | Guardrail 성숙도 | P | ArchUnit에 sample 포함, StartupRule, 방향 게이트. `@RequiresPermission`인데 advisor 없음을 막는 장치 없음 |
|
||||
| 22 | 추상화 성숙도 | O | `StartupRule`·`RequiredProductionSecrets`·`SecretSourceStrategy` 같은 확장점은 소비자가 있거나 의도된 확장점 |
|
||||
| 23 | 일관성 | P | durable operation만 bootstrap 조립, bootstrap만 관대한 바인딩, 예시 배치 세 갈래 |
|
||||
| 24 | 네이밍 / 의미 | P | `*Config`(일반 설정)와 `*AutoConfiguration`(imports 등록)이 섞여 이름으로 등록 방식을 알 수 없음(`DurableOperationConfig`는 imports 등록) |
|
||||
| 25 | 조직 확장성 | ? | 작성자 외 사용자의 기능 추가 증거 없음 |
|
||||
| 26 | Ownership 성숙도 | P | 모듈 README가 env 키를 소유. 권한 매핑·볼륨은 bootstrap이 소유(07-08) |
|
||||
| 27 | 삭제 가능성 | P | capability·sample 삭제 경로는 검증됨. 지운 capability의 설정 흔적이 bootstrap에 남음 |
|
||||
| 28 | 회복 가능성 | - | 기본 조합에 상태 저장소 없음. 마이그레이션 복구는 05 영역 |
|
||||
@@ -0,0 +1,389 @@
|
||||
# 08 빌드 · CI · 테스트 실행 체계 리뷰
|
||||
|
||||
- 영역: `src/build-logic`, `src/settings.gradle`, `src/build.gradle`, `src/gradle`(카탈로그·wrapper), `src/gradle.properties`,
|
||||
`src/config/architecture`, `.github/workflows/*`·`.github/actions/*`, `src/optional-platforms`의 빌드 부분,
|
||||
strict test lane과 보조 test suite, ArchUnit lane, Spotless·Checkstyle·Error Prone·SpotBugs 설정.
|
||||
- 기준 커밋: `main` `01a8a2a70`.
|
||||
- 리뷰 날짜: 2026-11-01.
|
||||
|
||||
## 1. 범위
|
||||
|
||||
| 항목 | 기록 |
|
||||
| --- | --- |
|
||||
| 대상 | `clean-architecture-backend-template`, Gradle 루트 `src/` |
|
||||
| 커밋·작업 상태 | `01a8a2a70`, 작업 트리 깨끗함. 실험은 scratchpad worktree(`wt-08`)에서만 했다 |
|
||||
| 목적과 지원 실행 구성 | 템플릿. PR 게이트 = `ci-quality-gates.yml`(`:ci :verifyDependencyLocks`, sample, optional-platforms, buf), main 단계 = `integration-main.yml`(`:mainCheck` 외 컨테이너 lane), 태그 = `release.yml` |
|
||||
| 규모·운영 목표 | 합의된 CI 시간 목표 없음. "PR 게이트는 분 단위"라는 주석만 있다(`integration-main.yml` 주석). 아래 시간은 측정값이지 목표 대비 판정이 아니다 |
|
||||
| 읽은 코드·구성 | build-logic main 전부(2,854줄), root `build.gradle`·`settings.gradle`·`gradle.properties`, `libs.versions.toml`, 15개 workflow, setup action, leaf `build.gradle` 중 app-bootstrap·web·persistence-jpa·persistence-mongo·sample-portfolio·httpclient·objectstorage·messaging-kafka, `modules.json`, Checkstyle·SpotBugs 설정, 테스트 소스 1,635개 파일(정규식 표본 조사) |
|
||||
| 실행한 것 | (1) 오케스트레이터 게이트 로그 읽기: `ci` rc=0 434초, `mainCheck` rc=1 162초. (2) worktree에서 `./gradlew ci mainCheck --dry-run`, `./gradlew integrationCheck --dry-run`(둘 다 rc=0, 시작 부하 8.22). (3) build cache 실험(아래 08-02). (4) `StrictTestLanePlugin` 변이 3개 + `StrictTestLaneConventionTest` 실행(부하 7.16, 18초, 18개 중 5개 실패 = 변이 3개 모두 잡힘). (5) ci 실행이 남긴 `build/test-results/**/*.xml` 984개 집계 |
|
||||
| 확인 못 한 것 | GitHub(이 저장소의 원격은 `git.learn.hyeonworks.com`)에서 workflow가 실제로 도는지. Docker Hub에서 MinIO 이미지가 사라진 시점·대체 이미지. SpotBugs 신뢰도 `HIGH` 제한이 실제로 놓치는 결함 수. 컴파일·정적분석 태스크별 시간(로그에 태스크 시간이 없고 프로파일을 돌리지 않았다) |
|
||||
| 이전 리뷰와 비교 | 2026-09-18 techlead `13-build-dependency-ci.md`, 2026-09-25 followup-status 「1차 O Build/CI」 「2차 BUILD · TEST」. 그때의 실행 결과는 증거로 쓰지 않고 현재 코드로 다시 확인했다 |
|
||||
|
||||
### 게이트 결과 요약
|
||||
|
||||
- `ci` rc=0, 434초(잠금 대기 포함). 663 태스크 중 643 실행, 캐시 적중 1(로컬 build cache가 16MB로 거의 비어 있었다). 시작 부하 9.15, 실행 중 20~31까지 올라갔다.
|
||||
- `mainCheck` rc=1, 162초. 실패는 `:adapter:outbound:objectstorage:objectStorageMinioContractTest`·`objectStorageMinioFaultTest` 두 lane이다. 원인은 `ContainerFetchException` — `minio/minio@sha256:4c4a48…`를 Docker Hub에서 받을 수 없다(오케스트레이터 확인: `alpine:3`은 받아지고 `minio/minio:latest`도 거부됨). 코드 결함이 아니라 고정한 외부 이미지 공급원이 사라진 것이다. 이미지 자체는 05 영역이 다루고, 이 문서는 게이트 반응만 본다(08-04).
|
||||
- 경고: 두 로그 모두 `--warning-mode=fail`에서 경고 없음. ci에서 건너뛴 테스트 8개는 모두 의도된 skip(`OptionalAdapterConditionalExecutionContractTest` 4, `NfsAmbiguityIntegrationTest` 3, `ProviderSandboxSmokeTest` 1).
|
||||
|
||||
## 2. 지난 발견 재확인
|
||||
|
||||
| ID | 상태 | 근거 |
|
||||
| --- | --- | --- |
|
||||
| O-3d (ignored-source 검사 테스트 0개) | 해결 | `src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/VerifyNoIgnoredSourcePackagesFunctionalTest.java` 존재. ci 로그 `verifyNoIgnoredSourcePackages: OK — 4628 Java sources` |
|
||||
| O-5a (의존성 checksum 검증 없음) | 보류(결정 19) | `src/gradle/verification-metadata.xml` 없음. 결정대로 |
|
||||
| O-10a (httpclient sysprop 반복) | 남음 | `src/adapter/outbound/httpclient/build.gradle` 141~222행에 `httpclient.contract.transports`·`httpclient.http3.tests.enabled` 쌍이 6번 반복 |
|
||||
| O-10b (`user.timezone=UTC` 반복) | 남음 | `git grep -c user.timezone -- '*.gradle'` = 11개 파일 28번. `JavaConventionsPlugin`에 없음 |
|
||||
| O-11b (카탈로그 주석이 override 위치를 잘못 적음) | 남음 | `src/gradle/libs.versions.toml:27-31`은 `src/build.gradle`에 이유와 함께 있다고 적는다. 실제는 `src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java:135-136`이고 이유 문장이 없다 |
|
||||
| O-11c (`netty.version` override가 효과 없음) | 남음 | `JavaConventionsPlugin.java:136` = `4.2.17.Final`. Boot 4.0.8 BOM(`spring-boot-dependencies-4.0.8.pom`)의 `netty.version`도 `4.2.17.Final`. `commons-lang3`는 BOM 3.19.0 → 3.20.0이라 효과 있음 |
|
||||
| O-11d (optional-platforms README 개수) | 해결 | `src/optional-platforms/README.md`에 개수 표기 없음 |
|
||||
| BUILD-바로할것-1b (runtime-membership 잔재 문구) | 바뀜(1곳 추가) | `.github/workflows/ci-quality-gates.yml:56`, `src/sample-portfolio/build.gradle:202`에 남음. 추가로 `src/config/architecture/README.md:12`가 "runtime membership은 build logic이 runtime classpath에서 도출한다"고 적지만 그 플러그인은 삭제됐다 |
|
||||
| BUILD-순수성-이름 | 남음 | `ArchitecturePlugin.java:65` 태스크 이름 `verifyApplicationCoreDependencyPurity`, 클래스 `VerifyApplicationCoreDependencyPurityTask`. 실제 대상은 domain-core·shared-contract·application-* |
|
||||
| BUILD-계획-B4-34 참고(app-bootstrap `check` → systemTest) | 남음 → 08-02로 | `src/app-bootstrap/build.gradle:90-92`. PR `ci`와 `mainCheck` 둘 다 같은 systemTest를 돌린다 |
|
||||
| BUILD-계획-B3 (변경 모듈만 실행) | 보류(결정 30) | 결정대로 전체 실행 |
|
||||
| P13-new-1 (plugin classpath 잠금) | 보류(결정 27) | 결정대로 |
|
||||
| NEW-1b (새 CI 잡이 실제로 돈 증거 없음) | 미검증 | 원격이 GitHub가 아니다(`origin` = `git.learn.hyeonworks.com`). 그 forge의 Actions 실행 기록은 확인하지 못했다 |
|
||||
| NEW-13e (집계에 묶이지 않은 lane) | 바뀜 | sample `posterImageMigrationTest`는 이제 돈다. 하지만 새로 확인한 미실행 lane 14개가 있다 → 08-01 |
|
||||
| TEST-F-1 (fake와 adapter 공유 계약 부족) | 남음 | application-*·domain-core main의 `public interface *Port` 83개. fake와 adapter가 같은 추상 계약을 상속하는 것은 `DurableOperationStoreContract`, `GrpcOperationLedgerContract`, `WorkLogRepositoryContract`, `OutboxLeaseFencingContract`, `DistributedLeaseContract` 등 소수 |
|
||||
| TEST-DisplayName (한국어로, 결정 5) | 남음 | `AGENTS.md:157`은 아직 "영어로 통일". 테스트 소스의 `@DisplayName` 2,444개 중 영어 2,272, 한국어 172. 규칙 문서와 소유자 결정이 서로 다르다 |
|
||||
| TEST-이행-4 (계층별 모범 모듈) | 남음 | 문장 3개 이상 테스트 3,514개 중 `// when`·`// then` 주석을 가진 것 610개(17%). sample-portfolio만 141/141(100%). `adapter/outbound/redis-sdk` 221개 중 0개(정규식 추정) |
|
||||
|
||||
## 3. 새 발견
|
||||
|
||||
### 08-01 — CI가 실행하지 않는 strict lane 14개
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 10, 21, 5, 11, 18 |
|
||||
| 근거 | `ci`·`mainCheck` dry-run 그래프와 15개 workflow의 `./gradlew` 인자를 대조했다. 어느 쪽에도 없는 lane: ① `:adapter:outbound:persistence-jpa`의 readiness lane 11개(`src/adapter/outbound/persistence-jpa/build.gradle:166-183`) — `postgresqlLifecycle`, `SecurityBaseline`, `Migration`, `Transaction`, `Aggregate`, `Query`, `Idempotency`, `FileserverMigration`, `FileserverMetadata`, `FileserverReclamation`, `NotificationSchemaActivation`. 이들은 `integrationCheck`(`src/build.gradle:100`)에만 들어가는데, `integrationCheck`를 실행하는 workflow는 없다(`integration-main.yml:96`은 `--dry-run`으로 저장 가능 여부만 본다). 그중 9개 클래스·57개 테스트에는 다른 lane이 고르는 `@Tag`도 없다. ② `:adapter:inbound:web:performanceTest`, `webJettyPerformanceTest`(`src/adapter/inbound/web/build.gradle:145,152`) — PERFORMANCE 집계는 어디에도 연결되지 않았다. `integration-main.yml:133`의 `web-load-abuse-and-shutdown` 잡은 이름과 달리 `:adapter:inbound:web:test`와 `webJettyCompatTest`만 돌린다. ③ `:sample-portfolio:systemTest`(`src/sample-portfolio/build.gradle:172`) — sample은 `leafPaths`에서 빠져 `systemTestCheck`에 없고, sample `check`(`:199-207`)도 이 lane을 부르지 않는다 |
|
||||
| 발생 조건 | 위 lane이 지키는 코드(JPA 멱등성 저장소, fileserver metadata·reclamation SQL, Flyway 경로, sample 전체 기동, Tomcat·Jetty 부하·종료)를 바꾸는 모든 PR과 main push |
|
||||
| 영향 | 실제 PostgreSQL에서만 드러나는 결함이 PR·main·release 어디서도 잡히지 않는다. `config/jpa/readiness-cards.yaml`은 이 lane들을 근거로 카드 상태를 `selected`·`implemented-candidate`로 적고, `src/build-logic/README.md:47`은 "readiness lanes that require every cited scenario and reject skips"가 삭제된 JPA evidence를 대신한다고 적는다. 둘 다 실행되지 않는 lane에 기대는 주장이다. `JpaReadinessRegistryTest`는 카드가 "존재하는 태스크"를 가리키는지만 보고, 그 태스크가 실행되는지는 보지 않는다 |
|
||||
| 심각도·우선순위 | High · P1. capability 완료 기준 5("실제 벤더로 도는 테스트")의 증거가 이 lane들이다. 같은 종류의 결함(H10, gRPC ledger lane)이 지난 리뷰에서 High였고, 그때 고친 방식(workflow에 이름을 하나씩 적기)이 같은 결함을 다시 만들었다 |
|
||||
| 확실성 | 직접 확인: dry-run 그래프, workflow 문자열, 클래스 태그. 추론: 이 lane이 지금 통과하는지는 모른다(돌리지 않았다) |
|
||||
| 결정의 근거 | 현재 선택은 "integration lane은 workflow가 이름으로 부른다"이다(`integration-main.yml:292` 주석: 카드 소속에 기대지 않고 이름으로 부른다). 이름 목록과 lane 목록이 따로 관리되니, 새 lane을 만들 때 workflow 한 줄을 빠뜨리면 아무도 모른다. `integration-main.yml:292` 주석은 "These six"라고 적지만 실제 단계는 5개다 |
|
||||
| 이해 비용 | lane을 추가하는 사람이 build.gradle·workflow·집계 태스크 세 곳을 알아야 한다. 이 규칙은 어디에도 강제돼 있지 않다 |
|
||||
| 최소 개선 방향 | (a) `integration-main.yml`에 `./gradlew :integrationCheck`(또는 lane별이 꼭 필요하면 `:adapter:outbound:persistence-jpa:integrationTestLaneCheck`) 한 단계를 둔다. (b) PERFORMANCE lane은 실행할 곳을 정하거나 `explicitOnly("이유")`로 바꿔 "부르지 않는다"를 코드에 드러낸다(gRPC `grpcPerformanceTest`처럼 문서로만 적지 않는다). (c) sample `systemTest`를 sample `check` 또는 `sampleWebContractCheck` 옆 main 단계에 연결한다. (d) 재발 방지: build-logic에 "explicitOnly가 아닌 모든 strict lane은 루트의 `ci`·`mainCheck`·`integrationCheck`·`performanceCheck` 중 하나에 도달한다"는 TestKit 테스트, 그리고 workflow가 그 네 집계를 모두 부른다는 테스트 하나 |
|
||||
| 대안 비교 | 현상 유지(이름 나열): 새 lane마다 누락 위험이 같다. 카테고리 집계 실행(제안): workflow는 집계 4개만 알면 된다. 단점은 한 잡이 길어지는 것 — lane별 단계가 필요하면 집계를 쪼개 부르되 "모든 lane이 어떤 집계에 속한다"는 검사로 묶는다. 텍스트 contains 테스트(`DeveloperExperienceContractTest.everyOptionalPlatformIntegrationLaneHasAnExecutingWorkflowCaller`)를 main 빌드에 복제: 주석 안의 문자열에도 통과하고 lane마다 테스트를 써야 해서 기각 |
|
||||
| 단순화의 보존 조건 | lane의 fail-closed 성질(아무것도 안 돌면 실패, `requires`, `rejectSkipped`)은 그대로 둔다. 변이 실험으로 이 장치는 테스트가 잘 지키고 있음을 확인했다 |
|
||||
| 비용·부작용 | main 단계 시간이 PostgreSQL lane 11개만큼 늘어난다(측정 안 함). 컨테이너 lane은 `exclusiveRealServerLane`으로 하나씩 돌기 때문에 합산 시간이 그대로 더해진다 |
|
||||
| 재검토 조건 | integration lane 수가 늘어 main 단계가 30분을 넘으면 집계를 잡 단위로 쪼갠다 |
|
||||
| 완료 기준 | 위 14개 lane이 어떤 workflow 실행 기록에 나온다. 새 lane을 집계 밖에 만들면 build-logic 테스트가 실패한다 |
|
||||
| 검증 방법 | `./gradlew ci mainCheck integrationCheck --dry-run`과 workflow 인자를 대조하는 테스트, 그리고 의도적으로 집계 밖 lane을 하나 만든 TestKit 변이 |
|
||||
|
||||
### 08-02 — strict lane은 build cache도 쓰지 않아서 바뀐 것이 없어도 매번 다시 돈다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(성능), 실험으로 확인 |
|
||||
| 관련 관점 | 14, 20, 9 |
|
||||
| 근거 | `StrictTestLanePlugin.java:221` `test.getOutputs().upToDateWhen(ignored -> false)`. 실험(scratchpad `cc08`, Gradle 9.0.0): `@CacheableTask`에 `upToDateWhen { false }`를 주고 출력을 지운 뒤 다시 실행하면 캐시 항목이 있어도 `executed`. 같은 태스크에서 그 한 줄만 빼면 `FROM-CACHE`. 즉 이 한 줄이 up-to-date 판정뿐 아니라 build cache 적재까지 막는다. ci에서 매번 다시 도는 hermetic lane: `architectureTest` 41초, app-bootstrap `systemTest` 14초, `mongoStableContractTest` 10초, `webSecurityBoundaryTest` 5초, `httpClientStableContractTest` 4초, `httpClientSecurityTest` 약 2초, `spring62ApiSurfaceScan` 1초 미만(테스트 JVM 구간, ci 로그 시점 기준). 합계 약 77초 + JVM 기동 7회. 추가로 app-bootstrap `check`가 `systemTestLaneCheck`에 의존하고(`src/app-bootstrap/build.gradle:90-92`) `mainCheck`의 `qualificationCheck`도 같은 lane을 부른다. main push에는 `ci-quality-gates`와 `integration-main`이 둘 다 돌기 때문에 같은 systemTest가 두 번 돈다(mainCheck 로그에서 20:42에 다시 실행됨, 8개 테스트) |
|
||||
| 발생 조건 | 모든 PR, main push, 로컬 `./gradlew <leaf>:check` 반복 실행 |
|
||||
| 영향 | PR 하나당 약 1~1.5분의 고정 비용. 문서만 고친 PR도 같다. 개발자가 `:adapter:outbound:persistence-mongo:check`를 두 번 연속 실행해도 465개 테스트가 다시 돈다 |
|
||||
| 심각도·우선순위 | Medium · P2. 정확성 문제는 아니지만 모든 PR에 반복되는 비용이고, 이 lane 수가 늘수록 커진다 |
|
||||
| 확실성 | 캐시 동작은 실험으로 확인(E3, 단일 태스크 실험). PR 단위 절감량은 ci 시점 측정값에서 계산한 추정 |
|
||||
| 결정의 근거 | 코드 주석에 이유가 없다. 추정되는 의도는 "lane은 실행됐다는 사실 자체가 증거"라는 것이다. 하지만 캐시된 결과도 그 입력으로 실행해서 `doLast` 검사(아무것도 안 돎·skip·required 누락)를 통과한 결과다. hermetic lane에서는 입력이 같으면 결과가 같다 |
|
||||
| 최소 개선 방향 | 카테고리로 나눈다: `TEST`·`ARCHITECTURE` lane은 `upToDateWhen(false)`를 빼서 캐시를 허용한다. 외부 이미지·네트워크·실제 시간에 기대는 `INTEGRATION`·`SYSTEM`·`PERFORMANCE`는 지금처럼 매번 돈다(이미지 태그가 입력으로 추적되지 않기 때문). app-bootstrap `check`→`systemTestLaneCheck` 연결은 지우거나, 남긴다면 `qualificationCheck`에서 app-bootstrap을 뺀다 |
|
||||
| 대안 비교 | 현상 유지: 단순하지만 고정 비용. 전부 캐시 허용: 컨테이너 lane은 이미지가 바뀌어도 캐시 적중할 수 있어 기각. `cacheIf { category == TEST }` 같은 명시 선언(제안과 같은 효과를 이름으로 드러냄)이 가장 읽기 쉽다 |
|
||||
| 단순화의 보존 조건 | lane이 실제로 실행될 때의 세 검사(0개 실행, skip, required 누락)는 그대로 둔다. `requires` 목록이 바뀌면 캐시 키도 바뀌어야 한다 — 현재 `filter.includeTestsMatching`은 Test 태스크 입력이라 키에 들어간다 |
|
||||
| 비용·부작용 | 캐시된 lane은 로그에 `FROM-CACHE`로만 나와 "이번에 돌았다"는 증거가 없다. release 같은 증거 수집 잡에서는 `--rerun-tasks`로 강제하면 된다 |
|
||||
| 재검토 조건 | build cache를 원격 캐시로 바꾸거나, lane이 외부 상태(파일·환경 변수)를 읽게 되면 그 lane은 캐시 대상에서 다시 뺀다 |
|
||||
| 완료 기준 | 코드 변경 없이 `./gradlew ci`를 두 번 돌리면 두 번째에 hermetic lane이 `FROM-CACHE` 또는 `UP-TO-DATE`. main push에서 app-bootstrap systemTest가 한 번만 돈다 |
|
||||
| 검증 방법 | build-logic TestKit: TEST 카테고리 lane을 두 번 실행해 두 번째 결과가 `UP_TO_DATE`/`FROM_CACHE`인지, INTEGRATION lane은 `SUCCESS`인지 단언 |
|
||||
|
||||
### 08-03 — app-bootstrap의 PR 테스트가 저장소 문서를 읽고, 저장소 전체를 입력으로 잡는다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(규칙 불일치) + 성능 비용 |
|
||||
| 관련 관점 | 23, 21, 14, 20 |
|
||||
| 근거 | `AGENTS.md`("저장소 문서와 대조하는 테스트는 `mainStage()` 레인(`document-contract` 태그)으로 leaf `mainCheck`에서 돈다")와 `integration-main.yml` 주석("documentation-drift gates … are gone rather than demoted"). 그런데 app-bootstrap `src/test`의 15개 클래스가 저장소 파일을 읽는다(`ca.repository.root`·repository root 탐색). 예: `CapabilityStatusDocumentTest.java:25-35`는 `docs/capability-status.md` 본문에 특정 문자열이 있는지 단언한다. `DeveloperExperienceContractTest.java:280-284`는 `CLAUDE.md`에 `./gradlew :app-bootstrap:architectureTest` 문자열이 있는지 단언한다. 같은 클래스의 다른 테스트들은 workflow YAML 본문을 문자열로 검사한다. 태그가 없어서 PR `test`에서 돈다. 그리고 `src/app-bootstrap/build.gradle:321-334`가 모든 Test 태스크에 `docs/**`, `.github/**`, `infra/**`, `scripts/**`, 저장소의 모든 `*.md`·`**/*.gradle`을 입력으로 선언한다 |
|
||||
| 발생 조건 | `CLAUDE.md`·`docs/` 문구 수정, 어느 leaf든 `build.gradle` 수정, workflow 수정 |
|
||||
| 영향 | 문서 한 줄 수정이 PR 게이트를 실패시킬 수 있다(정책과 반대). 또 저장소의 어떤 문서·빌드 파일을 바꿔도 app-bootstrap `test`(321개, 약 11초), `architectureTest`, `systemTest`, `integrationTest`의 캐시가 모두 무효가 된다. 이 리뷰 문서를 추가하는 것만으로도 무효다 |
|
||||
| 심각도·우선순위 | Medium · P2. 피해는 PR 시간과 소음이지만, 템플릿이 스스로 정한 규칙을 가장 큰 leaf가 어기고 있어 파생 프로젝트가 그대로 복제한다 |
|
||||
| 확실성 | 규칙 위반은 직접 확인. 캐시 무효화는 Gradle 입력 선언에서 정적으로 도출(실행 측정 안 함) |
|
||||
| 결정의 근거 | O-4a 수정(입력 미선언으로 UP-TO-DATE 거짓)에서 온 것이다. 정확성을 위해 입력을 넓혔고, 그 넓은 입력을 문서를 읽지 않는 테스트에까지 적용했다 |
|
||||
| 최소 개선 방향 | 저장소를 읽는 15개 클래스를 `@Tag("document-contract")`(문서 대조) 또는 별도 lane으로 모으고, 그 lane에만 `repositoryContractInputs`를 준다. 문서 본문 문자열을 단언하는 테스트(`CapabilityStatusDocumentTest`, `DeveloperExperienceContractTest`의 CLAUDE.md 단언)는 mainStage로 옮기거나 지운다. workflow 구조 검사(서명 잡의 OIDC 권한 같은 보안 성질)는 YAML 파싱 테스트로 남기되 그 lane의 입력은 `.github/**`만 둔다 |
|
||||
| 대안 비교 | 현상 유지: 정확하지만 PR 소음과 캐시 무효. 입력을 좁히기만: 문서 대조 테스트가 여전히 PR에 남아 규칙 위반은 그대로. 태그로 분리(제안): 규칙과 입력 범위가 같이 맞는다 |
|
||||
| 단순화의 보존 조건 | O-4a의 성질(읽는 파일이 바뀌면 테스트가 다시 돈다)은 분리된 lane에서 유지한다 |
|
||||
| 비용·부작용 | 문서 대조가 main 단계로 가면 PR에서는 못 잡고 merge 후에 잡는다. 이것이 AGENTS.md가 이미 고른 방향이다 |
|
||||
| 재검토 조건 | 특정 문서 대조가 보안·릴리스 계약(예: OIDC 권한)이라 merge 전에 막아야 하면 그 테스트만 PR lane에 두고 이유를 주석에 적는다 |
|
||||
| 완료 기준 | app-bootstrap `src/test`에서 저장소 파일을 읽는 클래스가 모두 태그·lane으로 분리된다. `docs/**`만 바꾼 커밋에서 app-bootstrap `test`가 `UP-TO-DATE`다 |
|
||||
| 검증 방법 | `git grep -l 'ca.repository.root\|repositoryRoot' -- 'src/app-bootstrap/src/test'`가 태그 붙은 클래스만 나오는지, 문서만 바꾼 뒤 `:app-bootstrap:test`의 up-to-date 여부 |
|
||||
|
||||
### 08-04 — 외부 컨테이너 이미지가 사라지면 main 단계가 통째로 멈춘다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(게이트 반응) + 구조적 위험(이미지 관리) |
|
||||
| 관련 관점 | 16, 6, 18, 28, 9 |
|
||||
| 근거 | (1) 이번 mainCheck 실패: MinIO lane 2개가 `ContainerFetchException`(Docker Hub `minio/minio` 저장소를 받을 수 없음)으로 실패. lane은 skip하지 않고 실패했다 — 이건 맞는 반응이다. (2) 하지만 CI의 main 단계는 `./gradlew :mainCheck --warning-mode=fail --stacktrace`(`integration-main.yml:81`)로 `--continue`가 없다. Gradle은 첫 실패 뒤 남은 태스크를 시작하지 않으므로, 외부 이미지 하나가 사라지면 env 계약·public path·전송 lane·문서 대조 lane의 결과가 그날 하나도 나오지 않는다(오케스트레이터는 `--continue`로 돌려서 나머지가 통과함을 확인했다). (3) 이미지 참조가 테스트 소스에 흩어져 있다: MinIO digest가 `MinioManagedObjectContractTest.java:51-52`, `MinioManagedObjectFaultTest.java:37-39`, evidence JSON 2개에 따로 있고, compose(`docker-compose.infra.yml:183`)는 다른 태그를 쓴다. `postgres:16-alpine`은 11곳에 떠 있는 태그(digest 아님)로 있다. httpclient는 build.gradle에서 httpbin digest를 주지만(`src/adapter/outbound/httpclient/build.gradle:219-224`) 테스트 기본값은 `kennethreitz/httpbin:latest`(`FailureInjectionContractTest.java:40`)다. Testcontainers 이미지 치환(`hub.image.name.prefix`·`ImageNameSubstitutor`)이나 미러 설정은 없다. (4) 같은 MinIO lane이 `object-storage-qualification.yml`(PR 경로 필터 + 주간)과 objectstorage `mainCheck`(`src/adapter/outbound/objectstorage/build.gradle:123-124`) 두 곳에서 돈다 |
|
||||
| 발생 조건 | Docker Hub 저장소 삭제·이동, rate limit, 사내 네트워크에서 Docker Hub 차단 |
|
||||
| 영향 | main 단계 신호 전체가 외부 공급원 하나에 묶인다. 이미지를 바꾸려면 Java 소스 여러 곳을 같이 고쳐야 하고, 빠뜨린 곳은 그 lane이 돌 때까지 모른다. 파생 서비스가 사내 레지스트리를 쓰려면 소스를 고쳐야 한다 |
|
||||
| 심각도·우선순위 | Medium · P2. 지금 실제로 main 단계가 빨갛다. 데이터 피해는 없지만 다른 회귀를 가린다 |
|
||||
| 확실성 | 실패와 `--continue` 부재는 직접 확인. "남은 태스크가 시작되지 않는다"는 Gradle 기본 동작이고, 이번 실행이 `--continue`로 돌아 CI와 같은 조건의 재현은 하지 않았다 |
|
||||
| 결정의 근거 | 이미지를 digest로 고정한 것 자체는 좋은 선택이다(httpclient 주석이 이유를 적는다: 빨간 결과가 남의 이미지 push 때문이 아니게). 문제는 고정값을 한 곳에서 관리하지 않는 것과, 공급원이 사라졌을 때의 대응이 없는 것이다 |
|
||||
| 최소 개선 방향 | (a) `integration-main.yml`의 main-check 단계에 `--continue`를 붙여 실패한 lane 이름이 전부 나오게 한다. (b) 테스트용 이미지를 한 파일(예: `src/config/testing/container-images.properties`)에 모으고, 테스트는 시스템 프로퍼티로 받는다. 각 Test 태스크가 그 파일을 입력으로 선언한다. compose·evidence JSON도 같은 값을 쓰거나, 다르면 그 이유를 적는다. (c) Testcontainers `hub.image.name.prefix`를 CI 변수로 받을 수 있게 해 사내 미러로 돌릴 수 있게 한다. (d) MinIO lane 중복은 하나만 남긴다 |
|
||||
| 대안 비교 | 현상 유지: 이미지가 사라질 때마다 소스 여러 곳 수정. 공급원을 GHCR·Quay로 옮기기만: 같은 문제가 다른 공급원에서 반복. 사내 미러 의무화: 템플릿 기본값으로는 과하다 — 선택할 수 있게만 연다 |
|
||||
| 단순화의 보존 조건 | digest 고정과 "받지 못하면 skip이 아니라 실패"는 유지한다 |
|
||||
| 비용·부작용 | 이미지 목록 파일 하나와 읽는 헬퍼 하나가 생긴다. 이미지 갱신 PR이 그 파일 하나만 바꾸면 된다 |
|
||||
| 재검토 조건 | 이미지 수가 5개 이하로 줄거나, 모든 컨테이너 테스트가 한 leaf로 모이면 파일 대신 상수 클래스 하나로 충분하다 |
|
||||
| 완료 기준 | MinIO 이미지를 바꾸는 변경이 파일 1곳만 수정한다. main-check 잡이 실패해도 나머지 main lane 결과가 로그에 남는다 |
|
||||
| 검증 방법 | `git grep -n 'minio/minio'` 결과가 이미지 목록 파일 하나. 존재하지 않는 digest로 바꾼 브랜치에서 main-check가 MinIO 두 lane만 실패로 보고하는지 |
|
||||
|
||||
### 08-05 — registry에 없는 leaf 디렉터리는 조용히 빌드에서 빠진다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험 |
|
||||
| 관련 관점 | 21, 20, 25 |
|
||||
| 근거 | `ModuleRegistrySettingsInstaller.java`는 registry의 모듈만 `include`한다. `VerifyCleanArchitectureDependenciesTask`의 `declaredModules`도 settings가 포함한 프로젝트에서 나오므로, registry에 없는 디렉터리는 비교 대상이 되지 못한다. 현재는 미등록 `build.gradle`이 없다(`git ls-files '*build.gradle'`과 registry `source_path` 대조, build-logic·root·optional-platforms 제외) |
|
||||
| 발생 조건 | 개발자가 새 leaf 디렉터리와 `build.gradle`을 만들고 registry 등록을 빠뜨림 |
|
||||
| 영향 | 그 leaf는 컴파일도 테스트도 되지 않는데 `ci`는 초록이다. 직접 `:<path>:test`를 부르면 "project not found"로 드러나지만 `ci`만 보면 모른다 |
|
||||
| 심각도·우선순위 | Low · P3. 발생하면 금방 드러날 가능성이 높고 현재 사례는 없다 |
|
||||
| 결정의 근거 | 적용 제외 — 대안이 사실상 하나인 단순 guard 누락 |
|
||||
| 최소 개선 방향 | settings 플러그인에서 `src/**/build.gradle` 중 registry에도 included build 목록에도 없는 파일이 있으면 실패하거나, `verifyCleanArchitectureDependencies`에 같은 검사를 둔다 |
|
||||
| 완료 기준 | 미등록 `build.gradle`을 하나 만들면 `ci`가 실패한다 |
|
||||
| 검증 방법 | `ModuleRegistryTest` 또는 TestKit에 미등록 디렉터리 사례 추가 |
|
||||
|
||||
### 08-06 — 병렬·캐시 설정이 빌드와 lane 종류에 따라 다르게 적용된다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 개선 제안(성능) |
|
||||
| 관련 관점 | 14, 23 |
|
||||
| 근거 | (1) `src/optional-platforms/`에 `gradle.properties`가 없다. `-p optional-platforms`로 돌리면 `src/gradle.properties`(parallel, caching, workers.max=4, jvmargs)가 적용되지 않는다. PR의 optional-platforms 잡과 release의 gRPC 잡이 직렬·캐시 없이 돈다. (2) `StrictTestLanePlugin.java:187-199`는 TEST가 아닌 모든 lane에 build 전체에서 1개짜리 `exclusiveRealServerLane`을 건다. 주석은 "서버나 컨테이너를 띄우는 lane"이라고 하지만 `ARCHITECTURE` lane(ArchUnit, 서버 없음)도 포함된다 |
|
||||
| 영향 | optional build 시간 미측정. ArchUnit lane(41초)이 서버 lane과 겹쳐 돌 수 없다 |
|
||||
| 심각도·우선순위 | Low · P3 |
|
||||
| 결정의 근거 | 적용 제외 — 설정 누락·조건 범위 문제 |
|
||||
| 최소 개선 방향 | optional-platforms에 같은 `gradle.properties`를 두거나 `src/gradle.properties`를 가리키는 문장을 README에 적는다. 서비스 제한 조건을 `category != TEST && category != ARCHITECTURE`로 좁힌다 |
|
||||
| 완료 기준 | optional build 로그에 parallel 실행. ArchUnit lane이 다른 lane과 동시에 돌 수 있다 |
|
||||
| 검증 방법 | `-p optional-platforms ci --dry-run`의 `--parallel` 여부, build-logic TestKit |
|
||||
|
||||
### 08-07 — SpotBugs·FindSecBugs가 신뢰도 HIGH만 보고한다
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 미검증(설정 사실은 확인, 영향은 미측정) |
|
||||
| 관련 관점 | 15, 21 |
|
||||
| 근거 | `QualityConventionsPlugin.java` `spotBugs.getReportLevel().set(Confidence.HIGH)`. FindSecBugs의 다수 규칙(SQL·경로 주입 등)은 보통 신뢰도 MEDIUM으로 보고된다. `exclude.xml`에는 `<Match>` 9개 |
|
||||
| 영향 | 보안 정적분석이 돈다는 사실과 실제로 보는 범위가 다르다. 얼마나 놓치는지는 MEDIUM으로 한 번 돌려 봐야 안다 |
|
||||
| 심각도·우선순위 | Low · P3 |
|
||||
| 결정의 근거 | 코드에 이유가 없다. 오탐을 줄이려는 선택으로 보이지만 기록이 없다 |
|
||||
| 최소 개선 방향 | 한 번 `Confidence.MEDIUM`으로 `qualityCheck`를 돌려 결과 수를 본다. 결과에 따라 MEDIUM + 제외 목록, 또는 HIGH 유지 + 이유 주석 |
|
||||
| 완료 기준 | 설정 옆에 고른 신뢰도와 그 근거(측정한 결과 수)가 적혀 있다 |
|
||||
| 검증 방법 | MEDIUM 실행 결과 수 비교 |
|
||||
|
||||
## 4. 31절 시나리오 추적
|
||||
|
||||
이 영역은 요청을 처리하지 않는다. 그래서 요청 대신 "변경 하나"를 따라갔다.
|
||||
|
||||
### 선택 어댑터 제거·추가 (적용)
|
||||
|
||||
한 서비스가 JPA를 고르고, 다른 서비스가 JPA leaf 자체를 지운다고 가정했다.
|
||||
|
||||
```text
|
||||
app-bootstrap/build.gradle 주석 해제(runtimeOnly persistence-jpa)
|
||||
-> strict lock 불일치 -> resolveAndLockAll --write-locks (주석이 안내)
|
||||
-> modules.json app-bootstrap.allowed_dependencies에 이미 있음 -> 방향 게이트 통과
|
||||
-> systemTest가 main runtime graph로 기동 -> JPA가 켜진 기동을 검증
|
||||
```
|
||||
|
||||
| 항목 | 결과 |
|
||||
| --- | --- |
|
||||
| 입력의 신뢰 수준 | 개발자가 고친 build 파일. 잘못 고치면 strict lock과 방향 게이트가 막는다(M3) |
|
||||
| 권한 판단 위치 | `modules.json` `allowed_dependencies`가 유일한 허용 목록. app-bootstrap은 capability 11개를 모두 미리 허용한다 |
|
||||
| 규칙 소유 | registry(edge), `capabilityProjects` 목록(`app-bootstrap/build.gradle` 134~146행, ArchUnit 입력과 qualification jar), 주석 처리된 `runtimeOnly` 줄. capability 목록이 이 두 곳과 registry 세 곳에 있다 |
|
||||
| 성공의 의미 | `ci` 초록 = 컴파일·단위·ArchUnit·systemTest(현재 조립). 고른 capability의 실제 벤더 lane은 PR에 없고, JPA readiness lane은 어디서도 돌지 않는다(08-01) |
|
||||
| 오류 변환 | lock 불일치, 금지 edge 모두 Gradle 오류로 위치와 함께 나온다 |
|
||||
| 제거(leaf 자체 삭제) | 선택 해제는 한 줄이지만 leaf 삭제는 아니다. app-bootstrap `build.gradle`에 `persistence-jpa`가 9번(`testImplementation`, `integrationTestImplementation`, testFixtures, `capabilityProjects`, `bootRunH2Classpath` 등) 나오고, app-bootstrap 테스트 7개 파일이 persistence 타입을 import한다. 파생 프로젝트가 JPA leaf를 지우려면 이 테스트들도 정리해야 한다. AGENTS.md 기준 7("한 줄을 지우면 기능이 완전히 사라진다")은 선택 해제에 대한 말이고, leaf 삭제 비용은 문서에 없다 |
|
||||
|
||||
### 적용 제외
|
||||
|
||||
정상 쓰기, 중복·동시 요청, 외부 응답 지연, DB 오류, 메시지 중복, 세션·토큰, 다른 사용자 리소스, 큰 입력, 종료·재시작: 빌드·CI 영역에는 요청 경로가 없다. 각 영역 리뷰가 다룬다. "신·구 버전 공존"은 gRPC buf breaking 검사(`ci-quality-gates.yml` `grpc-proto-buf`)만 이 영역에 있고, 확인했다(PR·push에서 baseline 대비 `buf breaking`).
|
||||
|
||||
## 5. 41절 설계 선택 검토
|
||||
|
||||
### 5.1 integration lane을 workflow가 이름으로 부르는 방식
|
||||
|
||||
1. 필요한 것: 컨테이너가 필요한 lane은 PR이 아니라 main 단계에서 실패가 보이게 돌아야 한다.
|
||||
2. 지킬 성질: 선언한 strict lane은 어딘가에서 반드시 실행된다.
|
||||
3. 현재 보장: 없다. lane 자체는 "실행되면 fail-closed"를 잘 지킨다(변이 3개 모두 테스트가 잡음). 하지만 "실행되는가"는 workflow 문자열에 달려 있고, 검사는 optional build 하나에 대한 문자열 contains 테스트뿐이다.
|
||||
4. 대안: (a) 현상 유지, (b) 카테고리 집계를 workflow가 부르기, (c) 집계 + "모든 lane은 집계에 속한다" 검사.
|
||||
5. 비용: (a) 누락 재발(지금 14개). (b) 잡 하나가 길어진다. (c) build-logic 테스트 하나 추가.
|
||||
6. 현재 조건의 선택: (c). 집계는 이미 있고(`integrationCheck`), 부르지 않을 뿐이다.
|
||||
7. 바뀔 조건: lane별 실패를 따로 보고 싶으면 집계를 여러 잡으로 나누되, 검사(c)는 유지한다.
|
||||
|
||||
### 5.2 strict lane을 항상 다시 실행하는 방식(`upToDateWhen(false)`)
|
||||
|
||||
1. 필요한 것: lane이 통과했다는 것이 "지정한 테스트가 실제로 돌았다"는 뜻이어야 한다.
|
||||
2. 지킬 성질: 0개 실행·skip·required 누락이 성공으로 보고되지 않는다.
|
||||
3. 현재 보장: `doLast` 검사로 지킨다. 그런데 이 검사는 캐시된 결과에도 이미 한 번 적용된 상태다. `upToDateWhen(false)`는 이 성질에 더하는 것이 없고, 외부 상태에 기대는 lane에서만 의미가 있다.
|
||||
4. 대안: 현상 유지 / 카테고리별 캐시 허용 / 전부 캐시.
|
||||
5. 비용: 현상 유지는 PR당 약 77초 + JVM 7회(08-02). 전부 캐시는 이미지 태그 변화를 못 본다.
|
||||
6. 선택: 카테고리별. hermetic(TEST·ARCHITECTURE)만 캐시.
|
||||
7. 바뀔 조건: hermetic lane이 저장소 파일이나 환경 변수를 읽기 시작하면 입력 선언을 먼저 하고, 못 하면 캐시에서 뺀다.
|
||||
|
||||
### 5.3 저장소 대조 테스트를 어디서 돌리는가
|
||||
|
||||
1. 필요한 것: 빌드·workflow·문서의 일부 계약(OIDC 권한, Docker 단계 구조)은 회귀하면 안 된다.
|
||||
2. 지킬 성질: 계약 회귀를 잡되, 문서 문구 수정으로 PR이 막히지 않는다(AGENTS.md의 정책).
|
||||
3. 현재 보장: 정책은 3개 leaf만 따른다. app-bootstrap은 15개 클래스가 PR `test`에서 문서를 읽는다(08-03).
|
||||
4. 대안: 현상 유지 / 전부 main 단계 / 보안·릴리스 계약만 PR, 나머지 main.
|
||||
5. 비용: 현상 유지는 문서 수정 PR 소음과 캐시 무효. 전부 main은 OIDC 권한 회귀를 merge 후에 잡는다.
|
||||
6. 선택: 세 번째. 보안 계약은 이유 주석과 함께 PR에 남긴다.
|
||||
7. 바뀔 조건: 문서 대조 테스트가 거의 없어지면 lane 없이 태그 하나로 충분하다.
|
||||
|
||||
## 6. 리팩토링 후보
|
||||
|
||||
| 무엇 | 왜 | 보존할 동작·실패 계약 |
|
||||
| --- | --- | --- |
|
||||
| lane 도달성 검사 추가, workflow가 카테고리 집계를 부르게 | 08-01 재발 방지 | lane의 fail-closed 검사 3종, `explicitOnly` 이유 출력 |
|
||||
| hermetic lane 캐시 허용 | 08-02 | 실행 시 3종 검사. INTEGRATION·SYSTEM·PERFORMANCE는 매번 실행 |
|
||||
| app-bootstrap 저장소 대조 테스트 분리, 입력 범위 축소 | 08-03 | 읽는 파일이 바뀌면 그 lane은 다시 돈다(O-4a) |
|
||||
| 테스트 컨테이너 이미지 목록 한 파일로 | 08-04 | digest 고정, 받지 못하면 실패 |
|
||||
| `-Duser.timezone=UTC`를 `JavaConventionsPlugin`의 모든 Test 태스크로 | O-10b, 28번 반복 | UTC 고정. lane이 jvmArgs를 덮어쓰는 현재 구조(`test.setJvmArgs`)에서 사라지지 않게 `jvmArgumentProviders`나 `systemProperty`로 넣는다 |
|
||||
| httpclient 공통 sysprop을 `tasks.withType(Test).configureEach` 하나로 | O-10a | lane별 다른 값(`performance.assertions.enabled`, httpbin 이미지)은 그 lane에만 |
|
||||
| 순수성 태스크 이름 `verifyModuleDependencyPurity` 계열로 통일 | BUILD-순수성-이름 | 루트 alias 이름이 바뀌면 workflow·문서 호출부도 같이 |
|
||||
| `netty.version` override 삭제, `commons-lang3` override에 이유 주석, 카탈로그 주석 위치 수정 | O-11b·O-11c | 해석되는 버전이 바뀌지 않음을 lockfile diff 0으로 확인 |
|
||||
|
||||
## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료)
|
||||
|
||||
### 템플릿이 주는 틀
|
||||
|
||||
- leaf 성격 선언: `ca.java-library` / `ca.spring-library` / `ca.platform-module` 중 하나. toolchain·lock·정적분석·Mockito agent·JUnit BOM이 따라온다.
|
||||
- 추가 테스트 소스: `testing { suites { xxx(JvmTestSuite) } }` + 같은 이름의 `strictTestLanes { lane('xxx') { integration() … } }`.
|
||||
- 아키텍처 경계: `modules.json`에 edge를 적으면 방향 게이트가 나머지를 막는다.
|
||||
- 모범 테스트: `sample-portfolio`(GWT 100%), 공유 계약 예시 `WorkLogRepositoryContract`·`DurableOperationStoreContract`.
|
||||
|
||||
### 빠진 것
|
||||
|
||||
- "새 leaf 추가" 순서를 한 곳에 적은 문서가 없다(registry → build.gradle → lock 생성 → capability면 app-bootstrap `capabilityProjects`·주석 줄 → README 3항목).
|
||||
- "새 lane을 어디서 돌릴지" 고르는 기준과 검사가 없다(08-01).
|
||||
- 테스트 컨테이너 이미지를 어디에 적는지 규칙이 없다(08-04).
|
||||
- application 포트 83개 중 공유 계약을 가진 것은 소수다. 새 포트를 만들 때 계약 클래스를 같이 만들라는 틀(예시 계약 + 빈 템플릿)은 sample에만 있다.
|
||||
|
||||
### 개발자가 내려야 하는 판단
|
||||
|
||||
1. 이 코드는 어느 leaf 소유인가 → `modules.json` `source_path`. 없는 leaf면 registry부터.
|
||||
2. 이 테스트는 어떤 lane인가 → 외부 프로세스 없음 = `test`. 문서·저장소 파일 대조 = `@Tag("document-contract")` + `mainStage()`. 컨테이너·실제 서버 = 별도 suite + `integration()`/`system()`. 측정 = `performance()`.
|
||||
3. 그 lane은 누가 실행하는가 → 지금은 사람이 workflow에 적어야 한다. 적지 않을 거면 `explicitOnly("이유")`.
|
||||
4. 테스트가 저장소 파일을 읽는가 → 그 파일을 그 Test 태스크의 `inputs`로 선언한다. 넓게 잡으면 캐시가 무효가 된다(08-03).
|
||||
5. 컨테이너 이미지는 digest로 고정했는가, 다른 테스트와 같은 값인가.
|
||||
6. 의존성을 바꿨는가 → `./gradlew resolveAndLockAll --write-locks`, lock diff 확인. BOM이 관리하는 버전은 카탈로그에 적지 않는다.
|
||||
7. 포트를 새로 만들었는가 → 포트 소유 모듈 testFixtures에 fake 하나와 추상 계약 하나, adapter 테스트가 같은 계약을 상속.
|
||||
|
||||
## 8. 테스트 실행 성능
|
||||
|
||||
측정 조건: 오케스트레이터 `ci` 1회, 같은 머신에서 다른 에이전트가 함께 돌아 부하 9~31. 로컬 build cache가 거의 비어 643/663 태스크가 실제 실행. 숫자는 이 조건의 한 번 측정이다.
|
||||
|
||||
| 항목 | 값 |
|
||||
| --- | --- |
|
||||
| `ci` 전체 | 434초(잠금 대기 포함), BUILD 7분 9초 |
|
||||
| ci가 실행한 Test 태스크 | 58개, 테스트 6,115개, skip 8 |
|
||||
| 테스트 클래스 시간 합 | 약 208초 |
|
||||
| Test 태스크 JVM 구간 합 | 약 257초(4 worker로 겹쳐 실행) |
|
||||
| 결론 | ci 시간의 대부분은 테스트가 아니라 컴파일(Error Prone 포함 55개)·SpotBugs 53개·Checkstyle 106개·Spotless 53개다. 태스크별 시간은 프로파일을 돌리지 않아 미측정 |
|
||||
|
||||
가장 느린 테스트 클래스(ci):
|
||||
|
||||
| 초 | leaf | 태스크 | 클래스 | 테스트 수 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 9.3 | persistence-jpa | test | PersistenceJpaCapabilityAssemblyTest | 5 |
|
||||
| 7.8 | app-bootstrap | systemTest | BootstrapCapabilityReachabilitySystemTest | 2 |
|
||||
| 6.6 | app-bootstrap | architectureTest | AdapterBoundaryArchitectureTest | 17 |
|
||||
| 5.9 | objectstorage | test | S3AsyncClientFactoryTest | 4 |
|
||||
| 5.4 | app-bootstrap | systemTest | DefaultCompositionBootTest | 4 |
|
||||
| 3.5 | objectstorage | test | ObjectStorageArchitectureTest | 1 |
|
||||
| 3.5 | messaging-kafka | test | KafkaCapabilityActivationTest | 4 |
|
||||
| 3.0 | cache-redis | test | RedisCapabilityActivationTest | 2 |
|
||||
| 2.9 | redis-runtime | test | RedisRuntimeAutoConfigurationTest | 20 |
|
||||
| 2.7 | graphql | test | GraphQlProductionClassesTest | 1 |
|
||||
| 2.5 | objectstorage | test | LocalDevObjectStorageRecoveryTest | 5 |
|
||||
| 2.5 | persistence-mongo | test | MongoCapabilityActivationTest | 4 |
|
||||
| 2.5 | web | test | SecurityModeWebContractTest | 5 |
|
||||
| 2.4 | notification-platform | test | ProviderCallbackIngressBridgeTest | 5 |
|
||||
| 2.4 | fileserver-platform | test | FileserverPlatformAutoConfigurationTest | 11 |
|
||||
| 2.4 | web | webSecurityBoundaryTest | CorsSecurityFilterIntegrationTest | 5 |
|
||||
| 2.2 | web-fileserver | test | MvcUploadExecutorSaturationTest | 5 |
|
||||
| 2.2 | cache-redis | test | RedisCapabilityCompositionTest | 9 |
|
||||
| 2.1 | idempotency | test | IdempotencyAutoConfigurationTest | 6 |
|
||||
| 2.1 | objectstorage | test | S3ProviderCompositionTest | 6 |
|
||||
|
||||
leaf·태스크별 합(상위): objectstorage `test` 19.4초(130), app-bootstrap `architectureTest` 17.1초(181, JVM 구간 41초 — ArchUnit 클래스 import가 클래스 시간 밖에서 쓰인다), persistence-jpa `test` 16.6초(502), app-bootstrap `systemTest` 14.2초(8), app-bootstrap `test` 10.2초(321), graphql `test` 9.7초(377).
|
||||
|
||||
Spring 컨텍스트:
|
||||
|
||||
- `@SpringBootTest`/`@WebMvcTest`/`@DataJpaTest` 사용 파일은 49개로 적고, 대부분 system·integration suite에 있다. `@DirtiesContext` 0개. `@MockitoBean` 6개 파일은 모두 sample-portfolio다(컨트롤러 wire 테스트마다 mock 조합이 달라 클래스마다 컨텍스트 캐시 미스가 난다. sample 테스트 합은 마지막 기록(9월 28일)에서 5.9초라 비용은 작다. 다만 adopter가 복사하는 원본이라 패턴이 퍼진다).
|
||||
- 가장 많이 쓰는 방식은 `ApplicationContextRunner` 109개 파일이다. 캐시가 없고 `run()`마다 작은 컨텍스트를 새로 만든다. ci에서 이 클래스 99개가 574개 테스트, 49.5초(테스트 시간의 26%)를 쓴다. 테스트당 약 86ms라 지금은 문제 없다. 가장 느린 20개 중 절반이 이 종류(조립·활성화 테스트)다.
|
||||
- JUnit 병렬 실행 설정(`junit-platform.properties`) 없음. app-bootstrap `test`만 `maxParallelForks = 2`.
|
||||
|
||||
Gradle 설정: `org.gradle.parallel=true`, `org.gradle.caching=true`, `workers.max=4`, configuration cache는 꺼져 있다(이유가 `src/gradle.properties`에 적혀 있고, `integration-main.yml` `configuration-cache` 잡이 저장 가능성을 매번 확인한다). optional-platforms는 이 설정을 받지 못한다(08-06). 강제 재실행 비용은 08-02.
|
||||
|
||||
## 9. 테스트 작성 규칙 표본 조사
|
||||
|
||||
방법: 테스트 소스(`testFixtures` 제외)의 `@Test`·`@ParameterizedTest` 메서드 6,943개를 정규식으로 읽었다. 문장 수는 깊이 0의 `;` 개수로 셌다. 추정치다.
|
||||
|
||||
| 규칙(AGENTS.md) | 결과 |
|
||||
| --- | --- |
|
||||
| 1. 행동 문장 이름 | 거의 지켜짐. `test` 접두·밑줄·대문자 시작 5개 |
|
||||
| 2. `@DisplayName` 언어 | 규칙은 영어, 소유자 결정 5는 한국어. 실제 영어 2,272 / 한국어 172. 최근 수정 파일(예: `DeveloperExperienceContractTest`, `JpaReadinessRegistryTest`)은 한국어, 같은 클래스 안에서도 섞인다 |
|
||||
| 3. GWT 주석, `// when` 하나 | 문장 3개 이상 3,514개 중 610개(17%)만 주석을 가짐. `// when` 2개 이상은 1개. 규칙은 "새로 쓰거나 고치는 테스트"에만 적용이라 위반으로 세지 않았다. 모범은 sample(100%)뿐이고 production leaf 중 최고는 support(53%) |
|
||||
| 5. 약한 단언만 있는 테스트 | 단언이 하나이고 그것이 `isNotNull`/`isPresent`/`doesNotThrowAnyException`인 테스트 125개 |
|
||||
| 예외 when 분리 | `assertThatThrownBy` 포함 1,528개, `catchThrowable` 227개 |
|
||||
| 6. 포트당 fake 하나, 공유 계약 | 포트 83개 중 fake와 adapter가 같은 추상 계약을 상속하는 것은 소수(2절 TEST-F-1) |
|
||||
|
||||
이 영역의 테스트가 위험을 잡는지: build-logic의 strict lane 장치에 변이 3개(0개 실행 검사 끄기, `rejectSkipped` 끄기, `explicitOnly` 필터 끄기)를 넣고 `StrictTestLaneConventionTest`를 돌렸다. 5개 테스트가 실패해 3개 변이를 모두 잡았다. 장치 자체의 테스트는 충분하다. 빠진 것은 "lane이 실행되는가"에 대한 검사다(08-01).
|
||||
|
||||
## 10. 28개 관점 판정표
|
||||
|
||||
| 번호 | 관점 | 판정 | 한 줄 이유 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 코드 성숙도 | O | build-logic은 작은 플러그인으로 나뉘고 TestKit 테스트가 있다(main 2,854줄) |
|
||||
| 2 | 구조적 성숙도 | O | registry 하나가 프로젝트 포함·방향·순수성의 근거이고 leaf별 태스크로 병렬 안전 |
|
||||
| 3 | 변경 용이성 | P | 선택 해제는 한 줄이지만 capability 목록이 registry·`capabilityProjects`·주석 줄 세 곳, lane 추가는 workflow까지 손대야 함 |
|
||||
| 4 | 인지 부하 | P | 주석은 이유를 잘 적지만 lane이 어디서 도는지 한눈에 볼 곳이 없다 |
|
||||
| 5 | 위험 가시성 | P | readiness 카드·README가 실행되지 않는 lane을 근거로 든다(08-01) |
|
||||
| 6 | 실패 성숙도 | P | lane은 fail-closed. 하지만 main 단계는 첫 실패에서 멈춘다(08-04) |
|
||||
| 7 | 운영 성숙도 | > | 배포·운영은 다른 영역. release 서명·SBOM은 확인만 함 |
|
||||
| 8 | 디버깅 가능성 | P | lane 실패 메시지가 구체적. 다만 main-check는 실패 하나 뒤 나머지 결과가 없다 |
|
||||
| 9 | 유지보수 성숙도 | P | 지난 Nit 다수 남음(O-10a·b, O-11b·c, 이름) |
|
||||
| 10 | 테스트 성숙도 | P | 장치 테스트는 강함(변이 3/3). 실제 벤더 lane 14개 미실행, GWT 17%, 공유 계약 소수 |
|
||||
| 11 | 데이터 성숙도 | > | 마이그레이션 검증 lane이 안 도는 것은 08-01로 연결, 데이터 자체는 05 영역 |
|
||||
| 12 | 동시성 성숙도 | - | 빌드 영역에 해당 없음(lane 직렬화 서비스만 확인) |
|
||||
| 13 | 확장성 | P | leaf·lane이 늘면 이름 나열 방식의 누락 위험이 비례해서 커진다 |
|
||||
| 14 | 성능 성숙도 | P | 테스트는 병목이 아님(클래스 합 208초). 강제 재실행 약 77초/PR, 중복 systemTest, optional build 설정 누락 |
|
||||
| 15 | 보안 성숙도 | P | action SHA 고정, wrapper 검증, Trivy+KEV, cosign 서명. SpotBugs는 HIGH만(08-07) |
|
||||
| 16 | 의존성 성숙도 | P | strict lock, 카탈로그, Renovate(보안만). 테스트 이미지 관리가 흩어짐(08-04), 효과 없는 override(O-11c) |
|
||||
| 17 | API / Contract 성숙도 | O | `ca.api-surface`가 PR `check`에서 돈다(결정 20), buf lint·breaking |
|
||||
| 18 | 배포 성숙도 | > | release.yml은 확인만, 배포 영역 |
|
||||
| 19 | 설정 성숙도 | O | `verifyEnvKeys`가 main 단계에서 돈다(결정 4). 빌드 설정값은 이유와 함께 `gradle.properties`에 있음 |
|
||||
| 20 | 개발자 경험 | P | leaf focused 명령이 단순. 문서 수정이 PR을 실패시킬 수 있고(08-03) hermetic lane이 캐시되지 않음 |
|
||||
| 21 | Guardrail 성숙도 | P | 방향·순수성·lock·ignored-source는 M3~M4. lane 도달성·미등록 leaf는 M0(08-01, 08-05) |
|
||||
| 22 | 추상화 성숙도 | O | `strictTestLanes` DSL 하나로 5개 구현을 대체했고 과하지 않다 |
|
||||
| 23 | 일관성 | P | document-contract 규칙을 3개 leaf만 따름(08-03), 이미지 고정 방식 혼재, upload-artifact v4·v7 혼재 |
|
||||
| 24 | 네이밍 / 의미 성숙도 | P | 순수성 태스크 이름, `web-load-abuse-and-shutdown` 잡 이름이 하는 일과 다름 |
|
||||
| 25 | 조직 확장성 | P | 새 기여자가 lane 실행 위치를 알 방법이 workflow 검색뿐 |
|
||||
| 26 | Ownership 성숙도 | ? | CODEOWNERS는 있으나 내용과 실제 리뷰 흐름은 확인 안 함 |
|
||||
| 27 | 삭제 가능성 | P | 선택 해제는 쉬움. leaf 삭제는 app-bootstrap 테스트·빌드 9곳 수정 필요(4절) |
|
||||
| 28 | 회복 가능성 | P | 외부 이미지가 사라졌을 때 미러·치환 경로가 없다(08-04) |
|
||||
|
||||
## 부록 — 실행 명령
|
||||
|
||||
```bash
|
||||
# 게이트 로그(오케스트레이터 실행, 읽기만)
|
||||
scratchpad/gates/{summary.txt,ci.log,mainCheck.log}
|
||||
|
||||
# 도달성 확인 (worktree wt-08, flock, 시작 부하 8.22)
|
||||
./gradlew ci mainCheck --dry-run --console=plain # rc=0
|
||||
./gradlew integrationCheck --dry-run --console=plain # rc=0
|
||||
|
||||
# build cache 실험 (scratchpad/cc08, Gradle 9.0.0)
|
||||
# upToDateWhen{false} + 출력 삭제 후 재실행 -> executed
|
||||
# 같은 태스크에서 그 줄 제거 -> FROM-CACHE
|
||||
|
||||
# 변이 실험 (worktree wt-08, 시작 부하 7.16, 18초)
|
||||
./gradlew -p build-logic test --tests 'dev.caskeleton.buildlogic.strictlane.StrictTestLaneConventionTest' --continue
|
||||
# 18개 중 5개 실패 = 변이 3개 모두 검출. 원복 확인(git status 깨끗)
|
||||
|
||||
# 테스트 시간 집계: build/test-results/**/TEST-*.xml (ci 실행 구간 20:33~20:41)
|
||||
```
|
||||
@@ -0,0 +1,556 @@
|
||||
# 09. 런타임 성능 실측 — 2026-11-01 성숙도 리뷰
|
||||
|
||||
이 문서는 코드 리뷰보다 측정 숫자를 앞에 둔다. 모든 숫자는 아래 「측정 조건」에서 나왔다. 같은 측정은 3회 반복했고, 표에는 중앙값을 적었다. 다른 세션이 같은 머신을 쓰고 있었으므로 측정 직전 load average를 함께 적었다. load average가 15를 넘은 회차는 표에 `(부하 높음)`으로 표시했다.
|
||||
|
||||
## 1. 범위 (36.1)
|
||||
|
||||
| 항목 | 기록 |
|
||||
| --- | --- |
|
||||
| 대상 | `clean-architecture-backend-template`, Gradle 루트 `src/` |
|
||||
| 커밋 | `main` `01a8a2a70`. 측정은 별도 worktree(`<scratchpad>/wt-09`)에서 했다. 메인 repo에서는 Gradle을 돌리지 않았다. |
|
||||
| 목적과 실행 구성 | (1) 기본 조합 `app-bootstrap` bootJar, `local` 프로필. (2) `sample-portfolio` bootJar + PostgreSQL 16(alpine, Docker, `--cpus 4 --memory 1g`), `local` 프로필. |
|
||||
| 규모 목표 | 템플릿에 명시된 지연·처리량 목표가 없다. 그래서 「좋다/나쁘다」 대신 요청당 비용(SQL 수, 지연, 처리량)과 그 비용이 데이터 수에 비례하는지를 판정 기준으로 썼다. |
|
||||
| 읽은 코드·설정 | `app-bootstrap/build.gradle`, `app-bootstrap/src/main/resources/{application.yml,application-local.yml,config/*.yml}`, `sample-portfolio/build.gradle`, `sample-portfolio/src/main/resources/application.yml`, `sample-portfolio` 의 web controller·use case·persistence adapter·entity·mapper·migration(V7), `adapter/outbound/persistence-jpa` 의 `SpringTransaction`·`module-defaults/persistence-jpa.yml`, `adapter/inbound/web` 의 `JwtDecoderConfig`·`PageParams`·`PresentationWebConfig`·필터 4종, `composition/service-runtime` 의 `ManagementSecurityConfig`, `Dockerfile` JVM 옵션 |
|
||||
| 실행한 측정 | 아래 「측정 명령」 절. bootJar 빌드 1회, 기동 3~4회씩, SQL 수 세기, 부하 측정 약 45회(워밍업 포함), 설정만 바꾼 실험 3종, JFR 2회, 동시 중복 생성 실험 3회 |
|
||||
| 확인 못 한 것 | 아래 「미검증」 절 |
|
||||
| 게이트 결과 | 오케스트레이터 실행: `ci` rc=0. `mainCheck` rc=1 — `objectStorageMinioContractTest`·`objectStorageMinioFaultTest`가 `minio/minio` 이미지 pull 실패(공급원 소멸)로 실패. 이 영역의 숫자와 무관하다. |
|
||||
| 이전 리뷰와 비교 | 이전 리뷰에는 성능 실측 영역이 없었다. 성능 관련 지난 발견(05-persistence-jpa의 N+1·Hikari 항목)만 2절에서 재확인했다. 지난 리뷰의 실행 숫자는 쓰지 않았다. |
|
||||
|
||||
### 측정 조건
|
||||
|
||||
| 항목 | 값 |
|
||||
| --- | --- |
|
||||
| 하드웨어 | 22 vCPU, RAM 30 GiB, Linux 7.0.0. 다른 세션(프론트 vitest, 게이트)이 같은 머신에서 돌았다. |
|
||||
| JVM | OpenJDK 21.0.12.1, `-Xmx1g -XX:+ExitOnOutOfMemoryError`, G1 기본. 컨테이너가 아니라 호스트에서 `java -jar`로 띄웠다. Dockerfile의 `MaxRAMPercentage=75`는 호스트에서 22 GiB 힙이 되므로 1 GiB 컨테이너에 가까운 `-Xmx1g`를 골랐다. |
|
||||
| DB | `postgres:16-alpine`, 127.0.0.1:25432, `--cpus 4 --memory 1g`, 튜닝 없음 |
|
||||
| 데이터 | `work_log` 10,000행(행마다 `tech_stack` 2행, `link` 1행, `content` 500자). `poster`는 측정 중 쌓여 23,071행까지 늘었다. |
|
||||
| 부하 도구 | `wrk`·`hey`·`ab` 미설치. JDK `HttpClient`로 만든 닫힌 루프 생성기(`perf/Load.java`). 동시성 N개 스레드가 응답을 받자마자 다음 요청을 보낸다. 측정 시간의 앞 20%는 워밍업으로 버린다. 부하 생성기가 같은 호스트에서 돈다. |
|
||||
| 캐시 | 애플리케이션 캐시 없음(샘플 기본값 `disabled`). PG 버퍼 캐시는 워밍업 뒤 상태. |
|
||||
|
||||
### 측정 명령 (다시 돌리는 법)
|
||||
|
||||
스크립트는 모두 `<scratchpad>/perf/`에 두고 썼다. 핵심 명령만 옮긴다. 무거운 실행은 전부 `flock <heavy.lock>`으로 감쌌다.
|
||||
|
||||
```bash
|
||||
# 0) worktree와 jar
|
||||
git -C <repo> worktree add <scratchpad>/wt-09 01a8a2a70
|
||||
cd <scratchpad>/wt-09/src
|
||||
flock <heavy.lock> ./gradlew :app-bootstrap:bootJar :sample-portfolio:bootJar --console=plain -q
|
||||
|
||||
# 1) jar 구성
|
||||
unzip -l app-bootstrap/build/libs/app-bootstrap-0.0.1-SNAPSHOT.jar | awk '$4 ~ /BOOT-INF\/lib\/.*\.jar$/'
|
||||
|
||||
# 2) 기동 측정 (run-app.sh: 백그라운드 기동 → "Started ... in" 대기 → 3초 뒤 RSS·heap·빈 수·스레드 수)
|
||||
# 빈 수는 spring.jmx.enabled=true + management.endpoints.jmx.exposure.include=beans 로 켜고
|
||||
# Attach API로 Beans MBean을 부르는 Beans.java 로 셌다(코드 변경 없음).
|
||||
java -Xmx1g -XX:+ExitOnOutOfMemoryError -Dspring.jmx.enabled=true \
|
||||
-Dmanagement.endpoints.jmx.exposure.include=beans -jar <jar>
|
||||
awk '/VmRSS/{print $2}' /proc/<pid>/status ; jcmd <pid> GC.heap_info ; java Beans.java <pid>
|
||||
|
||||
# 기본 조합
|
||||
SPRING_PROFILES_ACTIVE=local MANAGEMENT_SERVER_PORT=19001 ./run-app.sh boot-N <app-bootstrap jar>
|
||||
# 샘플
|
||||
docker run -d --name perf09-pg -e POSTGRES_DB=ca_skeleton -e POSTGRES_USER=ca_skeleton \
|
||||
-e POSTGRES_PASSWORD=ca_skeleton -p 127.0.0.1:25432:5432 --cpus 4 --memory 1g postgres:16-alpine
|
||||
APP_DATASOURCE_URL=jdbc:postgresql://127.0.0.1:25432/ca_skeleton APP_SERVER_PORT=18081 \
|
||||
MANAGEMENT_SERVER_PORT=19002 SPRING_PROFILES_ACTIVE=local ./run-app.sh sample-N <sample jar>
|
||||
|
||||
# 3) 요청당 SQL 수: PG 쪽에서 모든 문장을 로그로 남기고, 요청 하나 전후의 로그 줄을 센다(앱 설정 변경 없음)
|
||||
docker exec perf09-pg psql -U ca_skeleton -d ca_skeleton -c "alter system set log_statement='all'"
|
||||
docker exec perf09-pg psql -U ca_skeleton -d ca_skeleton -c "select pg_reload_conf()"
|
||||
./sqlcount.sh list20 "http://localhost:18081/api/worklogs" # LOG: statement|execute 줄 수
|
||||
# 측정 뒤 log_statement='none' 으로 되돌리고 부하 측정
|
||||
|
||||
# 4) 부하: java Load.java <METHOD> <URL> <동시성> <초> [body.json]
|
||||
java -Xmx512m Load.java GET http://localhost:18081/api/worklogs/<id> 16 15
|
||||
|
||||
# 5) 설정만 바꾼 실험
|
||||
java ... -Dspring.jpa.properties.hibernate.default_batch_fetch_size=100 -jar <sample jar>
|
||||
SPRING_THREADS_VIRTUAL_ENABLED=true ./run-app.sh sample-vt <sample jar>
|
||||
|
||||
# 6) JFR (부하 중 20초)
|
||||
jcmd <pid> JFR.start name=p settings=profile filename=getone.jfr duration=20s
|
||||
jfr print --events jdk.ExecutionSample getone.jfr # 상위 프레임 집계
|
||||
```
|
||||
|
||||
### 미검증
|
||||
|
||||
| 항목 | 이유 |
|
||||
| --- | --- |
|
||||
| `POST /api/worklogs`(대표 쓰기)와 `POST /api/worklogs:batchCreate`의 SQL 수·지연 | 단독 실행한 샘플에서 이 경로가 항상 500으로 끝난다(09-03). 대신 같은 outbox 패턴을 쓰는 `POST /api/posters`를 쟀다. |
|
||||
| async-profiler 기반 CPU flame graph | `asprof` 미설치. JFR(`jdk.ExecutionSample`)로 대신했다. |
|
||||
| 컨테이너 안(cgroup 1 GiB) 기동 시간·RSS | 이미지 빌드는 이 영역 범위 밖이고 base image pull이 필요하다. 호스트 `-Xmx1g`로 근사했다. |
|
||||
| 장시간(수십 분) 메모리·커넥션 누적 | 측정 창이 회차당 15~20초다. 누수 판정 근거가 없다. |
|
||||
| Redis·Kafka·Mongo 등 capability를 켠 조합 | 기본 조합과 샘플만 쟀다. |
|
||||
| 실제 IdP를 거친 JWT 검증 비용 | 샘플은 모든 경로를 `permitAll`로 연다. 기본 조합에는 JWT로 보호된 업무 엔드포인트가 없다. 토큰 없는 401 경로만 쟀다. |
|
||||
|
||||
## 2. 지난 발견 재확인
|
||||
|
||||
| ID (출처) | 내용 | 상태 | 근거 |
|
||||
| --- | --- | --- | --- |
|
||||
| 05-persistence-jpa 「N+1 구조적으로 불가」 | persistence-jpa leaf에 연관관계가 없어 N+1이 없다 | 바뀜 | leaf 안에서는 여전히 사실이다. 그러나 템플릿이 따라 하라고 내놓은 `sample-portfolio`의 목록 API가 N+1이다(09-01). 실측 SQL 46개/페이지(20건). |
|
||||
| 05-persistence-jpa M8 | `HibernateEnversHistoryReader.revisions`가 1+N | 해결 | `adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/envers/HibernateEnversHistoryReader.java:82` — 리비전 번호를 한 번에 읽고, 리비전별 `find()` 루프가 없다. |
|
||||
| 05-persistence-jpa H6 | 트랜잭션 포트가 `HikariDataSource`로 언랩을 강제 | 해결 | `persistence-jpa/src/main` 아래 `HikariDataSource` 참조 0건(grep). |
|
||||
| 05-persistence-jpa 「풀 env 조정 부분」 | `keepalive-time`·`leak-detection-threshold`·`validation-timeout`이 env 없이 하드코딩 | 남음 | `adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml:55,63,72`. 주석이 여전히 "UNSUPPORTED_IMPL_DECISION … delegated"라고 적는다. 성능 결함은 아니다. |
|
||||
| maintainability-review #16 | hikari `connection-timeout` 주석이 이력 서술 | 남음(Low) | `persistence-jpa.yml:28-38`. 같은 키를 샘플은 30000으로 덮는다(09-08). |
|
||||
|
||||
## 3. 측정 결과
|
||||
|
||||
### 3.1 아티팩트와 기동
|
||||
|
||||
| 항목 | 기본 조합 `app-bootstrap` | `sample-portfolio` |
|
||||
| --- | --- | --- |
|
||||
| bootJar 크기 | 41.4 MB | 99.0 MB |
|
||||
| `BOOT-INF/lib` jar 수 / 합계 | 114개 / 39.2 MiB | 203개 / 93.9 MiB |
|
||||
| 큰 의존성 | tomcat-embed-core 3.6 MB, spring-web 2.2, prometheus exposition 2.1, spring-security-config 2.1, **jackson-databind 3.1.5 1.9 + jackson-databind 2.21.5 1.7**, **kotlin-stdlib 1.8**(OTLP okhttp sender) | hibernate-core 14.5 MB, byte-buddy 9.0, s3 3.8, **h2 2.7**, aspectjweaver 2.2, netty 13개 |
|
||||
| 기동 `Started ... in` (3회) | 3.637 / 3.179 / 3.435 s → **중앙값 3.44 s** (4번째 회차 3.592) | 8.596(첫 회, Flyway 23개 적용) / 8.045 / 7.662 s → **중앙값 8.05 s** (VT 회차 7.607) |
|
||||
| JVM 시작부터 (`process running for`) | 3.55~4.07 s | 8.13~9.09 s |
|
||||
| 기동 3초 뒤 RSS | 499~512 MB | 511~558 MB |
|
||||
| heap used / Metaspace used | 109~115 MB / 55 MB | 98~112 MB / 106 MB |
|
||||
| 스프링 빈 수 | **407** | **603** |
|
||||
| 스레드 수 | 55~59 (VT 기본 on) | 79~81 (VT 기본 off) |
|
||||
| 직전 load average | 7.2~9.0 | 7.4~7.8 |
|
||||
|
||||
뒤 회차(3.4절 실험)에서 같은 샘플 jar는 load avg 4.7~19 사이에서 6.47~6.84 s(7회)로 떴다. 기동 시간은 머신 부하에 따라 ±20% 움직인다. 기본 조합은 마지막 회차에서도 3.436 s였다.
|
||||
|
||||
샘플 기동 로그에서 0.25초 넘는 공백은 다섯 곳이다(2회차): Spring Data 저장소 스캔 0.76 s, Tomcat 초기화 1.13 s, JPA 0.53 s, Hibernate 부팅 0.89 s, 나머지 빈 생성부터 Flyway 연결까지 2.34 s. 한 곳이 지배하지 않는다. 기동 시간은 템플릿 규모(빈 600개)에 비례하는 일반적인 값이다. 결함으로 보지 않는다.
|
||||
|
||||
### 3.2 요청당 SQL 수 (PG 문장 로그, 1회 요청)
|
||||
|
||||
| 요청 | SQL 문장 수 | 내역 |
|
||||
| --- | --- | --- |
|
||||
| `GET /api/worklogs` (size 20) | **46** | `SHOW TRANSACTION ISOLATION LEVEL` 1, `BEGIN READ ONLY` 1, 본문 select 1, `count(*)` 1, **tech_stack select 20, link select 20**, COMMIT 1, 빈 validation 1 |
|
||||
| `GET /api/worklogs?size=100&sort=periodStart,desc` | **206** | 위와 같고 lazy select가 200 |
|
||||
| `GET /api/worklogs?category=BACKEND` | 46 | 같은 모양 |
|
||||
| `GET /api/worklogs?page=490` (offset 9,800) | 46 | 같은 모양 |
|
||||
| `GET /api/worklogs/{id}` | 7 | SHOW 1, BEGIN 1, select 1, lazy 2, COMMIT 1, 빈 validation 1 |
|
||||
| `PATCH /api/worklogs/{id}` (title만) | 13 | select 3 + update 1 + **link delete 1·insert 1 + tech_stack delete 1·insert 2** + SHOW/BEGIN/COMMIT |
|
||||
| `DELETE /api/worklogs/{id}` | 9 | `count(*)`(existsById) + select + 컬렉션 delete 2 + 본문 delete |
|
||||
| `POST /api/posters` | 7 | SHOW, BEGIN, `upper(title)=upper(?)` 검사, insert poster, insert outbox_event, COMMIT |
|
||||
| `GET /api/posters` | 5 | |
|
||||
|
||||
동시 8개로 `GET /api/worklogs/{id}` 50회를 보낸 묶음에서도 `SHOW TRANSACTION ISOLATION LEVEL`은 정확히 50회였다. 즉 트랜잭션마다 1회다(09-05).
|
||||
|
||||
### 3.3 지연·처리량 (플랫폼 스레드, 샘플 기본값)
|
||||
|
||||
동시성 16, 15초(앞 3초 버림), 3회 중앙값. 모든 회차 오류 0, 상태 코드 전부 200/201.
|
||||
|
||||
| 요청 | rps (3회) | 중앙값 rps | p50 | p95 | p99 | load avg |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| `GET /api/worklogs/{id}` | 5348 / 5521 / 5954 | **5521** | 2.70 ms | 4.29 ms | 5.93 ms | 8.6~15.5 |
|
||||
| `GET /api/worklogs` (20건) | 806 / 837 / 829 | **829** | 15.54 ms | 38.88 ms | 41.22 ms | 16.9~17.9 (부하 높음) |
|
||||
| `GET /api/worklogs?size=100` | 174 / 171 / 185 | **174** | 94.70 ms | 108.17 ms | 134.79 ms | 10.9~16.4 |
|
||||
| `POST /api/posters` | 671 / 373 / 432 | **432** | 22.55 ms | 70.22 ms | 74.11 ms | 8.3~10.7 |
|
||||
|
||||
동시성 64:
|
||||
|
||||
| 요청 | 스레드 | 중앙값 rps | p50 | p95 | p99 | load avg |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| `GET /api/worklogs/{id}` | 플랫폼 | 5418 | 11.13 ms | 22.51 ms | 31.51 ms | 5.4~13.3 |
|
||||
| `GET /api/worklogs/{id}` | 가상(`SPRING_THREADS_VIRTUAL_ENABLED=true`) | 5325 | 11.55 ms | 19.97 ms | 24.60 ms | 19.0~22.4 (부하 높음) |
|
||||
|
||||
가상 스레드 동시성 16: `GET /{id}` 5702 rps(p50 2.71 ms), `GET /worklogs` 738 rps(3회 중 1회가 334 rps로 튐, load 23~25, 부하 높음 — 비교에 쓰지 않는다).
|
||||
|
||||
Hikari 지표(플랫폼 인스턴스, 동시 16·64 회차 누적): `hikaricp_connections_acquire_seconds` 평균 5.5 ms(2946 s / 536,852회), 최대 106 ms, `pending` 0, `timeout_total` 0, `max` 10.
|
||||
|
||||
읽는 법:
|
||||
|
||||
- 단건 조회는 동시 16과 64에서 처리량이 같다(5.4~5.5k rps). 동시성을 4배로 올리면 p50만 4배가 된다. 병목은 앱 스레드가 아니라 커넥션 10개와 DB 왕복이다. 그래서 가상 스레드를 켜도 처리량이 변하지 않았다.
|
||||
- 목록 20건은 단건보다 **처리량이 6.7배 낮다**. SQL 문장 수는 7 → 46으로 6.6배다. 숫자가 거의 같다. 목록 비용의 대부분이 N+1 왕복이다.
|
||||
- 목록 100건은 20건보다 처리량이 4.8배 낮다. SQL은 46 → 206으로 4.5배다. 페이지 크기에 선형이다.
|
||||
- `POST /api/posters` 처리량은 회차마다 떨어졌다(671 → 373 → 432). 같은 회차 동안 `poster` 행이 늘었다. 제목 중복 검사가 순차 스캔이라 행 수에 비례해 느려진다(09-02).
|
||||
|
||||
### 3.4 설정만 바꾼 실험
|
||||
|
||||
코드는 바꾸지 않았다. JVM 시스템 프로퍼티만 바꿨다.
|
||||
|
||||
**(a) `hibernate.default_batch_fetch_size=100`** (`-Dspring.jpa.properties.hibernate.default_batch_fetch_size=100`). 이 키는 `persistence-jpa.yml:150`에 env(`APP_JPA_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE`)로 이미 열려 있고 기본값이 0이다.
|
||||
|
||||
| 요청 | SQL 수 (기본 → 실험) | rps (3회, 실험) | 중앙값 rps (기본 → 실험) | p50 (기본 → 실험) | p95 | load avg |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| `GET /api/worklogs` (20건) | 46 → **8** | 2371 / 2415 / 2411 | 829 → **2411 (2.9배)** | 15.54 → 4.27 ms | 38.88 → 38.10 ms | 8.2~9.5 |
|
||||
| `GET /api/worklogs?size=100` | 206 → **8** | 465 / 530 / 527 | 174 → **527 (3.0배)** | 94.70 → 16.10 ms | 108.17 → 69.88 ms | 6.2~8.6 |
|
||||
| `GET /api/worklogs/{id}` | 7 → 7 | — | — | — | — | — |
|
||||
|
||||
같은 세션(load 12.7)에서 기본 설정으로 다시 잰 목록 20건은 847 rps, p50 15.42 ms였다. 위 「기본」 값과 같은 수준이다.
|
||||
|
||||
목록 20건의 p95(약 38 ms)와 p99(약 41 ms)는 SQL을 46 → 8로 줄여도 그대로였다. p50만 줄었다. 이 꼬리는 DB 왕복이 아닌 다른 원인이다. 응답이 큰 요청(목록)에서만 보이고 작은 응답(단건 p95 3~4 ms)에서는 보이지 않는다. TCP delayed ACK(리눅스 기본 40 ms)와 응답 분할 쓰기의 상호작용이 의심되지만 확인하지 않았다(미검증, 「다음 측정 후보」).
|
||||
|
||||
**(b) 관측(observation) 비용 A/B** — `management.observations.enable.spring.security=false` + `management.metrics.data.repository.autotime.enabled=false`. 끄면 `spring_security_*` 시계열 26개와 `spring_data_repository_*` 6개가 사라지는 것을 `/actuator/prometheus`로 확인했다. `GET /api/worklogs/{id}`, 동시 16, 15초, A·B를 번갈아 2회씩 두 묶음(A, B, A2, B2).
|
||||
|
||||
| 변형 | rps (4회) | 중앙값 | p50 | p95 | load avg |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| A 기본(관측 켬) | 6620 / 6512 / 6588 / 6700 | 6604 | 2.30~2.36 ms | 3.10~3.24 ms | 10.4~19.2 |
|
||||
| B 관측 끔 | 6755 / 6787 / 6849 / 7094 | 6818 (+3.2%) | 2.17~2.26 ms | 2.90~3.15 ms | 14.9~18.3 (부하 높음) |
|
||||
|
||||
차이는 3% 수준이다. 이 경로는 CPU가 아니라 커넥션·DB 왕복이 병목이라, 관측 비용은 처리량에 작게 나타난다. 결함으로 올리지 않았다. 다만 JFR에서 Micrometer 프레임이 CPU 표본의 16%를 차지했으므로(3.5절), CPU가 병목인 서비스에서는 더 크게 보일 수 있다.
|
||||
|
||||
**(c) 가상 스레드** — 3.3절. 처리량 차이 없음.
|
||||
|
||||
**(d) 기본 조합의 필터 체인 바닥값** — `app-bootstrap`, `local`, 공개 경로 `GET /api/healthcheck`와 토큰 없는 보호 경로(401). 동시 16, 15초, 3회. 이 수치가 「DB 없이 보안·관측·로깅 필터만 지나는 요청」의 비용이다.
|
||||
|
||||
| 요청 | rps (3회) | 중앙값 | p50 | p95 | p99 | load avg |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| `GET /api/healthcheck` → 200 | 26521 / 27276 / 27130 | **27130** | 0.51 ms | 0.91 ms | 1.40 ms | 10.2~14.8 |
|
||||
| `GET /api/anything` 토큰 없음 → 401 | 26291 / 26670 / 26690 | **26670** | 0.52 ms | 0.95 ms | 1.42 ms | 15.3~16.3 (부하 높음) |
|
||||
|
||||
필터 체인 자체의 비용은 요청당 0.5 ms 안팎이다. 샘플 단건 조회(2.7 ms)의 대부분은 DB 쪽이다.
|
||||
|
||||
### 3.5 요청당 CPU (JFR)
|
||||
|
||||
`settings=profile`, 15초, 동시 16, 샘플 기본 설정(플랫폼 스레드). 같은 회차 처리량: 단건 4801 rps, 목록 20건 847 rps(load 9.6~12.7). JFR은 스택을 64프레임에서 자르므로 「스택에 포함」 비율은 바깥 프레임(Tomcat, 필터) 쪽이 실제보다 낮게 나온다.
|
||||
|
||||
| 요청 | 표본 수 | 스택에 포함된 비율 (상위) | 잎 프레임 소유자 (상위) |
|
||||
| --- | --- | --- | --- |
|
||||
| `GET /api/worklogs/{id}` | 2146 | Tomcat 21%, **Micrometer 16%**, Spring MVC 14%, Hibernate 14%, Spring Security 9%, pgjdbc 6%, logback 5%, 앱 코드 4%, Jackson 3%, Hikari 3% | Tomcat 20%, Micrometer 16%, JDK 14%, Hibernate 12% |
|
||||
| `GET /api/worklogs` (20건) | 682 | **Hibernate 31%**, Micrometer 11%, Tomcat 10%, pgjdbc 9%, 앱 코드 7%, logback 6%, Jackson 5% | Hibernate 29%, JDK 12%, Tomcat 10% |
|
||||
|
||||
- 목록에서는 Hibernate가 CPU의 1/3이다. lazy 컬렉션 40개를 초기화하고 바인딩하는 비용이다(09-01).
|
||||
- 단건에서 Micrometer가 16%다. 가장 바깥 Micrometer 프레임은 `Meter$Id.equals`, `KeyValues.of`, `SimpleObservation.start/stop`, `MetricsTurboFilter.decide`(logback 이벤트마다 카운터)였다. Spring Security의 `ObservationFilterChainDecorator`가 보안 필터마다 observation을 열고 닫는 것이 보였다. (b)의 A/B에서 이 둘을 끄면 처리량이 3% 올랐다.
|
||||
- 앱 필터(`WebMvcRequestIdFilter`, `RequestLoggingFilter`, `CacheControlFilter`, `JsonBodyLimitFilter`)는 합쳐 2% 이하였다. 요청 본문을 통째로 버퍼링하는 필터는 없다(`JsonBodyLimitFilter`는 스트림을 감싼다).
|
||||
- 직렬화(Jackson) 비용은 3~5%로 작다.
|
||||
|
||||
로그량: 샘플은 요청마다 `RequestLoggingFilter`가 INFO 한 줄을 쓴다. 약 53.7만 요청에 콘솔 로그 112 MB(요청당 약 210 B)였다. 운영에서 로그 수집 비용으로 그대로 이어진다. 비용 기록이지 결함은 아니다.
|
||||
|
||||
## 4. 새 발견
|
||||
|
||||
요약: High 2, Medium 4, Low 5. P1 2, P2 4, P3 5. 경로는 모두 `src/` 기준이고 샘플 패키지 접두사 `sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/`는 `<S>/`로 줄였다.
|
||||
|
||||
| ID | 제목 | 성격 | 심각도·우선순위 | 다른 영역 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 09-01 | 샘플 목록 API가 N+1 — 페이지 20건에 SQL 46개 | 확인된 결함 | Medium · P2 | > 04 persistence, 01 feature pattern |
|
||||
| 09-02 | 포스터 제목 중복 규칙이 동시 요청에서 깨지고, 검사 쿼리가 순차 스캔 | 확인된 결함 | **High · P1** | > 04 persistence |
|
||||
| 09-03 | 단독 실행한 샘플에서 대표 쓰기 `POST /api/worklogs`가 항상 500 | 확인된 결함 | **High · P1** | > 07 bootstrap/sample, 02 inbound-web |
|
||||
| 09-04 | 단독 실행한 샘플에서 `/api/v3/api-docs`가 500 | 확인된 결함 | Medium · P2 | > 02 inbound-web |
|
||||
| 09-05 | 트랜잭션마다 `SHOW TRANSACTION ISOLATION LEVEL` 왕복 1회 | 확인된 결함(비용) | Low · P3 | > 04 persistence |
|
||||
| 09-06 | 제목 하나 고치는 PATCH가 컬렉션 테이블을 전부 지우고 다시 넣음 | 확인된 결함(비용) | Medium · P2 | > 04 persistence |
|
||||
| 09-07 | JDBC batch 기본 꺼짐 + 동기 `batchCreate` 1000건을 한 트랜잭션에서 처리 | 구조적 위험(미측정) | Medium · P2 | > 04 persistence |
|
||||
| 09-08 | 샘플의 런타임 기본값이 기본 조합과 다름(가상 스레드·풀 대기·로그 레벨) | 확인된 결함(일관성) | Low · P3 | > 07 bootstrap |
|
||||
| 09-09 | persistence-jpa가 H2 드라이버를 운영 아티팩트에 실어 보냄 | 개선 제안 | Low · P3 | > 04 persistence, 08 build |
|
||||
| 09-10 | `local` 프로필이 `server.port`를 8080으로 고정해 `APP_SERVER_PORT`를 무시 | 확인된 결함(DX) | Low · P3 | > 07 bootstrap |
|
||||
| 09-11 | 기본 조합 jar에 Jackson 2·3과 kotlin-stdlib가 함께 실림 | 개선 제안 | Low · P3 | > 08 build |
|
||||
|
||||
### 09-01. 샘플 목록 API가 N+1 — 페이지 20건에 SQL 46개
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 14 성능, 13 확장성, 5 위험 가시성, 23 일관성, 9 유지보수 |
|
||||
| 근거 | `<S>/adapter/outbound/persistence/repository/WorkLogRepositoryAdapter.java:79-80` — `findAll(pageRequest)` 뒤 `WorkLogPersistenceMapper::toDomain`. `<S>/adapter/outbound/persistence/mapper/WorkLogPersistenceMapper.java:50-51` — `getTechStack()`·`getLinks()`로 lazy 컬렉션 두 개를 건드린다. `<S>/adapter/outbound/persistence/entity/WorkLogEntity.java:52-60` — 두 `@ElementCollection(fetch = LAZY)`. 응답은 요약형인데(`WorkLogWebMapper.toSummary` — id·title·category·status·period만) 엔티티 전체(`content` 최대 10,000자 포함)와 컬렉션을 다 읽는다. 같은 모듈에 요약 전용 projection(`WorkLogJpaRepository.findRecentSummaryRows`, `WorkLogSummaryQueryPort`, `ListRecentWorkLogSummariesUseCase`)이 있지만 HTTP 목록은 그 길을 쓰지 않는다. `persistence-jpa.yml:150`의 `default_batch_fetch_size` 기본값은 0이다. |
|
||||
| 실행 결과 | PG 문장 로그: size 20 → 46문장, size 100 → 206문장(= 2N + 6). 처리량: 단건 5521 rps vs 목록 20건 829 rps vs 100건 174 rps. JFR: 목록 CPU의 31%가 Hibernate. 설정 한 줄(`default_batch_fetch_size=100`)로 8문장, 2411 rps(2.9배)·527 rps(3.0배). |
|
||||
| 발생 조건 | 목록 호출마다. 페이지 크기에 선형. 데이터 총량과는 무관(offset 9,800도 46문장). 상한 100이 있어 무한히 커지지는 않는다(`PageParams.MAX_SIZE`). |
|
||||
| 영향 | 같은 커넥션 풀(10개)에서 목록 처리량이 단건의 1/7로 떨어진다. 목록과 다른 요청이 섞이면 목록이 커넥션을 오래 잡아 다른 요청의 대기도 늘어난다. 템플릿을 복사한 서비스가 이 모양(`@ElementCollection` + 엔티티 전체 매핑 + 요약 응답)을 그대로 가져간다. |
|
||||
| 심각도·우선순위 | Medium · P2. 페이지 상한이 있어 자원 고갈로 번지지 않는다. 다만 샘플이 「따라 할 기준」이므로 복제 범위가 넓다. |
|
||||
| 확실성 | 직접 측정. 남은 가정 없음. |
|
||||
| 결정의 근거 | 기록된 의도: 엔티티 주석은 "CQRS-lite projection read … skipping aggregate hydration and lazy @ElementCollection joins"(`WorkLogJpaRepository.java:19-21`)라고 적는다. 즉 팀은 이 비용을 알고 projection을 만들었다. 그런데 HTTP 목록이 그 projection을 쓰지 않는다. 위험이 코드에 드러나지 않고 「어느 쿼리 경로를 쓰는지」를 기억해야 하는 상태다. |
|
||||
| 최소 개선 방향 | 목록 use case가 요약 projection을 쓰게 한다(필터·정렬·count를 projection 쿼리에 추가). |
|
||||
| 대안 비교 | (1) 현상 유지 — 비용 그대로. (2) `default_batch_fetch_size` 기본값을 50~100으로 — 한 줄, 모든 lazy 로딩이 IN 쿼리로 묶임(46 → 8 확인). 하지만 응답에 필요 없는 `content`와 컬렉션을 여전히 읽는다. (3) **요약 projection 사용**(고른 방법) — 응답에 필요한 열만 읽는다. SQL 3~4개(+count), 컬렉션 0. 이미 있는 코드를 재사용한다. (4) `@EntityGraph`/`join fetch` — 컬렉션 2개를 동시에 fetch join하면 곱집합과 페이지네이션 경고(HHH90003004)가 생긴다. 기각. 권장: (3)을 샘플에 적용하고, (2)를 persistence-jpa 기본값으로 켤지는 04 영역이 따로 판단한다. |
|
||||
| 단순화의 보존 조건 | 응답 JSON 모양(`WorkLogSummaryResponse`), `meta.page.total`, 정렬 허용 필드(`WorkLogWebMapper.SORT_FIELDS`), 카테고리 필터, 400 `SIZE_EXCEEDS_MAX`는 그대로여야 한다. OpenAPI 스냅샷이 바뀌지 않아야 한다. |
|
||||
| 비용·부작용 | projection 쿼리에 정렬·필터를 추가하는 코드 20~40줄. 도메인 `WorkLog`를 목록에 쓰지 않게 되므로 목록과 상세의 모델이 갈린다(이미 응답은 갈려 있다). |
|
||||
| 재검토 조건 | 목록 응답이 techStack·links를 포함하게 되면 (2) 또는 별도 IN 쿼리로 다시 비교한다. |
|
||||
| 완료 기준 | `GET /api/worklogs?size=100`의 SQL 문장 수가 페이지 크기와 무관한 상수(≤ 6)다. |
|
||||
| 검증 방법 | Testcontainers 통합 테스트에서 Hibernate statistics(`prepareStatementCount`)로 size 20과 100의 문장 수가 같은지 단언한다. 이 문서의 `sqlcount.sh` 절차로 재측정한다. |
|
||||
|
||||
### 09-02. 포스터 제목 중복 규칙이 동시 요청에서 깨지고, 검사 쿼리가 순차 스캔
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 12 동시성, 11 데이터, 14 성능, 5 위험 가시성, 21 Guardrail |
|
||||
| 근거 | `<S>/application/poster/CreatePosterUseCase.java:47-51` — 같은 트랜잭션 안에서 `existsByTitle` 확인 후 insert. `<S>/adapter/outbound/persistence/repository/PosterRepositoryAdapter.java:89-90` → `existsByTitleIgnoreCase` → SQL `where upper(title)=upper(?)`. `sample-portfolio/src/main/resources/db/sample-migration/V7__poster.sql:31` — `CREATE INDEX ix_poster_title ON poster (title)`: 유일 제약이 없고, `upper(title)` 식에는 쓸 수 없는 인덱스다. |
|
||||
| 실행 결과 | (a) 같은 제목으로 동시 16개 `POST /api/posters`를 3번: 응답 201 30개·409 18개, DB에는 제목마다 **10행**(`race-1`·`race-2`·`race-3` 각 10). (b) `EXPLAIN ANALYZE`: 23,071행에서 `Seq Scan on poster … Rows Removed by Filter: 23071`, 7.2 ms. (c) `POST /api/posters` 처리량이 행이 쌓이는 동안 671 → 373 → 432 rps로 떨어졌다. |
|
||||
| 발생 조건 | (a) 같은 제목 생성이 겹치면 READ COMMITTED에서 두 트랜잭션 모두 「없음」을 본다. 더블 클릭·재시도만으로 발생한다. (b) 생성 요청마다 테이블 전체를 읽는다. |
|
||||
| 영향 | 409 `POSTER_ALREADY_EXISTS`로 약속한 규칙이 지켜지지 않는다. 중복 행 각각에 `outbox_event`도 생긴다(같은 트랜잭션에서 append). 템플릿이 31절의 「중복·동시 요청」 시나리오를 보여 주는 바로 그 자리에서 잘못된 패턴(DB 제약 없는 check-then-insert)을 가르친다. 생성 비용이 행 수에 비례해 커진다. |
|
||||
| 심각도·우선순위 | High · P1. 계약 위반을 재현했다. 샘플이 복제 기준이므로 파생 서비스로 퍼진다. 샘플 안에서만 보면 Medium이지만 템플릿의 대표 예제라는 점에서 올렸다. |
|
||||
| 확실성 | 직접 재현. 다중 인스턴스가 아니라 단일 인스턴스에서도 재현된다. |
|
||||
| 결정의 근거 | 적용 제외 — 가이드 31절이 「DB 유일성 제약과 충돌 처리가 충분한지 먼저 본다」고 정한 경우이고, 다른 선택지(락·직렬화 격리)는 그보다 비싸다. |
|
||||
| 최소 개선 방향 | 마이그레이션 V9: `CREATE UNIQUE INDEX uq_poster_title_ci ON poster (upper(title))`(또는 `lower`). 어댑터가 유일 제약 위반(SQLSTATE 23505, 제약 이름)을 `PosterTitleAlreadyExistsException`으로 바꾼다. 사전 `exists` 검사는 빠른 실패용으로 남겨도 되고 빼도 된다. 같은 인덱스가 순차 스캔도 없앤다. 기존 `ix_poster_title`은 쓰는 곳을 확인한 뒤 정리한다. |
|
||||
| 완료 기준 | 같은 제목 동시 16개 생성에서 201이 정확히 1개, 나머지는 409이고 DB에 1행. `EXPLAIN`이 인덱스 스캔이다. |
|
||||
| 검증 방법 | Testcontainers PostgreSQL에서 `CountDownLatch`로 동시 생성 테스트. 마이그레이션 테스트에 기존 중복 데이터가 있을 때의 처리(실패 메시지)를 넣는다. |
|
||||
|
||||
### 09-03. 단독 실행한 샘플에서 대표 쓰기 `POST /api/worklogs`가 항상 500
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함 |
|
||||
| 관련 관점 | 6 실패, 17 API 계약, 20 개발자 경험, 10 테스트, 8 디버깅 |
|
||||
| 근거 | `<S>/bootstrap/security/SamplePublicAccessSecurityConfig.java:24-27` — `securityMatcher("/**")` + `anyRequest().permitAll()`, `@Order(-100)`. 이 체인에는 resource server가 없어 Bearer 토큰도 읽지 않는다. `<S>/adapter/inbound/web/controller/WorkLogController.java:221-228` — 인증 주체가 없으면 owner `null`. `<S>/domain/worklog/WorkLogOwner.java:10` — `requireNonNull(value, "owner is required")` → `NullPointerException` → `GlobalExceptionHandler`가 500 `INTERNAL_ERROR`. 같은 이유로 `POST /api/worklogs:batchCreate`(`WorkLogController.java:167`)도 같다. |
|
||||
| 실행 결과 | `java -jar sample-portfolio.jar` + PostgreSQL에서 README 예시 본문으로 `POST /api/worklogs` → 500, 로그 `java.lang.NullPointerException: owner is required at WorkLogOwner.of(WorkLogOwner.java:10)`. 시스템 테스트(`systemTest`, `webSystemTest`)에는 이 경로를 실제 서버로 부르는 테스트가 없다(grep). |
|
||||
| 발생 조건 | `Dockerfile.sample`로 만든 데모 이미지와 `bootRun`처럼 샘플을 단독으로 띄우는 모든 경우. |
|
||||
| 영향 | 샘플의 대표 쓰기 흐름(검증·outbox·멱등성 시연)을 실제로 실행해 볼 수 없다. 인증 부재가 401이 아니라 500으로 보여 원인을 찾기 어렵다. README의 curl 예시는 경로도 틀렸다(`sample-portfolio/README.md:11,26,37,48`의 `/work-logs`, 실제 경로는 `/api/worklogs`). |
|
||||
| 심각도·우선순위 | High · P1. 템플릿이 배포 가능한 데모(`Dockerfile.sample`)로 내놓은 구성에서 대표 기능이 실패한다. 데이터 피해는 없다. |
|
||||
| 확실성 | 직접 재현. |
|
||||
| 결정의 근거 | 적용 제외 — 기대 동작(인증 없으면 401, 또는 데모용 고정 owner)이 둘 중 하나로 정해지기만 하면 되는 단순 결함이다. 어느 쪽을 고를지는 07 영역·소유자 판단이다. |
|
||||
| 최소 개선 방향 | 둘 중 하나. (1) 샘플 공개 체인이 쓰기 메서드는 JWT를 요구하도록 바꾸고 인증 없음을 401로 돌려준다. (2) 데모 프로필에서만 고정 owner(`demo`)를 넣는 `AuditContextPort`/owner 공급자를 둔다. 어느 쪽이든 owner 누락은 500이 아니라 4xx로 변환한다. README 경로를 고친다. |
|
||||
| 완료 기준 | 단독 실행한 샘플에서 README의 curl이 그대로 성공(또는 문서화된 401)한다. |
|
||||
| 검증 방법 | `webSystemTest`에 실제 서버로 `POST /api/worklogs`를 부르는 테스트를 하나 추가한다. |
|
||||
|
||||
### 09-04. 단독 실행한 샘플에서 `/api/v3/api-docs`가 500
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(원인은 추론) |
|
||||
| 관련 관점 | 17 API 계약, 10 테스트, 20 개발자 경험 |
|
||||
| 근거 | 실행 결과: `GET /v3/api-docs` → 404 `ROUTE_NOT_FOUND`, `GET /api/v3/api-docs` → 500, 로그 `ClassCastException: class dev.caskeleton.shared.response.Envelope cannot be cast to class [B`. `adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/config/PresentationWebConfig.java:24-25`가 springdoc 컨트롤러에도 `/api` 접두사를 붙인다. `adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java:26-49`는 모든 컨트롤러에 적용되고, JSON 응답이면 `Envelope`로 감싼다. springdoc은 `byte[]`를 JSON 타입으로 돌려주므로 `ByteArrayHttpMessageConverter`가 `Envelope`를 받는다(추론). 스냅샷 테스트(`OpenApiSnapshotTest.java:43-51`)는 별도 슬라이스 앱으로 `/v3/api-docs`를 불러 이 조합을 보지 않는다. |
|
||||
| 영향 | 실제로 띄운 샘플에서 OpenAPI 문서를 받을 수 없다. 계약 스냅샷 테스트는 통과하므로 게이트는 초록이다. |
|
||||
| 심각도·우선순위 | Medium · P2. |
|
||||
| 결정의 근거 | 적용 제외 — 단순 결함. |
|
||||
| 최소 개선 방향 | `EnvelopeBodyAdvice.supports`가 `byte[]`/`String`/springdoc 컨트롤러를 제외하거나, springdoc 컨트롤러에 `@OwnsAbsoluteWebRoute` 같은 접두사 예외를 준다. |
|
||||
| 완료 기준·검증 | 전체 샘플 조합(`SamplePortfolioApplication`)을 띄우는 테스트에서 OpenAPI 문서 경로가 200이다. |
|
||||
|
||||
### 09-05. 트랜잭션마다 `SHOW TRANSACTION ISOLATION LEVEL` 왕복 1회
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(비용) |
|
||||
| 관련 관점 | 14 성능, 22 추상화 |
|
||||
| 근거 | `adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java:93` — 모든 템플릿에 `ISOLATION_READ_COMMITTED`를 명시. 기본값이 아닌 격리 수준이 지정되면 Spring이 트랜잭션 시작 때 `Connection.getTransactionIsolation()`을 부르고, pgjdbc는 이를 매번 서버 왕복(`SHOW TRANSACTION ISOLATION LEVEL`)으로 처리한다. |
|
||||
| 실행 결과 | 동시 8개 단건 조회 50회 → `SHOW TRANSACTION ISOLATION LEVEL` 정확히 50회. 단건 조회 1회의 DB 왕복 6개 중 1개다. |
|
||||
| 영향 | 모든 트랜잭션에 왕복 1회(로컬 DB에서 수십~수백 µs, 원격 DB면 RTT 1회)가 붙는다. 단건 조회 기준 DB 왕복의 약 17%. PostgreSQL 기본 격리 수준이 이미 READ COMMITTED이므로 얻는 것이 없다. |
|
||||
| 심각도·우선순위 | Low · P3. |
|
||||
| 결정의 근거 | 기록된 의도: "all pinned to READ_COMMITTED"(`SpringTransaction.java` 클래스 주석). DB 기본값이 바뀌어도 격리 수준이 흔들리지 않게 하려는 고정으로 읽힌다(추론). |
|
||||
| 대안 비교 | (1) 현상 유지 — 의도는 코드에 드러나지만 왕복 비용. (2) `ISOLATION_DEFAULT` + Hikari `transaction-isolation: TRANSACTION_READ_COMMITTED` — 커넥션을 만들 때 한 번만 설정, 트랜잭션마다 왕복 없음. 풀 설정이 격리 수준을 소유하게 되어 의도가 설정 파일로 옮겨간다. (3) `ISOLATION_DEFAULT` + 기동 시 `SHOW default_transaction_isolation` 검사 — 검사는 1회. 권장 (2). |
|
||||
| 단순화의 보존 조건 | 모든 `TransactionPort` 경로가 READ COMMITTED로 도는 것. `inNew` 30초 타임아웃과 읽기 전용 플래그는 그대로. |
|
||||
| 재검토 조건 | 모드별로 다른 격리 수준(예: 일부 쓰기에 REPEATABLE READ)이 필요해지면 (1)이 맞다. |
|
||||
| 완료 기준·검증 | PG 문장 로그(또는 `pg_stat_statements`)에서 단건 조회 1회당 `SHOW TRANSACTION ISOLATION LEVEL` 0회, 그리고 트랜잭션 안에서 `SHOW transaction_isolation`이 `read committed`인 통합 테스트. |
|
||||
|
||||
### 09-06. 제목 하나 고치는 PATCH가 컬렉션 테이블을 전부 지우고 다시 넣음
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(비용) |
|
||||
| 관련 관점 | 14 성능, 11 데이터, 12 동시성 |
|
||||
| 근거 | `<S>/adapter/outbound/persistence/repository/WorkLogRepositoryAdapter.java` `save` — 도메인 객체에서 새 엔티티를 만들고(`WorkLogPersistenceMapper.toEntity`) `jpa.save`(merge)한다. 새 `List` 인스턴스가 들어가므로 Hibernate가 컬렉션 전체를 교체로 본다. |
|
||||
| 실행 결과 | `PATCH {"title":"patched2"}` 1회 = 13문장: select 3, update 1, `delete from work_log_link` 1 + insert 1, `delete from work_log_tech_stack` 1 + insert 2. |
|
||||
| 영향 | 바뀌지 않은 자식 행도 매번 삭제·삽입된다. WAL·인덱스 갱신·락 범위가 커진다. 자식 행이 많을수록 커진다(행 수에 선형). 감사·CDC를 붙이면 가짜 변경 이벤트가 생긴다. |
|
||||
| 심각도·우선순위 | Medium · P2. |
|
||||
| 결정의 근거 | 기록된 의도: 도메인에 감사 필드를 두지 않고 어댑터에서 붙이기 위해 엔티티를 새로 만든다(README 참조 주석). 이 선택의 비용이 컬렉션 교체다. |
|
||||
| 대안 비교 | (1) 현상 유지. (2) 기존 관리 엔티티를 읽어 필드를 복사(`existing.apply(domain)`)하고 컬렉션은 내용이 다를 때만 `clear/addAll` — 변경 없는 컬렉션은 SQL 0. (3) 컬렉션을 JSON/배열 컬럼으로 — 스키마 변경. 권장 (2). |
|
||||
| 단순화의 보존 조건 | `@Version` 낙관적 잠금과 412 응답, `created_*` 보존·`updated_*` 갱신, ETag 값. |
|
||||
| 완료 기준·검증 | 제목만 바꾸는 PATCH의 SQL에 `delete from work_log_link`/`work_log_tech_stack`가 없다(Hibernate statistics 단언). |
|
||||
|
||||
### 09-07. JDBC batch 기본 꺼짐 + 동기 `batchCreate` 1000건을 한 트랜잭션에서 처리
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 구조적 위험(미측정 — 09-03 때문에 실행 불가) |
|
||||
| 관련 관점 | 14 성능, 13 확장성, 12 동시성 |
|
||||
| 근거 | `adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml:147-150` — `batch_size` 0, `order_inserts` false. `<S>/adapter/inbound/web/controller/WorkLogController.java:178` — `MAX_BATCH_SIZE = 1000`, 「Sync = atomic」 한 트랜잭션. 항목마다 work_log insert 1 + tech_stack k + link m + outbox insert 1. |
|
||||
| 발생 조건 | 1000건 요청 1회 = 최소 약 3,000~5,000 왕복을 한 커넥션이 한 트랜잭션으로 잡는다. JSON 본문 상한(`JsonBodyLimitFilter`)이 크기를 막지만 건수 1000은 허용한다. |
|
||||
| 영향 | 요청 하나가 커넥션 1개를 수 초 잡는다. 풀이 10개이므로 동시에 몇 건만 와도 다른 요청이 `connection-timeout`(기본 5 s)까지 기다린다. |
|
||||
| 심각도·우선순위 | Medium · P2. 측정하지 못했으므로 High로 올리지 않았다. |
|
||||
| 최소 개선 방향 | (1) 샘플에서 `APP_JPA_HIBERNATE_BATCH_SIZE`·`ORDER_INSERTS`를 켜고 `HibernateJpaBatchExecutor`의 증명 방식을 따른다. (2) 동기 배치 상한을 100 정도로 낮추고 그 이상은 기존 비동기 operation(`OperationsController`)으로 보낸다. |
|
||||
| 완료 기준·검증 | 09-03을 고친 뒤 1000건 요청의 SQL 왕복 수와 커넥션 점유 시간을 측정해 문서화한다. |
|
||||
|
||||
### 09-08. 샘플의 런타임 기본값이 기본 조합과 다름
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(일관성) |
|
||||
| 관련 관점 | 23 일관성, 19 설정, 14 성능 |
|
||||
| 근거 | 가상 스레드: `app-bootstrap/src/main/resources/application.yml:54-57` `SPRING_THREADS_VIRTUAL_ENABLED:true` vs `sample-portfolio/src/main/resources/application.yml:69-71` `:false`. 풀 대기: `persistence-jpa.yml:38` `connection-timeout` 5000(주석: fail-fast 원칙) vs 샘플 `application.yml:36` 30000. 앱 로그 레벨: `app-bootstrap/.../config/observability.yml:108` INFO vs 샘플 `application.yml:139` DEBUG. 샘플 파일 머리말은 "Mirrors app-bootstrap/application.yml"이라고 적는다. |
|
||||
| 실행 결과 | 스레드 수 55~59(기본) vs 79~81(샘플). 가상 스레드 켜기/끄기의 처리량 차이는 없었다(3.3절, 커넥션 10개가 병목). |
|
||||
| 영향 | 샘플로 측정한 숫자(대기 시간, 스레드 수)가 기본 조합의 동작을 대표하지 않는다. 풀이 마른 상황에서 샘플은 30초를 기다리고 기본 조합은 5초에 실패한다. |
|
||||
| 심각도·우선순위 | Low · P3. |
|
||||
| 최소 개선 방향 | 샘플이 기본값을 덮어쓰는 키를 지우고 모듈 기본값을 따르게 한다. 다르게 둘 이유가 있으면 그 키 옆에 이유를 적는다. |
|
||||
| 완료 기준·검증 | 두 조합의 effective 값 비교 테스트(이미 있는 `ProfileSeparationContractTest` 계열에 키 목록 추가). |
|
||||
|
||||
### 09-09. persistence-jpa가 H2 드라이버를 운영 아티팩트에 실어 보냄
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 개선 제안 |
|
||||
| 관련 관점 | 16 의존성, 15 보안, 18 배포 |
|
||||
| 근거 | `adapter/outbound/persistence-jpa/build.gradle:82` — `runtimeOnly 'com.h2database:h2'`. 실행 결과: 샘플 bootJar에 `BOOT-INF/lib/h2-2.4.240.jar`(2.7 MB). JPA를 켠 모든 서비스 jar에 같은 일이 생긴다. |
|
||||
| 영향 | 운영 이미지에 쓰지 않는 인메모리 DB 엔진이 들어간다. 크기 2.7 MB와 취약점 스캔 대상이 늘어난다. H2 콘솔 설정은 없다(`spring.h2.console` grep 0건, Boot 기본값 꺼짐). |
|
||||
| 심각도·우선순위 | Low · P3. |
|
||||
| 대안 비교 | (1) 현상 유지 — `bootRunH2` 편의. (2) H2를 `bootRunH2Classpath`·테스트 구성에만 둔다(`app-bootstrap/build.gradle`의 `bootRunH2`가 이미 별도 classpath를 만든다). 권장 (2). |
|
||||
| 완료 기준·검증 | `unzip -l` 결과 bootJar에 `h2-*.jar`가 없고 `bootRunH2`가 여전히 뜬다. |
|
||||
|
||||
### 09-10. `local` 프로필이 `server.port`를 8080으로 고정
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 확인된 결함(DX) |
|
||||
| 관련 관점 | 20 개발자 경험, 19 설정 |
|
||||
| 근거 | `app-bootstrap/src/main/resources/application-local.yml:127` `port: 8080`. 실행 결과: `APP_SERVER_PORT=18080`을 줬는데 `Tomcat started on port 8080`. 파일 머리말은 「완전한 독립 설정」이라 의도된 모양이지만, 이 키만은 env를 받을 이유가 있다. |
|
||||
| 영향 | 같은 머신에서 두 서비스(또는 기본 조합과 샘플)를 동시에 띄우면 포트 충돌. env로 피할 수 없다. |
|
||||
| 심각도·우선순위 | Low · P3. |
|
||||
| 최소 개선 방향 | `port: ${APP_SERVER_PORT:8080}`. |
|
||||
|
||||
### 09-11. 기본 조합 jar에 Jackson 2·3과 kotlin-stdlib가 함께 실림
|
||||
|
||||
| 필드 | 내용 |
|
||||
| --- | --- |
|
||||
| 성격 | 개선 제안 |
|
||||
| 관련 관점 | 16 의존성, 18 배포 |
|
||||
| 근거 | 기본 조합 `BOOT-INF/lib`: `jackson-databind-3.1.5`(1.9 MB)와 `jackson-databind-2.21.5`(1.7 MB)·`jackson-core-2.21.5`·`jackson-dataformat-yaml-2.21.5`·`jackson-datatype-jsr310-2.21.5`, `kotlin-stdlib-2.2.21`(1.8 MB)·`okhttp-jvm`·`okio-jvm`. 2 계열의 출처는 logstash encoder와 OTel 쪽으로 추정한다(미확인 — `dependencyInsight` 미실행). kotlin은 `opentelemetry-exporter-sender-okhttp`를 따라온다. |
|
||||
| 영향 | 기본 jar 39 MiB 중 약 5~6 MiB. 두 Jackson 계열의 보안 패치를 따로 추적해야 한다. |
|
||||
| 심각도·우선순위 | Low · P3. |
|
||||
| 최소 개선 방향 | `./gradlew :app-bootstrap:dependencyInsight --dependency com.fasterxml.jackson.core:jackson-databind`로 출처를 확인한다. OTLP sender를 JDK HttpClient 구현(`opentelemetry-exporter-sender-jdk`)으로 바꾸면 kotlin·okhttp가 빠진다. |
|
||||
|
||||
## 5. 31절 시나리오 추적
|
||||
|
||||
이 영역은 실측이므로, 실제로 요청을 보내 따라간 시나리오만 적는다.
|
||||
|
||||
### 5.1 큰 입력·목록 조회 — `GET /api/worklogs?size=100&sort=periodStart,desc`
|
||||
|
||||
```text
|
||||
HTTP → 보안 체인(샘플: permitAll) → 앱 필터 4개 → WorkLogController.list
|
||||
→ PageParams.of (size 1..100 검사) ← 상한 있음
|
||||
→ ListWorkLogsUseCase.handle → tx.inRead ← 트랜잭션 시작: SHOW ISOLATION + BEGIN READ ONLY
|
||||
→ WorkLogRepositoryAdapter.findPage
|
||||
→ select work_log … offset/limit ← 1
|
||||
→ select count(*) ← 1
|
||||
→ 행마다 tech_stack select, link select ← 200 (N+1)
|
||||
→ COMMIT
|
||||
→ toSummary (컬렉션 안 씀) → Envelope + meta.page → Jackson
|
||||
```
|
||||
|
||||
| 항목 | 결과 |
|
||||
| --- | --- |
|
||||
| 입력 신뢰 수준 | 외부 입력. `page`·`size`·`sort`·`category` 모두 컨트롤러 경계에서 검사(size ≤ 100, sort 문법·허용 필드, enum). |
|
||||
| 인가 위치 | 샘플은 없음(permitAll). |
|
||||
| 규칙 소유 | 페이지 상한은 web 어댑터 `PageParams`. |
|
||||
| 트랜잭션 | use case가 `inRead`로 연다. 읽기 전용, READ COMMITTED. |
|
||||
| 외부 부작용 | 없음. |
|
||||
| 성공의 의미 | 200, `meta.page.total` 포함. |
|
||||
| 오류 변환 | size 초과 → 400 `VALIDATION_FAILED`/`SIZE_EXCEEDS_MAX`, 정렬 문법 오류 → 400 `SORT_SYNTAX_INVALID`(실행으로 확인). |
|
||||
| 진단 정보 | 응답 `meta.requestId/traceId/correlationId`, 요청마다 INFO 로그 1줄. |
|
||||
| 판정 | 응답 크기와 페이지 크기는 제한된다. **호출 수는 페이지 크기에 비례**한다(206문장). 깊은 offset(page 490)도 허용되고 비용은 같았다(인덱스 없는 정렬 + offset 9,800 → `EXPLAIN` 12.8 ms). 데이터 총량이 늘면 `count(*)`와 offset 정렬이 함께 커진다. |
|
||||
|
||||
### 5.2 중복·동시 요청 — `POST /api/posters` 같은 제목 16개 동시
|
||||
|
||||
| 항목 | 결과 |
|
||||
| --- | --- |
|
||||
| 요청 식별 | 없음. 멱등성 키를 받지 않는다(샘플의 멱등성은 poster image 경로에만). |
|
||||
| DB 제약 | 제목에 유일 제약 없음(`V7__poster.sql:31`). |
|
||||
| 규칙 소유 | `CreatePosterUseCase`의 사전 `exists` 검사 하나. |
|
||||
| 트랜잭션 | `inWrite`, READ COMMITTED — 겹친 트랜잭션은 서로의 미커밋 insert를 못 본다. |
|
||||
| 외부 부작용 | 같은 트랜잭션의 `outbox_event` insert. 중복 행마다 이벤트도 중복. |
|
||||
| 결과 | 제목마다 10행. **계약 위반 재현**(09-02). |
|
||||
|
||||
### 5.3 정상 쓰기 요청 — `POST /api/worklogs`
|
||||
|
||||
실행 불가. 단독 실행에서 500(09-03). 대신 같은 모양(검사 → insert → outbox append, 한 트랜잭션)인 `POST /api/posters`를 쟀다: 7문장, 432 rps(행 증가 중), p50 22.6 ms.
|
||||
|
||||
### 적용 제외
|
||||
|
||||
| 시나리오 | 사유 |
|
||||
| --- | --- |
|
||||
| 외부 응답 지연·유실 | 샘플의 외부 호출(`RepoStatsPortClient.fetchRaw`)은 스텁이다. 요청 경로에 실제 동기 외부 호출이 없다. 05 영역(httpclient)이 다룬다. |
|
||||
| DB 오류·경쟁 | 09-02의 경쟁 외에는 이 영역에서 다루지 않았다(> 04). |
|
||||
| 메시지 중복·역순, 신·구 버전, 여러 서버 작업, 세션·토큰, 다른 사용자 리소스, 종료·재시작, 선택 어댑터 제거 | 성능 실측 범위 밖. 각 담당 영역(06, 07, 02, 04). |
|
||||
|
||||
## 6. 41절 설계 선택 검토
|
||||
|
||||
### 6.1 커넥션 풀 10개 + (기본 조합) 가상 스레드 on
|
||||
|
||||
| 질문 | 답 |
|
||||
| --- | --- |
|
||||
| 1. 무엇이 필요한가 | 요청 동시성이 커져도 DB 연결 수를 작게 유지하고, 풀이 마르면 오래 기다리지 않는 것. |
|
||||
| 2. 지킬 성질 | DB 커넥션 상한(10), 대기 상한(`connection-timeout` 5 s), REQUIRES_NEW 깊이를 고려한 최소 풀 크기(`persistence-jpa.yml:15-22` 주석의 공식). |
|
||||
| 3. 현재 보장 | 풀 크기·대기 시간은 설정으로 고정, `HikariPoolConstraintValidator`가 기동 때 값 관계를 검사한다. 가상 스레드를 켜면 Tomcat `threads.max: 200`이 더 이상 요청 동시성을 막지 않는다. 그러면 동시성 상한은 풀 대기열뿐이다. |
|
||||
| 4. 대안 | (a) 현상 유지. (b) 플랫폼 스레드(샘플 기본) — 스레드 200개가 상한. (c) 가상 스레드 + 앱 입구의 동시 실행 제한(web-advanced의 opt-in `VirtualThreadAdmissionGuard`). (d) 풀 크기를 CPU에 맞춰 키움. |
|
||||
| 5. 얻고 잃는 것 | 실측: 단건 조회 처리량은 (a)·(b) 모두 약 5.4k rps, 동시 16→64에서 p50만 2.7→11 ms. Hikari 평균 획득 대기 5.5 ms. 즉 지금 부하에서는 스레드 모델이 결과를 바꾸지 않는다. (a)는 블로킹 외부 호출이 섞일 때 스레드 고갈이 없다. 대신 폭주 시 대기가 풀 앞에 무한히 쌓이고 5 s 뒤 일괄 실패한다. (b)는 200에서 멈추고 나머지는 accept 큐(100)·커넥션(8192)에서 기다린다. |
|
||||
| 6. 왜 이 선택인가 | 기록된 의도는 "Java 21 virtual threads for Tomcat request handlers". 측정으로 보면 DB가 병목인 한 손해도 이득도 없다. 외부 HTTP 호출이 많은 서비스에서 이득이 생긴다. |
|
||||
| 7. 바뀔 조건 | 풀 대기(`hikaricp_connections_pending`)가 지속적으로 0보다 크면 (c)를 기본 경로로 고려한다. DB 왕복이 없는 CPU 위주 서비스면 차이 없음. |
|
||||
|
||||
판정: 선택은 타당하다. 다만 샘플이 반대 기본값을 써서(09-08) 템플릿이 하나의 답을 보여 주지 않는다.
|
||||
|
||||
### 6.2 `SpringTransaction`의 READ COMMITTED 명시
|
||||
|
||||
41.2 일곱 질문의 답은 09-05 표에 있다. 요약: 의도(격리 수준 고정)는 지킬 가치가 있지만, 같은 보장을 풀 설정(Hikari `transaction-isolation`)으로 옮기면 트랜잭션마다 왕복 1회가 없어진다. 모드별로 다른 격리 수준이 필요해지면 지금 방식이 맞다.
|
||||
|
||||
### 6.3 목록 조회가 도메인 집계를 통째로 읽기 (vs 요약 projection)
|
||||
|
||||
| 질문 | 답 |
|
||||
| --- | --- |
|
||||
| 1. 필요 | 페이지·정렬·필터가 되는 요약 목록. |
|
||||
| 2. 지킬 성질 | 응답 모양, 페이지 메타, 정렬 허용 필드. |
|
||||
| 3. 현재 보장 | 집계 전체를 읽어 요약으로 줄인다(09-01). 요약 projection은 따로 있지만 HTTP가 쓰지 않는다. |
|
||||
| 4. 대안 | 09-01 대안 비교 (1)~(4). |
|
||||
| 5. 비용 | 실측: 46문장 vs (batch fetch) 8문장, 829 vs 2411 rps. projection은 측정하지 않았지만 lazy 0개라 8문장보다 적다(추론). |
|
||||
| 6. 선택 이유 | 기록 없음. 같은 모듈에 projection이 있다는 사실은 의도가 projection 쪽이었음을 보여 준다. |
|
||||
| 7. 바뀔 조건 | 목록 응답이 컬렉션을 포함하게 되면 batch fetch가 낫다. |
|
||||
|
||||
## 7. 리팩토링 후보
|
||||
|
||||
| 대상 | 무엇을 왜 | 보존해야 할 동작·타입·실패 계약 |
|
||||
| --- | --- | --- |
|
||||
| `ListWorkLogsUseCase` + `WorkLogRepository.findPage` / `WorkLogSummaryQueryPort` | 목록 읽기 경로가 둘(집계형 `findPage`, 요약형 `findRecentSummaries`)로 갈라져 있다. HTTP 목록을 요약형 하나로 합치면 N+1이 사라지고 중복 경로가 하나 준다. | `WorkLogSummaryResponse` JSON, `meta.page`(number·size·total·sort), 정렬 필드 집합, 카테고리 필터, 400 코드. OpenAPI 스냅샷 불변. |
|
||||
| `WorkLogRepositoryAdapter.save` | 새 엔티티 merge → 관리 엔티티에 변경 적용. 컬렉션 재작성(09-06)과 adapter 안의 두 번째 `findById`가 없어진다. | `@Version` 충돌 시 412, 감사 필드 의미(created 보존, updated 갱신), 반환 도메인 객체의 version. |
|
||||
| `SpringTransaction.template` | 격리 수준 명시를 풀 설정으로 이동(09-05). | 모든 모드 READ COMMITTED, `inNew` 30 s, 읽기 전용, `inRootWrite` 중첩 거부. |
|
||||
| `CreatePosterUseCase` | 사전 검사 + DB 유일 제약 변환(09-02). | 409 `POSTER_ALREADY_EXISTS` 응답 모양, 대소문자 무시 비교 의미. |
|
||||
|
||||
## 8. 기능 개발 패턴과 판단 지점 (매뉴얼 재료)
|
||||
|
||||
### 템플릿이 주는 틀
|
||||
|
||||
- 페이지 파라미터 검사(`PageParams`, 상한 100)와 `meta.page` 응답 모양.
|
||||
- 요약 projection 예시(`WorkLogJpaRepository.findRecentSummaryRows` + `WorkLogSummaryQueryPort`).
|
||||
- JPA 성능 손잡이(`APP_JPA_HIBERNATE_BATCH_SIZE`, `…ORDER_INSERTS`, `…DEFAULT_BATCH_FETCH_SIZE`, `…GENERATE_STATISTICS`)와, batch가 실제로 일어났는지 증명하는 `HibernateJpaBatchExecutor`.
|
||||
- Hikari 풀 기본값과 값 관계 검사(`HikariPoolConstraintValidator`), Prometheus의 `hikaricp_*` 지표.
|
||||
- JFR·SQL 로그를 켤 수 있는 설정 경로(코드 변경 없이 이 문서의 모든 측정이 가능했다).
|
||||
|
||||
### 빠진 것
|
||||
|
||||
- 「요청 하나에 SQL이 몇 개인가」를 단언하는 테스트 틀이 없다. Hibernate statistics 손잡이는 있지만 그것으로 문장 수를 고정하는 예제 테스트가 없다. 그래서 09-01·09-06이 게이트를 통과했다.
|
||||
- 성능 기준선(숫자)이 없다. gRPC에는 performance lane이 있지만 HTTP·JPA 경로에는 없다.
|
||||
- 동시 생성 경쟁을 재현하는 테스트 예시가 없다(09-02).
|
||||
- 샘플을 단독으로 띄워 대표 요청을 한 바퀴 도는 스모크가 없다(09-03·09-04).
|
||||
|
||||
### 개발자가 여기서 내려야 하는 판단
|
||||
|
||||
1. **목록 응답이 집계 전체를 필요로 하는가?** 아니면 요약 projection으로 읽는다. 필요하면 컬렉션마다 batch fetch 또는 별도 IN 쿼리를 쓴다. `@ElementCollection`을 쓰면 「목록에서 몇 번 읽히는가」를 먼저 센다.
|
||||
2. **유일해야 하는 값인가?** 그렇다면 DB 유일 제약(대소문자 무시면 식 인덱스)을 먼저 만들고, 사전 검사는 친절한 오류용으로만 둔다.
|
||||
3. **수정 시 무엇을 다시 쓰는가?** 새 엔티티를 merge하면 컬렉션이 전부 다시 쓰인다. 관리 엔티티에 변경만 적용한다.
|
||||
4. **동기 배치의 상한은 몇인가?** 「한 트랜잭션에서 커넥션을 몇 초까지 잡아도 되는가」로 정한다. 넘으면 비동기 operation으로 보낸다. 배치를 쓰면 `batch_size`와 `order_inserts`를 켠다.
|
||||
5. **스레드 모델과 풀 크기**: 요청 경로에 블로킹 외부 호출이 있으면 가상 스레드가 이득이다. DB만 있으면 풀 크기와 쿼리 수가 처리량을 정한다. 풀 대기 지표(`hikaricp_connections_pending`, `acquire_seconds`)를 대시보드에 둔다.
|
||||
6. **새 엔드포인트의 SQL 수를 테스트로 고정할 것인가?** 목록·쓰기 경로에는 고정한다. 단건 조회는 선택.
|
||||
|
||||
### 다음 측정 후보
|
||||
|
||||
- 목록 응답 p95 ≈ 38 ms 고정 꼬리의 원인(TCP delayed ACK 의심) — `ss -ti`, `tcpdump`, 응답 크기별 분포로 확인.
|
||||
- 09-03 수정 뒤 `POST /api/worklogs`와 `batchCreate` 1000건의 SQL 수·커넥션 점유 시간.
|
||||
- 30분 이상 부하에서 heap·RSS·커넥션 추이.
|
||||
- 컨테이너(cgroup 1 GiB) 안 기동 시간과 RSS.
|
||||
|
||||
## 9. 28개 관점 판정표
|
||||
|
||||
기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역.
|
||||
|
||||
| 번호 | 관점 | 판정 | 이유 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 코드 성숙도 | > | 01·04 영역. 이 영역은 측정 경로의 코드만 읽었다. |
|
||||
| 2 | 구조적 성숙도 | > | 01 영역. |
|
||||
| 3 | 변경 용이성 | P | 성능 손잡이 대부분이 env로 열려 있어 코드 없이 바꿀 수 있었다. 목록 읽기 경로가 둘로 갈려 있다(09-01). |
|
||||
| 4 | 인지 부하 | P | 「어느 쿼리 경로가 HTTP에 쓰이는가」를 따라가야 비용을 안다. |
|
||||
| 5 | 위험 가시성 | X | N+1·컬렉션 재작성·중복 경쟁이 코드에 드러나지 않는다. 주석은 projection이 있다고 말하지만 실제 경로는 다르다(09-01, 09-02, 09-06). |
|
||||
| 6 | 실패 성숙도 | P | 페이지·정렬 오류는 깔끔한 400. 인증 부재가 500으로 새는 경로가 있다(09-03). |
|
||||
| 7 | 운영 성숙도 | P | Hikari·HTTP·보안 지표가 Prometheus에 있다. 성능 기준선이 없다. |
|
||||
| 8 | 디버깅 가능성 | O | requestId·traceId가 응답과 로그에 있다. 코드 수정 없이 SQL 로그·JFR·빈 수를 얻었다. |
|
||||
| 9 | 유지보수 성숙도 | P | 샘플 설정이 모듈 기본값을 말없이 덮는다(09-08). |
|
||||
| 10 | 테스트 성숙도 | X | 요청당 SQL 수, 동시 생성 경쟁, 단독 실행 샘플의 대표 쓰기·OpenAPI 경로를 잡는 테스트가 없다. 게이트는 초록인데 09-02·09-03·09-04가 실행으로 재현된다. |
|
||||
| 11 | 데이터 성숙도 | X | 제목 유일 규칙이 DB에 없다(09-02). |
|
||||
| 12 | 동시성 성숙도 | X | check-then-insert 경쟁 재현(09-02). |
|
||||
| 13 | 확장성 | P | 페이지 상한·풀 상한이 있다. 목록 비용이 페이지 크기에 선형, 포스터 생성 비용이 행 수에 선형(09-01, 09-02). |
|
||||
| 14 | 성능 성숙도 | P | 기동 3.4 s(기본)/6.5~8.0 s(샘플), 필터 체인 0.5 ms, 단건 2.7 ms는 양호. 목록 N+1, 트랜잭션마다 추가 왕복, 성능 기준선 부재. |
|
||||
| 15 | 보안 성숙도 | > | 02 영역. 측정 중 본 것: H2 jar 동봉(09-09), 샘플 전체 permitAll은 의도된 데모 구성. |
|
||||
| 16 | 의존성 성숙도 | P | Jackson 2·3 공존, kotlin·okhttp, H2 동봉(09-09, 09-11). |
|
||||
| 17 | API / Contract 성숙도 | P | 실제 서버의 `/api/v3/api-docs` 500, README 경로 불일치(09-03, 09-04). |
|
||||
| 18 | 배포 성숙도 | > | 08 영역. jar 크기만 측정(41.4 / 99.0 MB). |
|
||||
| 19 | 설정 성숙도 | P | env 손잡이는 충분하다. 샘플·local 프로필이 일부 키를 고정·덮어쓴다(09-08, 09-10). |
|
||||
| 20 | 개발자 경험 | P | 샘플 단독 실행 시 대표 쓰기 실패, local 포트 고정(09-03, 09-10). |
|
||||
| 21 | Guardrail 성숙도 | P | 풀 값 관계 검사와 batch 증명 장치는 있다. SQL 수·유일 제약 같은 성능·데이터 가드는 없다. |
|
||||
| 22 | 추상화 성숙도 | - | 성능 실측 범위 밖(09-05의 격리 수준 위치만 언급). |
|
||||
| 23 | 일관성 | P | 기본 조합과 샘플의 스레드·풀 대기·로그 기본값 불일치(09-08). |
|
||||
| 24 | 네이밍 / 의미 성숙도 | - | 범위 밖. |
|
||||
| 25 | 조직 확장성 | - | 범위 밖. |
|
||||
| 26 | Ownership 성숙도 | - | 범위 밖. |
|
||||
| 27 | 삭제 가능성 | - | 범위 밖(H2 분리는 09-09). |
|
||||
| 28 | 회복 가능성 | ? | 장시간·장애 조건 측정을 하지 않았다. |
|
||||
|
||||
## 정리 상태
|
||||
|
||||
측정에 쓴 프로세스(샘플·기본 조합 JVM)와 컨테이너 `perf09-pg`는 모두 내렸고, 이 측정에서만 받은 `postgres:16-alpine` 이미지도 지웠다. worktree `<scratchpad>/wt-09`는 `git worktree remove --force`로 지웠다. 측정 스크립트와 원시 출력(`Load.java`, `Beans.java`, `run-app.sh`, `sqlcount.sh`, `bench.sh`, `phase3.sh`, `phase4.sh`, `bench-*.txt`, `sql-*.txt`, `*.jfr`, `jfr-summary.txt`)은 세션 scratchpad의 `perf/`에 남아 있다. 이 문서의 「측정 명령」 절만으로 다시 만들 수 있다.
|
||||
@@ -0,0 +1,380 @@
|
||||
# 백엔드 성숙도 리뷰 — 2026-11-01
|
||||
|
||||
> 기준: `clean-architecture-frontend-template/docs/reviews/TEMPLATE-MATURITY-REVIEW-GUIDE.md`(31절 Backend 시나리오). 기준 커밋: `main` `01a8a2a70`(리뷰 후속 Wave 1–3 머지 직후). repo 전체를 9개 영역으로 나눠 영역 에이전트가 병렬로 읽고 실험했다. 이 문서는 오케스트레이터가 결과를 모으고 High 발견을 코드에서 다시 확인한 것이다. 영역 문서는 리뷰 시점 기록이라 수정 후에도 고치지 않는다.
|
||||
|
||||
## 1. 사용 결정 (36.5-1)
|
||||
|
||||
| 용도 | 결정 | 막는 항목 |
|
||||
|---|---|---|
|
||||
| 기본 조합(web·observability·cores)으로 새 서비스 시작 | **조건부 사용 가능** | 02-03(JWT audience가 비면 검증 안 함), 07-01(트레이스가 나가지 않음), 07-02(prod 기동 검사가 마이그레이션 뒤에 돔), 04-01(커밋 중 끊김을 재시도 가능으로 응답) |
|
||||
| 짝 프론트 템플릿과 그대로 붙여 쓰기 | **사용 보류** | 02-02(Envelope의 null 필드를 프론트 strict 스키마가 거절), 02-01(처리 중 409의 클라이언트 행동이 계약에 없음) |
|
||||
| sample-portfolio를 새 기능의 따라 할 예시로 복제 | **사용 보류** | 07-03·09-03(실행 중 권한 검사 없음, 대표 쓰기 500), 09-02(중복 규칙이 DB 제약 없이 조회 후 insert), 04-09·09-01(목록 N+1), 01-02(onboarding fixture가 기동 실패 모양) |
|
||||
| 알림(notification) capability를 여러 인스턴스로 운영 | **사용 보류** | 05-01(발송 중 crash → 같은 알림 재발송), 04-02(정산 job 중복 처리) |
|
||||
| outbox relay + Kafka로 운영 | 사용 보류 | 06-01(재시도 가능한 거부를 즉시 DEAD, 같은 aggregate 뒤 이벤트까지 막힘), 06-03(broker 5분 정지로 대량 DEAD) |
|
||||
| Redis 멱등성·캐시 capability | 조건부 사용 가능 | 05-02(renew가 lease를 늘리지 못함 — 현재 호출자 없음), 05-03(revision 조건 무시) |
|
||||
| HTTP client capability | 조건부 사용 가능 | 05-05(4xx가 breaker를 연다), 05-06(전체 시간 예산이 진행 중 요청을 못 끊음) |
|
||||
| 파일 서버 capability | 조건부 사용 가능 | 05-07(copy가 디스크 수위·쿼터 우회), 05-08(소유자 검사를 지워도 테스트 통과) |
|
||||
| GraphQL 공개 | 사용 보류 | 03-01(복잡도 점수가 목록 크기를 놓침) |
|
||||
| gRPC operation ledger 채택 | 사용 보류 | 03-10(`IN_PROGRESS` 회수 없음), 03-11(설정만 있고 처리 코드 없음) |
|
||||
| 이 repo의 CI를 머지 차단 장치로 믿기 | 조건부 | 08-01(strict lane 14개를 어떤 workflow도 돌리지 않음), 05-09·08-04(MinIO 이미지 소멸로 mainCheck 빨강, main 단계가 첫 실패에서 멈춤) |
|
||||
|
||||
## 2. 차단 항목 — High와 P1 (36.5-3)
|
||||
|
||||
같은 결함을 두 영역이 적은 것은 하나로 합쳤다. "코드 확인"은 오케스트레이터가 해당 줄을 직접 읽었다는 뜻이다. "에이전트 실행"은 영역 에이전트가 worktree에서 실행해 재현했다는 뜻이다.
|
||||
|
||||
### 2.1 High (21건, 합친 뒤 19건)
|
||||
|
||||
| ID | 내용 | 재확인 |
|
||||
|---|---|---|
|
||||
| [05-01](05-outbound-capabilities.md) | 알림 attempt를 `notStarted()`(PROVEN, false)로 저장한 채 provider를 호출한다. 발송 중 워커가 죽으면 recovery가 "확실히 시작 안 함"으로 읽고 다시 큐에 넣는다 → 같은 알림 재발송 | 코드 확인: `DeliveryAttemptFactory.java:54-56` → `NotificationDispatchService.java:189-216`(갱신 없이 `submitOutsideTransaction`) → `LeaseRecoveryService.java:101-106` |
|
||||
| [04-02](04-persistence.md) | 알림 정산 job claim(`SELECT … FOR UPDATE SKIP LOCKED`)이 트랜잭션 없이 돈다. 잠금이 문장 끝에서 풀려 여러 인스턴스가 같은 job을 처리한다 | 코드 확인: `JdbcReconciliationJobStore.java:43-52,117-123`(`jdbc.query`만), `ReconciliationJobWorker.java:81`(트랜잭션 없음) |
|
||||
| [04-01](04-persistence.md) | 커밋 중 연결이 끊기면(`08*`) `DB_UNAVAILABLE`(retryable)로 답한다. 실제로는 커밋됐을 수 있어 재시도가 쓰기를 중복시킨다. ADR-JPA-003과 반대 | 코드 확인: `PersistenceExceptionTranslator.java:97-99`, `SpringTransaction.java:98-105`(커밋 단계 구분 없음) + 에이전트 실험 테스트 |
|
||||
| [06-01](06-messaging.md) | platform의 `retryable` 정보를 버리고 NOT_TRANSMITTED 거부를 `REJECTED_BEFORE_SEND`로 바꿔 즉시 DEAD. 종료 중·permit 부족도 DEAD가 되고 같은 aggregate 뒤 이벤트가 막힌다 | 코드 확인: `PlatformIntegrationEventPublishAdapter.java:140-151`, `PublishPendingOutboxEventsUseCase.java:149-153` + 에이전트 실행(`SHUTTING_DOWN retryable=true` → DEAD) |
|
||||
| [06-03](06-messaging.md) (P2) | 재시도 3회·30초 고정이라 broker가 약 5분 멈추면 대량 DEAD, 복구는 row마다 수동 SQL | 에이전트 계산(실측 없음) |
|
||||
| [05-02](05-outbound-capabilities.md) | Redis 멱등성 `renew()`가 `EXECUTING→EXECUTING` 전이라 Lua의 "이미 목표 상태" 분기에 걸려 항상 ALREADY, lease를 늘리지 않는다 | 코드 확인: `RedisIdempotencyStoreAdapter.java:183-190` + `IdempotencyScripts.java:101-108`. 현재 템플릿 안 호출자 없음(잠복) |
|
||||
| [05-03](05-outbound-capabilities.md) | 캐시 `ONLY_IF_SOURCE_REVISION_NEWER`가 `ALWAYS`로 떨어져 조건 없이 SET | 코드 확인: `RedisCacheRegionAdapter.java:262-266`(`presenceOf`는 ONLY_IF_ABSENT만 구분) |
|
||||
| [05-05](05-outbound-capabilities.md) | HTTP client: 404 같은 정상 4xx도 circuit breaker 실패로 센다 | 에이전트 코드 읽기(E1). 수정 단계에서 RED 테스트로 확인 |
|
||||
| [05-06](05-outbound-capabilities.md) | HTTP client: 전체 시간 예산이 진행 중 attempt를 끊지 못한다(소켓 read-idle만 있음) | 에이전트 코드 읽기(E1). 수정 단계에서 확인 |
|
||||
| [05-07](05-outbound-capabilities.md) | 파일 서버: copy가 디스크 수위 검사를 우회하고 쿼터는 기록만 한다 | 에이전트 코드 읽기(E1). 수정 단계에서 확인 |
|
||||
| [03-01](03-inbound-realtime-graphql-grpc.md) | GraphQL 복잡도 점수가 `first` 생략·변수 기본값·일반 list에서 하위 비용을 곱하지 않고 페이지 상한 검사도 건너뛴다(`first:20` 410점, 생략 40점) | 에이전트 실행(임시 테스트 재현) |
|
||||
| [03-10](03-inbound-realtime-graphql-grpc.md) | gRPC ledger `IN_PROGRESS` 행에 만료·회수가 없다. 소유자가 죽으면 key가 영구히 막힌다 | 코드 확인: `GrpcOperationLedgerRepository.java:76-92`(회수는 `FAILED_TERMINAL`만), `GrpcIdempotencyInterceptor.java:118-121`. 채택 전 차단(03-11) |
|
||||
| [02-01](02-inbound-web.md) | "처리 중" 응답은 `409 IDEMPOTENT_IN_FLIGHT`, `retryable=false`, `Retry-After` 없음. "같은 키로 재전송"이 백엔드 어디에도 없고 runbook·error-codes.yaml은 없는 헤더·polling을 말한다 | 에이전트 실행(`@WebMvcTest` 출력) + 문서 대조 |
|
||||
| [02-02](02-inbound-web.md) | 실제 Envelope에 `data:null`·`error:null`·`meta.page:null`이 항상 실린다. 짝 프론트 strict 스키마가 거절한다. 백엔드 `doesNotExist` 단언은 null도 통과시킨다 | 에이전트 실행(`@WebMvcTest` 출력) + 프론트 코드 읽기 |
|
||||
| [02-03](02-inbound-web.md) + [07-05](07-bootstrap-composition-config.md) | JWT audience가 비면(템플릿 기본값) 검증을 건너뛴다. env 레지스트리는 `required: true`. role은 모든 client의 `resource_access`에서 합친다 | 코드 확인: `SecuritySettings.java:35-42` |
|
||||
| [07-01](07-bootstrap-composition-config.md) | 자체 `Tracer`에 span processor·exporter가 없어 OTLP endpoint를 넣어도 아무것도 나가지 않는다 | 코드 확인: `TracingConfig.java:66-91`(`SdkTracerProvider`에 sampler만) + 에이전트 실행(exporter 0개) |
|
||||
| [07-02](07-bootstrap-composition-config.md) | prod 기동 검사(TLS·Flyway)가 `afterSingletonsInstantiated`에서 돌아 DB 연결·마이그레이션이 먼저 실행된다 | 코드 확인: `StartupRuleRunner.java:35`. PostgreSQL 실측 없음 |
|
||||
| [07-03](07-bootstrap-composition-config.md) + [09-03](09-performance-measurement.md) | 샘플이 `WebSecurityAutoConfiguration`을 통째로 빼면서 `MethodSecurityConfig`도 빠졌다. `@RequiresPermission`이 동작하지 않아 익명 삭제 가능, owner가 null이라 `POST /api/worklogs`는 항상 500 | 코드 확인: `SamplePortfolioApplication.java:31`, `WebSecurityAutoConfiguration.java:41-49` + 에이전트 실행(`java -jar`로 500 재현) |
|
||||
| [09-02](09-performance-measurement.md) | 포스터 제목 중복 규칙이 DB 유일 제약 없이 "조회 후 insert". 같은 제목 16개 동시 요청 3회 모두 10행씩 들어감. 검사 쿼리는 순차 스캔 | 에이전트 실행(동시 요청 실측) |
|
||||
| [08-01](08-build-ci-test.md) + [04-04](04-persistence.md) + [03-12](03-inbound-realtime-graphql-grpc.md) | CI가 한 번도 돌리지 않는 strict lane 14개(JPA 실 PostgreSQL 11, web 부하·종료 2, sample 전체 기동 1). `integration-main.yml:96`은 `integrationCheck --dry-run`만 한다. persistence-fileserver는 자기 테스트가 0개 | 에이전트 `--dry-run` 그래프와 workflow 15개 대조. 04 영역이 그중 4 lane을 직접 돌려 44건 통과 |
|
||||
|
||||
### 2.2 P1 (High 제외)
|
||||
|
||||
| ID | 심각도 | 내용 | 재확인 |
|
||||
|---|---|---|---|
|
||||
| [05-09](05-outbound-capabilities.md) + [08-04](08-build-ci-test.md) | Medium | MinIO 이미지(`minio/minio@sha256:4c4a48…`)를 받을 수 없어 mainCheck가 빨갛다. 이미지 참조가 네 곳에 복사돼 있고 main 단계는 `--continue` 없이 돌아 다른 lane 결과를 가린다 | 오케스트레이터 실행: Docker Hub `minio/minio` pull 거부, `alpine:3`는 성공, `quay.io/minio/minio`도 해당 digest·태그 없음 |
|
||||
| [04-03](04-persistence.md) | Medium | JPA 양방향 연관관계 금지(사용자 원칙)를 막는 장치가 없고 `docs/jpa/entity-mapping-guide.md:50-57`과 testFixtures 예제는 `mappedBy` 양방향을 가르친다. 운영 엔티티 28개는 지금 연관관계 0개 | 에이전트 전수 확인 |
|
||||
| [05-08](05-outbound-capabilities.md) | Medium | 파일 서버 copy·download의 소유자 검사를 지워도 442개 테스트가 전부 통과(소유자 결정 14의 회귀 방지 없음) | 에이전트 변이 실험 |
|
||||
| [06-02](06-messaging.md) | Medium | platform 종료 순서가 앱 outbox relay를 모른다 | 에이전트 코드 읽기 |
|
||||
|
||||
## 3. 확인된 강점 (36.5-2)
|
||||
|
||||
- **PR 게이트가 녹색이다.** `ci` rc=0(434초). leaf check(compile·test·Spotless·Checkstyle·Error Prone) 전체, `architectureCheck`(의존 방향·순수성·ArchUnit 181건), `qualityCheck`(SpotBugs·FindSecBugs)가 통과했다.
|
||||
- **지난 리뷰의 High/P1이 모두 닫혔다.** 9개 영역 모두 "남은 High/P1 없음"으로 재확인했다. 남은 것은 문서·테스트 규칙(W4·W5) 성격이다.
|
||||
- **JPA 엔티티는 사용자 원칙을 지킨다.** 운영 엔티티 28개에 연관관계 매핑이 하나도 없다(04 영역). 막는 장치만 없다(04-03).
|
||||
- **실 PostgreSQL lane은 돌리면 통과한다.** JPA 4 lane 44건(04), gRPC ledger 18건(03). 문제는 CI가 돌리지 않는다는 것(08-01)이다.
|
||||
- **테스트가 빠르다.** 테스트 결과 XML 984개 합계 약 208초, 가장 느린 클래스 9.3초(08 영역). ci 434초의 병목은 테스트 실행이 아니다.
|
||||
- **기본 조합이 가볍다.** bootJar 41.4 MB, 기동 중앙값 3.44초, 빈 407개. 필터 체인만 지나는 요청 27k rps(09 영역).
|
||||
- **변이 실험 대부분을 테스트가 잡는다.** strict lane 장치 3/3, GraphQL 구조 상한·STOMP destination, outbox offset 검사 등. 잡지 못한 것은 각 발견으로 적었다(05-08, 06-05, 01-03, 02-09).
|
||||
|
||||
## 4. 반복되는 원인 (36.5-4)
|
||||
|
||||
1. **결과 불명을 "확실함"으로 기록한다.** 05-01(시작 안 함 PROVEN으로 저장 후 호출), 04-01(커밋 중 끊김을 재시도 가능으로), 06-01(재시도 가능 거부를 확정 거부로), 05-17(Redis 연결 실패를 결과 불명으로 — 반대 방향). 결과 불명 처리를 정한 문서(ADR-JPA-003, 알림 evidence 모델)는 있지만 경계마다 다시 구현되며 갈라졌다.
|
||||
2. **중복·경쟁을 DB가 아니라 코드 순서로 막는다.** 09-02(조회 후 insert), 04-08(upsert), 04-02(트랜잭션 없는 SKIP LOCKED), 03-10(lease 없는 claim). 가이드 31절 "DB 유일성 제약과 충돌 처리가 충분한지 먼저 본다"에 해당한다.
|
||||
3. **샘플이 운영 경로와 다르게 조립된다.** 07-03·09-03(보안 자동 설정 통째 제외), 09-08(런타임 기본값 다름), 07-04(`Dockerfile.sample` 빌드 실패), 07-09·01-01(따라 할 예시가 세 갈래). 매뉴얼 재료가 될 예시가 실제로는 실행되지 않는다.
|
||||
4. **설정·이미지 참조·식별자 규칙이 여러 벌이다.** `TenantId` 3벌(01-03), 이벤트 ID 문법 5곳(01-07), SQLState 분류표 2벌(04-06), MinIO 이미지 참조 4곳(05-09), 로그 설정 2곳(07-06). 사용자 원칙 "갈라진 중복 복사본은 결함"에 정면으로 걸린다.
|
||||
5. **선언과 실행이 떨어져 있다.** strict lane을 선언하고 돌리지 않는다(08-01), 설정 키는 바인딩되지만 동작하지 않는다(05-15, 03-11), 레지스트리는 `required`인데 코드는 빈 값을 허용한다(02-03).
|
||||
|
||||
## 5. 결정이 필요한 것
|
||||
|
||||
> 2026-11-01 22:00 소유자 결정: 아래 다섯 항목 모두 권장안으로 정했다. 05-09의 대체 이미지 선택만 보류(이미지 참조 한 곳·pull 실패 메시지 구분·main 단계 `--continue`까지 진행).
|
||||
|
||||
| 항목 | 선택지 | 권고 | 승인자 |
|
||||
|---|---|---|---|
|
||||
| 02-01 처리 중 409 | (A) `retryable=true` + `Retry-After` + 계약 문서 고정 (B) `retryable=false` 유지, 문서만 (C) executor가 잠시 대기 후 replay (D) 키 조회 엔드포인트 | (A). 같은 키 재전송은 서버가 replay·in-flight·422로 안전하게 판정한다. 짝 프론트 분류기와 같이 바꾼다 | 템플릿 소유자(두 repo) |
|
||||
| 02-02 Envelope null 필드 | (A) 백엔드가 `@JsonInclude(NON_NULL)`로 생략 (B) 프론트 strict 완화 | (A). 프론트의 "unknown field 거절" 방어를 유지한다 | 템플릿 소유자(두 repo) |
|
||||
| 02-03 JWT audience·role 범위 | (A) audience 필수 + 자기 client role만 (B) prod에서만 필수 (C) 문서만 | (A). 기존 배포는 env 하나를 채워야 한다(호환성 깨짐) | 템플릿 소유자 |
|
||||
| 05-09 MinIO 이미지 공급원 | (a) 조직 레지스트리 미러 (b) 다른 공식 레지스트리 (c) 커뮤니티 재배포 이미지 (d) 다른 S3 구현 (e) lane 제외 | 원본 digest를 가진 곳이 없고(로컬·quay.io 모두 없음) 조직 레지스트리도 없어 (a)(b)는 지금 불가. 단기: 이미지 참조를 한 곳으로 모으고 pull 실패를 별도 메시지로 구분, 대체 이미지는 소유자가 고른다 | 템플릿 소유자 |
|
||||
| 07-01 트레이싱 | (A) 자체 Tracer를 지우고 Boot 4 tracing·OTLP 모듈로 (B) 자체 Tracer에 exporter 직접 연결 (C) 트레이싱 범위 제거 | (A) | 템플릿 소유자 |
|
||||
|
||||
## 6. 미검증 (36.5-5)
|
||||
|
||||
| 무엇 | 왜 | 확인하려면 |
|
||||
|---|---|---|
|
||||
| GitHub Actions 실제 실행 결과 | 원격이 `git.learn.hyeonworks.com`이고 외부 조회를 하지 않았다 | runner 결과 |
|
||||
| 미실행 strict lane 14개 중 10개의 현재 통과 여부 | 04 영역이 4 lane만 돌렸다 | `integrationCheck` 실행 |
|
||||
| MinIO 계약·fault lane | 이미지를 받을 수 없다 | 5절 결정 후 |
|
||||
| 실제 다중 인스턴스 경쟁(05-01, 04-02, 06-01) | 코드 경로와 단위 실험만 했다 | 2개 인스턴스 + 실 DB 통합 테스트(수정 단계 RED 테스트로 일부 대체) |
|
||||
| Redis·Toxiproxy·SES/SMTP·Kafka 실연 | 외부 서비스·컨테이너 lane을 돌리지 않았다 | 해당 lane |
|
||||
| 실제 SIGTERM 종료 순서(06-02, 07-07) | 측정하지 않았다 | 컨테이너에서 종료 실측 |
|
||||
| 실제 `docker build` | Dockerfile COPY 집합만 재현했다(`Dockerfile.sample` 실패) | 빌드 실행 |
|
||||
| 짝 프론트와의 결합 실행(02-01, 02-02) | 프론트는 코드만 읽었다 | 두 템플릿 통합 환경 |
|
||||
|
||||
## 7. 개선 순서 (36.5-6)
|
||||
|
||||
| 순서 | 대상 | 이유 | 완료 기준 |
|
||||
|---|---|---|---|
|
||||
| 1 | 05-01, 04-02, 04-01, 06-01, 05-02, 05-03, 05-05, 05-06, 05-07, 03-01, 03-10, 07-02, 07-03+09-03, 09-02 | High·P1 중 결정이 필요 없는 코드 결함. 각각 막는 테스트를 먼저 넣는다 | 각 영역 문서의 완료 기준. 수정 전 실패하는 테스트가 있어야 한다 |
|
||||
| 2 | 02-01, 02-02, 02-03+07-05, 07-01, 05-09+08-04 | 5절 결정 후 | 결정 내용대로 |
|
||||
| 3 | 08-01+04-04+03-12, 04-03, 05-08, 06-02, 06-03 | CI·회귀 방지 장치와 P1 Medium | lane이 workflow에서 돌고, 금지 규칙이 ArchUnit으로 막고, 변이가 잡힌다 |
|
||||
| 4 | 01-01, 01-02, 07-09, 01-05, 01-03, 01-07, 04-06 | 개발 매뉴얼(`docs/manual/`)과 기능 생성 명령의 재료. 예시 하나, 규칙 한 벌 | 생성 명령으로 만든 기능이 모든 게이트를 통과 |
|
||||
| 5 | 나머지 P2·P3 | 영역별 | 각 영역 문서 |
|
||||
|
||||
## 8. 재검토 조건 (36.5-7)
|
||||
|
||||
- 개선 순서 1·2가 끝나면 해당 영역만 다시 본다.
|
||||
- 개발 매뉴얼과 기능 생성 명령이 생기면 01·07 영역을 그 명령으로 만든 기능 기준으로 다시 본다.
|
||||
- MinIO 대체 공급원이 정해지면 objectstorage 벤더 증거를 다시 측정한다.
|
||||
- gRPC ledger나 Redis 멱등성 renew를 실제로 쓰는 경로가 생기면 03·05 영역을 다시 본다.
|
||||
|
||||
## 9. 리뷰 범위 (36.1)
|
||||
|
||||
- 기준 커밋 `01a8a2a70`. 게이트는 오케스트레이터가 한 번 실행했다(프론트 세션과 공유 잠금).
|
||||
|
||||
| 게이트 | 결과 | 시간 | 실행 직전 부하 |
|
||||
|---|---|---|---|
|
||||
| `ci` | rc=0 | 434초(잠금 대기 포함) | load 9.15 |
|
||||
| `mainCheck` | rc=1 — `objectStorageMinioContractTest`, `objectStorageMinioFaultTest`만 실패(이미지 pull 404). `sampleWebContractCheck`, sample `webSystemTest`, `verifyEnvKeys`, app-bootstrap `systemTest` 통과 | 162초 | load 20.68 |
|
||||
|
||||
- 영역 9개와 담당 leaf:
|
||||
|
||||
| 영역 | 범위 |
|
||||
|---|---|
|
||||
| [01](01-core-and-feature-pattern.md) core·기능 패턴 | `domain-core`, `shared-contract`, `application-core` + repo 전체 폴더 구조·리팩토링·새 기능 흐름 |
|
||||
| [02](02-inbound-web.md) inbound web | `adapter:inbound:web*`, `composition:idempotency` HTTP 계약 |
|
||||
| [03](03-inbound-realtime-graphql-grpc.md) realtime·graphql·grpc | `websocket`, `graphql`, `grpc` 어댑터 + `grpc:*`, `grpc-advanced:*` |
|
||||
| [04](04-persistence.md) persistence | `persistence-jpa`, `-mongo`, `-fileserver`, `-notification`, 마이그레이션 |
|
||||
| [05](05-outbound-capabilities.md) outbound capability | redis·cache·httpclient·objectstorage·notification·fileserver·identifier·support + `application-*` capability, composition |
|
||||
| [06](06-messaging.md) messaging | `messaging:*`, `adapter:outbound:messaging(-kafka)`, `composition:outbox-relay` |
|
||||
| [07](07-bootstrap-composition-config.md) bootstrap·설정 | `app-bootstrap`, `composition:service-runtime`, `sample-portfolio`, env 계약, Dockerfile, compose |
|
||||
| [08](08-build-ci-test.md) build·CI·테스트 | `build-logic`, settings, 루트 lifecycle, workflow 15개, 테스트 lane, 테스트 실행 시간 |
|
||||
| [09](09-performance-measurement.md) 성능 실측 | 기동·jar·SQL 수·처리량·JFR |
|
||||
|
||||
## 10. 이번 라운드 추가 렌즈 요약
|
||||
|
||||
- **성능(09).** bootJar 기본 41.4 MB / 샘플 99.0 MB. 기동 중앙값 3.44초(빈 407) / 8.05초(빈 603). 요청당 SQL: 목록 20건 46개, 100건 206개, 단건 7개, 제목만 바꾸는 PATCH 13개. 처리량: 단건 5,521 rps, 목록 20건 829 rps. `default_batch_fetch_size=100`만으로 목록 2.9배. 관측 기능 비용 약 3%, 가상 스레드는 차이 없음.
|
||||
- **테스트 성능(08).** 테스트 시간 합 약 208초. strict lane의 `upToDateWhen(false)`가 build cache 적재까지 막아 PR마다 약 77초가 매번 다시 돈다(08-02). PR `test`에 저장소 문서를 읽는 클래스 15개(08-03).
|
||||
- **폴더 구조·기능 패턴(01·07).** 새 기능을 두는 모양이 세 가지(core 안, `application-*` capability, sample 수직)이고 고르는 기준이 없다(01-01). 따라 할 예시도 세 갈래(07-09). 01 영역 문서 7절에 "새 도메인 하나 추가" 단계별 틀·빠진 것·판단 지점과 생성 명령 후보 목록이 있다 — 매뉴얼 재료.
|
||||
- **리팩토링 후보.** 각 영역 문서 6절. 공통: 식별자 문법·SQLState 표·이미지 참조를 한 곳으로(4절 원인 4).
|
||||
|
||||
## 11. 28개 관점 판정 (36.2)
|
||||
|
||||
영역별 기호: O 충족 · P 부분 · X 미충족 · ? 미검증 · - 적용 제외 · > 다른 영역. 종합은 평균하지 않는다. 한 영역이라도 X면 X다(35.7절).
|
||||
|
||||
| 관점 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 종합 |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 1 코드 성숙도 | O | P | P | P | P | P | P | O | > | P |
|
||||
| 2 구조적 성숙도 | P | O | P | P | O | P | P | O | > | P |
|
||||
| 3 변경 용이성 | P | P | P | P | P | P | P | P | P | P |
|
||||
| 4 인지 부하 | P | P | P | P | P | P | P | P | P | P |
|
||||
| 5 위험 가시성 | P | X | X | X | P | P | X | P | X | **X** |
|
||||
| 6 실패 성숙도 | P | P | P | X | P | X | P | P | P | **X** |
|
||||
| 7 운영 성숙도 | > | P | P | P | P | P | P | > | P | P |
|
||||
| 8 디버깅 가능성 | P | O | P | P | P | P | P | P | O | P |
|
||||
| 9 유지보수 성숙도 | P | P | P | P | P | P | P | P | P | P |
|
||||
| 10 테스트 성숙도 | P | P | P | P | P | P | P | P | X | **X** |
|
||||
| 11 데이터 성숙도 | P | - | P | P | P | P | > | > | X | **X** |
|
||||
| 12 동시성 성숙도 | P | P | P | P | P | P | P | - | X | **X** |
|
||||
| 13 확장성 | - | ? | X | P | ? | P | ? | P | P | **X** |
|
||||
| 14 성능 성숙도 | O | ? | P | P | P | ? | P | P | P | P |
|
||||
| 15 보안 성숙도 | P | X | P | O | P | O | P | P | > | **X** |
|
||||
| 16 의존성 성숙도 | O | O | O | O | P | P | P | P | P | P |
|
||||
| 17 API·계약 성숙도 | P | X | P | P | P | P | > | O | P | **X** |
|
||||
| 18 배포 성숙도 | > | > | P | ? | > | X | P | > | > | **X** |
|
||||
| 19 설정 성숙도 | - | P | P | P | P | P | P | O | P | P |
|
||||
| 20 개발자 경험 | X | P | P | P | P | P | P | P | P | **X** |
|
||||
| 21 Guardrail | P | P | P | P | P | P | P | P | P | P |
|
||||
| 22 추상화 성숙도 | P | O | P | P | P | P | O | O | - | P |
|
||||
| 23 일관성 | X | P | P | P | P | P | P | P | P | **X** |
|
||||
| 24 네이밍·의미 | P | P | P | P | P | P | P | P | - | P |
|
||||
| 25 조직 확장성 | P | P | - | P | ? | P | ? | P | - | P |
|
||||
| 26 Ownership | P | P | P | P | P | P | P | ? | - | P |
|
||||
| 27 삭제 가능성 | P | O | O | O | P | O | P | P | - | P |
|
||||
| 28 회복 가능성 | > | P | X | P | P | X | - | P | ? | **X** |
|
||||
|
||||
미충족(X)의 이유:
|
||||
- 5 위험 가시성 — 02-03(레지스트리 required, 코드는 빈 값 허용), 03-01, 04-01, 07-03, 09-03: 위험이 기본값·설정 뒤에 숨어 있다.
|
||||
- 6 실패 성숙도 — 04-01(커밋 중 끊김 오분류), 06-01·06-03(재시도 가능 실패를 DEAD로).
|
||||
- 10 테스트 성숙도 — 09 영역: 대표 쓰기 500·동시 중복을 테스트가 잡지 못한다. 05-08 변이 생존.
|
||||
- 11 데이터 성숙도 — 09-02: 중복 규칙에 DB 제약 없음.
|
||||
- 12 동시성 성숙도 — 09-02, 04-02(트랜잭션 없는 SKIP LOCKED).
|
||||
- 13 확장성 — 03-06·03-09: WebSocket·gRPC 연결·동시 호출 상한 없음.
|
||||
- 15 보안 성숙도 — 02-03(audience 기본 꺼짐, 타 client role 합침).
|
||||
- 17 API·계약 — 02-01, 02-02: 짝 프론트와 wire 계약 불일치.
|
||||
- 18 배포 성숙도 — 06 영역: 종료 순서가 relay를 모름(06-02), broker 실연 lane 없음(06-09).
|
||||
- 20 개발자 경험·23 일관성 — 01 영역: 새 기능 모양 세 갈래(01-01), 식별자·이름 규칙 여러 벌(01-03, 01-07, 01-12).
|
||||
- 28 회복 가능성 — 03-10(ledger 영구 잠김), 06-03(DEAD 복구 수작업).
|
||||
|
||||
## 12. 발견 색인
|
||||
|
||||
영역 문서에 36.3 양식으로 적힌 발견 119건: High 21 · Medium 64 · Low 34, P1 25 · P2 59 · P3 35. Critical 0. 두 영역이 같은 결함을 적은 묶음(07-03+09-03, 02-03+07-05, 08-01+04-04+03-12, 05-09+08-04, 04-09+09-01)은 색인에 각각 남기고 2절에서 합쳤다. 06·08 영역 문서는 원래 `NN-` 접두사로 적혀 있어 `06-`·`08-`로 바꿨다.
|
||||
|
||||
| ID | 심각도 | 우선순위 | 내용 |
|
||||
|---|---|---|---|
|
||||
| [02-01](02-inbound-web.md) | High | P1 | "처리 중" 409의 클라이언트 행동이 코드·문서·짝 계약에서 서로 다르다 |
|
||||
| [02-02](02-inbound-web.md) | High | P1 | 실제 Envelope JSON이 `data:null`·`error:null`·`meta.page`를 싣는데 짝 프론트 계약은 이를 거절한다 |
|
||||
| [02-03](02-inbound-web.md) | High | P1 | JWT audience 검증이 기본으로 꺼져 있고, 모든 client의 role을 합친다 |
|
||||
| [03-01](03-inbound-realtime-graphql-grpc.md) | High | P1 | GraphQL 복잡도 점수가 목록 크기를 놓친다 — 페이지 인자 생략·변수 기본값·일반 list 필드 |
|
||||
| [03-10](03-inbound-realtime-graphql-grpc.md) | High | P1 | operation ledger의 `IN_PROGRESS` claim에 만료·회수가 없다 — 소유자가 죽으면 그 key는 영구히 막힌다 |
|
||||
| [04-01](04-persistence.md) | High | P1 | 커밋 중 연결이 끊기면 "재시도 가능(DB_UNAVAILABLE)"으로 답한다 |
|
||||
| [04-02](04-persistence.md) | High | P1 | 다중 인스턴스에서 알림 정산 job이 중복 처리된다 |
|
||||
| [05-01](05-outbound-capabilities.md) | High | P1 | 알림 attempt를 "요청 시작 안 함(확정)"으로 저장한 채 provider를 호출한다 — 워커가 발송 중 죽으면 같은 알림이 다시 나간다 |
|
||||
| [05-02](05-outbound-capabilities.md) | High | P1 | Redis 멱등성 `renew()`가 처리 lease를 연장하지 못한다 |
|
||||
| [05-03](05-outbound-capabilities.md) | High | P1 | 캐시 `ONLY_IF_SOURCE_REVISION_NEWER`가 조건 없이 덮어쓴다 |
|
||||
| [05-05](05-outbound-capabilities.md) | High | P1 | HTTP client: 4xx 응답이 circuit breaker 실패로 집계된다 |
|
||||
| [05-06](05-outbound-capabilities.md) | High | P1 | HTTP client: 전체 시간 예산이 진행 중인 attempt를 끊지 못한다 |
|
||||
| [05-07](05-outbound-capabilities.md) | High | P1 | 파일 서버: copy가 디스크 수위 검사를 우회하고, 쿼터는 기록만 한다 |
|
||||
| [06-01](06-messaging.md) | High | P1 | 다시 시도하면 될 거부를 relay가 즉시 DEAD로 보낸다 |
|
||||
| [07-01](07-bootstrap-composition-config.md) | High | P1 | 트레이스가 어디로도 나가지 않는다 — OTLP endpoint를 설정해도 span을 만들지도 보내지도 않는다 |
|
||||
| [07-02](07-bootstrap-composition-config.md) | High | P1 | prod 기동 검사가 DB 연결과 Flyway 마이그레이션이 끝난 뒤에 돈다 |
|
||||
| [07-03](07-bootstrap-composition-config.md) | High | P1 | 실행 중인 샘플에서는 `@RequiresPermission`이 아무 일도 하지 않는다 — 익명 삭제 가능, 생성은 500 |
|
||||
| [08-01](08-build-ci-test.md) | High | P1 | CI가 실행하지 않는 strict lane 14개 |
|
||||
| [09-02](09-performance-measurement.md) | High | P1 | 포스터 제목 중복 규칙이 동시 요청에서 깨지고, 검사 쿼리가 순차 스캔 |
|
||||
| [09-03](09-performance-measurement.md) | High | P1 | 단독 실행한 샘플에서 대표 쓰기 `POST /api/worklogs`가 항상 500 |
|
||||
| [06-03](06-messaging.md) | High | P2 | broker가 몇 분만 멈춰도 row가 대량으로 DEAD가 되고 복구는 수작업이다 |
|
||||
| [04-03](04-persistence.md) | Medium | P1 | JPA 연관관계 원칙(양방향 금지)을 막는 장치가 없고, 템플릿 문서와 fixture는 반대로 가르친다 |
|
||||
| [04-04](04-persistence.md) | Medium | P1 | 실 PostgreSQL lane 9개(57개 테스트)가 어떤 게이트·workflow에서도 돌지 않는다. persistence-fileserver는 자기 테스트가 0개다 |
|
||||
| [05-08](05-outbound-capabilities.md) | Medium | P1 | 파일 서버: 소유자 검사를 지워도 테스트가 하나도 실패하지 않는다 |
|
||||
| [05-09](05-outbound-capabilities.md) | Medium | P1 | 객체 저장소: MinIO 이미지 공급원이 사라져 mainCheck가 빨갛다 |
|
||||
| [06-02](06-messaging.md) | Medium | P1 | platform 종료 순서가 앱 relay를 모른다 |
|
||||
| [01-01](01-core-and-feature-pattern.md) | Medium | P2 | 새 기능을 어느 leaf에 두는지 세 가지 모양이 있고, 고르는 기준이 없다 |
|
||||
| [01-02](01-core-and-feature-pattern.md) | Medium | P2 | onboarding fixture가 "새 기능의 계약 모양"으로 박아 둔 유스케이스가 실제로는 기동에 실패하는 모양이다 |
|
||||
| [01-03](01-core-and-feature-pattern.md) | Medium | P2 | `TenantId`가 3벌이고 받아들이는 문법이 셋 다 다르다 |
|
||||
| [01-04](01-core-and-feature-pattern.md) | Medium | P2 | `IllegalArgumentException` 하나가 "입력이 틀렸다"와 "서버 조립이 틀렸다"를 함께 뜻하고, web은 둘 다 로그 없이 400으로 바꾼다 |
|
||||
| [01-05](01-core-and-feature-pattern.md) | Medium | P2 | application-core가 소유한 포트 중 절반이 "fake와 실제 adapter가 같은 계약 테스트를 통과한다"는 규칙 밖에 있다 |
|
||||
| [02-04](02-inbound-web.md) | Medium | P2 | rate-limit 거부 본문이 실제 Tomcat에서 ISO-8859-1로 나가 한국어 문구가 깨진다 |
|
||||
| [02-05](02-inbound-web.md) | Medium | P2 | CORS에 노출 헤더가 없어 브라우저가 계약 헤더를 못 읽는다 |
|
||||
| [02-06](02-inbound-web.md) | Medium | P2 | `String`을 반환하는 컨트롤러는 `Accept: application/json`에서 500이 된다 |
|
||||
| [02-07](02-inbound-web.md) | Medium | P2 | web-advanced 예외 10종이 문서의 상태 대신 500으로 나간다 |
|
||||
| [03-02](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | GraphQL 요청 deadline(10초)이 실행 중에는 강제되지 않는다 |
|
||||
| [03-03](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | N+1을 막는 길이 adopter 기억에만 있다 |
|
||||
| [03-06](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | WebSocket 연결 수·구독 수·연결 수명 상한이 없고, STOMP 전송 한도가 코드에 드러나지 않는다 |
|
||||
| [03-07](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | `SerializedOutboundWriter`의 offer와 close가 겹치면 노드 버퍼 예산이 영구히 샌다 |
|
||||
| [03-08](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | `PlatformWebSocketHandler.stop()` 뒤에 들어온 연결은 1001을 받지 못한다 |
|
||||
| [03-09](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | gRPC 어댑터 서버가 io.grpc 기본값으로 뜬다 — deadline·동시 호출·executor·메시지 크기 상한이 없고, 플랫폼 한도는 testkit 서버에만 적용된다 |
|
||||
| [03-11](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | `app.grpc.platform.operation-ledger-enabled`는 검증만 통과시키고 실제로 key를 처리하는 코드가 없다 |
|
||||
| [04-05](04-persistence.md) | Medium | P2 | `@Version` 충돌이 변환되지 않고 500 INTERNAL_ERROR로 나간다 |
|
||||
| [04-06](04-persistence.md) | Medium | P2 | SQLState 분류표가 두 벌이고 이미 갈라졌다 |
|
||||
| [04-07](04-persistence.md) | Medium | P2 | bulk UPDATE가 `@Version`을 올리지 않는다 |
|
||||
| [04-08](04-persistence.md) | Medium | P2 | upsert가 "찾고 없으면 넣기"라 동시 요청에서 깨진다 |
|
||||
| [04-09](04-persistence.md) | Medium | P2 | sample 목록 조회가 N+1이다(페이지당 최대 202쿼리) |
|
||||
| [04-10](04-persistence.md) | Medium | P2 | 기본 쓰기·읽기 트랜잭션에 시간 제한이 없다 |
|
||||
| [04-11](04-persistence.md) | Medium | P2 | Mongo 트랜잭션 본문의 일시 오류가 재시도되지 않는다 |
|
||||
| [04-12](04-persistence.md) | Medium | P2 | Mongo 기본 경로(URI만 준 배포)에 timeout·pool 제한이 없다 |
|
||||
| [04-13](04-persistence.md) | Medium | P2 | persistence adapter가 정책을 소유하고, claim 토큰을 프로세스 메모리에 둔다 |
|
||||
| [04-14](04-persistence.md) | Medium | P2 | notification·fileserver 영속 leaf가 테스트 규칙(공유 계약)을 따르지 않는다 |
|
||||
| [04-15](04-persistence.md) | Medium | P2 | Mongo 라이브러리를 파생 서비스가 쓸 경로와 예시가 없다 |
|
||||
| [05-04](05-outbound-capabilities.md) | Medium | P2 | 캐시 무효화와 느린 loader의 경합, stampede 보호 없음, 문서는 jitter를 주장 |
|
||||
| [05-10](05-outbound-capabilities.md) | Medium | P2 | 알림: collapse 미지원 예외가 try 밖에서 터져 끝없이 재시도된다 |
|
||||
| [05-11](05-outbound-capabilities.md) | Medium | P2 | 알림: SMTP 실패가 전부 "결과 불명"이 되어 재시도 없이 운영자 대기로 멈춘다 |
|
||||
| [05-12](05-outbound-capabilities.md) | Medium | P2 | 파일 서버: tus PATCH가 쓰기를 커밋한 뒤 `file:read`를 요구한다 |
|
||||
| [05-13](05-outbound-capabilities.md) | Medium | P2 | 파일 서버: 정리 worker가 기본으로 꺼져 있다 |
|
||||
| [05-14](05-outbound-capabilities.md) | Medium | P2 | HTTP client: 기본 설정에서 결과 불명 분류가 틀린 경로로 나간다 |
|
||||
| [05-15](05-outbound-capabilities.md) | Medium | P2 | HTTP client: 바인딩되지만 동작하지 않는 설정 키, 0 timeout 허용 |
|
||||
| [05-16](05-outbound-capabilities.md) | Medium | P2 | capability 완료 기준 5가 영역 전체에서 지켜지지 않는다 |
|
||||
| [05-17](05-outbound-capabilities.md) | Medium | P2 | Redis: 연결 실패를 "결과 불명"으로 보고하고, 시간 초과된 연결을 pool에 돌려준다 |
|
||||
| [05-20](05-outbound-capabilities.md) | Medium | P2 | SES 콜백: replay 창 5분이 장애 뒤 SNS 재전송을 버린다 |
|
||||
| [06-04](06-messaging.md) | Medium | P2 | aggregate 하나의 발행 속도가 poll 주기당 1건으로 묶인다 |
|
||||
| [06-05](06-messaging.md) | Medium | P2 | relay가 꺼져 있거나 실패하는 동안 outbox 지표가 갱신되지 않는다 |
|
||||
| [06-06](06-messaging.md) | Medium | P2 | application EventId 문법과 platform MessageId(UUID)가 다르다 |
|
||||
| [06-07](06-messaging.md) | Medium | P2 | 샘플이 aggregate 순서 번호를 벽시계로 만든다 |
|
||||
| [06-08](06-messaging.md) | Medium | P2 | 소비(consume)를 지원한다는 결정이 application 쪽 경로로 이어지지 않는다 |
|
||||
| [06-09](06-messaging.md) | Medium | P2 | 실제로 쓰는 발행 경로에는 broker 실연 테스트가 없고, broker 실연 lane은 어떤 기본 게이트에도 없다 |
|
||||
| [07-04](07-bootstrap-composition-config.md) | Medium | P2 | `Dockerfile.sample`은 빌드되지 않는다 |
|
||||
| [07-05](07-bootstrap-composition-config.md) | Medium | P2 | prod에서 JWT audience를 비워도 기동하고, 경고도 없이 audience 검사를 끈다 |
|
||||
| [07-06](07-bootstrap-composition-config.md) | Medium | P2 | 로그 설정이 두 군데에서 읽힌다 — `LoggingSettings`는 아무도 쓰지 않고, logback은 env 키를 직접 읽는다 |
|
||||
| [07-07](07-bootstrap-composition-config.md) | Medium | P2 | 종료 시간 예산표에 async executor 대기 19초가 빠져 있다 |
|
||||
| [07-08](07-bootstrap-composition-config.md) | Medium | P2 | 기본 조립 루트가 아직 선택 capability를 안다 (capability 기준 7 위반) |
|
||||
| [07-09](07-bootstrap-composition-config.md) | Medium | P2 | 새 기능을 만들 때 따라 할 예시가 세 갈래다 |
|
||||
| [08-02](08-build-ci-test.md) | Medium | P2 | strict lane은 build cache도 쓰지 않아서 바뀐 것이 없어도 매번 다시 돈다 |
|
||||
| [08-03](08-build-ci-test.md) | Medium | P2 | app-bootstrap의 PR 테스트가 저장소 문서를 읽고, 저장소 전체를 입력으로 잡는다 |
|
||||
| [08-04](08-build-ci-test.md) | Medium | P2 | 외부 컨테이너 이미지가 사라지면 main 단계가 통째로 멈춘다 |
|
||||
| [09-01](09-performance-measurement.md) | Medium | P2 | 샘플 목록 API가 N+1 — 페이지 20건에 SQL 46개 |
|
||||
| [09-04](09-performance-measurement.md) | Medium | P2 | 단독 실행한 샘플에서 `/api/v3/api-docs`가 500 |
|
||||
| [09-06](09-performance-measurement.md) | Medium | P2 | 제목 하나 고치는 PATCH가 컬렉션 테이블을 전부 지우고 다시 넣음 |
|
||||
| [09-07](09-performance-measurement.md) | Medium | P2 | JDBC batch 기본 꺼짐 + 동기 `batchCreate` 1000건을 한 트랜잭션에서 처리 |
|
||||
| [01-06](01-core-and-feature-pattern.md) | Medium | P3 | `@RequiresPermission`은 application 계약인데, 검사는 web leaf가 켜 주는 AOP에만 있다 |
|
||||
| [01-08](01-core-and-feature-pattern.md) | Medium | P3 | 장기 실행 작업(LRO) 공개 계약이 두 벌이다 |
|
||||
| [01-09](01-core-and-feature-pattern.md) | Medium | P3 | 통합 이벤트를 만드는 규칙(tenant 범위·순서·correlation)을 기능마다 다시 정한다 |
|
||||
| [02-08](02-inbound-web.md) | Low | P2 | Spring MVC 예외의 상태→코드 변환이 의미를 잃는다 |
|
||||
| [02-09](02-inbound-web.md) | Low | P2 | JSON 본문 상한의 두 갈래가 테스트로 묶여 있지 않고, JSON 아닌 본문은 상한이 없다 |
|
||||
| [01-07](01-core-and-feature-pattern.md) | Low | P3 | 이벤트 식별자 문법이 다섯 곳에 복사되어 있고 길이 상한이 둘로 갈린다 |
|
||||
| [01-10](01-core-and-feature-pattern.md) | Low | P3 | application-core 한 이름공간에 커널·플랫폼 기능·(파생 시) 업무 기능이 섞인다 |
|
||||
| [01-11](01-core-and-feature-pattern.md) | Low | P3 | 공용 다이제스트 헬퍼가 있는데 복사본이 남아 있고, 일부 leaf는 registry 때문에 복사가 강제된다 |
|
||||
| [01-12](01-core-and-feature-pattern.md) | Low | P3 | 이름 규칙의 정본 문서가 없고, 같은 역할에 이름이 여러 가지다 |
|
||||
| [01-13](01-core-and-feature-pattern.md) | Low | P3 | 참조 예시의 수정 유스케이스에 소유자 검사가 없다는 사실이 코드에 보이지 않는다 |
|
||||
| [01-14](01-core-and-feature-pattern.md) | Low | P3 | 작은 결함 묶음 (각각 독립, Low / P3) |
|
||||
| [02-10](02-inbound-web.md) | Low | P3 | `GlobalExceptionHandler`가 두 경로로 등록된다 |
|
||||
| [02-11](02-inbound-web.md) | Low | P3 | `X-Correlation-Id` 허용 문자·길이가 요청 ID 규칙·짝 계약과 다르다 |
|
||||
| [02-12](02-inbound-web.md) | Low | P3 | `Idempotency-Key` 헤더 검증이 컨트롤러마다 새로 쓰인다 |
|
||||
| [03-04](03-inbound-realtime-graphql-grpc.md) | Low | P3 | `GraphQlDataLoaderRequestRegistry`는 도달 불가인데 README가 요청 스코프 장치로 설명한다 |
|
||||
| [03-05](03-inbound-realtime-graphql-grpc.md) | Low | P3 | batch loader가 플랫폼 context 없이 불리면 `REQUEST_TIMEOUT`으로 나간다 |
|
||||
| [03-12](03-inbound-realtime-graphql-grpc.md) | Low | P3 | ledger PG lane은 main push·nightly에서만 돌고 PR·릴리스 게이트에 없다 |
|
||||
| [04-16](04-persistence.md) | Low | P3 | notification·fileserver leaf에 가까운 안내 문서가 없고 패키지가 평평하다 |
|
||||
| [04-17](04-persistence.md) | Low | P3 | 미리 정한 UUID + primitive `long` version이라 `save()`가 merge로 동작한다 |
|
||||
| [05-18](05-outbound-capabilities.md) | Low | P3 | 설정 prefix·바인딩 방식이 capability 기준 4와 다르다 |
|
||||
| [05-19](05-outbound-capabilities.md) | Low | P3 | bootstrap이 알림·파일 서버 권한 이름을 안다 |
|
||||
| [05-21](05-outbound-capabilities.md) | Low | P3 | identifier leaf: 이름·문서가 내용과 맞지 않는다 |
|
||||
| [05-22](05-outbound-capabilities.md) | Low | P3 | 파일 서버: finalize가 writer lease 없이 돈다 |
|
||||
| [05-23](05-outbound-capabilities.md) | Low | P3 | 작은 결함 묶음 (각각 독립, Low / P3) |
|
||||
| [07-10](07-bootstrap-composition-config.md) | Low | P3 | 설정 오타·죽은 키가 기동에서도 게이트에서도 안 잡히는 곳이 있다 |
|
||||
| [07-11](07-bootstrap-composition-config.md) | Low | P3 | 주석·문서가 현재 동작과 다르다 (이번에 새로 찾은 것) |
|
||||
| [07-12](07-bootstrap-composition-config.md) | Low | P3 | virtual thread를 켠 상태에서 `server.tomcat.threads.max`는 동시 처리 상한이 아니다 |
|
||||
| [07-13](07-bootstrap-composition-config.md) | Low | P3 | 기본 compose가 관리 포트 9001을 모든 인터페이스에 연다 |
|
||||
| [07-14](07-bootstrap-composition-config.md) | Low | P3 | 프로필 검증기가 main class 이름을 문자열로 비교한다 |
|
||||
| [08-05](08-build-ci-test.md) | Low | P3 | registry에 없는 leaf 디렉터리는 조용히 빌드에서 빠진다 |
|
||||
| [08-06](08-build-ci-test.md) | Low | P3 | 병렬·캐시 설정이 빌드와 lane 종류에 따라 다르게 적용된다 |
|
||||
| [08-07](08-build-ci-test.md) | Low | P3 | SpotBugs·FindSecBugs가 신뢰도 HIGH만 보고한다 |
|
||||
| [09-05](09-performance-measurement.md) | Low | P3 | 트랜잭션마다 `SHOW TRANSACTION ISOLATION LEVEL` 왕복 1회 |
|
||||
| [09-08](09-performance-measurement.md) | Low | P3 | 샘플의 런타임 기본값이 기본 조합과 다름 |
|
||||
| [09-09](09-performance-measurement.md) | Low | P3 | persistence-jpa가 H2 드라이버를 운영 아티팩트에 실어 보냄 |
|
||||
| [09-10](09-performance-measurement.md) | Low | P3 | `local` 프로필이 `server.port`를 8080으로 고정 |
|
||||
| [09-11](09-performance-measurement.md) | Low | P3 | 기본 조합 jar에 Jackson 2·3과 kotlin-stdlib가 함께 실림 |
|
||||
|
||||
## 13. 조치 현황 (개선 순서 1~3)
|
||||
|
||||
리뷰 뒤 같은 기준 커밋(`01a8a2a70`)에서 수정했다. 발견마다 수정 에이전트 하나가 별도 worktree에서 실패하는 테스트를 먼저 쓰고(RED) 고친 뒤(GREEN) 패치를 냈다. 오케스트레이터가 패치를 메인 작업 트리에 합쳤다. **커밋하지 않았다**(commit policy `human-only`). 영역 문서는 리뷰 시점 기록이라 고치지 않았다.
|
||||
|
||||
| ID | 상태 | GREEN (에이전트 worktree 실행) | RED (수정 전 실패) | 남은 것·결정 필요 |
|
||||
|---|---|---|---|---|
|
||||
| 05-01 | 충족 | application-notification 231 pass, PG BackgroundPass8/WorkerCrash6/Evidence5 pass | anAttemptLeftAsTheFactoryWroteItIsReconciledNotRequeued 등 3건 수정 전 실패 | 남음: WorkerCrashRecoveryContractTest 이름/설명 불일치, 05-10 원인 그대로 |
|
||||
| 07-02 | 충족 | support68/persistence-jpa503/app-bootstrap329/sample295 pass | aViolatedRuleFailsTheBootBeforeAnyOtherBeanIsCreated, aProdPlaintextDatabaseUrlFailsTheBootBeforeTheDataSourceExists | 남음: 빈이 필요한 검사(SecretSourceValidator 등)는 기존 시점, 실 PG systemTest 미실행 |
|
||||
| 04-01 | 충족 | persistence-jpa 519 pass, PG transaction IT 4 + jpaPlatformFailure 1 pass | connectionLossDuringCommitIsReportedAsCompletionUnknownNotRetryable, IT(57P01 미분류) | 남음: flush 실패와 COMMIT 실패 미구분(안전한 쪽), 08 접두어 두 곳(04-06), SPI 메서드 commitOutcomeUnknownStates() 추가(기본 구현) |
|
||||
| 03-01 | 충족 | graphql test 392 + systemTest 29 pass | 단위 15중 11 실패(410 vs 40 등), systemTest 거부 3건 | 결정 필요: 크기 선언 없는 일반 list를 20개로 계산(기존 깊은 쿼리 거부 가능), first·last 둘 다면 큰 쪽 |
|
||||
| 04-02 | 충족 | PG jpaPlatformContractTest 53 + schemaActivation 8 pass, leaf check 4개, architectureCheck pass | aClaimedJobIsNotHandedToAnotherInstance, twoConcurrentClaimsShareNoJob(40개 전부 겹침) | 결정 필요: 포트 claimDue 시그니처·ReconciliationJob.claimFence 변경(application-notification), lease는 기존 lease-duration 2분 재사용. 새 마이그레이션 V11 |
|
||||
| 02-03+07-05 | 충족 | web 278, app-bootstrap test 321, verifyEnvKeys OK, sample test·webSystemTest pass | 6건(기동 허용, 첫 값만 비교, 타 client role 합침) | 남음: sample application.yml:196 audience 미사용 설정, env 미설정 시 ${} 문자열 남는지 미확인, app-bootstrap systemTest 미실행. 호환성 깨짐: 기존 배포는 APP_SECURITY_JWT_AUDIENCE 필수 |
|
||||
| 09-02 | 충족 | sample check(test 295)+systemTest 3+integrationTest 55 pass, 동시성 3회 반복 pass | 16동시 생성에 DB 7행·outbox 7개 | 결정 필요: 마이그레이션 번호 V8_1(V9는 production과 합친 Flyway에서 충돌). 기존 중복 제목 있으면 마이그레이션 중단. 제목 변경 PATCH도 409 |
|
||||
| 06-01+06-03 | 충족 | application-core 222, outbound:messaging 38, messaging-kafka 84, runtime-core 30, composition·starter·persistence-jpa·testkit, RunbookCoverage, architectureCheck pass | 11건(REJECTED_BEFORE_SEND, DEAD, 10분 장애 20행 DEAD) | 결정 필요: vendored messaging leaf 2곳 수정, 예산 설정 키화 안 함(일시 실패가 예산을 쓰지 않음). 한계: attempt_count가 일시 실패도 셈. 위험: 진짜 인증 오류도 5분 간격 무한 재시도(runbook 기재). PG 통합 미실행 |
|
||||
| 07-03+09-03 | 충족 | web check 259+13, sample check 298·systemTest 8·webSystemTest 5, app-bootstrap 관련 test 15·IT 9, architectureCheck pass | 실서버+PG 5중 4 실패(익명 DELETE 204, demo-user DELETE 204, POST 500) | 결정 필요: 데모 계정 비밀번호=이름(README 공개), 익명 쓰기 401로 변경(export 포함). 남음: 기동 실패 rule 미구현, 09-04 api-docs 500은 다른 원인, qualityCheck 미실행 |
|
||||
| 02-01+02-02 | 충족 | shared-contract 260, web 279, architectureCheck, app-bootstrap registry 테스트 19 pass | 7건(키 집합에 error/data/results, retryable false·Retry-After 없음) | 방법: shared-contract는 stdlib-only라 web 어댑터 Jackson mixin으로 null 생략. IN_FLIGHT retryable=true, Retry-After 2초. 남음: gRPC trailer·GraphQL extension retryable도 true로 바뀜(테스트 없음), 프론트 분류기·계약 §4.1/§6 갱신 필요, CORS Retry-After 노출(02-05) |
|
||||
| 05-07+05-08 | 충족 | application-fileserver 272, composition 33, web-fileserver 142, architectureCheck pass; 05-08 변이(copy·prepare-download descriptor 제거) 새 테스트가 잡음 | 3건(수위 0.90 미거절, 쿼터 예약 없음, 실패 시 반환 없음) | 남음: 쿼터 상한 비교 없음(정책 결정 필요), 대상 namespace 허용 목록 없음, MOVE·READ_METADATA 소유자 테스트 없음 |
|
||||
| 05-05+05-06 | 충족 | httpclient check(test 293, stableContract 20, security 9, spring62 7), spring70 20, perf 5, deadline 3회 반복 pass | 404×200에 약 100번째부터 breaker 열림, 예산 1초인데 Apache 5.58초 성공·JDK 2.05초 | 결정 필요: profile별 breaker 설정 키 없음. 남음: RETURN_RESULT 정책 5xx는 breaker 성공 기록, Toxiproxy 케이스·streaming·http3 미포함 |
|
||||
| 05-02+05-03 | 충족 | cache-redis 143 + redis-runtime 49, 실 Redis redisTopologyTest 23 pass | fake 52중 7, 실 Redis 23중 3(renew ALREADY, 작은 revision RECORDED, ONLY_IF_OBSERVED INDETERMINATE) | 새 발견: ONLY_IF_OBSERVED가 application 계정 EVALSHA 권한 없어 실 Redis에서 INDETERMINATE → SCRIPT lane으로 이동해 수정. 결정 필요: revision 순서 규칙(10진 정수)을 포트(application-core)로 옮길지, cache 전용 배포의 script 권한 기동 probe, redis-runtime testFixtures 수정(leaf 경계) |
|
||||
| 04-03 | 충족 | persistence-jpa 507, jpaPlatformContractTest(PG) 15, sample check, app-bootstrap architectureTest, architectureCheck pass | 빈 조건에서 새 규칙 테스트 4 실패, 운영 패키지 임시 양방향 엔티티로 JpaProductionArchitectureTest 실패 확인 | 결정 필요: @JoinColumn 단방향 @OneToMany 허용(문서엔 예외), sample test 의존성·lockfile 변경. DisplayName은 AGENTS.md(영어) 따름 — 소유자 결정 5(한국어)와 AGENTS.md 불일치는 08 영역 기존 지적 |
|
||||
| 03-10 | 충족 | core-api 89, runtime 278, ledger-jpa 12, 실 PG integrationTest 30, 동시 재claim 5회 반복 pass | 계약 in-memory 4, PG 5, interceptor 4 실패 | 결정 필요: TTL을 설정 키 대신 interceptor 생성자 인자(starter가 interceptor 미조립 03-11), 넘겨받기는 ledger commit이 mutation과 같은 트랜잭션일 때만 안전(ADR 기재). 남음: COMMITTED 보존 기간 정리 없음 |
|
||||
| 05-09 | 부분 충족(결정 대기) | objectstorage check 136, architectureCheck pass, 실제 lane 2개는 'pinned image unavailable'로 실패(의도) | 7중 4(원 예외 그대로 등) | 남음: 대체 이미지 소유자 결정 필요, compose minio/mc도 Docker Hub |
|
||||
| 06-02 | 충족 | outbox-relay check 20, 종료 순서 테스트 3회 반복 pass | relayFinishesItsRunningCycleBeforeThePlatformClosesAdmission(회차 미기록 상태로 platform 정지) | 남음: 남은 claim lease 해제 없음(OutboxStorePort 메서드 필요), 테스트에 platform phase 값 MAX-1024 하드코딩 |
|
||||
| 07-01 | 충족 | service-runtime 98, shared-contract 260, web 273, app-bootstrap check 321 + systemTest 10, architectureCheck, verifyDependencyLocks, verifyEnvKeys pass | TracingExportSystemTest 로컬 수신기에 아무것도 안 옴→이후 trace id 불일치 | 결정 필요: shared-contract(ActiveTrace)·web 필터까지 범위 확장. 남음: sample 테스트 미실행(합친 뒤 게이트에서), lockfile 재생성 확인 |
|
||||
| 08-01+08-04+03-12 | 충족 | verifyStrictLaneStages(RED 44건→GREEN), build-logic 87, 14 lane Docker 실행 82 pass, spring70 20, webAdvanced 124, ledger 18, configuration-cache dry-run 5 lifecycle pass | verifyStrictLaneStages 44건 | 남음: integration-check 잡 실행 시간 미측정(timeout 240분), websocketNginx·messagingCertification·mongo lane 로컬 미실행, 다른 workflow '>-' 블록 --stacktrace 결함 22곳(미확인·미수정). 결정 필요: integration 잡 5개 대체, 중복 lane, CLAUDE.md/AGENTS.md에 performanceCheck 추가 |
|
||||
|
||||
### 13.1 합친 뒤 전체 게이트
|
||||
|
||||
19개 패치를 모두 합친 메인 작업 트리에서 오케스트레이터가 실행했다(프론트 세션과 공유 잠금).
|
||||
|
||||
| 게이트 | 결과 | 시간 | 실행 직전 부하 |
|
||||
|---|---|---|---|
|
||||
| `ci` | rc=0 | 397초 | load 22.19 |
|
||||
| `mainCheck` | rc=1 — `objectStorageMinioContractTest`, `objectStorageMinioFaultTest` 2건만 실패. 둘 다 이제 `PinnedImageUnavailableException: pinned image unavailable: minio/minio@sha256:4c4a48…`(05-09 의도대로). 새로 mainCheck에 들어간 `:sample-portfolio:systemTest` 포함 나머지 통과 | 118초 | load 18.97 |
|
||||
| `:verifyStrictLaneStages --dry-run` (새 PR 게이트, 08-01) | rc=0 | 45초 | load 8.81 |
|
||||
| `-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건 통과 확인).
|
||||
|
||||
### 13.2 결정이 필요한 것 (수정 중 새로 생김)
|
||||
|
||||
| 항목 | 내용 | 권고 |
|
||||
|---|---|---|
|
||||
| 03-01 list 기본 크기 | 크기를 선언하지 않은 일반 list를 원소 20개로 계산한다. 이전에 통과하던 깊은 목록 쿼리가 거부될 수 있다 | 유지. 필요한 필드만 `estimatedListSize` 선언 |
|
||||
| 04-02 포트 변경 | `ReconciliationJobStorePort.claimDue`에 lease 인자, `ReconciliationJob.claimFence` 추가(application-notification) | 유지 |
|
||||
| 06-01 vendored 수정 | messaging runtime-core·kafka의 retryable 표시를 고쳤다. 예산 설정 키는 만들지 않았다. 진짜 인증 오류도 5분 간격 무한 재시도(runbook 기재) | 유지. 인증 오류 경보 임계는 운영에서 정한다 |
|
||||
| 07-03 데모 계정 | 샘플이 공개 데모 계정 HTTP Basic을 쓴다(비밀번호=계정 이름, README 공개). 익명 쓰기는 401 | 샘플 한정이라 유지. 운영 복제 금지를 README에 명시됨 |
|
||||
| 09-02 마이그레이션 번호 | `V8_1`(V9는 운영 마이그레이션과 합친 Flyway에서 충돌) | 유지. 샘플 번호 규칙을 매뉴얼에 적는다 |
|
||||
| 05-02/03 revision 규칙 | revision은 10진 정수만. 규칙을 포트(application-core)로 옮길지, cache 전용 배포의 script 권한 기동 확인 | 포트로 옮긴다(후속) |
|
||||
| 05-05 breaker 설정 키 | client별 breaker 설정 키 없음 | 후속 |
|
||||
| 05-07 쿼터 상한 | 쿼터는 기록만 하고 상한 비교 없음 | 정책 결정 필요 |
|
||||
| 03-10 TTL | 설정 키 대신 interceptor 생성자 인자(starter가 아직 조립 안 함, 03-11) | 03-11과 함께 |
|
||||
| 07-01 범위 | trace id를 맞추려고 shared-contract(`ActiveTrace`)·web 필터까지 바꿈 | 유지 |
|
||||
| 08-01 단계 | integration 잡 5개를 `:integrationCheck` 하나로, `performanceCheck` 신설. 루트 `CLAUDE.md`/`AGENTS.md` 단계 목록 미반영 | 유지하고 문서 반영 |
|
||||
| 04-03 DisplayName | 에이전트가 AGENTS.md(영어)를 따름. 소유자 결정 5(한국어)와 AGENTS.md 불일치(08 영역 기존 지적) | AGENTS.md를 소유자 결정에 맞춘다 |
|
||||
| 05-09 MinIO 대체 이미지 | 여전히 미정. lane 2개는 구분된 메시지로 실패 | 소유자 결정 |
|
||||
|
||||
@@ -18,7 +18,8 @@ status: stub
|
||||
## Diagnosis
|
||||
|
||||
- Check token `aud` claim value
|
||||
- Compare against configured `spring.security.oauth2.resourceserver.jwt.audiences`
|
||||
- Compare against configured `app.security.audience` (`APP_SECURITY_JWT_AUDIENCE`, comma-separated;
|
||||
the token must name at least one)
|
||||
|
||||
## Action
|
||||
|
||||
|
||||
@@ -38,8 +38,17 @@ the time, and which half is not knowable from the status.
|
||||
6. If the method is not keyed, there is no ledger row. Resolve it against the business resource, or
|
||||
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,
|
||||
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
|
||||
before letting the retry through.
|
||||
|
||||
**Escalate when** the reconciler's pending list grows across passes. That means the ledger is
|
||||
unreachable rather than slow.
|
||||
unreachable rather than slow. A case pending as `IN_PROGRESS` for longer than the claim TTL with no
|
||||
retry arriving is a caller that gave up; it needs the business resource checked, not a ledger fix.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -23,11 +23,12 @@ status: stub
|
||||
### Step 1 — 확인
|
||||
1. ERROR log에서 `OUTBOX_DEAD_LETTER` 라인 확인: `event_id`, `event_type`, `correlation_id`, 마지막 실패 원인 예외 추출
|
||||
2. DB에서 DEAD row 확인: `SELECT * FROM outbox_event WHERE status = 'DEAD' ORDER BY occurred_at;`
|
||||
3. **차단 영향 파악 (중요)**: strict per-aggregate FIFO 정책상 DEAD row는 같은 `aggregate_id`의 후행 이벤트를 계속 차단함 —
|
||||
`SELECT count(*) FROM outbox_event b WHERE b.status <> 'PUBLISHED' AND EXISTS (SELECT 1 FROM outbox_event d WHERE d.status='DEAD' AND d.aggregate_id=b.aggregate_id AND d.occurred_at < b.occurred_at);`
|
||||
3. **차단 영향 파악 (중요)**: strict per-aggregate FIFO 정책상 DEAD row는 같은 aggregate(`tenant_scope`, `aggregate_type`, `aggregate_id`)의 후행 이벤트를 계속 차단함. 순서는 `(aggregate_sequence, event_index)`로 비교한다(claim SQL `PostgreSqlOutboxClaimRepository`와 같은 키) —
|
||||
`SELECT count(*) FROM outbox_event b WHERE b.status <> 'PUBLISHED' AND EXISTS (SELECT 1 FROM outbox_event d WHERE d.status='DEAD' AND d.tenant_scope=b.tenant_scope AND d.aggregate_type=b.aggregate_type AND d.aggregate_id=b.aggregate_id AND (d.aggregate_sequence < b.aggregate_sequence OR (d.aggregate_sequence = b.aggregate_sequence AND d.event_index < b.event_index)));`
|
||||
|
||||
### Step 2 — 임시 격리
|
||||
- DEAD는 max attempts(3) 소진의 최종 상태 — 자동 재시도 없음, 수동 개입 필수
|
||||
- DEAD는 확정 거부(`REJECTED_BEFORE_SEND`·`REJECTED_AFTER_BROKER`) 또는 분류되지 않은 발행 예외의 max attempts(3) 소진의 최종 상태 — 자동 재시도 없음, 수동 개입 필수
|
||||
- broker 정지·종료 중 거부·Kafka 인증/인가 실패는 DEAD가 되지 않는다(FAILED로 계속 재시도). 이것들로 DEAD가 보이면 이 변경 이전에 생긴 행이다
|
||||
- 차단된 aggregate가 비즈니스 크리티컬하면 아래 §4의 수동 처분(재발행 또는 skip)을 우선 수행
|
||||
|
||||
## 3. Diagnosis
|
||||
@@ -35,7 +36,7 @@ status: stub
|
||||
- log query: `{service="app"} | error.code="OUTBOX_DEAD_LETTER" | stats count by event_type`
|
||||
- 마지막 실패 원인 분류:
|
||||
- poison event (payload 직렬화/계약 위반) → payload 자체 결함, 재발행해도 실패 — 수정 후 재발행 또는 skip
|
||||
- broker 장기 outage 중 attempts 소진 → broker 회복 후 재발행으로 해결 가능
|
||||
- broker 장기 outage 중 attempts 소진 → 현재 relay에서는 일어나지 않는다(일시적 실패는 예산을 쓰지 않음). 이전 버전에서 생긴 행은 broker 회복 후 재발행으로 해결 가능
|
||||
- 구성 오류 (Kafka disabled 상태에서 producer 활성) → 구성 수정 후 재발행
|
||||
- 가능한 원인 우선순위: 구성 오류 > broker outage > poison payload
|
||||
|
||||
@@ -43,6 +44,8 @@ status: stub
|
||||
|
||||
- **재발행 (기본)**: 원인 해소 후 해당 row를 다시 claim 가능 상태로 되돌림 —
|
||||
`UPDATE outbox_event SET status = 'PENDING', attempt_count = 0, next_attempt_at = now() WHERE event_id = '<id>' AND status = 'DEAD';`
|
||||
장애 구간 전체를 한 번에 되돌리려면(원인이 해소된 것을 확인한 뒤):
|
||||
`UPDATE outbox_event SET status = 'PENDING', attempt_count = 0, next_attempt_at = now() WHERE status = 'DEAD' AND occurred_at BETWEEN '<장애 시작>' AND '<장애 끝>';` (outbox_event에는 DEAD가 된 시각 컬럼이 없어 이벤트 발생 시각으로 고른다 — 먼저 같은 조건의 SELECT로 대상을 확인한다)
|
||||
(consumer는 at-least-once + idempotencyKey dedupe 의무가 있으므로 중복 발행은 안전)
|
||||
- **skip (영구 폐기)**: 이벤트가 더 이상 유효하지 않으면 PUBLISHED로 마킹해 FIFO 차단을 해제 —
|
||||
`UPDATE outbox_event SET status = 'PUBLISHED' WHERE event_id = '<id>' AND status = 'DEAD';`
|
||||
|
||||
@@ -40,8 +40,9 @@ status: stub
|
||||
3. `outbox.pending.size` status 분포 확인 (FAILED 누적 vs PENDING 누적)
|
||||
|
||||
### Step 2 — 임시 격리
|
||||
- 일시 실패는 자동 backoff 재시도(30s × 2^(attempt-1) + jitter, max attempts 3)가 동작 — 즉시 수동 개입 불필요
|
||||
- broker 장기 다운이면 DEAD 전이 누적 전에 broker 회복을 우선 (max attempts 소진 시 `runbook://outbox/dead-letter`로 이관)
|
||||
- 일시 실패는 자동 backoff 재시도(30s × 2^(attempt-1) + jitter, 상한 5분)가 동작 — 즉시 수동 개입 불필요
|
||||
- broker 정지·종료 중 거부·Kafka 인증/인가 실패(`AMBIGUOUS`, `REJECTED_RETRYABLE`)는 시도 예산을 쓰지 않는다 — 장애가 길어도 DEAD가 되지 않고, broker가 돌아오면 늦어도 약 5분 30초 안에 자동 재발행된다
|
||||
- max attempts 3은 adapter가 분류하지 못하고 던진 발행 예외에만 적용된다 (소진 시 `runbook://outbox/dead-letter`로 이관)
|
||||
- relay 자체를 멈춰야 하면 `app.outbox.relay-enabled=false`로 스케줄러 비활성 (이벤트는 outbox 테이블에 안전하게 보존됨 — 유실 없음)
|
||||
|
||||
## 3. Diagnosis
|
||||
@@ -55,7 +56,8 @@ status: stub
|
||||
- 가능한 원인:
|
||||
- broker outage/네트워크 → broker 측 회복 대기
|
||||
- Kafka adapter 미구성(enabled인데 brokers 누락은 기동 시 차단됨) / disabled 상태에서 producer 활성화
|
||||
- poison event (직렬화 불가/payload 계약 위반) → 재시도 무의미, attempts 소진 후 DEAD로 흘러감 (의도된 동작)
|
||||
- poison event (직렬화 불가/payload 계약 위반) → 확정 거부(`REJECTED_*`)면 바로, 분류되지 않은 예외면 attempts 소진 후 DEAD로 흘러감 (의도된 동작)
|
||||
- 같은 행의 `OUTBOX_PUBLISH_FAILED`가 5분 간격으로 끝없이 반복되고 원인이 Kafka 인증/인가면 credential·ACL이 실제로 틀린 것이다 — 고치면 다음 재시도에서 저절로 빠진다
|
||||
- 동일 aggregate head 실패로 후행 이벤트가 FIFO 게이트에 차단되어 lag 증가 (strict per-aggregate FIFO — 설계 의도)
|
||||
|
||||
## 4. Mitigation
|
||||
|
||||
@@ -1136,12 +1136,19 @@ GQL-007이 *"named fragment가 custom introspection gate를 우회하고 variabl
|
||||
> *Guessing it from the operation root would price `order { customer { orders { … } } }` as three
|
||||
> root fields and miss the multiplication entirely.*
|
||||
|
||||
**(2) 카디널리티는 스키마가 아니라 요청에서 온다.**
|
||||
**(2) 목록을 돌려주는 필드는 클라이언트가 어떻게 물어도 원소 수만큼 곱한다.** page 필드(스키마에
|
||||
`first`/`last` 가 있거나 catalog 에 connection 으로 등록)는 리터럴 → 요청 변수 → 연산의 변수
|
||||
기본값 → 스키마 인자 기본값 순서로 page 를 찾고, 없으면 기본 page 크기로 곱한다. 찾은 값은 전부
|
||||
상한으로 검사한다. page 인자가 없는 일반 list 는 catalog 에 선언한 추정 크기(없으면 기본 page
|
||||
크기)로 차원마다 곱한다. connection 객체 바로 안의 `edges`·`nodes` 는 이미 곱한 page 라서 다시
|
||||
곱하지 않는다.
|
||||
|
||||
> *a connection's children are multiplied by the effective page size, and a page size supplied
|
||||
> through a variable is resolved from the request variables rather than assumed to be the default.
|
||||
> That is the difference between a budget and a suggestion — `first: $n` would otherwise cost the
|
||||
> same at 1 and at 1000.*
|
||||
> *Pricing an omitted argument as one row was the bypass: `items(first: 20)` scored 410 while
|
||||
> `items` scored 40, and four nested lists added up instead of multiplying.*
|
||||
|
||||
2026-11-01 리뷰 03-01 이 이 구멍을 찾았다. 그 전 javadoc 은 "변수로 준 page 를 요청 변수에서
|
||||
읽는다"까지만 말했고, 변수 기본값과 생략한 인자, 일반 list 는 1 로 계산됐다. 상세는
|
||||
`src/adapter/inbound/graphql/README.md` 의 「목록을 돌려주는 필드는…」 절.
|
||||
|
||||
**(3) 순회 자체가 유한하다.** 기본 `maximumVisitedNodes = 200_000`, fragment cycle은 확장 경로
|
||||
추적으로 끊는다. javadoc이 왜 검증된 문서에도 경계를 유지하는지 쓴다 — 이 scorer는 pre-execution
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# HTTP wire 계약
|
||||
|
||||
이 백엔드의 HTTP 응답을 읽는 클라이언트(짝 프론트, 파생 서비스의 다른 앱)가 기대해도 되는 것을 한
|
||||
곳에 적는다. 응답 모양과 멱등성 응답의 뜻은 이 문서가 정본이다. 다른 문서(web README 예외 표,
|
||||
`docs/web/runbook.md`, `docs/registries/error-codes.yaml` 주석)는 이 문서를 가리키고 같은 문장을 쓴다.
|
||||
|
||||
코드가 이 문서를 지키는지는 다음 테스트가 확인한다.
|
||||
|
||||
- 응답 원문의 키 집합: `src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java`
|
||||
- 멱등성 응답의 status·code·retryable·`Retry-After`: `IdempotencyExceptionMappingTest`,
|
||||
`RetryAfterAdvisorTest`, `OperationalErrorTest`
|
||||
|
||||
## 1. Envelope 키 존재 규칙
|
||||
|
||||
JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). **값이 `null`인 필드는 키째 생략한다.**
|
||||
빈 목록(`[]`)은 `null`이 아니므로 생략하지 않는다.
|
||||
|
||||
| 응답 | 최상위 키 | 없는 키 |
|
||||
| --- | --- | --- |
|
||||
| 성공 | `success`(=`true`), `data`, `meta` | `error` |
|
||||
| 실패 | `success`(=`false`), `error`, `meta` | `data` |
|
||||
| bulk 전체 성공 | `success`(=`true`), `results`, `meta` | `error` |
|
||||
| bulk 부분 실패 | `success`(=`false`), `error`(`code=BATCH_PARTIAL_FAILURE`, `details`=항목별 결과), `meta` | `results` |
|
||||
|
||||
- `success`가 판별자다. 클라이언트는 `success`로 갈라 읽고, 키가 있는지로 판단하지 않는다.
|
||||
- 성공인데 `data`가 `null`이면 `data` 키도 없다. 본문이 아예 없는 응답(204)은 Envelope가 아니다.
|
||||
- 빈 컬렉션 결과는 `"data": []`, 빈 bulk 결과는 `"results": []`, 항목 없는 부분 실패는
|
||||
`"details": []`로 나간다.
|
||||
|
||||
### `error` 키
|
||||
|
||||
| 키 | 항상 있음 | 뜻 |
|
||||
| --- | --- | --- |
|
||||
| `code` | 예 | 안정된 기계용 식별자. 클라이언트는 이것으로 분기한다 |
|
||||
| `category` | 예 | `Category` enum 이름(`VALIDATION`, `CONFLICT` …) |
|
||||
| `message` | 예 | 사용자에게 보여도 되는 한국어 문구(`ClientErrorMessages`). 분기에 쓰지 않는다 |
|
||||
| `retryable` | 예 | 같은 요청을 다시 보내도 안전하고 의미가 있는지 |
|
||||
| `details` | 아니오 | 코드별 구조 정보(검증 실패 필드 목록, bulk 항목 결과). 없으면 키도 없다 |
|
||||
|
||||
### `meta` 키
|
||||
|
||||
| 키 | 언제 있나 |
|
||||
| --- | --- |
|
||||
| `requestId` | 요청 id 필터(`WebMvcRequestIdFilter`)를 지난 모든 응답 |
|
||||
| `traceId` | 위와 같음. 추적이 꺼져 있어도 필터가 만든 W3C trace id가 들어간다 |
|
||||
| `correlationId` | 위와 같음. 값이 없으면 키가 없다 |
|
||||
| `page` | 페이지 목록 응답에만. `number`·`size`·`total`·`sort`(미정렬이면 `sort: null`) |
|
||||
|
||||
필터 앞에서 끊긴 응답(필터 체인 밖의 오류)은 id 키가 빠질 수 있다. 클라이언트는 `meta`의 모르는
|
||||
키를 무시한다.
|
||||
|
||||
### 왜 이렇게 나가는가
|
||||
|
||||
`Envelope`·`BulkEnvelope`·`ApiError`·`ResponseMeta`는 `shared-contract`에 있고, 이 leaf는 Java
|
||||
표준 라이브러리 외에는 의존하지 않는다. 그래서 `@JsonInclude`를 타입에 붙이지 않고, web 어댑터의
|
||||
`EnvelopeWireFormatConfig`가 Jackson mix-in으로 같은 규칙을 Boot의 `JsonMapper`에 등록한다. 이
|
||||
어댑터의 모든 HTTP writer(MVC 변환기, 보안 entry point, rate-limit interceptor)가 그 `JsonMapper`를
|
||||
쓴다. GraphQL·STOMP·gRPC는 이 타입들을 직렬화하지 않으므로 이 규칙의 영향을 받지 않는다.
|
||||
|
||||
## 2. 멱등성 응답
|
||||
|
||||
`Idempotency-Key`를 받는 쓰기 엔드포인트(KEYED)는 `IdempotencyExecutor`를 거친다. 같은 키로 다시
|
||||
보낸 요청은 서버가 아래 넷 중 하나로 판정한다. 키는 인증 주체와 operation 범위 안에서만 같은 키다.
|
||||
|
||||
| 경우 | status | `error.code` | `retryable` | `Retry-After` | 클라이언트 행동 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 재생(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` | 없음 | 키를 붙여 다시 보낸다 |
|
||||
|
||||
- **처리 중을 `retryable=true`로 두는 이유.** 같은 키 재전송은 서버가 재생·처리 중·불일치로 안전하게
|
||||
판정하므로, 다시 보내는 것이 맞는 행동이다. 새 키로 보내면 서버는 다른 요청으로 보고 막지 못해,
|
||||
첫 요청이 끝나면 같은 작업이 두 번 적용된다.
|
||||
- **`Retry-After: 2`의 근거.** 기본 processing lease(`app.capabilities.idempotency.processing-lease`,
|
||||
30s)보다 짧아, 첫 시도가 아직 끝날 수 있는 동안 다시 묻는다. 너무 이르면 409를 한 번 더 받을 뿐이고
|
||||
결과가 바뀌지는 않는다. lease를 2초보다 짧게 설정한 서비스는 이 값이 lease를 넘으므로 값을 다시
|
||||
정한다(`RetryAfterAdvisor`, `docs/registries/error-codes.yaml`).
|
||||
- executor는 기다리지 않는다. 처리 중이면 바로 409를 돌려준다. 키로 결과를 조회하는 엔드포인트는 없다.
|
||||
- 키 누락 처리는 엔드포인트가 정한다(공용 검증 부품 없음, 리뷰 02-12). 템플릿 예시
|
||||
(`PosterImagePublicationController`)는 헤더가 없으면 `MissingRequestHeaderException`, 비었거나
|
||||
256자를 넘으면 `IllegalArgumentException`으로 둘 다 400 `BAD_PARAMETER`다. 키를 요구하지 않는
|
||||
엔드포인트는 키 없이 보호 없이 실행된다.
|
||||
|
||||
같은 executor가 내는 나머지 두 실패:
|
||||
|
||||
| 경우 | status | `error.code` | `retryable` | `Retry-After` | 클라이언트 행동 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 멱등성 저장소 응답 없음 | 503 | `IDEMPOTENCY_UNAVAILABLE` | `true` | 없음 | 작업 실행 전에 거부됐다. 같은 키로 나중에 다시 보낸다 |
|
||||
| 이전 시도의 효과를 증명할 수 없음 | 500 | `IDEMPOTENCY_RECOVERY_REQUIRED` | `false` | 없음 | 재전송도 재실행도 안전하지 않다. 업무 데이터로 결과를 확인한다 |
|
||||
|
||||
## 3. 바꿀 때
|
||||
|
||||
- 응답 키를 더하거나 빼면 `EnvelopeWireShapeTest`와 이 문서 1절을 같이 고친다.
|
||||
- 멱등성 코드의 status·retryable·`Retry-After`를 바꾸면 `OperationalError`, `RetryAfterAdvisor`,
|
||||
`docs/registries/error-codes.yaml`, 이 문서 2절을 같은 변경에서 고친다.
|
||||
- 짝 프론트의 백엔드 계약 문서(`clean-architecture-frontend-template`
|
||||
`docs/architecture/backend-api-and-server-state-contract.md` §4.1·§6)는 이 문서를 가리켜야 한다.
|
||||
+4
-2
@@ -38,8 +38,10 @@ The idempotency key is the control, and there are exactly three ways it fails to
|
||||
3. **The record expired.** TTL is per-operation with a 72h cap. A retry after expiry is a new
|
||||
request by definition.
|
||||
|
||||
A `409 IDEMPOTENT_IN_FLIGHT` is not a failure: an earlier attempt is still running and
|
||||
the caller should retry after `Retry-After`.
|
||||
A `409 IDEMPOTENT_IN_FLIGHT` (retryable=true, `Retry-After: 2`) is not a failure: an earlier
|
||||
attempt is still running and its result is unknown. The caller resends with the **same**
|
||||
`Idempotency-Key` after `Retry-After`; a new key is a new request and is how a write ends up
|
||||
applied twice. The four idempotency answers are in `http-contract.md` §2.
|
||||
|
||||
## Rolling deploy stalls with instances half-drained
|
||||
|
||||
|
||||
+6
-2
@@ -27,8 +27,10 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇
|
||||
| `configContractCheck` | `:app-bootstrap:verifyEnvKeys`로 환경 설정 계약을 검사 |
|
||||
| `qualificationCheck` | 전체 기동(system) 레인과 보조 source set Checkstyle을 실행 |
|
||||
| `integrationCheck` | 선언된 strict integration lane(sample 포함)을 실행. 대부분 container runtime이 필요. 입력이 필요한 lane(Redis topology: `-Predis.topology.mode`, AWS: 보호 자격 증명 env)은 입력이 없으면 빠지고 집계가 그 이유를 출력 |
|
||||
| `performanceCheck` | 선언된 strict performance lane(부하·종료·pool·자원 상한)을 실행. 실서버·container가 필요. `integration-main.yml` `performance-check`가 main·nightly에 돌림 |
|
||||
| `verifyStrictLaneStages` | `--dry-run` 전용. `explicitOnly`가 아닌 strict lane이 workflow가 실제 실행하는 단계(`ci`·`:sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) 중 하나의 계획에 있는지, 각 단계를 workflow가 `--dry-run` 없이 실행하는지 검사. PR 게이트가 돌림 |
|
||||
| `ci` | PR 게이트: 모든 leaf `check`(API surface 검사 포함, 소유자 결정 20) + `architectureCheck` + `qualityCheck` |
|
||||
| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + `verifyPublicPathSnapshot` + 전송·메시징 qualification 레인 + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) |
|
||||
| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + sample 전체 기동(`:sample-portfolio:systemTest`) + `verifyPublicPathSnapshot` + 전송·메시징 qualification 레인 + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) |
|
||||
| `releaseCheck` | tag 전용 검사: `verifyReleaseProvenance` + `verifyPublicPathSnapshot`(`ci`를 다시 돌리지 않음) |
|
||||
|
||||
따라서 로컬에서 한 모듈만 수정했다면 `./gradlew :domain-core:check`처럼 focused task를
|
||||
@@ -489,7 +491,9 @@ Boot 기본값이 바뀌어도 wire 계약이 조용히 깨지지 않게 합니
|
||||
|
||||
- **`APP_SECURITY_JWT_ISSUER`** — OIDC issuer URI(Keycloak realm, Auth0 tenant 등). **필수** — 없으면
|
||||
기동 실패. 예: `https://keycloak.example.com/realms/ca-skeleton`.
|
||||
- **`APP_SECURITY_JWT_AUDIENCE`** — 기대하는 `aud` claim. 빈 값으로 두면 audience 검증을 건너뜁니다.
|
||||
- **`APP_SECURITY_JWT_AUDIENCE`** — 기대하는 `aud` claim(쉼표 목록 가능, 하나라도 맞으면 통과).
|
||||
JWT 모드에서 **필수** — 비어 있으면 기동 실패. 이 목록의 client 에 대한 `resource_access` role 만
|
||||
권한으로 읽습니다. 예: `ca-skeleton-api`.
|
||||
- **`SECURITY_PUBLIC_PATHS`** — 인증을 우회하는 경로 CSV. `api-base-path` 뒤의 full path 를 씁니다(예:
|
||||
`/api/healthcheck`). 이 값의 변경은 `verifyPublicPathSnapshot` 게이트가 감시합니다(위 build.gradle
|
||||
설명 참조).
|
||||
|
||||
@@ -188,6 +188,41 @@ data 다. GraphQL over HTTP 초안의 status 294 는 쓰지 않는다. 이 leaf
|
||||
모델(`GraphQlHttpStatusMapper`, `GraphQlHttpProfile` 등)은 요청 경로에 없어서 2026-09-25 에
|
||||
삭제했다(`docs/capability-status.md` 제거 표).
|
||||
|
||||
## 목록을 돌려주는 필드는 클라이언트가 어떻게 물어도 원소 수만큼 곱한다
|
||||
|
||||
복잡도 점수(`cost/GraphQlDocumentComplexityScorer`)는 실행 전에 매긴다. 목록 필드의 하위 비용에
|
||||
곱하는 수는 이렇게 정한다.
|
||||
|
||||
| 필드 | 곱하는 수 |
|
||||
| --- | --- |
|
||||
| page 필드 — 스키마에 `first`/`last` 인자가 있거나 catalog 에 `connection=true` 로 등록 | 리터럴 → 요청 변수 → 연산의 변수 기본값 → 스키마 인자 기본값 순서로 찾은 page. 없으면 기본 page 크기(`defaultPageSize`). 찾은 값은 모두 `maximum-page-size` 로 검사하고, `first`·`last` 를 둘 다 주면 큰 쪽 |
|
||||
| page 인자가 없는 일반 list | catalog 의 `GraphQlFieldCostDescriptor.estimatedListSize`, 선언이 없으면 기본 page 크기. `[[T]]` 는 차원마다 한 번 |
|
||||
| page 필드가 돌려준 connection 객체 바로 안의 list(`edges`·`nodes`) | 곱하지 않는다. connection 이 이미 page 만큼 곱했다 |
|
||||
|
||||
2026-11-01 리뷰(03-01) 전에는 인자가 값으로 보일 때만 곱했다. `items(first: 20)` 은 410 점,
|
||||
`items` 는 40 점, list 4단 중첩은 100 점이었고 `query($n: Int = 100000)` 은 상한 검사 없이
|
||||
통과했다. 예산(기본 10,000)과 page 상한(기본 100)이 목록 필드가 생기는 순간 꺼져 있었다.
|
||||
|
||||
**도입하는 서비스에 미치는 영향.** 크기를 선언하지 않은 일반 list 는 이제 원소 20 개로 계산된다.
|
||||
작은 고정 목록(예: 태그 몇 개)이 예산을 많이 먹으면 `GraphQlCostCatalog` 빈에
|
||||
`new GraphQlFieldCostDescriptor("Item.tags", base, weight, false, 5)` 처럼 추정 크기를 선언한다.
|
||||
점수가 커지는 쪽으로만 바뀌므로, 이전에 통과하던 깊은 목록 쿼리가 `GRAPHQL_COMPLEXITY_EXCEEDED` 로
|
||||
거부될 수 있다.
|
||||
|
||||
**고른 방법과 버린 대안.**
|
||||
|
||||
- 변수 기본값은 연산 문서의 `VariableDefinition` 기본값을 직접 읽는다. graphql-java 의
|
||||
`ValuesResolver.coerceVariableValues` 로 강제 변환한 값을 쓰는 방법은 버렸다. 그 호출은 잘못된
|
||||
변수에서 예외를 던지므로, 지금 실행 단계가 내는 변수 오류가 비용 단계에서 다른 모양으로 나오게
|
||||
된다. page 크기에 필요한 것은 Int 하나라서 직접 읽는 쪽이 오류 계약을 건드리지 않는다.
|
||||
- 일반 list 의 크기는 스키마 지시어(`@listSize` 등)가 아니라 기존 cost catalog 에 선언한다. 비용
|
||||
정책이 이미 catalog 한 곳에 있고, 지시어는 스키마 파일과 SDL 처리 경로를 하나 더 만든다.
|
||||
- graphql-java 기본 `MaxQueryComplexityInstrumentation` 은 쓰지 않는다. 그것도 list 배수를 모르는
|
||||
필드 개수 합이라 같은 구멍이 남고, 점수가 두 벌이 된다.
|
||||
- 점수가 `long` 을 넘으면 `Long.MAX_VALUE` 에서 멈춘다(포화 산술). 목록마다 곱하면 적대적인 문서
|
||||
몇 단으로 `long` 끝에 닿는데, 그때 `ArithmeticException` 이 내부 오류로 새지 않고 예산 초과로
|
||||
거부되게 하기 위해서다.
|
||||
|
||||
## 요청 단위 DB 트랜잭션을 열지 않는다
|
||||
|
||||
GraphQL 한 요청은 여러 root field 를 담을 수 있고, 각 root 는 자기 use case 를 호출한다.
|
||||
|
||||
+84
-12
@@ -23,7 +23,8 @@ public final class GraphQlComplexityCalculator {
|
||||
* Creates the calculator.
|
||||
*
|
||||
* @param catalog registered field costs
|
||||
* @param defaultPageSize page size assumed when a connection omits {@code first}/{@code last}
|
||||
* @param defaultPageSize page size assumed when a connection omits {@code first}/{@code last},
|
||||
* and the element count of a list whose size was never declared
|
||||
* @param maximumPageSize largest page size a client may request
|
||||
*/
|
||||
public GraphQlComplexityCalculator(
|
||||
@@ -39,24 +40,63 @@ public final class GraphQlComplexityCalculator {
|
||||
/**
|
||||
* Cost of a connection field.
|
||||
*
|
||||
* <p>Both page arguments are checked against the maximum, and the larger one is the multiplier:
|
||||
* which of the two a resolver honours is its business, and pricing the smaller one would let
|
||||
* {@code first: 1, last: 100000} through on the strength of the argument it ignores.
|
||||
*
|
||||
* @param coordinate schema coordinate of the connection field
|
||||
* @param first requested forward page size, or {@code null}
|
||||
* @param last requested backward page size, or {@code null}
|
||||
* @param childCost cost of one child subtree
|
||||
* @throws GraphQlComplexityRejectedException when the requested page exceeds the maximum
|
||||
* @throws GraphQlComplexityRejectedException when a requested page exceeds the maximum
|
||||
*/
|
||||
public GraphQlComplexityResult connectionCost(
|
||||
String coordinate, Integer first, Integer last, long childCost) {
|
||||
int requested = first != null ? first : last != null ? last : defaultPageSize;
|
||||
if (requested > maximumPageSize) {
|
||||
throw new GraphQlComplexityRejectedException("page size exceeds maximum");
|
||||
}
|
||||
if (requested < 1) {
|
||||
throw new GraphQlComplexityRejectedException("page size must be positive");
|
||||
}
|
||||
requireAllowedPage(first);
|
||||
requireAllowedPage(last);
|
||||
int requested =
|
||||
first != null && last != null
|
||||
? Math.max(first, last)
|
||||
: first != null ? first : last != null ? last : defaultPageSize;
|
||||
long root = catalog.require(coordinate).baseCost();
|
||||
return new GraphQlComplexityResult(
|
||||
Math.addExact(root, Math.multiplyExact((long) requested, childCost)));
|
||||
return new GraphQlComplexityResult(saturatedAdd(root, saturatedMultiply(requested, childCost)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Cost of a list-returning field that takes no page arguments.
|
||||
*
|
||||
* <p>A plain list is not one child, it is as many children as it holds. The registered {@link
|
||||
* GraphQlFieldCostDescriptor#estimatedListSize()} is that count when the adopter declared one;
|
||||
* otherwise the default page size stands in for it, because a list nobody sized is exactly the
|
||||
* one whose size nobody bounded. A list of lists multiplies once per dimension.
|
||||
*
|
||||
* @param coordinate schema coordinate
|
||||
* @param dimensions how many list wrappers the field type has, at least one
|
||||
* @param childCost cost of one element's subtree
|
||||
*/
|
||||
public GraphQlComplexityResult listCost(String coordinate, int dimensions, long childCost) {
|
||||
if (dimensions < 1) {
|
||||
throw new IllegalArgumentException("a list field has at least one dimension");
|
||||
}
|
||||
GraphQlFieldCostDescriptor descriptor = catalog.require(coordinate);
|
||||
int size =
|
||||
descriptor.estimatedListSize() == GraphQlFieldCostDescriptor.UNDECLARED_LIST_SIZE
|
||||
? defaultPageSize
|
||||
: descriptor.estimatedListSize();
|
||||
long elements = childCost;
|
||||
for (int dimension = 0; dimension < dimensions; dimension++) {
|
||||
elements = saturatedMultiply(size, elements);
|
||||
}
|
||||
return new GraphQlComplexityResult(saturatedAdd(descriptor.weightedCost(), elements));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a coordinate is registered as a paginated connection.
|
||||
*
|
||||
* <p>Such a field is priced at the default page even when its schema declares no page argument.
|
||||
*/
|
||||
public boolean connection(String coordinate) {
|
||||
return catalog.require(coordinate).connection();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -67,7 +107,7 @@ public final class GraphQlComplexityCalculator {
|
||||
*/
|
||||
public GraphQlComplexityResult fieldCost(String coordinate, long childCost) {
|
||||
GraphQlFieldCostDescriptor descriptor = catalog.require(coordinate);
|
||||
return new GraphQlComplexityResult(Math.addExact(descriptor.weightedCost(), childCost));
|
||||
return new GraphQlComplexityResult(saturatedAdd(descriptor.weightedCost(), childCost));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -85,4 +125,36 @@ public final class GraphQlComplexityCalculator {
|
||||
public int effectivePageSize(Integer first, Integer last) {
|
||||
return first != null ? first : last != null ? last : defaultPageSize;
|
||||
}
|
||||
|
||||
private void requireAllowedPage(Integer requested) {
|
||||
if (requested == null) {
|
||||
return;
|
||||
}
|
||||
if (requested > maximumPageSize) {
|
||||
throw new GraphQlComplexityRejectedException("page size exceeds maximum");
|
||||
}
|
||||
if (requested < 1) {
|
||||
throw new GraphQlComplexityRejectedException("page size must be positive");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Addition that stops at {@link Long#MAX_VALUE}.
|
||||
*
|
||||
* <p>Scores multiply with every nested list, so a few levels of a hostile document reach the end
|
||||
* of {@code long}. Overflow must read as "over any budget", not as an arithmetic error that
|
||||
* escapes the rejection path as an internal failure.
|
||||
*/
|
||||
static long saturatedAdd(long left, long right) {
|
||||
long sum = left + right;
|
||||
return ((left ^ sum) & (right ^ sum)) < 0 ? Long.MAX_VALUE : sum;
|
||||
}
|
||||
|
||||
/** Multiplication of non-negative values that stops at {@link Long#MAX_VALUE}. */
|
||||
static long saturatedMultiply(long left, long right) {
|
||||
if (left == 0 || right == 0) {
|
||||
return 0;
|
||||
}
|
||||
return left > Long.MAX_VALUE / right ? Long.MAX_VALUE : left * right;
|
||||
}
|
||||
}
|
||||
|
||||
+158
-36
@@ -12,7 +12,9 @@ import graphql.language.OperationDefinition;
|
||||
import graphql.language.Selection;
|
||||
import graphql.language.SelectionSet;
|
||||
import graphql.language.Value;
|
||||
import graphql.language.VariableDefinition;
|
||||
import graphql.language.VariableReference;
|
||||
import graphql.schema.GraphQLArgument;
|
||||
import graphql.schema.GraphQLFieldDefinition;
|
||||
import graphql.schema.GraphQLFieldsContainer;
|
||||
import graphql.schema.GraphQLList;
|
||||
@@ -20,6 +22,8 @@ import graphql.schema.GraphQLNonNull;
|
||||
import graphql.schema.GraphQLObjectType;
|
||||
import graphql.schema.GraphQLSchema;
|
||||
import graphql.schema.GraphQLType;
|
||||
import graphql.schema.InputValueWithState;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
@@ -36,10 +40,24 @@ import java.util.Objects;
|
||||
* against the schema. Guessing it from the operation root would price {@code order { customer {
|
||||
* orders { … } } }} as three root fields and miss the multiplication entirely.
|
||||
*
|
||||
* <p>Cardinality comes from the request, not from the schema: a connection's children are
|
||||
* multiplied by the effective page size, and a page size supplied through a variable is resolved
|
||||
* from the request variables rather than assumed to be the default. That is the difference between
|
||||
* a budget and a suggestion — {@code first: $n} would otherwise cost the same at 1 and at 1000.
|
||||
* <p>Every field that returns many things multiplies its children, however the client phrased the
|
||||
* request:
|
||||
*
|
||||
* <ul>
|
||||
* <li>A paginated field — one whose schema declares {@code first}/{@code last}, or one registered
|
||||
* as a connection — multiplies by the page it will be asked for. That page is the literal, or
|
||||
* the request variable, or the operation's variable default, or the schema argument default,
|
||||
* in that order; when none applies it is the default page size, never one. Each of these is
|
||||
* checked against the maximum page size, so {@code ($n: Int = 100000)} is refused exactly as
|
||||
* the literal would be.
|
||||
* <li>A list-returning field without page arguments multiplies by its registered estimated size,
|
||||
* or the default page size, once per list dimension.
|
||||
* <li>The list fields directly inside a paginated object (a Relay connection's {@code edges} or
|
||||
* {@code nodes}) are the page the connection already paid for, and are not multiplied again.
|
||||
* </ul>
|
||||
*
|
||||
* <p>Pricing an omitted argument as one row was the bypass: {@code items(first: 20)} scored 410
|
||||
* while {@code items} scored 40, and four nested lists added up instead of multiplying.
|
||||
*
|
||||
* <p>Traversal is bounded, and fragment cycles are cut by tracking the expansion path. This runs on
|
||||
* documents that have passed validation, but the bound stays because the scorer is also used from
|
||||
@@ -50,6 +68,9 @@ public final class GraphQlDocumentComplexityScorer {
|
||||
/** Prefix that marks an introspection field, which is gated rather than priced. */
|
||||
public static final String INTROSPECTION_FIELD_PREFIX = "__";
|
||||
|
||||
private static final String FIRST = "first";
|
||||
private static final String LAST = "last";
|
||||
|
||||
private final GraphQlComplexityCalculator calculator;
|
||||
private final int maximumVisitedNodes;
|
||||
|
||||
@@ -79,7 +100,8 @@ public final class GraphQlDocumentComplexityScorer {
|
||||
* @param schema schema the document was validated against
|
||||
* @param document the parsed document
|
||||
* @param operation the selected operation
|
||||
* @param variables the request variables, used to resolve page sizes
|
||||
* @param variables the request variables as the client sent them, used to resolve page sizes; the
|
||||
* operation's own variable defaults fill in what the client left out
|
||||
* @throws GraphQlComplexityRejectedException when a requested page exceeds the maximum
|
||||
* @throws GraphQlStructuralLimitException when traversal exceeds the node budget
|
||||
*/
|
||||
@@ -112,9 +134,10 @@ public final class GraphQlDocumentComplexityScorer {
|
||||
root,
|
||||
operation.getSelectionSet(),
|
||||
fragments,
|
||||
variables == null ? Map.of() : variables,
|
||||
PageVariables.of(operation, variables),
|
||||
new Counter(),
|
||||
new ArrayDeque<>());
|
||||
new ArrayDeque<>(),
|
||||
false);
|
||||
return new GraphQlComplexityResult(total);
|
||||
}
|
||||
|
||||
@@ -123,9 +146,10 @@ public final class GraphQlDocumentComplexityScorer {
|
||||
GraphQLFieldsContainer parent,
|
||||
SelectionSet selectionSet,
|
||||
Map<String, FragmentDefinition> fragments,
|
||||
Map<String, Object> variables,
|
||||
PageVariables variables,
|
||||
Counter counter,
|
||||
Deque<String> expansionPath) {
|
||||
Deque<String> expansionPath,
|
||||
boolean listsAreThePage) {
|
||||
|
||||
if (selectionSet == null || parent == null) {
|
||||
return 0;
|
||||
@@ -137,16 +161,24 @@ public final class GraphQlDocumentComplexityScorer {
|
||||
|
||||
if (selection instanceof Field field) {
|
||||
total =
|
||||
Math.addExact(
|
||||
GraphQlComplexityCalculator.saturatedAdd(
|
||||
total,
|
||||
fieldCost(schema, parent, field, fragments, variables, counter, expansionPath));
|
||||
fieldCost(
|
||||
schema,
|
||||
parent,
|
||||
field,
|
||||
fragments,
|
||||
variables,
|
||||
counter,
|
||||
expansionPath,
|
||||
listsAreThePage));
|
||||
} else if (selection instanceof InlineFragment inlineFragment) {
|
||||
GraphQLFieldsContainer target =
|
||||
inlineFragment.getTypeCondition() == null
|
||||
? parent
|
||||
: fieldsContainer(schema, inlineFragment.getTypeCondition().getName());
|
||||
total =
|
||||
Math.addExact(
|
||||
GraphQlComplexityCalculator.saturatedAdd(
|
||||
total,
|
||||
selectionSetCost(
|
||||
schema,
|
||||
@@ -155,7 +187,8 @@ public final class GraphQlDocumentComplexityScorer {
|
||||
fragments,
|
||||
variables,
|
||||
counter,
|
||||
expansionPath));
|
||||
expansionPath,
|
||||
listsAreThePage));
|
||||
} else if (selection instanceof FragmentSpread spread) {
|
||||
FragmentDefinition fragment = fragments.get(spread.getName());
|
||||
// A fragment already on this path is a cycle. Validation rejects it, but the scorer must
|
||||
@@ -169,7 +202,7 @@ public final class GraphQlDocumentComplexityScorer {
|
||||
: fieldsContainer(schema, fragment.getTypeCondition().getName());
|
||||
expansionPath.push(spread.getName());
|
||||
total =
|
||||
Math.addExact(
|
||||
GraphQlComplexityCalculator.saturatedAdd(
|
||||
total,
|
||||
selectionSetCost(
|
||||
schema,
|
||||
@@ -178,7 +211,8 @@ public final class GraphQlDocumentComplexityScorer {
|
||||
fragments,
|
||||
variables,
|
||||
counter,
|
||||
expansionPath));
|
||||
expansionPath,
|
||||
listsAreThePage));
|
||||
expansionPath.pop();
|
||||
}
|
||||
}
|
||||
@@ -190,9 +224,10 @@ public final class GraphQlDocumentComplexityScorer {
|
||||
GraphQLFieldsContainer parent,
|
||||
Field field,
|
||||
Map<String, FragmentDefinition> fragments,
|
||||
Map<String, Object> variables,
|
||||
PageVariables variables,
|
||||
Counter counter,
|
||||
Deque<String> expansionPath) {
|
||||
Deque<String> expansionPath,
|
||||
boolean listsAreThePage) {
|
||||
|
||||
if (field.getName().startsWith(INTROSPECTION_FIELD_PREFIX)) {
|
||||
// Introspection is an allow/deny decision made by the authorization stage. Pricing it here
|
||||
@@ -202,53 +237,110 @@ public final class GraphQlDocumentComplexityScorer {
|
||||
|
||||
GraphQLFieldDefinition definition = parent.getFieldDefinition(field.getName());
|
||||
String coordinate = parent.getName() + "." + field.getName();
|
||||
GraphQLFieldsContainer childContainer =
|
||||
definition == null ? null : fieldsContainer(unwrap(definition.getType()));
|
||||
if (definition == null) {
|
||||
// Validation rejects an unknown field; price what is there rather than invent a type.
|
||||
return calculator.fieldCost(coordinate, 0).total();
|
||||
}
|
||||
int dimensions = listDimensions(definition.getType());
|
||||
boolean paginated =
|
||||
definition.getArgument(FIRST) != null
|
||||
|| definition.getArgument(LAST) != null
|
||||
|| calculator.connection(coordinate);
|
||||
|
||||
long childCost =
|
||||
selectionSetCost(
|
||||
schema,
|
||||
childContainer,
|
||||
fieldsContainer(definition.getType()),
|
||||
field.getSelectionSet(),
|
||||
fragments,
|
||||
variables,
|
||||
counter,
|
||||
expansionPath);
|
||||
expansionPath,
|
||||
// A connection object's own lists are the page it was charged for.
|
||||
paginated && dimensions == 0);
|
||||
|
||||
Integer first = pageArgument(field, "first", variables);
|
||||
Integer last = pageArgument(field, "last", variables);
|
||||
if (first != null || last != null) {
|
||||
if (paginated) {
|
||||
Integer first = pageArgument(definition, field, FIRST, variables);
|
||||
Integer last = pageArgument(definition, field, LAST, variables);
|
||||
return calculator.connectionCost(coordinate, first, last, childCost).total();
|
||||
}
|
||||
if (dimensions > 0 && !listsAreThePage) {
|
||||
return calculator.listCost(coordinate, dimensions, childCost).total();
|
||||
}
|
||||
return calculator.fieldCost(coordinate, childCost).total();
|
||||
}
|
||||
|
||||
private static Integer pageArgument(Field field, String name, Map<String, Object> variables) {
|
||||
/**
|
||||
* The page a field will be asked for, or {@code null} when nothing names one.
|
||||
*
|
||||
* <p>An argument the document leaves out still reaches the resolver as the schema default, so
|
||||
* that default is the page; an explicit {@code null} is not replaced by it.
|
||||
*/
|
||||
private static Integer pageArgument(
|
||||
GraphQLFieldDefinition definition, Field field, String name, PageVariables variables) {
|
||||
for (Argument argument : field.getArguments()) {
|
||||
if (!argument.getName().equals(name)) {
|
||||
continue;
|
||||
if (argument.getName().equals(name)) {
|
||||
return intValue(argument.getValue(), variables);
|
||||
}
|
||||
return intValue(argument.getValue(), variables);
|
||||
}
|
||||
return null;
|
||||
GraphQLArgument declared = definition.getArgument(name);
|
||||
if (declared == null || !declared.hasSetDefaultValue()) {
|
||||
return null;
|
||||
}
|
||||
InputValueWithState fallback = declared.getArgumentDefaultValue();
|
||||
if (fallback.isLiteral() && fallback.getValue() instanceof Value<?> literal) {
|
||||
return intValue(literal, variables);
|
||||
}
|
||||
return fallback.isExternal() ? intValue(fallback.getValue()) : null;
|
||||
}
|
||||
|
||||
private static Integer intValue(Value<?> value, Map<String, Object> variables) {
|
||||
private static Integer intValue(Value<?> value, PageVariables variables) {
|
||||
if (value instanceof IntValue intValue) {
|
||||
BigInteger raw = intValue.getValue();
|
||||
// A literal outside int range cannot be a page size; treating it as the maximum lets the
|
||||
// calculator reject it rather than silently overflowing to something affordable.
|
||||
return raw.bitLength() >= Integer.SIZE ? Integer.MAX_VALUE : raw.intValue();
|
||||
if (raw.bitLength() >= Integer.SIZE) {
|
||||
return raw.signum() < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
|
||||
}
|
||||
return raw.intValue();
|
||||
}
|
||||
if (value instanceof VariableReference reference) {
|
||||
Object supplied = variables.get(reference.getName());
|
||||
if (supplied instanceof Number number) {
|
||||
long asLong = number.longValue();
|
||||
return asLong > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) asLong;
|
||||
}
|
||||
return variables.resolve(reference.getName());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Integer intValue(Object supplied) {
|
||||
if (!(supplied instanceof Number number)) {
|
||||
// Not an Int: coercion rejects it after this stage, and pricing it as no page is the same
|
||||
// answer the resolver would give an absent argument.
|
||||
return null;
|
||||
}
|
||||
BigDecimal exact = new BigDecimal(number.toString());
|
||||
if (exact.compareTo(BigDecimal.valueOf(Integer.MAX_VALUE)) > 0) {
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
if (exact.compareTo(BigDecimal.valueOf(Integer.MIN_VALUE)) < 0) {
|
||||
return Integer.MIN_VALUE;
|
||||
}
|
||||
return exact.intValue();
|
||||
}
|
||||
|
||||
private static int listDimensions(GraphQLType type) {
|
||||
int dimensions = 0;
|
||||
GraphQLType current = type;
|
||||
while (true) {
|
||||
if (current instanceof GraphQLNonNull nonNull) {
|
||||
current = nonNull.getWrappedType();
|
||||
} else if (current instanceof GraphQLList list) {
|
||||
dimensions++;
|
||||
current = list.getWrappedType();
|
||||
} else {
|
||||
return dimensions;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static GraphQLObjectType rootType(GraphQLSchema schema, OperationDefinition operation) {
|
||||
OperationDefinition.Operation kind =
|
||||
operation.getOperation() == null
|
||||
@@ -282,6 +374,36 @@ public final class GraphQlDocumentComplexityScorer {
|
||||
return current;
|
||||
}
|
||||
|
||||
/**
|
||||
* The values a variable reference can stand for, before graphql-java coerces them.
|
||||
*
|
||||
* <p>The request map holds only what the client sent. A variable it left out takes the
|
||||
* operation's declared default, which is the value the resolver will see — reading the request
|
||||
* map alone priced {@code ($n: Int = 100000)} as if no page had been asked for. A variable the
|
||||
* client sent as {@code null} stays {@code null}; it does not fall back to the default.
|
||||
*/
|
||||
private record PageVariables(Map<String, Object> supplied, Map<String, Value<?>> defaults) {
|
||||
|
||||
static PageVariables of(OperationDefinition operation, Map<String, Object> supplied) {
|
||||
Map<String, Value<?>> defaults = new LinkedHashMap<>();
|
||||
for (VariableDefinition definition : operation.getVariableDefinitions()) {
|
||||
if (definition.getDefaultValue() != null) {
|
||||
defaults.put(definition.getName(), definition.getDefaultValue());
|
||||
}
|
||||
}
|
||||
return new PageVariables(supplied == null ? Map.of() : supplied, defaults);
|
||||
}
|
||||
|
||||
Integer resolve(String name) {
|
||||
if (supplied.containsKey(name)) {
|
||||
return intValue(supplied.get(name));
|
||||
}
|
||||
Value<?> fallback = defaults.get(name);
|
||||
// A default is a constant literal by the grammar, so it cannot refer to another variable.
|
||||
return fallback instanceof IntValue ? intValue(fallback, this) : null;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Counter {
|
||||
|
||||
private int visited;
|
||||
|
||||
+21
-2
@@ -9,10 +9,20 @@ import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate;
|
||||
* @param baseCost fixed cost of resolving the field once
|
||||
* @param resolverWeight what the resolver actually does
|
||||
* @param connection whether the field returns a paginated connection, whose children multiply by
|
||||
* page size
|
||||
* page size even when it declares no {@code first}/{@code last} argument
|
||||
* @param estimatedListSize how many elements a list-returning field without page arguments is
|
||||
* expected to hold, multiplied into its children's cost; {@link #UNDECLARED_LIST_SIZE} means
|
||||
* "not declared" and the client policy's default page size is used instead
|
||||
*/
|
||||
public record GraphQlFieldCostDescriptor(
|
||||
String coordinate, long baseCost, GraphQlResolverWeight resolverWeight, boolean connection) {
|
||||
String coordinate,
|
||||
long baseCost,
|
||||
GraphQlResolverWeight resolverWeight,
|
||||
boolean connection,
|
||||
int estimatedListSize) {
|
||||
|
||||
/** No list size was declared; a plain list is then priced at the default page size. */
|
||||
public static final int UNDECLARED_LIST_SIZE = 0;
|
||||
|
||||
public GraphQlFieldCostDescriptor {
|
||||
GraphQlSchemaCoordinate.parse(coordinate);
|
||||
@@ -22,6 +32,15 @@ public record GraphQlFieldCostDescriptor(
|
||||
if (resolverWeight == null) {
|
||||
throw new IllegalArgumentException("resolver weight is required");
|
||||
}
|
||||
if (estimatedListSize < UNDECLARED_LIST_SIZE) {
|
||||
throw new IllegalArgumentException("estimated list size cannot be negative");
|
||||
}
|
||||
}
|
||||
|
||||
/** A descriptor that leaves a plain list's size to the default page size. */
|
||||
public GraphQlFieldCostDescriptor(
|
||||
String coordinate, long baseCost, GraphQlResolverWeight resolverWeight, boolean connection) {
|
||||
this(coordinate, baseCost, resolverWeight, connection, UNDECLARED_LIST_SIZE);
|
||||
}
|
||||
|
||||
/** Base cost plus resolver weight, before any cardinality multiplier. */
|
||||
|
||||
+62
-1
@@ -17,8 +17,10 @@ import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -187,6 +189,48 @@ class GraphQlPlatformExecutionPathTest {
|
||||
assertThatRejected(response, "GRAPHQL_COMPLEXITY_EXCEEDED");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("page 인자를 생략한 list 는 기본 page 크기로 곱해져 resolver 전에 복잡도 초과로 거부된다")
|
||||
void aPageOmittedListIsPricedAtTheDefaultPageAndRejected() {
|
||||
// when
|
||||
ResponseEntity<String> response = post("{ platformPage { id } }");
|
||||
|
||||
// then
|
||||
assertThatRejected(response, "GRAPHQL_COMPLEXITY_EXCEEDED");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("page 인자가 없는 일반 list 를 중첩하면 원소 수만큼 곱해져 resolver 전에 거부된다")
|
||||
void aNestedPlainListIsMultipliedAndRejected() {
|
||||
// when
|
||||
ResponseEntity<String> response = post("{ platformNodes { id child { id } } }");
|
||||
|
||||
// then
|
||||
assertThatRejected(response, "GRAPHQL_COMPLEXITY_EXCEEDED");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("변수 기본값으로 숨긴 page 크기가 상한을 넘으면 resolver 전에 거부된다")
|
||||
void aPageSizeHiddenInAVariableDefaultIsRejected() {
|
||||
// when
|
||||
ResponseEntity<String> response =
|
||||
post("query P($n: Int = 100000) { platformPage(first: $n) { id } }");
|
||||
|
||||
// then
|
||||
assertThatRejected(response, "GRAPHQL_COMPLEXITY_EXCEEDED");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("예산 안의 작은 page 는 list resolver 까지 도달한다")
|
||||
void aSmallPageWithinTheBudgetReachesTheResolver() {
|
||||
// when
|
||||
ResponseEntity<String> response = post("{ platformPage(first: 2) { id } }");
|
||||
|
||||
// then
|
||||
assertThat(response.getBody()).contains("\"platformPage\":[{\"id\":\"p-0\"},{\"id\":\"p-1\"}]");
|
||||
assertThat(RESOLVER_INVOCATIONS).hasValue(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnauthorizedCoordinateIsRejectedBeforeAnyResolverRuns() {
|
||||
ResponseEntity<String> response = post("{ platformSecret }");
|
||||
@@ -376,6 +420,21 @@ class GraphQlPlatformExecutionPathTest {
|
||||
return "must-never-be-returned";
|
||||
}
|
||||
|
||||
@QueryMapping
|
||||
List<PlatformNode> platformPage(@Argument Integer first) {
|
||||
RESOLVER_INVOCATIONS.incrementAndGet();
|
||||
int size = first == null ? 0 : first;
|
||||
return IntStream.range(0, size)
|
||||
.mapToObj(index -> new PlatformNode("p-" + index, "page-" + index, null))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@QueryMapping
|
||||
List<PlatformNode> platformNodes() {
|
||||
RESOLVER_INVOCATIONS.incrementAndGet();
|
||||
return List.of();
|
||||
}
|
||||
|
||||
/** Reports which of the three variable cases actually reached coercion. */
|
||||
@QueryMapping
|
||||
String platformEcho(@Argument String value) {
|
||||
@@ -429,7 +488,7 @@ class GraphQlPlatformExecutionPathTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* A deny-by-default policy with three coordinates opened.
|
||||
* A deny-by-default policy with the coordinates under test opened.
|
||||
*
|
||||
* <p>Deliberately the fail-closed shape an adopter is expected to ship, so the denial test is
|
||||
* exercising the same configuration a production deployment would have rather than a special
|
||||
@@ -445,6 +504,8 @@ class GraphQlPlatformExecutionPathTest {
|
||||
.allow(GraphQlSchemaCoordinate.parse("Query.platformNode"), anonymous)
|
||||
.allow(GraphQlSchemaCoordinate.parse("Query.platformStamp"), anonymous)
|
||||
.allow(GraphQlSchemaCoordinate.parse("Query.platformEcho"), anonymous)
|
||||
.allow(GraphQlSchemaCoordinate.parse("Query.platformPage"), anonymous)
|
||||
.allow(GraphQlSchemaCoordinate.parse("Query.platformNodes"), anonymous)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
+6
-2
@@ -1,8 +1,9 @@
|
||||
# Schema used by the execution-path evidence test.
|
||||
#
|
||||
# Shaped to exercise the policies the platform claims to enforce: a self-referencing type for depth,
|
||||
# a repeatable field for alias budgets, a coordinate the authorization policy denies, and a custom
|
||||
# scalar so wiring and coercion are proved on a real request rather than in a unit test.
|
||||
# a repeatable field for alias budgets, a coordinate the authorization policy denies, a custom
|
||||
# scalar so wiring and coercion are proved on a real request rather than in a unit test, and two
|
||||
# list fields — one paginated, one plain — so list cardinality is priced on the real path.
|
||||
|
||||
scalar Instant
|
||||
|
||||
@@ -14,6 +15,9 @@ extend type Query {
|
||||
# The argument default is what makes the three variable cases distinguishable at the resolver:
|
||||
# an omitted variable falls back to it, an explicit null does not.
|
||||
platformEcho(value: String = "default-applied"): String!
|
||||
|
||||
platformPage(first: Int): [PlatformNode!]!
|
||||
platformNodes: [PlatformNode!]!
|
||||
}
|
||||
|
||||
type PlatformNode {
|
||||
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
package dev.caskeleton.adapter.inbound.graphql.cost;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import graphql.language.Document;
|
||||
import graphql.language.OperationDefinition;
|
||||
import graphql.parser.Parser;
|
||||
import graphql.schema.GraphQLSchema;
|
||||
import graphql.schema.idl.RuntimeWiring;
|
||||
import graphql.schema.idl.SchemaGenerator;
|
||||
import graphql.schema.idl.SchemaParser;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* A list-returning field costs its children once per element, however the client asks for it.
|
||||
*
|
||||
* <p>Every number below is priced against the production default: an empty catalogue, so each field
|
||||
* is the conservative unregistered weight (base 10, weighted 20), a default page of 20 and a
|
||||
* maximum page of 100. The review probe (2026-11-01, 03-01) measured {@code items(first: 20)} at
|
||||
* 410 while {@code items} alone was 40 and four nested lists were 100 — the omitted argument, the
|
||||
* variable default and the plain list each skipped the multiplication the explicit literal got.
|
||||
*/
|
||||
class GraphQlDocumentComplexityScorerTest {
|
||||
|
||||
private static final String SDL =
|
||||
"""
|
||||
type Query {
|
||||
items(first: Int, last: Int): [Item!]!
|
||||
pagedWithDefault(first: Int = 50): [Item!]!
|
||||
itemConnection(first: Int): ItemConnection
|
||||
node: Item
|
||||
}
|
||||
type Item {
|
||||
name: String!
|
||||
children: [Item!]!
|
||||
grid: [[Item!]!]!
|
||||
}
|
||||
type ItemConnection {
|
||||
edges: [ItemEdge!]!
|
||||
}
|
||||
type ItemEdge {
|
||||
node: Item!
|
||||
}
|
||||
""";
|
||||
|
||||
private static final GraphQLSchema SCHEMA =
|
||||
new SchemaGenerator()
|
||||
.makeExecutableSchema(
|
||||
new SchemaParser().parse(SDL), RuntimeWiring.newRuntimeWiring().build());
|
||||
|
||||
private static final long BUDGET = 10_000;
|
||||
|
||||
private final GraphQlComplexityCalculator calculator =
|
||||
new GraphQlComplexityCalculator(GraphQlCostCatalog.of(), 20, 100);
|
||||
|
||||
@Test
|
||||
@DisplayName("first 를 명시한 page 는 하위 비용을 그 크기만큼 곱한다")
|
||||
void anExplicitPageMultipliesChildrenByThePageSize() {
|
||||
// when
|
||||
long score = score("query Q { items(first: 20) { name } }", Map.of());
|
||||
|
||||
// then
|
||||
assertThat(score).isEqualTo(10L + 20L * 20L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("first 를 생략한 page 는 기본 page 크기로 곱해서 명시한 기본 page 와 같은 점수다")
|
||||
void anOmittedPageArgumentCostsTheDefaultPage() {
|
||||
// when
|
||||
long score = score("query Q { items { name } }", Map.of());
|
||||
|
||||
// then
|
||||
assertThat(score).isEqualTo(score("query Q { items(first: 20) { name } }", Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("first 에 명시한 null 은 생략과 같아서 기본 page 크기로 곱한다")
|
||||
void anExplicitNullPageArgumentCostsTheDefaultPage() {
|
||||
// when
|
||||
long score = score("query Q { items(first: null) { name } }", Map.of());
|
||||
|
||||
// then
|
||||
assertThat(score).isEqualTo(10L + 20L * 20L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("일반 list 를 4단 중첩하면 점수가 단마다 곱으로 늘어 예산을 넘는다")
|
||||
void nestedPlainListsMultiplyRatherThanAdd() {
|
||||
// given
|
||||
String document = "query Q { items { children { children { children { name } } } } }";
|
||||
|
||||
// when
|
||||
long score = score(document, Map.of());
|
||||
|
||||
// then
|
||||
long innermost = 20L + 20L * 20L;
|
||||
long second = 20L + 20L * innermost;
|
||||
long first = 20L + 20L * second;
|
||||
assertThat(score).isEqualTo(10L + 20L * first);
|
||||
assertThatThrownBy(() -> calculator.verify(new GraphQlComplexityResult(score), BUDGET))
|
||||
.isInstanceOf(GraphQlComplexityRejectedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("변수 기본값으로 숨긴 page 크기도 상한을 넘으면 page size exceeds maximum 으로 거부된다")
|
||||
void aPageSizeHiddenInAVariableDefaultIsCheckedAgainstTheMaximum() {
|
||||
// given
|
||||
String document = "query Q($n: Int = 100000) { items(first: $n) { name } }";
|
||||
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> score(document, Map.of()));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(GraphQlComplexityRejectedException.class)
|
||||
.hasMessageContaining("page size exceeds maximum");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("요청이 보낸 변수 값은 변수 기본값보다 우선한다")
|
||||
void aSuppliedVariableOverridesItsDefault() {
|
||||
// when
|
||||
long score = score("query Q($n: Int = 100000) { items(first: $n) { name } }", Map.of("n", 5));
|
||||
|
||||
// then
|
||||
assertThat(score).isEqualTo(10L + 5L * 20L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("요청이 변수에 명시한 null 은 기본값을 쓰지 않고 기본 page 크기로 곱한다")
|
||||
void anExplicitNullVariableCostsTheDefaultPage() {
|
||||
// given
|
||||
Map<String, Object> variables = new HashMap<>();
|
||||
variables.put("n", null);
|
||||
|
||||
// when
|
||||
long score = score("query Q($n: Int = 100000) { items(first: $n) { name } }", variables);
|
||||
|
||||
// then
|
||||
assertThat(score).isEqualTo(10L + 20L * 20L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("스키마가 page 인자에 준 기본값은 생략했을 때 resolver 가 받는 값이라 그 크기로 곱한다")
|
||||
void aSchemaArgumentDefaultIsThePageAnOmittedArgumentGets() {
|
||||
// when
|
||||
long score = score("query Q { pagedWithDefault { name } }", Map.of());
|
||||
|
||||
// then
|
||||
assertThat(score).isEqualTo(10L + 50L * 20L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("last 만 상한을 넘어도 first 가 있다는 이유로 통과하지 않는다")
|
||||
void bothPageArgumentsAreCheckedAgainstTheMaximum() {
|
||||
// given
|
||||
String document = "query Q { items(first: 1, last: 100000) { name } }";
|
||||
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> score(document, Map.of()));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(GraphQlComplexityRejectedException.class)
|
||||
.hasMessageContaining("page size exceeds maximum");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("cost catalog 에 선언한 list 추정 크기가 기본 page 크기 대신 곱해진다")
|
||||
void aDeclaredListSizeReplacesTheDefaultMultiplier() {
|
||||
// given
|
||||
var declared =
|
||||
new GraphQlComplexityCalculator(
|
||||
GraphQlCostCatalog.of(
|
||||
new GraphQlFieldCostDescriptor(
|
||||
"Item.children", 2, GraphQlResolverWeight.PROPERTY, false, 3)),
|
||||
20,
|
||||
100);
|
||||
|
||||
// when
|
||||
long score = score(declared, "query Q { items(first: 1) { children { name } } }", Map.of());
|
||||
|
||||
// then
|
||||
assertThat(score).isEqualTo(10L + 1L * ((2L + 1L) + 3L * 20L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("list 안의 list 는 차원마다 한 번씩 곱한다")
|
||||
void eachListDimensionMultipliesOnce() {
|
||||
// when
|
||||
long score = score("query Q { node { grid { name } } }", Map.of());
|
||||
|
||||
// then
|
||||
assertThat(score).isEqualTo(20L + (20L + 20L * 20L * 20L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("connection 객체 안의 edges 는 connection 이 이미 곱한 그 page 라서 다시 곱하지 않는다")
|
||||
void aConnectionsEdgesAreThePageTheConnectionAlreadyPaidFor() {
|
||||
// when
|
||||
long score =
|
||||
score("query Q { itemConnection(first: 5) { edges { node { name } } } }", Map.of());
|
||||
|
||||
// then
|
||||
assertThat(score).isEqualTo(10L + 5L * (20L + (20L + 20L)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("page 인자를 생략한 connection 은 기본 page 크기로 곱한다")
|
||||
void anOmittedConnectionPageCostsTheDefaultPage() {
|
||||
// when
|
||||
long score = score("query Q { itemConnection { edges { node { name } } } }", Map.of());
|
||||
|
||||
// then
|
||||
assertThat(score).isEqualTo(10L + 20L * (20L + (20L + 20L)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("곱이 long 범위를 넘을 만큼 깊은 list 도 산술 오류가 아니라 예산 초과로 거부된다")
|
||||
void anOverflowingScoreSaturatesAndIsRejectedByTheBudget() {
|
||||
// given
|
||||
String document =
|
||||
"query Q { items { " + "children { ".repeat(20) + "name" + " }".repeat(21) + " }";
|
||||
|
||||
// when
|
||||
long score = score(document, Map.of());
|
||||
|
||||
// then
|
||||
assertThat(score).isEqualTo(Long.MAX_VALUE);
|
||||
assertThatThrownBy(() -> calculator.verify(new GraphQlComplexityResult(score), BUDGET))
|
||||
.isInstanceOf(GraphQlComplexityRejectedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("list 가 아닌 단일 객체 필드는 하위 비용을 곱하지 않고 더한다")
|
||||
void aSingleObjectFieldAddsItsChildrenOnce() {
|
||||
// when
|
||||
long score = score("query Q { node { name } }", Map.of());
|
||||
|
||||
// then
|
||||
assertThat(score).isEqualTo(20L + 20L);
|
||||
}
|
||||
|
||||
private long score(String source, Map<String, Object> variables) {
|
||||
return score(calculator, source, variables);
|
||||
}
|
||||
|
||||
private static long score(
|
||||
GraphQlComplexityCalculator calculator, String source, Map<String, Object> variables) {
|
||||
Document document = Parser.parse(source);
|
||||
OperationDefinition operation =
|
||||
document.getDefinitionsOfType(OperationDefinition.class).getFirst();
|
||||
return new GraphQlDocumentComplexityScorer(calculator)
|
||||
.score(SCHEMA, document, operation, variables)
|
||||
.total();
|
||||
}
|
||||
}
|
||||
@@ -38,3 +38,9 @@ strictTestLanes {
|
||||
jvmArgs '-Duser.timezone=UTC'
|
||||
}
|
||||
}
|
||||
|
||||
// The tests run in `test` already; the main stage runs the lane so its fail-closed selection is
|
||||
// proven before release.yml names it, not first there (review 2026-11-01 08-01).
|
||||
tasks.named('mainCheck') {
|
||||
dependsOn 'webAdvancedTest'
|
||||
}
|
||||
|
||||
@@ -24,8 +24,9 @@ Package root: `dev.caskeleton.adapter.inbound.web`.
|
||||
|
||||
Every service ships this leaf, so it holds only what the servlet production path reaches: its
|
||||
`AutoConfiguration.imports` roots (`WebAdapterAutoConfiguration` imports the envelope, filters,
|
||||
health and rate-limit beans; `WebSecurityAutoConfiguration` imports the JWT chain, method security
|
||||
and permission port, so an application with its own posture excludes only that root; nobody scans
|
||||
health and rate-limit beans; `WebSecurityAutoConfiguration` imports the JWT chain, so an application
|
||||
with its own posture excludes only that root; `WebMethodSecurityAutoConfiguration` imports method
|
||||
security and the permission port and stays when the chain is replaced; nobody scans
|
||||
this leaf), and the types
|
||||
`app-bootstrap`, `sample-portfolio`, `web-fileserver` and `composition:fileserver-platform` name —
|
||||
plus their transitive references. Library code that no production path reaches (streaming, virtual
|
||||
|
||||
@@ -41,8 +41,14 @@ production configuration and compare the result with the committed snapshot.
|
||||
- Spring Boot auto-config decoder 를 대체해 validator chain 을 기본값 의존이 아닌 **명시적 구성**으로 만든다.
|
||||
- **D2 — clock skew 60s 명시 고정**(`JwtTimestampValidator`). framework 기본값에 의존하면 Spring
|
||||
업그레이드로 기본값이 바뀔 때 silent-drift 위험이 있어 여기서 못박는다.
|
||||
- **D4 — issuer 검증**(`SecuritySettings.issuerUri()`). **D3 — audience 검증**(`SecuritySettings.audience()`),
|
||||
단 blank audience 면 검사 건너뜀(기존 settings 계약과 일치).
|
||||
- **D4 — issuer 검증**(`SecuritySettings.issuerUri()`). **D3 — audience 검증**(`SecuritySettings.audience()`).
|
||||
JWT 모드에서 audience 는 필수이고(비면 기동 실패, 메시지에 `APP_SECURITY_JWT_AUDIENCE`), 쉼표 목록을
|
||||
받는다. 토큰 `aud` 가 설정 목록 중 하나라도 담으면 통과한다. "비우면 검사 생략"은 없앴다 — 같은
|
||||
issuer 의 다른 client 용 토큰이 통과하기 때문이다(2026-11-01 리뷰 02-03·07-05, 소유자 결정 대안 A).
|
||||
버린 대안: prod 프로필에서만 필수(dev·staging 이 열리고 보안이 프로필 이름에 걸린다), 문서 강조만.
|
||||
- **role 범위**: `JwtToAuthenticatedPrincipalConverter` 는 `realm_access.roles` 와, `resource_access` 중
|
||||
**audience 목록에 있는 client** 의 roles 만 읽는다. 다른 client 가 같은 이름의 role 을 정의해도 이
|
||||
서비스 권한이 되지 않는다. client id 와 audience 가 다른 IdP 구성이 생기면 별도 키를 둔다(지금은 없음).
|
||||
- **JWKS lazy discovery** (`SupplierJwtDecoder`): 기동 시 IdP 가 reachable 일 필요가 없고, 첫 decode
|
||||
시점에 issuer-uri/`.well-known` 네트워크 호출이 일어난다(Spring Boot auto-config 와 동일한 lazy 동작).
|
||||
lazy 초기화 중 외부 discovery/JWKS I/O 실패는 필터 밖 runtime exception으로 탈출시키지 않고
|
||||
@@ -121,6 +127,14 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
|
||||
|
||||
## authz — 인가 (`@RequiresPermission` 강제)
|
||||
|
||||
### WebMethodSecurityAutoConfiguration — 인가는 인증 체인과 따로 켜진다
|
||||
- `MethodSecurityConfig`·`AuthorizationAdapter`·`RolePermissionRegistry`·`RolePermissionPolicy`(`app.authz`)는
|
||||
`WebSecurityAutoConfiguration`(JWT/session 체인)이 아니라 이 auto-configuration이 들여온다.
|
||||
- 이유: 인증 방식(체인)을 바꾸는 애플리케이션은 `WebSecurityAutoConfiguration`만 뺀다. 둘이 한 root에
|
||||
있을 때는 체인을 빼면 advisor도 같이 빠져서, 그 애플리케이션의 `@RequiresPermission`이 아무 경고 없이
|
||||
주석이 됐다(샘플이 그랬다 — 익명 삭제 가능). 이제 체인을 바꿔도 권한 검사는 남는다.
|
||||
- 메서드 보안까지 끄려면 이 클래스를 따로 exclude 해야 한다. 그 결정은 exclude 목록에 이름으로 드러난다.
|
||||
|
||||
### MethodSecurityConfig
|
||||
- `RequiresPermission` 강제 지점을 Spring method security 에 배선한다.
|
||||
- `@EnableMethodSecurity(prePostEnabled = false)` — method-security 인프라는 켜되 `@PreAuthorize`/
|
||||
@@ -213,8 +227,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
|
||||
| `PageValidationException` | `VALIDATION_FAILED` | 400 | D18/D20/D21: 계약 범위 밖 페이지/정렬/필터 파라미터. field + reasonCode 를 details 로 |
|
||||
| `IdempotencyUnavailableException` | `IDEMPOTENCY_UNAVAILABLE` | 503 (retryable=true) | 조정 저장소가 응답하지 않아 action 전에 거부. carrier 분기 |
|
||||
| `IdempotencyRecoveryRequiredException` | `IDEMPOTENCY_RECOVERY_REQUIRED` | 500 (retryable=false) | 이전 시도의 외부 효과 여부를 판단할 수 없음. carrier 분기 |
|
||||
| `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=false) | 같은 scope 의 다른 시도가 아직 처리 중(executor 는 기다리지 않는다). 진단정보(scope digest)는 클라이언트 미도달 |
|
||||
| `IdempotencyRequestMismatchException` | `IDEMPOTENT_REQUEST_MISMATCH` | 422 | D8: `Idempotency-Key` 를 다른 본문으로 재사용. fingerprint/scope 노출 금지 |
|
||||
| `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=true, `Retry-After: 2`) | 같은 scope 의 다른 시도가 아직 처리 중(executor 는 기다리지 않는다). 클라이언트 행동: 결과 불명. 같은 `Idempotency-Key`로 `Retry-After` 뒤 재전송. 새 키 금지(`docs/web/http-contract.md` §2). 진단정보(scope digest)는 클라이언트 미도달 |
|
||||
| `IdempotencyRequestMismatchException` | `IDEMPOTENT_REQUEST_MISMATCH` | 422 (retryable=false) | D8: `Idempotency-Key` 를 다른 본문으로 재사용. 다시 보내지 않는다(`docs/web/http-contract.md` §2). fingerprint/scope 노출 금지 |
|
||||
| `PersistenceFailureException` (JPA `JpaPersistenceException` 포함) | `ex.errorCode()` (사전분류 `DB_*`) | 코드 결정 | adapter-persistence translator 가 SQLState→`DB_*` 로 이미 분류, JPA 예외는 `FailureCategory`→`DB_*`. 클라이언트 메시지는 category 문구, **절대 `ex.getMessage()` 아님**(SQLState/제약명 담음, 서버 로그 전용) |
|
||||
| `DependencyFailureException` | `ex.errorCode()` (사전분류 `DEPENDENCY_*`) | 코드 결정 | adapter-outbound `OutboundHttpErrorMapper` 가 upstream 실패를 분류. 클라이언트 메시지는 category 문구, **절대 `ex.getMessage()` 아님**. retryable + `retry_after_seconds` 있으면 `RetryAfterAdvisor` 로 `Retry-After` 부착 |
|
||||
| `HttpRequestMethodNotSupportedException` | `METHOD_NOT_ALLOWED` | 405 | D12: 405 는 지원 메서드를 나열한 `Allow` 헤더 필수 |
|
||||
@@ -238,7 +252,12 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
|
||||
|
||||
### EnvelopeBodyAdvice
|
||||
- 컨트롤러는 도메인/DTO 타입을 반환하고, 이 advice 가 와이어 형태를 항상
|
||||
`{success, data | error, traceId}` 로 보장한다.
|
||||
`{success, data | error, meta}` 로 보장한다.
|
||||
- **null 필드는 키째 생략한다.** 성공에는 `error` 키가, 실패에는 `data` 키가, 단일 아이템 `meta` 에는
|
||||
`page` 키가 없다. 빈 목록은 생략하지 않는다. 규칙은 `EnvelopeWireFormatConfig` 의 Jackson mix-in 이
|
||||
Boot `JsonMapper` 에 등록한다(shared-contract 는 Jackson 에 의존하지 않으므로 타입에 애너테이션을
|
||||
달지 않는다). 키 목록과 근거는 `docs/web/http-contract.md` §1, 원문 키 집합 단언은
|
||||
`EnvelopeWireShapeTest`.
|
||||
- 위치: sample 모듈이 아니라 adapter-web. 실행 앱은 adapter-web 에 의존하지만 sample-portfolio 에는 의존하지
|
||||
않으므로, 응답 래핑이 실제로 동작하려면 여기 있어야 한다.
|
||||
|
||||
@@ -417,6 +436,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
|
||||
- 필드 `RETRY_AFTER_SECONDS` 는 error-codes.yaml 의 `retry_after_seconds` 컬럼 미러.
|
||||
이 advisor 가 유일한 Retry-After 노출 지점이라 여기 중앙화한다.
|
||||
`DEPENDENCY_4XX_CLIENT` 는 비재시도(retryable=false)라 `shouldAdvise` 가드로 empty 반환.
|
||||
- `IDEMPOTENT_IN_FLIGHT` 는 2초: 기본 processing lease(30s)보다 짧아 첫 시도가 끝날 수 있는 동안
|
||||
같은 키로 다시 묻게 한다. 근거와 클라이언트 행동은 `docs/web/http-contract.md` §2.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+16
-10
@@ -24,9 +24,9 @@ import org.springframework.web.client.RestClientException;
|
||||
|
||||
/**
|
||||
* Custom {@link JwtDecoder} for the resource server with an explicit validator chain: timestamp
|
||||
* (60s clock skew) + issuer, plus an optional audience check when configured. JWKS discovery is
|
||||
* deferred via {@link SupplierJwtDecoder} so startup does not require the IdP to be reachable. See
|
||||
* README for the design rationale.
|
||||
* (60s clock skew) + issuer + audience (required). JWKS discovery is deferred via {@link
|
||||
* SupplierJwtDecoder} so startup does not require the IdP to be reachable. See README for the
|
||||
* design rationale.
|
||||
*/
|
||||
@Configuration
|
||||
@ConditionalOnProperty(name = "app.security.auth-mode", havingValue = "jwt", matchIfMissing = true)
|
||||
@@ -70,16 +70,21 @@ public class JwtDecoderConfig {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The explicit validator chain: timestamp (60s skew) + issuer + optional audience. */
|
||||
static OAuth2TokenValidator<Jwt> jwtValidator(String issuerUri, String audience) {
|
||||
/**
|
||||
* The explicit validator chain: timestamp (60s skew) + issuer + audience. The token's {@code aud}
|
||||
* must name at least one configured audience; an empty list is refused, never read as "skip".
|
||||
*/
|
||||
static OAuth2TokenValidator<Jwt> jwtValidator(String issuerUri, List<String> audiences) {
|
||||
if (audiences.isEmpty()) {
|
||||
throw new IllegalArgumentException(
|
||||
"APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required");
|
||||
}
|
||||
List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
|
||||
validators.add(
|
||||
taggedValidator(
|
||||
new JwtTimestampValidator(Duration.ofSeconds(60)), ERROR_TIMESTAMP_INVALID));
|
||||
validators.add(taggedValidator(new JwtIssuerValidator(issuerUri), ERROR_ISSUER_MISMATCH));
|
||||
if (audience != null && !audience.isBlank()) {
|
||||
validators.add(audienceValidator(audience));
|
||||
}
|
||||
validators.add(audienceValidator(List.copyOf(audiences)));
|
||||
return new DelegatingOAuth2TokenValidator<>(validators);
|
||||
}
|
||||
|
||||
@@ -98,9 +103,10 @@ public class JwtDecoderConfig {
|
||||
};
|
||||
}
|
||||
|
||||
private static OAuth2TokenValidator<Jwt> audienceValidator(String audience) {
|
||||
private static OAuth2TokenValidator<Jwt> audienceValidator(List<String> audiences) {
|
||||
return jwt -> {
|
||||
if (jwt.getAudience() != null && jwt.getAudience().contains(audience)) {
|
||||
List<String> tokenAudience = jwt.getAudience();
|
||||
if (tokenAudience != null && audiences.stream().anyMatch(tokenAudience::contains)) {
|
||||
return OAuth2TokenValidatorResult.success();
|
||||
}
|
||||
OAuth2Error error =
|
||||
|
||||
+16
-4
@@ -1,5 +1,6 @@
|
||||
package dev.caskeleton.adapter.inbound.web.auth;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings;
|
||||
import dev.caskeleton.application.tenant.TenantId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
@@ -22,8 +23,12 @@ import org.springframework.stereotype.Component;
|
||||
/**
|
||||
* Maps an OIDC JWT to a JwtAuthenticationToken whose principal is our {@link
|
||||
* AuthenticatedPrincipal}. We pull {@code sub} as the IdP user id and union Keycloak-style {@code
|
||||
* realm_access.roles} with {@code resource_access[*].roles} into a single role set. Roles also
|
||||
* become Spring authorities (ROLE_*).
|
||||
* realm_access.roles} with {@code resource_access.<client>.roles} into a single role set. Roles
|
||||
* also become Spring authorities (ROLE_*).
|
||||
*
|
||||
* <p>Only the clients named by {@code app.security.audience} contribute {@code resource_access}
|
||||
* roles. Another client of the same issuer may define a role with the same name (for example {@code
|
||||
* operation-submit}); reading every client would hand that role to this service.
|
||||
*/
|
||||
@Component
|
||||
public class JwtToAuthenticatedPrincipalConverter
|
||||
@@ -37,6 +42,13 @@ public class JwtToAuthenticatedPrincipalConverter
|
||||
*/
|
||||
public static final String TENANT_CLAIM = "tenant_id";
|
||||
|
||||
/** The clients whose {@code resource_access} roles this service honours: its own audiences. */
|
||||
private final Set<String> roleClients;
|
||||
|
||||
public JwtToAuthenticatedPrincipalConverter(SecuritySettings settings) {
|
||||
this.roleClients = Set.copyOf(settings.audience());
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractAuthenticationToken convert(Jwt jwt) {
|
||||
Set<String> roles = extractRoles(jwt);
|
||||
@@ -79,8 +91,8 @@ public class JwtToAuthenticatedPrincipalConverter
|
||||
}
|
||||
Map<String, Object> resourceAccess = jwt.getClaimAsMap("resource_access");
|
||||
if (resourceAccess != null) {
|
||||
for (Object client : resourceAccess.values()) {
|
||||
if (client instanceof Map<?, ?> clientMap
|
||||
for (String clientId : roleClients) {
|
||||
if (resourceAccess.get(clientId) instanceof Map<?, ?> clientMap
|
||||
&& clientMap.get("roles") instanceof Collection<?> rolesCol) {
|
||||
rolesCol.forEach(x -> roles.add(String.valueOf(x)));
|
||||
}
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package dev.caskeleton.adapter.inbound.web.envelope;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import dev.caskeleton.shared.response.ApiError;
|
||||
import dev.caskeleton.shared.response.BulkEnvelope;
|
||||
import dev.caskeleton.shared.response.Envelope;
|
||||
import dev.caskeleton.shared.response.ResponseMeta;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import tools.jackson.databind.module.SimpleModule;
|
||||
|
||||
/**
|
||||
* Leaves a {@code null} field of the response envelope types off the wire: a success body carries
|
||||
* no {@code error} key, a failure body no {@code data} key, a single item no {@code meta.page}, and
|
||||
* an error without details no {@code details}. An empty list is not {@code null} and stays.
|
||||
*
|
||||
* <p>The rule lives here, not as {@code @JsonInclude} on the records, because {@code
|
||||
* shared-contract} depends on the Java standard library only. Boot registers every {@link
|
||||
* SimpleModule} bean on its {@code JsonMapper}, which every HTTP writer in this adapter uses — the
|
||||
* MVC converters and the filter-level writers alike. The wire contract this produces is {@code
|
||||
* docs/web/http-contract.md}.
|
||||
*/
|
||||
@Configuration
|
||||
public class EnvelopeWireFormatConfig {
|
||||
|
||||
@Bean
|
||||
public SimpleModule envelopeWireFormatModule() {
|
||||
SimpleModule module = new SimpleModule("EnvelopeWireFormatModule");
|
||||
module.setMixInAnnotation(Envelope.class, OmitNullFields.class);
|
||||
module.setMixInAnnotation(BulkEnvelope.class, OmitNullFields.class);
|
||||
module.setMixInAnnotation(ApiError.class, OmitNullFields.class);
|
||||
module.setMixInAnnotation(ResponseMeta.class, OmitNullFields.class);
|
||||
return module;
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
private abstract static class OmitNullFields {}
|
||||
}
|
||||
+5
-2
@@ -5,6 +5,7 @@ import dev.caskeleton.adapter.inbound.web.config.OpenApiContractConfig;
|
||||
import dev.caskeleton.adapter.inbound.web.config.PresentationWebConfig;
|
||||
import dev.caskeleton.adapter.inbound.web.controller.HealthcheckController;
|
||||
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice;
|
||||
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeWireFormatConfig;
|
||||
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
|
||||
import dev.caskeleton.adapter.inbound.web.filter.CacheControlFilter;
|
||||
import dev.caskeleton.adapter.inbound.web.filter.RequestLoggingFilter;
|
||||
@@ -20,8 +21,9 @@ import org.springframework.core.Ordered;
|
||||
|
||||
/**
|
||||
* The HTTP adapter this leaf ships, minus its security posture: error envelope, filters, health
|
||||
* endpoint, rate limiting and their settings. The JWT security chain and method security are {@link
|
||||
* WebSecurityAutoConfiguration}, a separate root an application can exclude on its own.
|
||||
* endpoint, rate limiting and their settings. The JWT security chain is {@link
|
||||
* WebSecurityAutoConfiguration}, a separate root an application can exclude on its own; method
|
||||
* security is {@link WebMethodSecurityAutoConfiguration}, which stays when the chain is replaced.
|
||||
*
|
||||
* <p>These used to be found by the composition root's component scan of the whole {@code
|
||||
* dev.caskeleton} tree. Registering them here means an application gets them from this module being
|
||||
@@ -44,6 +46,7 @@ import org.springframework.core.Ordered;
|
||||
PresentationWebConfig.class,
|
||||
HealthcheckController.class,
|
||||
EnvelopeBodyAdvice.class,
|
||||
EnvelopeWireFormatConfig.class,
|
||||
GlobalExceptionHandler.class,
|
||||
CacheControlFilter.class,
|
||||
RequestLoggingFilter.class,
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter;
|
||||
import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig;
|
||||
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy;
|
||||
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
/**
|
||||
* The enforcement of {@code @RequiresPermission}: the method-security advisor, the
|
||||
* role-to-permission authorization port and the {@code app.authz} policy it reads.
|
||||
*
|
||||
* <p>Separate from {@link WebSecurityAutoConfiguration} because the two answer different questions.
|
||||
* That root decides how a request is authenticated (the JWT or session chain) and an application
|
||||
* with its own posture replaces it. This one decides whether an authenticated caller may run a use
|
||||
* case, and replacing the way callers authenticate must not switch it off. While both lived in one
|
||||
* root, excluding the chain removed the advisor too, and every {@code @RequiresPermission} in that
|
||||
* application became a comment that nothing reported.
|
||||
*/
|
||||
@AutoConfiguration
|
||||
@EnableConfigurationProperties(RolePermissionPolicy.class)
|
||||
@Import({AuthorizationAdapter.class, MethodSecurityConfig.class, RolePermissionRegistry.class})
|
||||
public class WebMethodSecurityAutoConfiguration {}
|
||||
+10
-3
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure;
|
||||
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
|
||||
import dev.caskeleton.adapter.inbound.web.mvc.filter.JsonBodyLimitFilter;
|
||||
import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter;
|
||||
import dev.caskeleton.shared.tracing.ActiveTrace;
|
||||
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
@@ -51,13 +52,19 @@ public class WebMvcPlatformAutoConfiguration {
|
||||
return new GlobalExceptionHandler(spanErrorRecorderProvider);
|
||||
}
|
||||
|
||||
/** Assigns the correlation identifiers, validating anything a caller proposed. */
|
||||
/**
|
||||
* Assigns the correlation identifiers, validating anything a caller proposed. With a tracer in
|
||||
* the composition the trace id is the tracer's: the filter runs inside Boot's server observation
|
||||
* ({@code HIGHEST_PRECEDENCE + 1}), whose span is then the active one.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public WebMvcRequestIdFilter webMvcRequestIdFilter(WebMvcPlatformSettings properties) {
|
||||
public WebMvcRequestIdFilter webMvcRequestIdFilter(
|
||||
WebMvcPlatformSettings properties, ObjectProvider<ActiveTrace> activeTrace) {
|
||||
return new WebMvcRequestIdFilter(
|
||||
properties.trustInboundRequestId(),
|
||||
org.springframework.core.Ordered.HIGHEST_PRECEDENCE + 10);
|
||||
org.springframework.core.Ordered.HIGHEST_PRECEDENCE + 10,
|
||||
activeTrace.getIfAvailable(() -> ActiveTrace.NONE));
|
||||
}
|
||||
|
||||
/** Refuses a JSON body over the configured ceiling before the converter reads it. */
|
||||
|
||||
+9
-18
@@ -4,10 +4,6 @@ import dev.caskeleton.adapter.inbound.web.auth.JwtDecoderConfig;
|
||||
import dev.caskeleton.adapter.inbound.web.auth.JwtToAuthenticatedPrincipalConverter;
|
||||
import dev.caskeleton.adapter.inbound.web.auth.RedisSessionWebConfig;
|
||||
import dev.caskeleton.adapter.inbound.web.auth.SecurityConfig;
|
||||
import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter;
|
||||
import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig;
|
||||
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy;
|
||||
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry;
|
||||
import dev.caskeleton.adapter.inbound.web.settings.CorsSettings;
|
||||
import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
@@ -17,13 +13,15 @@ import org.springframework.context.annotation.Import;
|
||||
import org.springframework.core.Ordered;
|
||||
|
||||
/**
|
||||
* The production security posture this leaf ships: the JWT security filter chain, method security,
|
||||
* the role-to-permission authorization port and their settings.
|
||||
* How a request is authenticated in production: the JWT (or session) security filter chain, the
|
||||
* envelope entry point and access-denied handler, CORS and their settings.
|
||||
*
|
||||
* <p>Separate from {@link WebAdapterAutoConfiguration} so an application that brings its own
|
||||
* posture — the public demo sample, a contract fixture — excludes exactly this class and still gets
|
||||
* the error envelope, filters, health endpoint and rate limiting from the web root. Before the
|
||||
* split the only way to drop the security chain was to drop the whole root and component-scan the
|
||||
* posture — the demo sample, a contract fixture — excludes exactly this class and still gets the
|
||||
* error envelope, filters, health endpoint and rate limiting from the web root. Excluding it does
|
||||
* not switch off {@code @RequiresPermission}: that is {@link WebMethodSecurityAutoConfiguration},
|
||||
* which an application keeps while it replaces the chain. Before this root was split from the web
|
||||
* root, the only way to drop the security chain was to drop the whole root and component-scan the
|
||||
* leaf back in minus two classes, and every new controller in the leaf then arrived in that scan
|
||||
* whether it was meant to or not.
|
||||
*
|
||||
@@ -33,18 +31,11 @@ import org.springframework.core.Ordered;
|
||||
*/
|
||||
@AutoConfiguration
|
||||
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
|
||||
@EnableConfigurationProperties({
|
||||
CorsSettings.class,
|
||||
RolePermissionPolicy.class,
|
||||
SecuritySettings.class
|
||||
})
|
||||
@EnableConfigurationProperties({CorsSettings.class, SecuritySettings.class})
|
||||
@Import({
|
||||
JwtDecoderConfig.class,
|
||||
JwtToAuthenticatedPrincipalConverter.class,
|
||||
RedisSessionWebConfig.class,
|
||||
SecurityConfig.class,
|
||||
AuthorizationAdapter.class,
|
||||
MethodSecurityConfig.class,
|
||||
RolePermissionRegistry.class
|
||||
SecurityConfig.class
|
||||
})
|
||||
public class WebSecurityAutoConfiguration {}
|
||||
|
||||
+24
-2
@@ -4,6 +4,7 @@ import dev.caskeleton.adapter.inbound.web.core.WebRequestId;
|
||||
import dev.caskeleton.adapter.inbound.web.core.WebTraceId;
|
||||
import dev.caskeleton.adapter.inbound.web.observability.HeaderSanitizer;
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import dev.caskeleton.shared.tracing.ActiveTrace;
|
||||
import dev.caskeleton.shared.tracing.TraceParent;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
@@ -31,7 +32,10 @@ import org.springframework.web.filter.OncePerRequestFilter;
|
||||
* investigation ends up reading somebody else's exchange.
|
||||
*
|
||||
* <p>The trace id is different: propagating an inbound {@code traceparent} is the entire point of
|
||||
* distributed tracing, so it is honoured when it parses, and replaced when it does not.
|
||||
* distributed tracing, so it is honoured when it parses, and replaced when it does not. When a
|
||||
* tracer is running, its server span already made that decision — it continued a valid inbound
|
||||
* trace or started a new one — and the filter takes the span's context as it is, so the id in the
|
||||
* response and the logs is the id the exported spans carry.
|
||||
*
|
||||
* <p>This is the one place the identifiers are made. It puts them on MDC and on the response before
|
||||
* anything else runs — Spring Security included, so a {@code 401}/{@code 403} written inside the
|
||||
@@ -65,6 +69,7 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements
|
||||
|
||||
private final boolean trustInboundRequestId;
|
||||
private final int order;
|
||||
private final ActiveTrace activeTrace;
|
||||
|
||||
/** A filter that mints its own request ids and propagates a valid inbound trace. */
|
||||
public WebMvcRequestIdFilter() {
|
||||
@@ -79,8 +84,21 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements
|
||||
* @param order the filter order
|
||||
*/
|
||||
public WebMvcRequestIdFilter(boolean trustInboundRequestId, int order) {
|
||||
this(trustInboundRequestId, order, ActiveTrace.NONE);
|
||||
}
|
||||
|
||||
/**
|
||||
* A filter that takes the trace context from a running tracer when one has a span active.
|
||||
*
|
||||
* @param trustInboundRequestId whether a client may choose the request id
|
||||
* @param order the filter order; it must run inside the tracer's server observation for the
|
||||
* active span to be the request's
|
||||
* @param activeTrace the tracer's active span, or {@link ActiveTrace#NONE} without a tracer
|
||||
*/
|
||||
public WebMvcRequestIdFilter(boolean trustInboundRequestId, int order, ActiveTrace activeTrace) {
|
||||
this.trustInboundRequestId = trustInboundRequestId;
|
||||
this.order = order;
|
||||
this.activeTrace = activeTrace;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -145,7 +163,11 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements
|
||||
.orElseGet(() -> new WebRequestId(UUID.randomUUID().toString()));
|
||||
}
|
||||
|
||||
private static TraceParent resolveTrace(HttpServletRequest request) {
|
||||
private TraceParent resolveTrace(HttpServletRequest request) {
|
||||
Optional<TraceParent> traced = activeTrace.current();
|
||||
if (traced.isPresent()) {
|
||||
return traced.get();
|
||||
}
|
||||
// A malformed traceparent is replaced rather than rejected: refusing the request would let an
|
||||
// upstream misconfiguration take an API down, and the platform still needs a correlation id.
|
||||
return TraceParent.parse(request.getHeader(TRACEPARENT_HEADER))
|
||||
|
||||
+3
@@ -14,6 +14,9 @@ public final class RetryAfterAdvisor {
|
||||
private static final Map<String, Integer> RETRY_AFTER_SECONDS =
|
||||
Map.of(
|
||||
"RATE_LIMIT_EXCEEDED", 1,
|
||||
// Below the default processing lease (30s): the resend arrives while the first attempt
|
||||
// can still finish, and an early resend costs one more 409. docs/web/http-contract.md.
|
||||
"IDEMPOTENT_IN_FLIGHT", 2,
|
||||
"AUTH_KID_UNKNOWN", 5,
|
||||
"AUTH_JWKS_UNAVAILABLE", 30,
|
||||
"DEPENDENCY_TIMEOUT", 2,
|
||||
|
||||
+16
-14
@@ -1,29 +1,29 @@
|
||||
package dev.caskeleton.adapter.inbound.web.settings;
|
||||
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.bind.ConstructorBinding;
|
||||
|
||||
/**
|
||||
* Exclusive JWT or Redis-backed browser-session security policy bound from {@code app.security.*}.
|
||||
*
|
||||
* <p>In JWT mode both {@code issuerUri} and {@code audience} are required. {@code audience} is a
|
||||
* comma-separated list: a token passes when its {@code aud} names any of them, and only those
|
||||
* clients' {@code resource_access} roles are read.
|
||||
*/
|
||||
@ConfigurationProperties(prefix = "app.security")
|
||||
public record SecuritySettings(
|
||||
AuthenticationMode authMode,
|
||||
String issuerUri,
|
||||
String audience,
|
||||
List<String> audience,
|
||||
List<String> publicPaths,
|
||||
SessionCookieSettings session) {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SecuritySettings.class);
|
||||
|
||||
@ConstructorBinding
|
||||
public SecuritySettings(
|
||||
AuthenticationMode authMode,
|
||||
String issuerUri,
|
||||
String audience,
|
||||
List<String> audience,
|
||||
List<String> publicPaths,
|
||||
SessionCookieSettings session) {
|
||||
this.authMode = authMode == null ? AuthenticationMode.JWT : authMode;
|
||||
@@ -32,13 +32,15 @@ public record SecuritySettings(
|
||||
"APP_SECURITY_JWT_ISSUER (app.security.issuer-uri) is required");
|
||||
}
|
||||
this.issuerUri = issuerUri == null ? "" : issuerUri.trim();
|
||||
if (audience == null) {
|
||||
if (this.authMode == AuthenticationMode.JWT) {
|
||||
log.warn("APP_SECURITY_JWT_AUDIENCE is missing; skipping audience validation");
|
||||
}
|
||||
this.audience = "";
|
||||
} else {
|
||||
this.audience = audience.trim();
|
||||
this.audience =
|
||||
audience == null
|
||||
? List.of()
|
||||
: audience.stream().map(String::trim).filter(value -> !value.isEmpty()).toList();
|
||||
if (this.authMode == AuthenticationMode.JWT && this.audience.isEmpty()) {
|
||||
// No "skip the check" default: a token minted for another client of the same issuer must
|
||||
// not authenticate here.
|
||||
throw new IllegalArgumentException(
|
||||
"APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required");
|
||||
}
|
||||
if (publicPaths == null) {
|
||||
this.publicPaths = List.of();
|
||||
@@ -48,7 +50,7 @@ public record SecuritySettings(
|
||||
this.session = session == null ? SessionCookieSettings.defaults() : session;
|
||||
}
|
||||
|
||||
public SecuritySettings(String issuerUri, String audience, List<String> publicPaths) {
|
||||
public SecuritySettings(String issuerUri, List<String> audience, List<String> publicPaths) {
|
||||
this(AuthenticationMode.JWT, issuerUri, audience, publicPaths, null);
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -1,3 +1,4 @@
|
||||
dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration
|
||||
dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration
|
||||
dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMethodSecurityAutoConfiguration
|
||||
dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration
|
||||
|
||||
+43
-7
@@ -1,11 +1,14 @@
|
||||
package dev.caskeleton.adapter.inbound.web.auth;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
||||
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
|
||||
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
@@ -21,7 +24,7 @@ class JwtDecoderConfigTest {
|
||||
private static final String AUDIENCE = "ca-skeleton-api";
|
||||
|
||||
private final OAuth2TokenValidator<Jwt> validator =
|
||||
JwtDecoderConfig.jwtValidator(ISSUER, AUDIENCE);
|
||||
JwtDecoderConfig.jwtValidator(ISSUER, List.of(AUDIENCE));
|
||||
|
||||
private Jwt.Builder validJwt() {
|
||||
Instant now = Instant.now();
|
||||
@@ -76,11 +79,44 @@ class JwtDecoderConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankAudienceSkipsTheAudienceCheck() {
|
||||
OAuth2TokenValidator<Jwt> noAud = JwtDecoderConfig.jwtValidator(ISSUER, "");
|
||||
Jwt jwt = validJwt().audience(List.of("anything")).build();
|
||||
assertThat(noAud.validate(jwt).hasErrors())
|
||||
.as("a blank configured audience disables audience validation")
|
||||
.isFalse();
|
||||
@DisplayName("설정한 audience 목록 중 하나라도 토큰 aud에 있으면 통과한다")
|
||||
void aTokenNamingAnyConfiguredAudiencePasses() {
|
||||
// given
|
||||
OAuth2TokenValidator<Jwt> listed =
|
||||
JwtDecoderConfig.jwtValidator(ISSUER, List.of("ca-skeleton-admin", AUDIENCE));
|
||||
Jwt jwt = validJwt().audience(List.of("account", AUDIENCE)).build();
|
||||
|
||||
// when
|
||||
OAuth2TokenValidatorResult result = listed.validate(jwt);
|
||||
|
||||
// then
|
||||
assertThat(result.hasErrors()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("토큰에 aud claim이 없으면 AUTH_AUDIENCE_MISMATCH 오류 코드로 거부한다")
|
||||
void aTokenWithoutAnAudClaimIsRejectedAsAudienceMismatch() {
|
||||
// given
|
||||
Jwt jwt = validJwt().claims(claims -> claims.remove("aud")).build();
|
||||
|
||||
// when
|
||||
OAuth2TokenValidatorResult result = validator.validate(jwt);
|
||||
|
||||
// then
|
||||
assertThat(result.getErrors())
|
||||
.extracting(OAuth2Error::getErrorCode)
|
||||
.containsExactly(JwtDecoderConfig.ERROR_AUDIENCE_MISMATCH);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("audience 목록이 비면 검사를 건너뛰지 않고 검증기 조립을 거부한다")
|
||||
void anEmptyAudienceListIsRefusedInsteadOfSkippingTheCheck() {
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> JwtDecoderConfig.jwtValidator(ISSUER, List.of()));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("APP_SECURITY_JWT_AUDIENCE");
|
||||
}
|
||||
}
|
||||
|
||||
+58
-5
@@ -3,9 +3,11 @@ package dev.caskeleton.adapter.inbound.web.auth;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings;
|
||||
import dev.caskeleton.application.tenant.TenantId;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
@@ -14,6 +16,8 @@ import org.springframework.security.oauth2.server.resource.InvalidBearerTokenExc
|
||||
|
||||
class JwtToAuthenticatedPrincipalConverterTest {
|
||||
|
||||
private static final String OWN_CLIENT = "ca-skeleton-api";
|
||||
|
||||
@Test
|
||||
void roleAuthoritiesUseLocaleIndependentUppercase() {
|
||||
Locale originalDefault = Locale.getDefault();
|
||||
@@ -26,7 +30,7 @@ class JwtToAuthenticatedPrincipalConverterTest {
|
||||
.claim("roles", List.of("admin"))
|
||||
.build();
|
||||
|
||||
var authentication = new JwtToAuthenticatedPrincipalConverter().convert(jwt);
|
||||
var authentication = converter().convert(jwt);
|
||||
|
||||
assertThat(authentication.getAuthorities())
|
||||
.extracting(GrantedAuthority::getAuthority)
|
||||
@@ -42,7 +46,7 @@ class JwtToAuthenticatedPrincipalConverterTest {
|
||||
Jwt jwt = token().claim(JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM, "acme").build();
|
||||
|
||||
// when
|
||||
var authentication = new JwtToAuthenticatedPrincipalConverter().convert(jwt);
|
||||
var authentication = converter().convert(jwt);
|
||||
|
||||
// then
|
||||
assertThat(((AuthenticatedPrincipal) authentication.getPrincipal()).tenant())
|
||||
@@ -52,7 +56,7 @@ class JwtToAuthenticatedPrincipalConverterTest {
|
||||
@Test
|
||||
void aTokenWithoutATenantClaimHasNoTenant() {
|
||||
// when
|
||||
var authentication = new JwtToAuthenticatedPrincipalConverter().convert(token().build());
|
||||
var authentication = converter().convert(token().build());
|
||||
|
||||
// then
|
||||
assertThat(((AuthenticatedPrincipal) authentication.getPrincipal()).tenant()).isEmpty();
|
||||
@@ -65,8 +69,7 @@ class JwtToAuthenticatedPrincipalConverterTest {
|
||||
Jwt jwt = token().claim(JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM, "ac me").build();
|
||||
|
||||
// when
|
||||
Throwable thrown =
|
||||
catchThrowable(() -> new JwtToAuthenticatedPrincipalConverter().convert(jwt));
|
||||
Throwable thrown = catchThrowable(() -> converter().convert(jwt));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
@@ -74,6 +77,56 @@ class JwtToAuthenticatedPrincipalConverterTest {
|
||||
.hasMessage("the token's tenant claim is malformed");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 issuer의 다른 client role은 이 서비스의 권한이 되지 않는다")
|
||||
void anotherClientsRolesGrantNoAuthority() {
|
||||
// given
|
||||
Jwt jwt =
|
||||
token()
|
||||
.claim(
|
||||
"resource_access",
|
||||
Map.of("other-app", Map.of("roles", List.of("operation-submit"))))
|
||||
.build();
|
||||
|
||||
// when
|
||||
var authentication = converter().convert(jwt);
|
||||
|
||||
// then
|
||||
assertThat(authentication.getAuthorities()).isEmpty();
|
||||
assertThat(((AuthenticatedPrincipal) authentication.getPrincipal()).roles()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("설정한 client의 role과 realm role은 권한이 된다")
|
||||
void theOwnClientsRolesAndRealmRolesBecomeAuthorities() {
|
||||
// given
|
||||
Jwt jwt =
|
||||
token()
|
||||
.claim("realm_access", Map.of("roles", List.of("user")))
|
||||
.claim(
|
||||
"resource_access",
|
||||
Map.of(
|
||||
OWN_CLIENT,
|
||||
Map.of("roles", List.of("operation-submit")),
|
||||
"other-app",
|
||||
Map.of("roles", List.of("file-admin"))))
|
||||
.build();
|
||||
|
||||
// when
|
||||
var authentication = converter().convert(jwt);
|
||||
|
||||
// then
|
||||
assertThat(authentication.getAuthorities())
|
||||
.extracting(GrantedAuthority::getAuthority)
|
||||
.containsExactlyInAnyOrder("ROLE_USER", "ROLE_OPERATION-SUBMIT");
|
||||
}
|
||||
|
||||
private static JwtToAuthenticatedPrincipalConverter converter() {
|
||||
return new JwtToAuthenticatedPrincipalConverter(
|
||||
new SecuritySettings(
|
||||
"https://issuer.example/realms/ca-skeleton", List.of(OWN_CLIENT), List.of()));
|
||||
}
|
||||
|
||||
private static Jwt.Builder token() {
|
||||
return Jwt.withTokenValue("token").header("alg", "none").subject("user-1");
|
||||
}
|
||||
|
||||
+3
-1
@@ -23,7 +23,9 @@ class RedisSessionWebConfigTest {
|
||||
void jwtModeCreatesNoSessionFilterOrCookieSerializer() {
|
||||
runner
|
||||
.withPropertyValues(
|
||||
"app.security.auth-mode=jwt", "app.security.issuer-uri=https://issuer.example")
|
||||
"app.security.auth-mode=jwt",
|
||||
"app.security.issuer-uri=https://issuer.example",
|
||||
"app.security.audience=ca-skeleton-api")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
|
||||
+2
@@ -157,6 +157,7 @@ class SecurityModeWebContractTest {
|
||||
.withPropertyValues(
|
||||
"app.security.auth-mode=jwt",
|
||||
"app.security.issuer-uri=https://issuer.example",
|
||||
"app.security.audience=ca-skeleton-api",
|
||||
"app.security.public-paths=/probe",
|
||||
"app.cors.enabled=false")
|
||||
.run(
|
||||
@@ -177,6 +178,7 @@ class SecurityModeWebContractTest {
|
||||
.withPropertyValues(
|
||||
"app.security.auth-mode=jwt",
|
||||
"app.security.issuer-uri=https://issuer.example",
|
||||
"app.security.audience=ca-skeleton-api",
|
||||
"app.cors.enabled=false")
|
||||
.run(
|
||||
context -> {
|
||||
|
||||
+10
-3
@@ -1,6 +1,9 @@
|
||||
package dev.caskeleton.adapter.inbound.web.envelope;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@@ -25,7 +28,11 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
controllers = EnvelopeBodyAdviceTest.Probe.class,
|
||||
excludeAutoConfiguration = SecurityAutoConfiguration.class)
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
@Import({EnvelopeBodyAdviceTest.Probe.class, EnvelopeBodyAdvice.class})
|
||||
@Import({
|
||||
EnvelopeBodyAdviceTest.Probe.class,
|
||||
EnvelopeBodyAdvice.class,
|
||||
EnvelopeWireFormatConfig.class
|
||||
})
|
||||
class EnvelopeBodyAdviceTest {
|
||||
|
||||
@Autowired MockMvc mvc;
|
||||
@@ -54,7 +61,7 @@ class EnvelopeBodyAdviceTest {
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.success").value(true))
|
||||
.andExpect(jsonPath("$.data.k").value("v"))
|
||||
.andExpect(jsonPath("$.error").doesNotExist());
|
||||
.andExpect(content().string(not(containsString("\"error\""))));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -79,7 +86,7 @@ class EnvelopeBodyAdviceTest {
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.results[0].k").value("v"))
|
||||
.andExpect(jsonPath("$.success").value(true))
|
||||
.andExpect(jsonPath("$.data").doesNotExist());
|
||||
.andExpect(content().string(not(containsString("\"data\""))));
|
||||
}
|
||||
|
||||
@SpringBootConfiguration
|
||||
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
package dev.caskeleton.adapter.inbound.web.envelope;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyInFlightException;
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import dev.caskeleton.shared.response.BulkEnvelope;
|
||||
import dev.caskeleton.shared.response.BulkItemResult;
|
||||
import dev.caskeleton.shared.response.Envelope;
|
||||
import dev.caskeleton.shared.response.PageMeta;
|
||||
import dev.caskeleton.shared.response.ResponseMeta;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringBootConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.security.autoconfigure.SecurityAutoConfiguration;
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* The raw JSON keys a client receives — the wire contract in {@code docs/web/http-contract.md}.
|
||||
*
|
||||
* <p>Asserted on the response text, never with {@code jsonPath(..).doesNotExist()}: that matcher
|
||||
* passes for a key that is present with a {@code null} value, which is exactly the difference a
|
||||
* strict client rejects.
|
||||
*/
|
||||
@WebMvcTest(
|
||||
controllers = EnvelopeWireShapeTest.Probe.class,
|
||||
excludeAutoConfiguration = SecurityAutoConfiguration.class)
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
@Import({
|
||||
EnvelopeWireShapeTest.Probe.class,
|
||||
EnvelopeBodyAdvice.class,
|
||||
GlobalExceptionHandler.class,
|
||||
EnvelopeWireFormatConfig.class
|
||||
})
|
||||
class EnvelopeWireShapeTest {
|
||||
|
||||
private static final JsonMapper READER = JsonMapper.builder().build();
|
||||
|
||||
@Autowired MockMvc mvc;
|
||||
|
||||
@RestController
|
||||
static class Probe {
|
||||
|
||||
@GetMapping("/probe/item")
|
||||
public Map<String, String> item() {
|
||||
ids(true);
|
||||
return Map.of("k", "v");
|
||||
}
|
||||
|
||||
@GetMapping("/probe/empty-list")
|
||||
public List<String> emptyList() {
|
||||
ids(true);
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@GetMapping("/probe/page")
|
||||
public Envelope<List<String>> page() {
|
||||
return Envelope.ok(
|
||||
List.of("a"),
|
||||
new ResponseMeta("req-1", "trace-1", "corr-1").withPage(new PageMeta(0, 20, 1, "id")));
|
||||
}
|
||||
|
||||
@GetMapping("/probe/in-flight")
|
||||
public Map<String, String> inFlight() {
|
||||
ids(false);
|
||||
throw IdempotencyInFlightException.forScopeDigest("CREATE::v1::" + "a".repeat(64));
|
||||
}
|
||||
|
||||
@GetMapping("/probe/bulk-ok")
|
||||
public BulkEnvelope<String> bulkOk() {
|
||||
return BulkEnvelope.allOk(List.of(), new ResponseMeta("req-1", "trace-1", "corr-1"));
|
||||
}
|
||||
|
||||
@GetMapping("/probe/bulk-partial")
|
||||
public BulkEnvelope<String> bulkPartial() {
|
||||
return BulkEnvelope.partial(
|
||||
List.<BulkItemResult>of(), new ResponseMeta("req-1", "trace-1", "corr-1"));
|
||||
}
|
||||
|
||||
private static void ids(boolean withCorrelation) {
|
||||
MDC.put(MdcKeys.REQUEST_ID, "req-1");
|
||||
MDC.put(MdcKeys.TRACE_ID, "trace-1");
|
||||
if (withCorrelation) {
|
||||
MDC.put(MdcKeys.CORRELATION_ID, "corr-1");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void clearMdc() {
|
||||
MDC.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("성공 응답 원문에는 success·data·meta 키만 있고 error 키는 없다")
|
||||
void successBodyCarriesOnlySuccessDataAndMetaKeys() throws Exception {
|
||||
// when
|
||||
JsonNode body = rawBody("/probe/item");
|
||||
|
||||
// then
|
||||
assertThat(keys(body)).containsExactlyInAnyOrder("success", "data", "meta");
|
||||
assertThat(keys(body.get("meta")))
|
||||
.containsExactlyInAnyOrder("requestId", "traceId", "correlationId");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("빈 목록 data는 생략되지 않고 빈 배열로 나간다")
|
||||
void emptyListDataIsKeptAsAnEmptyArray() throws Exception {
|
||||
// when
|
||||
JsonNode body = rawBody("/probe/empty-list");
|
||||
|
||||
// then
|
||||
assertThat(keys(body)).containsExactlyInAnyOrder("success", "data", "meta");
|
||||
assertThat(body.get("data").isArray() && body.get("data").isEmpty()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("목록 응답의 meta에만 page 키가 있다")
|
||||
void pagedBodyCarriesPageInMeta() throws Exception {
|
||||
// when
|
||||
JsonNode body = rawBody("/probe/page");
|
||||
|
||||
// then
|
||||
assertThat(keys(body.get("meta")))
|
||||
.containsExactlyInAnyOrder("requestId", "traceId", "correlationId", "page");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("실패 응답 원문에는 success·error·meta 키만 있고 data·null 필드는 없다")
|
||||
void failureBodyCarriesOnlySuccessErrorAndMetaKeys() throws Exception {
|
||||
// when
|
||||
JsonNode body = rawBody("/probe/in-flight");
|
||||
|
||||
// then
|
||||
assertThat(keys(body)).containsExactlyInAnyOrder("success", "error", "meta");
|
||||
assertThat(keys(body.get("error")))
|
||||
.containsExactlyInAnyOrder("code", "category", "message", "retryable");
|
||||
assertThat(keys(body.get("meta"))).containsExactlyInAnyOrder("requestId", "traceId");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("bulk 전체 성공은 빈 results를 남기고 error 키를 싣지 않는다")
|
||||
void bulkSuccessKeepsEmptyResultsWithoutErrorKey() throws Exception {
|
||||
// when
|
||||
JsonNode body = rawBody("/probe/bulk-ok");
|
||||
|
||||
// then
|
||||
assertThat(keys(body)).containsExactlyInAnyOrder("success", "results", "meta");
|
||||
assertThat(body.get("results").isArray() && body.get("results").isEmpty()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("bulk 부분 실패는 results 키 없이 error의 빈 details 목록을 남긴다")
|
||||
void bulkPartialFailureCarriesErrorWithoutResultsKey() throws Exception {
|
||||
// when
|
||||
JsonNode body = rawBody("/probe/bulk-partial");
|
||||
|
||||
// then
|
||||
assertThat(keys(body)).containsExactlyInAnyOrder("success", "error", "meta");
|
||||
JsonNode details = body.get("error").get("details");
|
||||
assertThat(details.isArray() && details.isEmpty()).isTrue();
|
||||
}
|
||||
|
||||
private JsonNode rawBody(String path) throws Exception {
|
||||
String text = mvc.perform(get(path)).andReturn().getResponse().getContentAsString();
|
||||
return READER.readTree(text);
|
||||
}
|
||||
|
||||
private static Set<String> keys(JsonNode node) {
|
||||
Set<String> keys = new TreeSet<>();
|
||||
node.properties().forEach(entry -> keys.add(entry.getKey()));
|
||||
return keys;
|
||||
}
|
||||
|
||||
@SpringBootConfiguration
|
||||
@EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
|
||||
static class TestBootstrap {}
|
||||
}
|
||||
+10
-2
@@ -2,12 +2,14 @@ package dev.caskeleton.adapter.inbound.web.error;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.http.ApiHeaders;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyInFlightException;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyRequestMismatchException;
|
||||
import dev.caskeleton.shared.error.Category;
|
||||
import dev.caskeleton.shared.error.ClientErrorMessages;
|
||||
import dev.caskeleton.shared.response.Envelope;
|
||||
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
@@ -18,7 +20,8 @@ class IdempotencyExceptionMappingTest {
|
||||
private final GlobalExceptionHandler handler = new GlobalExceptionHandler(SpanErrorRecorder.NOOP);
|
||||
|
||||
@Test
|
||||
void inFlightMapsToNonRetryable409ConflictWithTheConflictMessage() {
|
||||
@DisplayName("처리 중 409는 retryable=true와 Retry-After를 실어 같은 키 재전송을 알린다")
|
||||
void inFlightMapsToRetryable409WithRetryAfterSoTheClientResendsTheSameKey() {
|
||||
// given
|
||||
IdempotencyInFlightException inFlight =
|
||||
IdempotencyInFlightException.forScopeDigest(SCOPE_DIAGNOSTIC);
|
||||
@@ -30,19 +33,22 @@ class IdempotencyExceptionMappingTest {
|
||||
assertThat(response)
|
||||
.extracting(
|
||||
r -> r.getStatusCode().value(),
|
||||
r -> r.getHeaders().getFirst(ApiHeaders.RETRY_AFTER),
|
||||
r -> r.getBody().error().code(),
|
||||
r -> r.getBody().error().category(),
|
||||
r -> r.getBody().error().retryable(),
|
||||
r -> r.getBody().error().message())
|
||||
.containsExactly(
|
||||
409,
|
||||
"2",
|
||||
"IDEMPOTENT_IN_FLIGHT",
|
||||
"CONFLICT",
|
||||
false,
|
||||
true,
|
||||
ClientErrorMessages.of(Category.CONFLICT));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("다른 본문으로 키를 재사용하면 Retry-After 없는 재시도 불가 422다")
|
||||
void mismatchMapsToNonRetryable422ValidationWithTheValidationMessage() {
|
||||
// given
|
||||
IdempotencyRequestMismatchException mismatch =
|
||||
@@ -55,12 +61,14 @@ class IdempotencyExceptionMappingTest {
|
||||
assertThat(response)
|
||||
.extracting(
|
||||
r -> r.getStatusCode().value(),
|
||||
r -> r.getHeaders().getFirst(ApiHeaders.RETRY_AFTER),
|
||||
r -> r.getBody().error().code(),
|
||||
r -> r.getBody().error().category(),
|
||||
r -> r.getBody().error().retryable(),
|
||||
r -> r.getBody().error().message())
|
||||
.containsExactly(
|
||||
422,
|
||||
null,
|
||||
"IDEMPOTENT_REQUEST_MISMATCH",
|
||||
"VALIDATION",
|
||||
false,
|
||||
|
||||
+1
@@ -37,6 +37,7 @@ class WebAutoConfigurationRegistrationTest {
|
||||
List.of(
|
||||
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration",
|
||||
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration",
|
||||
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMethodSecurityAutoConfiguration",
|
||||
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration");
|
||||
|
||||
@Test
|
||||
|
||||
+25
@@ -76,6 +76,31 @@ class WebMvcRequestIdFilterTest {
|
||||
.isPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("tracer가 span을 열어 두었으면 응답·MDC의 trace id는 그 span의 것이다")
|
||||
void theActiveSpanOfARunningTracerNamesTheTrace() throws Exception {
|
||||
// given
|
||||
TraceParent serverSpan =
|
||||
TraceParent.of("4bf92f3577b34da6a3ce929d0e0e4736", "00f067aa0ba902b7", true);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader(WebMvcRequestIdFilter.TRACEPARENT_HEADER, "garbage");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
Map<String, String> duringChain = new HashMap<>();
|
||||
|
||||
// when
|
||||
new WebMvcRequestIdFilter(false, 0, () -> java.util.Optional.of(serverSpan))
|
||||
.doFilter(request, response, (rq, rs) -> duringChain.putAll(mdc()));
|
||||
|
||||
// then
|
||||
assertThat(WebMvcRequestIdFilter.traceId(request).orElseThrow().value())
|
||||
.isEqualTo(serverSpan.traceId());
|
||||
assertThat(duringChain)
|
||||
.containsEntry(MdcKeys.TRACE_ID, serverSpan.traceId())
|
||||
.containsEntry(MdcKeys.SPAN_ID, serverSpan.spanId());
|
||||
assertThat(response.getHeader(WebMvcRequestIdFilter.TRACEPARENT_HEADER))
|
||||
.isEqualTo(serverSpan.toHeader());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(
|
||||
strings = {
|
||||
|
||||
+9
-1
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.observability;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class RetryAfterAdvisorTest {
|
||||
@@ -45,10 +46,17 @@ class RetryAfterAdvisorTest {
|
||||
|
||||
@Test
|
||||
void nonRetryableCodeHasNoRetryAfterValue() {
|
||||
assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.IDEMPOTENT_IN_FLIGHT))
|
||||
assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.IDEMPOTENT_REQUEST_MISMATCH))
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("처리 중 409는 기본 processing lease(30s)보다 짧은 2초 Retry-After를 준다")
|
||||
void idempotentInFlightHasRetryAfter2s() {
|
||||
assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.IDEMPOTENT_IN_FLIGHT))
|
||||
.hasValue(2);
|
||||
}
|
||||
|
||||
// feature-outbound-http-client-baseline D12: dependency codes — rows 636~711 in
|
||||
// docs/registries/error-codes.yaml, retry_after_seconds column.
|
||||
|
||||
|
||||
+57
-14
@@ -4,15 +4,12 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
import org.springframework.boot.test.system.CapturedOutput;
|
||||
import org.springframework.boot.test.system.OutputCaptureExtension;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@ExtendWith(OutputCaptureExtension.class)
|
||||
class SecuritySettingsTest {
|
||||
|
||||
private final ApplicationContextRunner runner =
|
||||
@@ -29,15 +26,59 @@ class SecuritySettingsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void audienceMissingWarnsAndDefaultsToEmpty(CapturedOutput output) {
|
||||
runner
|
||||
.withPropertyValues("app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
assertThat(context.getBean(SecuritySettings.class).audience()).isEmpty();
|
||||
assertThat(output.getOut()).contains("APP_SECURITY_JWT_AUDIENCE is missing");
|
||||
});
|
||||
@DisplayName("JWT 모드에서 audience가 없으면 env 키 이름을 담아 기동을 거부한다")
|
||||
void aJwtModeWithoutAnAudienceFailsStartupNamingTheEnvKey() {
|
||||
// given
|
||||
var withoutAudience =
|
||||
runner.withPropertyValues(
|
||||
"app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton");
|
||||
|
||||
// when
|
||||
withoutAudience.run(
|
||||
context -> {
|
||||
// then
|
||||
assertThat(context).hasFailed();
|
||||
assertThat(context.getStartupFailure())
|
||||
.hasStackTraceContaining("APP_SECURITY_JWT_AUDIENCE");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("JWT 모드에서 audience가 빈 값이거나 공백 항목뿐이면 기동을 거부한다")
|
||||
void aJwtModeWithABlankAudienceFailsStartup() {
|
||||
// given
|
||||
var blankAudience =
|
||||
runner.withPropertyValues(
|
||||
"app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton",
|
||||
"app.security.audience= , ");
|
||||
|
||||
// when
|
||||
blankAudience.run(
|
||||
context -> {
|
||||
// then
|
||||
assertThat(context).hasFailed();
|
||||
assertThat(context.getStartupFailure())
|
||||
.hasStackTraceContaining("APP_SECURITY_JWT_AUDIENCE");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("audience는 쉼표 목록을 받아 공백을 다듬은 목록으로 묶는다")
|
||||
void aCommaSeparatedAudienceBindsAsATrimmedList() {
|
||||
// given
|
||||
var listedAudiences =
|
||||
runner.withPropertyValues(
|
||||
"app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton",
|
||||
"app.security.audience=ca-skeleton-api, ca-skeleton-admin");
|
||||
|
||||
// when
|
||||
listedAudiences.run(
|
||||
context -> {
|
||||
// then
|
||||
assertThat(context).hasNotFailed();
|
||||
assertThat(context.getBean(SecuritySettings.class).audience())
|
||||
.containsExactly("ca-skeleton-api", "ca-skeleton-admin");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -60,7 +101,8 @@ class SecuritySettingsTest {
|
||||
List<String> paths = new ArrayList<>(List.of("/healthcheck"));
|
||||
|
||||
SecuritySettings settings =
|
||||
new SecuritySettings("http://localhost:8081/realms/ca-skeleton", "ca-skeleton-api", paths);
|
||||
new SecuritySettings(
|
||||
"http://localhost:8081/realms/ca-skeleton", List.of("ca-skeleton-api"), paths);
|
||||
paths.add("/admin/**");
|
||||
|
||||
assertThat(settings.publicPaths()).containsExactly("/healthcheck");
|
||||
@@ -83,6 +125,7 @@ class SecuritySettingsTest {
|
||||
assertThat(settings.authMode())
|
||||
.isEqualTo(SecuritySettings.AuthenticationMode.REDIS_SESSION);
|
||||
assertThat(settings.issuerUri()).isEmpty();
|
||||
assertThat(settings.audience()).isEmpty();
|
||||
assertThat(settings.session().cookieName()).isEqualTo("APP_SESSION");
|
||||
assertThat(settings.session().sameSite()).isEqualTo("Strict");
|
||||
});
|
||||
|
||||
+2
-1
@@ -29,7 +29,8 @@ import org.springframework.security.web.SecurityFilterChain;
|
||||
* production security chain and its JWT settings) and {@link WebAdapterAutoConfiguration} (the
|
||||
* request-logging filter and the composition-root pseudonymizer that filter needs). Together they
|
||||
* are the "sum of the leaf" the paragraph above keeps out. Excluded by class, so a rename breaks
|
||||
* compilation rather than the gate.
|
||||
* compilation rather than the gate. The third root, {@code WebMethodSecurityAutoConfiguration}, is
|
||||
* left in: no fixture route runs a permissioned use case, so it decides nothing here.
|
||||
*/
|
||||
// Outside `dev.caskeleton.adapter.inbound.web`, which the composition root component-scans.
|
||||
// A fixture application under that root is loaded into the real deployment: its permit-all
|
||||
|
||||
@@ -122,7 +122,10 @@ Redis checks a script's inner commands against the ACL only when they run, so a
|
||||
nothing proved `EVALSHA` and nothing else: an account granted by category (`@read`/`@write`) lacks
|
||||
`TIME` and failed every rate-limit and idempotency request after a clean start. A deployment whose
|
||||
effective Redis account lacks script permissions fails during startup rather than at the first
|
||||
request. Cache-only deployments do not run this probe.
|
||||
request. Cache-only deployments do not run this probe, although the cache's conditional intents
|
||||
(`ONLY_IF_OBSERVED`, `ONLY_IF_SOURCE_REVISION_NEWER`) also run on the SCRIPT lane: a cache-only
|
||||
deployment whose script-lane account lacks `EVALSHA` finds out as `INDETERMINATE` conditional
|
||||
writes, not at startup.
|
||||
|
||||
At runtime, `redisRequired` (redis-runtime) probes the SCRIPT lane too when a script role is
|
||||
selected, so a broken advanced-account credential makes the pod unready instead of leaving the
|
||||
@@ -153,6 +156,24 @@ script to perform:
|
||||
inside one Redis execution. A stale source load therefore cannot overwrite a value written between
|
||||
observation and replacement.
|
||||
|
||||
`ONLY_IF_SOURCE_REVISION_NEWER` is an atomic server-side revision comparison. The source revision
|
||||
must be a non-negative decimal integer without leading zeros (a row version, an offset, epoch
|
||||
millis); any other revision is refused with `IllegalArgumentException` before anything is sent,
|
||||
because text order would rank revision `10` below `9`. The script reads the stored envelope's
|
||||
schema version, revision and generation and writes only when:
|
||||
|
||||
- nothing is stored, or the stored entry is from an older region generation (already invalidated);
|
||||
- otherwise, the stored revision is a decimal integer and the caller's is strictly greater.
|
||||
|
||||
Everything else — an equal or smaller revision, a stored revision with no numeric order (for
|
||||
example one written by `UPSERT` as `rev-1`), another schema version, a generation newer than the
|
||||
writer knows — is `NOT_RECORDED_CONDITION`.
|
||||
|
||||
Both conditional intents run registered scripts, so they borrow the SCRIPT lane (the advanced
|
||||
account when one is configured, the application account otherwise). The application account is not
|
||||
granted `EVALSHA`; on the REGULAR lane every conditional write came back `INDETERMINATE`. `UPSERT`
|
||||
and `ONLY_IF_ABSENT` stay on the REGULAR lane.
|
||||
|
||||
### Region invalidation
|
||||
|
||||
Region invalidation increments a generation key; it never scans/deletes the keyspace.
|
||||
@@ -184,6 +205,15 @@ programs atomically. `RedisIdempotencyConfig` contributes only the `IdempotencyS
|
||||
revision) come from app-bootstrap `IdempotencySettings`. This leaf reads only `key-version` and
|
||||
`command-timeout` under `app.capabilities.idempotency`.
|
||||
|
||||
`renew` has its own program rather than the generic transition. Renewal keeps the record in
|
||||
`EXECUTING`, and the transition answers "already in the target state" before it reads the revision
|
||||
(that answer exists for a retry whose first reply was lost), so a renewal sent through it was always
|
||||
`ALREADY_RENEWED_SAME_OPERATION` and never moved the lease. The renew program checks owner,
|
||||
operation, revision and state, then extends `leaseUntil` from Redis `TIME` and bumps the revision.
|
||||
A lost renewal reply is recognised by what the renewal recorded — the revision it started from and
|
||||
the lease it asked for: the same lease is `ALREADY_RENEWED_SAME_OPERATION` with the current handle,
|
||||
a different lease is `OPERATION_CONFLICT`.
|
||||
|
||||
Redis `TIME` determines lease deadlines. A failure after a command may have executed is returned
|
||||
as an indeterminate outcome; the adapter does not convert an ambiguous write into a clean
|
||||
unavailable result that would invite duplicate execution.
|
||||
|
||||
+99
@@ -22,9 +22,88 @@ final class CacheScripts {
|
||||
return 1
|
||||
""";
|
||||
|
||||
/**
|
||||
* Replaces the entry only when the caller's source revision is strictly newer than the stored
|
||||
* one.
|
||||
*
|
||||
* <p>Revisions are canonical non-negative decimal integers, compared by length and then digit by
|
||||
* digit, so the order is numeric at any length (no 2^53 limit, no locale collation). The stored
|
||||
* envelope header is {@code digest|version|revision|generation|...}; the digest is not
|
||||
* re-verified here, the reader does that on lookup.
|
||||
*
|
||||
* <p>The write applies when nothing is stored, or when the stored entry belongs to an older
|
||||
* region generation (semantically invalidated). It is refused when the stored entry has another
|
||||
* schema version, a newer generation than the writer knows, or a revision that has no numeric
|
||||
* order: nothing proves the caller's revision is newer than any of those.
|
||||
*/
|
||||
private static final String REPLACE_IF_REVISION_NEWER =
|
||||
"""
|
||||
local function canonicalDecimal(text)
|
||||
return string.match(text, '^%d+$') ~= nil
|
||||
and (string.len(text) == 1 or string.sub(text, 1, 1) ~= '0')
|
||||
end
|
||||
local function strictlyNewer(candidate, stored)
|
||||
if string.len(candidate) ~= string.len(stored) then
|
||||
return string.len(candidate) > string.len(stored)
|
||||
end
|
||||
for i = 1, string.len(candidate) do
|
||||
local a = string.byte(candidate, i)
|
||||
local b = string.byte(stored, i)
|
||||
if a ~= b then
|
||||
return a > b
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
local current = redis.call('GET', KEYS[1])
|
||||
if current ~= false then
|
||||
if string.sub(current, 65, 65) ~= '|' then
|
||||
return 0
|
||||
end
|
||||
local fields = {}
|
||||
local cursor = 66
|
||||
for i = 1, 3 do
|
||||
local stop = string.find(current, '|', cursor, true)
|
||||
if stop == nil then
|
||||
return 0
|
||||
end
|
||||
fields[i] = string.sub(current, cursor, stop - 1)
|
||||
cursor = stop + 1
|
||||
end
|
||||
if fields[1] ~= ARGV[4] then
|
||||
return 0
|
||||
end
|
||||
local storedGeneration = tonumber(fields[3])
|
||||
local writerGeneration = tonumber(ARGV[5])
|
||||
if storedGeneration == nil or storedGeneration > writerGeneration then
|
||||
return 0
|
||||
end
|
||||
if storedGeneration == writerGeneration then
|
||||
if not canonicalDecimal(fields[2]) or not strictlyNewer(ARGV[1], fields[2]) then
|
||||
return 0
|
||||
end
|
||||
end
|
||||
end
|
||||
redis.call('SET', KEYS[1], ARGV[2], 'PX', ARGV[3])
|
||||
return 1
|
||||
""";
|
||||
|
||||
private final RegisteredLuaScript replaceIfObserved =
|
||||
new RegisteredLuaScript(REPLACE_IF_OBSERVED);
|
||||
|
||||
private final RegisteredLuaScript replaceIfRevisionNewer =
|
||||
new RegisteredLuaScript(REPLACE_IF_REVISION_NEWER);
|
||||
|
||||
/**
|
||||
* Whether a revision has the numeric order {@link #replaceIfRevisionNewer} compares by.
|
||||
*
|
||||
* @param revision the source revision
|
||||
* @return true for a canonical non-negative decimal integer
|
||||
*/
|
||||
static boolean hasNumericOrder(String revision) {
|
||||
return revision.matches("0|[1-9][0-9]*");
|
||||
}
|
||||
|
||||
CompletionStage<Boolean> replaceIfObserved(
|
||||
SemanticRedisCommands commands,
|
||||
byte[] key,
|
||||
@@ -40,4 +119,24 @@ final class CacheScripts {
|
||||
.evaluateForLong(commands, key, arguments)
|
||||
.thenApply(applied -> applied != null && applied == 1L);
|
||||
}
|
||||
|
||||
CompletionStage<Boolean> replaceIfRevisionNewer(
|
||||
SemanticRedisCommands commands,
|
||||
byte[] key,
|
||||
String sourceRevision,
|
||||
byte[] replacement,
|
||||
long ttlMillis,
|
||||
int schemaVersion,
|
||||
long writerGeneration) {
|
||||
List<byte[]> arguments =
|
||||
List.of(
|
||||
sourceRevision.getBytes(StandardCharsets.US_ASCII),
|
||||
replacement,
|
||||
Long.toString(ttlMillis).getBytes(StandardCharsets.US_ASCII),
|
||||
Integer.toString(schemaVersion).getBytes(StandardCharsets.US_ASCII),
|
||||
Long.toString(writerGeneration).getBytes(StandardCharsets.US_ASCII));
|
||||
return replaceIfRevisionNewer
|
||||
.evaluateForLong(commands, key, arguments)
|
||||
.thenApply(applied -> applied != null && applied == 1L);
|
||||
}
|
||||
}
|
||||
|
||||
+77
-44
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.cache;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.SemanticRedisCall;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.keyspace.CapabilityKeyspace;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace;
|
||||
@@ -54,6 +55,12 @@ public final class RedisCacheRegionAdapter<K, V> implements CacheRegionPort<K, V
|
||||
|
||||
private final SemanticRedisCall call;
|
||||
|
||||
/**
|
||||
* The conditional writes, which are registered programs and so run on the SCRIPT lane: the
|
||||
* application account the REGULAR lane authenticates as is not granted {@code EVALSHA}.
|
||||
*/
|
||||
private final SemanticRedisCall scriptCall;
|
||||
|
||||
private final CacheKeys keys;
|
||||
|
||||
private final Function<K, String> keyDigest;
|
||||
@@ -103,6 +110,8 @@ public final class RedisCacheRegionAdapter<K, V> implements CacheRegionPort<K, V
|
||||
RedisConnectionKind.REGULAR,
|
||||
Objects.requireNonNull(commandTimeout, "command timeout must be non-null"),
|
||||
"cache");
|
||||
this.scriptCall =
|
||||
new SemanticRedisCall(owner, RedisConnectionKind.SCRIPT, commandTimeout, "cache");
|
||||
this.keys = Objects.requireNonNull(keys, "keys must be non-null");
|
||||
this.keyDigest = Objects.requireNonNull(keyDigest, "key digest must be non-null");
|
||||
this.encoder = Objects.requireNonNull(encoder, "encoder must be non-null");
|
||||
@@ -215,55 +224,79 @@ public final class RedisCacheRegionAdapter<K, V> implements CacheRegionPort<K, V
|
||||
K key, byte[] payload, String absence, CacheRecordMetadata metadata, Duration ttl) {
|
||||
Objects.requireNonNull(key, "key must be non-null");
|
||||
Objects.requireNonNull(metadata, "metadata must be non-null");
|
||||
CacheRecordIntent intent = metadata.intent();
|
||||
if (intent == CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER
|
||||
&& !CacheScripts.hasNumericOrder(metadata.sourceRevision())) {
|
||||
// Refused before anything is sent. "Newer" needs an order, and this provider orders
|
||||
// revisions as non-negative decimal integers only; text order would rank revision 10 below
|
||||
// revision 9. A caller error, so it fails loudly rather than degrading like an outage.
|
||||
throw new IllegalArgumentException(
|
||||
"ONLY_IF_SOURCE_REVISION_NEWER needs a source revision that is a non-negative decimal"
|
||||
+ " integer without leading zeros");
|
||||
}
|
||||
Instant now = clock.instant();
|
||||
Duration effectiveSoft = softTtl.compareTo(ttl) > 0 ? ttl : softTtl;
|
||||
byte[] physicalKey = keys.entryKey(keyDigest.apply(key));
|
||||
boolean scripted =
|
||||
intent == CacheRecordIntent.ONLY_IF_OBSERVED
|
||||
|| intent == CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER;
|
||||
// The write is marked sent only when the write command itself is handed to the driver. A
|
||||
// failure before that point — lane refusal, connection, the generation read — wrote nothing.
|
||||
return call.run(
|
||||
"record",
|
||||
session -> {
|
||||
resolveGeneration(session, now);
|
||||
CacheEnvelope envelope =
|
||||
new CacheEnvelope(
|
||||
CacheEnvelope.CURRENT_SCHEMA_VERSION,
|
||||
metadata.sourceRevision(),
|
||||
keys.generation(),
|
||||
now.plus(effectiveSoft),
|
||||
now.plus(ttl),
|
||||
absence,
|
||||
payload);
|
||||
session.markSent();
|
||||
Boolean applied =
|
||||
metadata.intent() == CacheRecordIntent.ONLY_IF_OBSERVED
|
||||
// Compare and replacement are one server-side execution. A GET followed by SET
|
||||
// would let a concurrent writer land between them and then be overwritten by
|
||||
// this stale source load.
|
||||
? session.await(
|
||||
scripts.replaceIfObserved(
|
||||
session.commands(),
|
||||
physicalKey,
|
||||
metadata.observedToken().value(),
|
||||
envelope.encode(),
|
||||
ttl.toMillis()))
|
||||
// The physical TTL is the hard expiry and nothing else.
|
||||
: session.await(
|
||||
session
|
||||
.commands()
|
||||
.set(physicalKey, envelope.encode(), presenceOf(metadata.intent()), ttl));
|
||||
return Boolean.TRUE.equals(applied)
|
||||
? CacheRecordOutcome.RECORDED
|
||||
: CacheRecordOutcome.NOT_RECORDED_CONDITION;
|
||||
},
|
||||
() -> CacheRecordOutcome.DEGRADED_UNAVAILABLE,
|
||||
() -> CacheRecordOutcome.INDETERMINATE);
|
||||
}
|
||||
|
||||
private static dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence
|
||||
presenceOf(CacheRecordIntent intent) {
|
||||
return intent == CacheRecordIntent.ONLY_IF_ABSENT
|
||||
? dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence.IF_ABSENT
|
||||
: dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence.ALWAYS;
|
||||
return (scripted ? scriptCall : call)
|
||||
.run(
|
||||
"record",
|
||||
session -> {
|
||||
resolveGeneration(session, now);
|
||||
CacheEnvelope envelope =
|
||||
new CacheEnvelope(
|
||||
CacheEnvelope.CURRENT_SCHEMA_VERSION,
|
||||
metadata.sourceRevision(),
|
||||
keys.generation(),
|
||||
now.plus(effectiveSoft),
|
||||
now.plus(ttl),
|
||||
absence,
|
||||
payload);
|
||||
session.markSent();
|
||||
// Each condition is checked and applied in one server-side execution. A GET followed
|
||||
// by SET would let a concurrent writer land between them and then be overwritten by
|
||||
// this stale source load. The physical TTL is the hard expiry and nothing else.
|
||||
Boolean applied =
|
||||
switch (intent) {
|
||||
case ONLY_IF_OBSERVED ->
|
||||
session.await(
|
||||
scripts.replaceIfObserved(
|
||||
session.commands(),
|
||||
physicalKey,
|
||||
metadata.observedToken().value(),
|
||||
envelope.encode(),
|
||||
ttl.toMillis()));
|
||||
case ONLY_IF_SOURCE_REVISION_NEWER ->
|
||||
session.await(
|
||||
scripts.replaceIfRevisionNewer(
|
||||
session.commands(),
|
||||
physicalKey,
|
||||
metadata.sourceRevision(),
|
||||
envelope.encode(),
|
||||
ttl.toMillis(),
|
||||
CacheEnvelope.CURRENT_SCHEMA_VERSION,
|
||||
keys.generation()));
|
||||
case ONLY_IF_ABSENT ->
|
||||
session.await(
|
||||
session
|
||||
.commands()
|
||||
.set(physicalKey, envelope.encode(), WritePresence.IF_ABSENT, ttl));
|
||||
case UPSERT ->
|
||||
session.await(
|
||||
session
|
||||
.commands()
|
||||
.set(physicalKey, envelope.encode(), WritePresence.ALWAYS, ttl));
|
||||
};
|
||||
return Boolean.TRUE.equals(applied)
|
||||
? CacheRecordOutcome.RECORDED
|
||||
: CacheRecordOutcome.NOT_RECORDED_CONDITION;
|
||||
},
|
||||
() -> CacheRecordOutcome.DEGRADED_UNAVAILABLE,
|
||||
() -> CacheRecordOutcome.INDETERMINATE);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+55
@@ -130,6 +130,56 @@ public final class IdempotencyScripts {
|
||||
return {'APPLIED', attempt, rev + 1, owner, '', ''}
|
||||
""";
|
||||
|
||||
/**
|
||||
* Renew: extend the processing lease of an EXECUTING record, and nothing else.
|
||||
*
|
||||
* <p>Not the generic {@link #TRANSITION}. Renewal does not change the state, so the transition's
|
||||
* "already in the target state" answer — which exists for a retry whose first reply was lost —
|
||||
* would match every renewal before the revision was ever read, and the lease would never move.
|
||||
*
|
||||
* <p>A lost renewal reply is recognised by what the renewal itself recorded instead: the revision
|
||||
* it started from and the lease it asked for. A retry from that revision with the same lease is
|
||||
* the same renewal; with a different lease it is a different request, because confirming it would
|
||||
* leave the caller believing it holds the record for a lease the record does not carry.
|
||||
*/
|
||||
private static final String RENEW =
|
||||
"""
|
||||
local state = redis.call('HGET', KEYS[1], 'state')
|
||||
if state == false then
|
||||
return {'ABSENT', 0, 0, '', '', ''}
|
||||
end
|
||||
local owner = redis.call('HGET', KEYS[1], 'owner')
|
||||
local rev = tonumber(redis.call('HGET', KEYS[1], 'rev'))
|
||||
local attempt = tonumber(redis.call('HGET', KEYS[1], 'attempt'))
|
||||
local op = redis.call('HGET', KEYS[1], 'op')
|
||||
if owner ~= ARGV[1] then
|
||||
return {'NOT_OWNER', attempt, rev, owner, '', ''}
|
||||
end
|
||||
if op ~= ARGV[3] then
|
||||
return {'OPERATION_CONFLICT', attempt, rev, owner, '', ''}
|
||||
end
|
||||
local handleRev = tonumber(ARGV[2])
|
||||
if rev ~= handleRev then
|
||||
if state == 'EXECUTING' and rev == handleRev + 1
|
||||
and redis.call('HGET', KEYS[1], 'renewedFromRev') == ARGV[2] then
|
||||
if redis.call('HGET', KEYS[1], 'renewedLease') == ARGV[4] then
|
||||
return {'ALREADY', attempt, rev, owner, '', ''}
|
||||
end
|
||||
return {'OPERATION_CONFLICT', attempt, rev, owner, '', ''}
|
||||
end
|
||||
return {'NOT_OWNER', attempt, rev, owner, '', ''}
|
||||
end
|
||||
if state ~= 'EXECUTING' then
|
||||
return {'WRONG_STATE', attempt, rev, owner, state, ''}
|
||||
end
|
||||
local t = redis.call('TIME')
|
||||
local nowMillis = (tonumber(t[1]) * 1000) + math.floor(tonumber(t[2]) / 1000)
|
||||
redis.call('HSET', KEYS[1],
|
||||
'leaseUntil', nowMillis + tonumber(ARGV[4]), 'rev', rev + 1,
|
||||
'renewedFromRev', ARGV[2], 'renewedLease', ARGV[4])
|
||||
return {'APPLIED', attempt, rev + 1, owner, '', ''}
|
||||
""";
|
||||
|
||||
/** Release before execution: only from CLAIMED, and only by the owner that holds it. */
|
||||
private static final String RELEASE =
|
||||
"""
|
||||
@@ -184,6 +234,7 @@ public final class IdempotencyScripts {
|
||||
|
||||
private final RegisteredLuaScript claim = new RegisteredLuaScript(CLAIM);
|
||||
private final RegisteredLuaScript transition = new RegisteredLuaScript(TRANSITION);
|
||||
private final RegisteredLuaScript renew = new RegisteredLuaScript(RENEW);
|
||||
private final RegisteredLuaScript release = new RegisteredLuaScript(RELEASE);
|
||||
private final RegisteredLuaScript inspect = new RegisteredLuaScript(INSPECT);
|
||||
|
||||
@@ -196,6 +247,10 @@ public final class IdempotencyScripts {
|
||||
return run(transition, commands, key, arguments);
|
||||
}
|
||||
|
||||
CompletionStage<Reply> renew(SemanticRedisCommands commands, byte[] key, List<String> arguments) {
|
||||
return run(renew, commands, key, arguments);
|
||||
}
|
||||
|
||||
CompletionStage<Reply> release(
|
||||
SemanticRedisCommands commands, byte[] key, List<String> arguments) {
|
||||
return run(release, commands, key, arguments);
|
||||
|
||||
+39
-10
@@ -32,6 +32,8 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
@@ -183,11 +185,19 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort
|
||||
public IdempotencyMutationResult<IdempotencyRenewOutcome> renew(
|
||||
IdempotencyOwner ownerHandle, Duration processingLeaseTtl, OperationId operationId) {
|
||||
Objects.requireNonNull(processingLeaseTtl, "processing lease TTL must be non-null");
|
||||
return transition(
|
||||
// Its own program, not the generic transition: EXECUTING -> EXECUTING is "already in the
|
||||
// target state" to the transition, which answered ALREADY without ever extending the lease.
|
||||
return ownerMutation(
|
||||
ownerHandle,
|
||||
operationId,
|
||||
new Transition(
|
||||
"EXECUTING", "EXECUTING", "", Long.toString(processingLeaseTtl.toMillis()), ""),
|
||||
session ->
|
||||
scripts.renew(
|
||||
session.commands(),
|
||||
keys.recordKey(ownerHandle.scope()),
|
||||
List.of(
|
||||
ownerHandle.ownerToken(),
|
||||
Long.toString(ownerHandle.stateRevision()),
|
||||
operationId.value(),
|
||||
Long.toString(processingLeaseTtl.toMillis()))),
|
||||
Map.of(
|
||||
ScriptStatus.APPLIED, IdempotencyRenewOutcome.RENEWED,
|
||||
ScriptStatus.ALREADY, IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION,
|
||||
@@ -429,15 +439,34 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort
|
||||
O indeterminate,
|
||||
O unavailable,
|
||||
Predicate<O> carriesOwner) {
|
||||
return ownerMutation(
|
||||
ownerHandle,
|
||||
session ->
|
||||
scripts.transition(
|
||||
session.commands(),
|
||||
keys.recordKey(ownerHandle.scope()),
|
||||
transition.arguments(ownerHandle, operationId)),
|
||||
outcomes,
|
||||
indeterminate,
|
||||
unavailable,
|
||||
carriesOwner);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one owner-checked program and maps its verdict, carrying the refreshed handle when the
|
||||
* outcome leaves the caller still owning the record.
|
||||
*/
|
||||
private <O extends Enum<O>> IdempotencyMutationResult<O> ownerMutation(
|
||||
IdempotencyOwner ownerHandle,
|
||||
Function<SemanticRedisCall.Session, CompletionStage<IdempotencyScripts.Reply>> program,
|
||||
Map<ScriptStatus, O> outcomes,
|
||||
O indeterminate,
|
||||
O unavailable,
|
||||
Predicate<O> carriesOwner) {
|
||||
return call.effect(
|
||||
"transition",
|
||||
session -> {
|
||||
IdempotencyScripts.Reply reply =
|
||||
session.await(
|
||||
scripts.transition(
|
||||
session.commands(),
|
||||
keys.recordKey(ownerHandle.scope()),
|
||||
transition.arguments(ownerHandle, operationId)));
|
||||
IdempotencyScripts.Reply reply = session.await(program.apply(session));
|
||||
O outcome = outcomes.getOrDefault(reply.status(), indeterminate);
|
||||
return new IdempotencyMutationResult<>(
|
||||
outcome,
|
||||
|
||||
+124
@@ -27,6 +27,8 @@ import dev.caskeleton.application.cache.CacheRegionPort;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyClaimRequest;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyOwner;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyRenewOutcome;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyScopeDigest;
|
||||
import dev.caskeleton.application.idempotency.RequestFingerprint;
|
||||
import dev.caskeleton.application.lease.LeaseAcquireOutcome;
|
||||
@@ -126,6 +128,83 @@ class LiveRedisSemanticPortsTest {
|
||||
assertThat(((CacheLookup.Hit<String>) lookup).value()).isEqualTo("payload");
|
||||
}
|
||||
|
||||
private CacheRegionPort<String, String> conditionalCache() {
|
||||
return new RedisCacheRegionAdapter<>(
|
||||
runtime(true),
|
||||
new RedisCacheRegionAdapter.CacheKeys(NAMESPACE, "orders", 1),
|
||||
key -> "hv1:" + Integer.toHexString(key.hashCode()),
|
||||
value -> value.getBytes(StandardCharsets.UTF_8),
|
||||
stored -> new String(stored, StandardCharsets.UTF_8),
|
||||
Clock.systemUTC(),
|
||||
Duration.ofSeconds(30),
|
||||
Duration.ofMinutes(5),
|
||||
Duration.ofSeconds(10),
|
||||
Duration.ofSeconds(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("실제 Redis에서 ONLY_IF_SOURCE_REVISION_NEWER는 저장된 것보다 작은 revision을 거부한다")
|
||||
void theRevisionConditionRefusesAnOlderRevisionOnARealServer() {
|
||||
// given
|
||||
CacheRegionPort<String, String> cache = conditionalCache();
|
||||
String key = "order-" + UUID.randomUUID();
|
||||
cache.record(key, "fresh", new CacheRecordMetadata("7", CacheRecordIntent.UPSERT));
|
||||
|
||||
// when
|
||||
CacheRecordOutcome outcome =
|
||||
cache.record(
|
||||
key,
|
||||
"stale",
|
||||
new CacheRecordMetadata("6", CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
|
||||
assertThat(((CacheLookup.Hit<String>) cache.lookup(key)).value()).isEqualTo("fresh");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("실제 Redis에서 ONLY_IF_SOURCE_REVISION_NEWER는 숫자로 더 큰 revision을 기록한다")
|
||||
void theRevisionConditionRecordsANumericallyNewerRevisionOnARealServer() {
|
||||
// given
|
||||
CacheRegionPort<String, String> cache = conditionalCache();
|
||||
String key = "order-" + UUID.randomUUID();
|
||||
cache.record(key, "old", new CacheRecordMetadata("9", CacheRecordIntent.UPSERT));
|
||||
|
||||
// when
|
||||
// DEGRADED_UNAVAILABLE or INDETERMINATE here means EVALSHA was refused on the lane it ran on.
|
||||
CacheRecordOutcome outcome =
|
||||
cache.record(
|
||||
key,
|
||||
"new",
|
||||
new CacheRecordMetadata("10", CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
|
||||
assertThat(((CacheLookup.Hit<String>) cache.lookup(key)).value()).isEqualTo("new");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("실제 Redis의 ACL 계정 구성에서 ONLY_IF_OBSERVED 조건부 교체가 실행된다")
|
||||
void theObservedConditionRunsUnderTheDeploymentAccounts() {
|
||||
// given
|
||||
CacheRegionPort<String, String> cache = conditionalCache();
|
||||
String key = "order-" + UUID.randomUUID();
|
||||
cache.record(key, "first", new CacheRecordMetadata("rev-1", CacheRecordIntent.UPSERT));
|
||||
CacheLookup.Hit<String> observed = (CacheLookup.Hit<String>) cache.lookup(key);
|
||||
|
||||
// when
|
||||
// On the REGULAR lane the application account has no EVALSHA, and this degraded every time.
|
||||
CacheRecordOutcome outcome =
|
||||
cache.record(
|
||||
key,
|
||||
"second",
|
||||
new CacheRecordMetadata(
|
||||
"rev-2", CacheRecordIntent.ONLY_IF_OBSERVED, observed.observationToken()));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Rate limit / idempotency / lease: the script lane, the advanced account
|
||||
// =========================================================================
|
||||
@@ -369,6 +448,51 @@ class LiveRedisSemanticPortsTest {
|
||||
.isInstanceOf(IdempotencyClaimOutcome.InProgress.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("실제 Redis에서 renew한 처리 lease는 원래 lease가 지난 뒤에도 다른 claim을 막는다")
|
||||
void aRenewedProcessingLeaseOutlivesTheOriginalLeaseOnARealServer() throws InterruptedException {
|
||||
// given
|
||||
RedisIdempotencyStoreAdapter store =
|
||||
new RedisIdempotencyStoreAdapter(
|
||||
runtime(true),
|
||||
new RedisIdempotencyStoreAdapter.IdempotencyKeys(NAMESPACE, 1),
|
||||
new IdempotencyScripts(),
|
||||
Clock.systemUTC(),
|
||||
Duration.ofSeconds(2));
|
||||
IdempotencyScopeDigest scope =
|
||||
new IdempotencyScopeDigest(
|
||||
UUID.randomUUID().toString().replace("-", "")
|
||||
+ UUID.randomUUID().toString().replace("-", ""),
|
||||
1,
|
||||
"CHARGE_CARD");
|
||||
IdempotencyClaimAttempt first = store.newClaimAttempt(new OperationId("operation-renew-aaaa"));
|
||||
IdempotencyOwner claimed =
|
||||
((IdempotencyClaimOutcome.Acquired)
|
||||
store.claim(
|
||||
new IdempotencyClaimRequest(
|
||||
scope,
|
||||
new RequestFingerprint("0".repeat(64)),
|
||||
first,
|
||||
Duration.ofSeconds(1),
|
||||
Duration.ofHours(1),
|
||||
"json-v2",
|
||||
1)))
|
||||
.owner();
|
||||
IdempotencyOwner executing =
|
||||
store.markExecutionStarted(claimed, first.operationId()).owner().orElseThrow();
|
||||
assertThat(store.renew(executing, Duration.ofSeconds(30), first.operationId()).outcome())
|
||||
.isEqualTo(IdempotencyRenewOutcome.RENEWED);
|
||||
// Past the one-second lease the claim was taken with; Redis TIME decides, not this JVM.
|
||||
Thread.sleep(1500);
|
||||
|
||||
// when
|
||||
IdempotencyClaimOutcome other =
|
||||
store.claim(claim(scope, store.newClaimAttempt(new OperationId("operation-renew-bbbb"))));
|
||||
|
||||
// then
|
||||
assertThat(other).isInstanceOf(IdempotencyClaimOutcome.InProgress.class);
|
||||
}
|
||||
|
||||
private static IdempotencyClaimRequest claim(
|
||||
IdempotencyScopeDigest scope, IdempotencyClaimAttempt attempt) {
|
||||
return new IdempotencyClaimRequest(
|
||||
|
||||
+117
@@ -311,6 +311,123 @@ class RedisCacheRegionAdapterTest {
|
||||
.isEqualTo(CacheRecordOutcome.RECORDED);
|
||||
}
|
||||
|
||||
private static CacheRecordMetadata newerThan(String sourceRevision) {
|
||||
return new CacheRecordMetadata(sourceRevision, CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 저장된 것보다 작은 revision을 기록하지 않는다")
|
||||
void onlyIfSourceRevisionNewerRefusesAnOlderRevision() {
|
||||
// given
|
||||
RedisCacheRegionAdapter<String, String> cache = cache(T0);
|
||||
cache.record("order-1", "fresh", new CacheRecordMetadata("7", CacheRecordIntent.UPSERT));
|
||||
|
||||
// when
|
||||
// A slow loader that read the source at revision 6 finishes after the revision-7 write.
|
||||
CacheRecordOutcome outcome = cache.record("order-1", "stale", newerThan("6"));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
|
||||
assertThat(((CacheLookup.Hit<String>) cache.lookup("order-1")).value()).isEqualTo("fresh");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 저장된 것과 같은 revision을 기록하지 않는다")
|
||||
void onlyIfSourceRevisionNewerRefusesTheSameRevision() {
|
||||
// given
|
||||
RedisCacheRegionAdapter<String, String> cache = cache(T0);
|
||||
cache.record("order-1", "first", new CacheRecordMetadata("7", CacheRecordIntent.UPSERT));
|
||||
|
||||
// when
|
||||
CacheRecordOutcome outcome = cache.record("order-1", "second", newerThan("7"));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
|
||||
assertThat(((CacheLookup.Hit<String>) cache.lookup("order-1")).value()).isEqualTo("first");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 더 큰 revision을 숫자 순서로 판단해 기록한다")
|
||||
void onlyIfSourceRevisionNewerRecordsANumericallyNewerRevision() {
|
||||
// given
|
||||
RedisCacheRegionAdapter<String, String> cache = cache(T0);
|
||||
cache.record("order-1", "old", new CacheRecordMetadata("9", CacheRecordIntent.UPSERT));
|
||||
|
||||
// when
|
||||
// "10" sorts before "9" as text. The order is numeric, or revision 10 could never replace 9.
|
||||
CacheRecordOutcome outcome = cache.record("order-1", "new", newerThan("10"));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
|
||||
CacheLookup.Hit<String> hit = (CacheLookup.Hit<String>) cache.lookup("order-1");
|
||||
assertThat(hit.value()).isEqualTo("new");
|
||||
assertThat(hit.sourceRevision()).isEqualTo("10");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 비어 있는 키에 기록한다")
|
||||
void onlyIfSourceRevisionNewerRecordsIntoAnAbsentKey() {
|
||||
// given
|
||||
RedisCacheRegionAdapter<String, String> cache = cache(T0);
|
||||
|
||||
// when
|
||||
CacheRecordOutcome outcome = cache.record("order-1", "first", newerThan("1"));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
|
||||
assertThat(((CacheLookup.Hit<String>) cache.lookup("order-1")).value()).isEqualTo("first");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 region 무효화 전 세대의 항목을 revision과 관계없이 교체한다")
|
||||
void onlyIfSourceRevisionNewerReplacesAnEntryFromAnInvalidatedGeneration() {
|
||||
// given
|
||||
RedisCacheRegionAdapter<String, String> cache = cache(T0);
|
||||
cache.record("order-1", "before", new CacheRecordMetadata("9", CacheRecordIntent.UPSERT));
|
||||
cache.invalidateRegion();
|
||||
|
||||
// when
|
||||
// The invalidated entry is semantically gone; its revision is no longer a fact to defend.
|
||||
CacheRecordOutcome outcome = cache.record("order-1", "after", newerThan("3"));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
|
||||
assertThat(((CacheLookup.Hit<String>) cache.lookup("order-1")).value()).isEqualTo("after");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 순서를 비교할 수 없는 저장 revision을 덮어쓰지 않는다")
|
||||
void onlyIfSourceRevisionNewerRefusesWhenTheStoredRevisionIsNotComparable() {
|
||||
// given
|
||||
RedisCacheRegionAdapter<String, String> cache = cache(T0);
|
||||
cache.record("order-1", "upserted", upsert());
|
||||
|
||||
// when
|
||||
// "rev-1" has no numeric order, so nothing proves revision 2 is newer than it.
|
||||
CacheRecordOutcome outcome = cache.record("order-1", "conditional", newerThan("2"));
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
|
||||
assertThat(((CacheLookup.Hit<String>) cache.lookup("order-1")).value()).isEqualTo("upserted");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER에 10진 정수가 아닌 revision을 주면 Redis에 보내기 전에 거부한다")
|
||||
void onlyIfSourceRevisionNewerRejectsARevisionWithoutANumericOrder() {
|
||||
// given
|
||||
RedisCacheRegionAdapter<String, String> cache = cache(T0);
|
||||
|
||||
// when
|
||||
Throwable refused =
|
||||
org.assertj.core.api.Assertions.catchThrowable(
|
||||
() -> cache.record("order-1", "payload", newerThan("rev-2")));
|
||||
|
||||
// then
|
||||
assertThat(refused)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("ONLY_IF_SOURCE_REVISION_NEWER");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("an unreachable Redis degrades: the cache is bypassed, nothing fails")
|
||||
void anUnreachableRedisDegrades() {
|
||||
|
||||
+110
@@ -257,6 +257,116 @@ class RedisIdempotencyStoreAdapterTest {
|
||||
.isEqualTo(IdempotencyReleaseOutcome.EXECUTION_ALREADY_STARTED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("renew는 RENEWED와 함께 더 새 revision의 owner 핸들을 돌려준다")
|
||||
void renewReturnsAHandleAtTheNewRevision() {
|
||||
// given
|
||||
IdempotencyOwner executing = executing();
|
||||
|
||||
// when
|
||||
var renewed = store.renew(executing, Duration.ofSeconds(30), OPERATION);
|
||||
|
||||
// then
|
||||
assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.RENEWED);
|
||||
assertThat(renewed.owner().orElseThrow().stateRevision())
|
||||
.isGreaterThan(executing.stateRevision());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("renew한 처리 lease는 원래 lease가 지난 뒤에도 다른 요청의 claim을 IN_PROGRESS로 막는다")
|
||||
void aRenewedLeaseStillExcludesAnotherClaimPastTheOriginalExpiry() {
|
||||
// given
|
||||
IdempotencyOwner executing = executing();
|
||||
gateway.advance(Duration.ofSeconds(20));
|
||||
store.renew(executing, Duration.ofSeconds(30), OPERATION);
|
||||
// 40 seconds after the claim: past the original 30-second lease, inside the renewed one.
|
||||
gateway.advance(Duration.ofSeconds(20));
|
||||
|
||||
// when
|
||||
IdempotencyClaimOutcome other = store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
|
||||
|
||||
// then
|
||||
// TAKEN_OVER here would hand a running operation to a second worker: the effect happens twice.
|
||||
assertThat(other).isInstanceOf(IdempotencyClaimOutcome.InProgress.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("renew 응답을 잃고 같은 핸들로 다시 renew하면 ALREADY_RENEWED와 현재 revision 핸들을 받는다")
|
||||
void aRenewRetriedAfterALostReplyIsAlreadyRenewed() {
|
||||
// given
|
||||
IdempotencyOwner executing = executing();
|
||||
var first = store.renew(executing, Duration.ofSeconds(30), OPERATION);
|
||||
|
||||
// when
|
||||
// The first reply was lost, so the caller still holds the pre-renewal handle.
|
||||
var retried = store.renew(executing, Duration.ofSeconds(30), OPERATION);
|
||||
|
||||
// then
|
||||
assertThat(retried.outcome()).isEqualTo(IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION);
|
||||
assertThat(retried.owner().orElseThrow().stateRevision())
|
||||
.isEqualTo(first.owner().orElseThrow().stateRevision());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("lost reply 재시도가 다른 lease 길이를 요청하면 이미 적용된 renew로 확인하지 않는다")
|
||||
void aRenewRetryAskingForADifferentLeaseIsAConflict() {
|
||||
// given
|
||||
IdempotencyOwner executing = executing();
|
||||
store.renew(executing, Duration.ofSeconds(30), OPERATION);
|
||||
|
||||
// when
|
||||
var retried = store.renew(executing, Duration.ofSeconds(90), OPERATION);
|
||||
|
||||
// then
|
||||
// Confirming it would leave the caller believing it holds the record for 90 seconds.
|
||||
assertThat(retried.outcome()).isEqualTo(IdempotencyRenewOutcome.OPERATION_CONFLICT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("renew한 뒤 받은 핸들로 complete할 수 있다")
|
||||
void theRenewedHandleCanComplete() {
|
||||
// given
|
||||
IdempotencyOwner renewed =
|
||||
store.renew(executing(), Duration.ofSeconds(30), OPERATION).owner().orElseThrow();
|
||||
|
||||
// when
|
||||
IdempotencyCompleteOutcome outcome =
|
||||
store.complete(renewed, new StoredResponse("{}"), Duration.ofHours(1), OPERATION);
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(IdempotencyCompleteOutcome.COMPLETED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("실행을 시작하지 않은 claim은 renew할 수 없다")
|
||||
void renewBeforeExecutionStartedIsNotInProgress() {
|
||||
// given
|
||||
IdempotencyOwner claimed =
|
||||
((IdempotencyClaimOutcome.Acquired) store.claim(claim(store.newClaimAttempt(OPERATION))))
|
||||
.owner();
|
||||
|
||||
// when
|
||||
var renewed = store.renew(claimed, Duration.ofSeconds(30), OPERATION);
|
||||
|
||||
// then
|
||||
assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.NOT_IN_PROGRESS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("lease를 넘겨받은 뒤 이전 owner는 renew할 수 없다")
|
||||
void aTakenOverOwnerCannotRenew() {
|
||||
// given
|
||||
IdempotencyOwner executing = executing();
|
||||
gateway.advance(Duration.ofSeconds(60));
|
||||
store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
|
||||
|
||||
// when
|
||||
var renewed = store.renew(executing, Duration.ofSeconds(30), OPERATION);
|
||||
|
||||
// then
|
||||
assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.NOT_OWNER);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("an expired processing lease can be taken over, and the attempt increments")
|
||||
void anExpiredLeaseIsTakenOver() {
|
||||
|
||||
@@ -37,7 +37,10 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d
|
||||
## What the platform decides for you
|
||||
|
||||
- **Time.** One effective deadline covers pool acquire, DNS, connect, TLS, write, read, and every
|
||||
retry backoff. Streaming splits setup, idle, and total lifetime.
|
||||
retry backoff. It is checked before each attempt and also ends an attempt still in flight: Apache
|
||||
cancels the request at the deadline, the JDK transport bounds its exchange timeout by the time
|
||||
left, and the caller gets `HttpDeadlineExceededException`. Streaming splits setup, idle, and total
|
||||
lifetime.
|
||||
- **Evidence.** Each attempt reports `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, or
|
||||
`PARTIAL_RESPONSE`. `NOT_SENT` is only claimed when a stage failure proves it.
|
||||
- **Retry.** Never from the HTTP method alone. Idempotency, body replayability, evidence, deadline,
|
||||
@@ -45,6 +48,9 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d
|
||||
raises `HttpAmbiguousExecutionException` instead of being retried or reported as a plain failure.
|
||||
- **Order.** Every physical attempt passes Circuit Breaker → Rate Limiter → Bulkhead, and holds no
|
||||
permit while a backoff waits.
|
||||
- **Circuit.** The breaker counts transport failures and 5xx, 408, and 429 against the upstream.
|
||||
Any other 4xx (404, 409, 422 …) is a healthy answer, even when it reaches the caller as
|
||||
`HttpRemoteErrorException`.
|
||||
- **Resources.** Connections and buffers are reclaimed after success, error, decode failure, size
|
||||
rejection, and cancellation alike.
|
||||
- **Secrets.** No URL, query value, path variable, token, cookie, or idempotency key reaches a log,
|
||||
|
||||
@@ -237,6 +237,14 @@ strictTestLanes {
|
||||
// httpClientFailureInjectionTest (needs Docker), httpClientPerformanceTest (machine-dependent
|
||||
// bounds) and jmh (minutes) stay out deliberately. Attaching them would make `check` fail on a
|
||||
// laptop without Docker, which teaches people to skip `check`.
|
||||
// spring70CompatibilityTest selects the same tagged suite httpClientStableContractTest runs in
|
||||
// `check`, under the name the release gate and the support matrix quote. The main stage runs it so the
|
||||
// name's fail-closed selection is proven before a release tag, not first on one (review 2026-11-01
|
||||
// 08-01).
|
||||
tasks.named('mainCheck') {
|
||||
dependsOn 'spring70CompatibilityTest'
|
||||
}
|
||||
|
||||
tasks.named('check') {
|
||||
dependsOn 'httpClientStableContractTest',
|
||||
'httpClientSecurityTest',
|
||||
|
||||
+1
-2
@@ -21,7 +21,6 @@ import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
import org.springframework.http.client.ClientHttpRequestFactory;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
|
||||
/**
|
||||
* Blocking default transport (design D-06, §13.4).
|
||||
@@ -84,7 +83,7 @@ public final class ApacheBlockingTransportProvider implements BlockingTransportP
|
||||
meterRegistry.ifPresent(
|
||||
registry -> ApachePoolMetricsBinder.bind(registry, profile.name(), runtime.pool()));
|
||||
listener.onRuntimeCreated(profile.name(), ID);
|
||||
return new HttpComponentsClientHttpRequestFactory(runtime.client());
|
||||
return new DeadlineAwareApacheRequestFactory(runtime.client());
|
||||
}
|
||||
|
||||
/** Live pool statistics; the pool-saturation and leak suites assert on these. */
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.apache;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline;
|
||||
import java.net.URI;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
import org.apache.hc.core5.concurrent.Cancellable;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
|
||||
/**
|
||||
* Spring's Apache request factory with every request cancellable at the attempt deadline.
|
||||
*
|
||||
* <p>The classic client's timeouts are all per-gap (connect, response header, socket read idle), so
|
||||
* none of them bounds a slow-drip response. Apache's own answer is request cancellation: {@code
|
||||
* HttpUriRequestBase.cancel()} cancels a pending pool lease or closes the leased connection
|
||||
* immediately, which wakes the blocked read on the caller's thread. The request is registered with
|
||||
* {@link AttemptDeadline} when it is created, on the caller's thread, inside the attempt scope.
|
||||
*/
|
||||
final class DeadlineAwareApacheRequestFactory extends HttpComponentsClientHttpRequestFactory {
|
||||
|
||||
DeadlineAwareApacheRequestFactory(HttpClient httpClient) {
|
||||
super(httpClient);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ClassicHttpRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
|
||||
ClassicHttpRequest request = super.createHttpUriRequest(httpMethod, uri);
|
||||
if (request instanceof Cancellable cancellable) {
|
||||
AttemptDeadline.abortOnExpiry(() -> cancellable.cancel());
|
||||
}
|
||||
return request;
|
||||
}
|
||||
}
|
||||
+1
@@ -162,6 +162,7 @@ public final class DefaultDynamicTargetGateway implements DynamicTargetGateway {
|
||||
credentials,
|
||||
1,
|
||||
runtime.support().clock().instant(),
|
||||
deadline,
|
||||
metadata);
|
||||
}
|
||||
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.jdk;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.time.Duration;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.Executor;
|
||||
import org.springframework.core.task.SimpleAsyncTaskExecutor;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.client.ClientHttpRequest;
|
||||
import org.springframework.http.client.ClientHttpRequestFactory;
|
||||
import org.springframework.http.client.JdkClientHttpRequestFactory;
|
||||
|
||||
/**
|
||||
* Spring's JDK request factory with the exchange timeout bounded by the attempt deadline.
|
||||
*
|
||||
* <p>Spring's JDK request enforces its read timeout over the whole exchange: when it fires it
|
||||
* cancels the pending response or closes the body stream, which also ends a slow-drip body. That
|
||||
* timeout is fixed per factory, so a factory is made per request with {@code min(response-header
|
||||
* timeout, remaining deadline)} from {@link AttemptDeadline}. The factory only holds references;
|
||||
* the client and the write executor are shared.
|
||||
*/
|
||||
final class DeadlineAwareJdkRequestFactory implements ClientHttpRequestFactory {
|
||||
|
||||
private final HttpClient client;
|
||||
private final Executor writeExecutor;
|
||||
private final Duration exchangeTimeout;
|
||||
|
||||
DeadlineAwareJdkRequestFactory(HttpClient client, Duration exchangeTimeout) {
|
||||
this.client = Objects.requireNonNull(client, "jdk http client");
|
||||
this.exchangeTimeout = Objects.requireNonNull(exchangeTimeout, "exchange timeout");
|
||||
// The executor Spring would pick itself, chosen once instead of once per request.
|
||||
this.writeExecutor = client.executor().orElseGet(SimpleAsyncTaskExecutor::new);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
|
||||
JdkClientHttpRequestFactory delegate = new JdkClientHttpRequestFactory(client, writeExecutor);
|
||||
delegate.setReadTimeout(AttemptDeadline.bound(exchangeTimeout));
|
||||
return delegate.createRequest(uri, httpMethod);
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -16,7 +16,6 @@ import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
import org.springframework.http.client.ClientHttpRequestFactory;
|
||||
import org.springframework.http.client.JdkClientHttpRequestFactory;
|
||||
|
||||
/**
|
||||
* Lightweight blocking alternative (design D-06, §13.5).
|
||||
@@ -62,8 +61,8 @@ public final class JdkBlockingTransportProvider implements BlockingTransportProv
|
||||
|
||||
HttpClient client = clientFactory.create(profile, tlsMaterialResolver.apply(profile));
|
||||
clients.put(new TransportResourceKey(profile.name(), generation), client);
|
||||
JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(client);
|
||||
factory.setReadTimeout(profile.timeout().responseHeader());
|
||||
ClientHttpRequestFactory factory =
|
||||
new DeadlineAwareJdkRequestFactory(client, profile.timeout().responseHeader());
|
||||
listener.onRuntimeCreated(profile.name(), ID);
|
||||
return factory;
|
||||
}
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.resilience;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.HttpStatus;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Which upstream status codes the circuit breaker records as a failure (design §18.1).
|
||||
*
|
||||
* <p>The breaker protects callers from an upstream that is failing or overloaded. A status counts
|
||||
* against the upstream only when it says exactly that: a 5xx, a 408 (the server gave up waiting),
|
||||
* or a 429 (the server is shedding load). Every other 4xx is the upstream working correctly and
|
||||
* answering a request it judged — a 404 for a missing record, a 409 for a conflict, a 422 for a
|
||||
* rejected payload — and is recorded as a success. Counting those used to open the breaker on a
|
||||
* perfectly healthy lookup API and reject every call of the profile for the breaker's wait time.
|
||||
*
|
||||
* <p>Transport failures (connect, timeout, reset) never reach this policy: they are exceptions, and
|
||||
* the pipeline records every exception as a failure.
|
||||
*/
|
||||
public final class CircuitBreakerStatusPolicy {
|
||||
|
||||
private static final int REQUEST_TIMEOUT = 408;
|
||||
private static final int TOO_MANY_REQUESTS = 429;
|
||||
|
||||
private CircuitBreakerStatusPolicy() {}
|
||||
|
||||
/** Whether this status is evidence that the upstream itself is failing or overloaded. */
|
||||
public static boolean countsAsUpstreamFailure(HttpStatus status) {
|
||||
Objects.requireNonNull(status, "status");
|
||||
return status.serverError()
|
||||
|| status.value() == REQUEST_TIMEOUT
|
||||
|| status.value() == TOO_MANY_REQUESTS;
|
||||
}
|
||||
}
|
||||
+96
-14
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.httpclient.restclient;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.HttpMethod;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpClientException;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpDeadlineExceededException;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpFailureMetadata;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRemoteErrorException;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage;
|
||||
@@ -11,9 +12,12 @@ import dev.caskeleton.adapter.outbound.httpclient.auth.RequestCredentials;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.observation.AttemptObservation;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.AttemptOutcome;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.AttemptProgressTracker;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.CircuitBreakerStatusPolicy;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.Deadline;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.ProtocolEvidence;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.security.PreparedOperation;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.security.PreparedTarget;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailure;
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
@@ -44,9 +48,41 @@ public final class BlockingAttemptExecutor {
|
||||
RequestCredentials credentials,
|
||||
int attemptNumber,
|
||||
Instant startedAt,
|
||||
Deadline deadline,
|
||||
HttpFailureMetadata baseMetadata) {
|
||||
|
||||
Objects.requireNonNull(runtime, "runtime");
|
||||
Objects.requireNonNull(deadline, "deadline");
|
||||
ExecutionSupport support = runtime.support();
|
||||
// The deadline scope is what lets the effective deadline end an attempt that is already in
|
||||
// flight. Before it, the deadline was only checked before an attempt started, and a slow-drip
|
||||
// upstream kept a started attempt alive past the total budget for as long as no single gap
|
||||
// reached a stage timeout. The transport reads the scope (see AttemptDeadline).
|
||||
try (AttemptDeadline.Scope scope = AttemptDeadline.open(deadline.remaining(support.clock()))) {
|
||||
return executeWithin(
|
||||
scope,
|
||||
runtime,
|
||||
prepared,
|
||||
responseType,
|
||||
statusHandlingPolicy,
|
||||
credentials,
|
||||
attemptNumber,
|
||||
startedAt,
|
||||
baseMetadata);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> AttemptOutcome<T> executeWithin(
|
||||
AttemptDeadline.Scope scope,
|
||||
BlockingClientRuntime runtime,
|
||||
PreparedOperation prepared,
|
||||
ResponseType<T> responseType,
|
||||
StatusHandlingPolicy statusHandlingPolicy,
|
||||
RequestCredentials credentials,
|
||||
int attemptNumber,
|
||||
Instant startedAt,
|
||||
HttpFailureMetadata baseMetadata) {
|
||||
|
||||
ExecutionSupport support = runtime.support();
|
||||
AttemptProgressTracker tracker = new AttemptProgressTracker();
|
||||
AttemptObservation observation =
|
||||
@@ -108,18 +144,14 @@ public final class BlockingAttemptExecutor {
|
||||
tracker.firstByteDelivered());
|
||||
}
|
||||
},
|
||||
outcome ->
|
||||
outcome.failureCategory() == FailureCategory.REMOTE_STATUS
|
||||
? outcome.failure().map(failure -> (Throwable) failure)
|
||||
: Optional.empty());
|
||||
stopObservation(observation, attemptOutcome);
|
||||
return attemptOutcome;
|
||||
BlockingAttemptExecutor::upstreamFailure);
|
||||
return finish(observation, scope, attemptOutcome);
|
||||
} catch (HttpClientException stable) {
|
||||
AttemptOutcome<T> outcome =
|
||||
return finish(
|
||||
observation,
|
||||
scope,
|
||||
AttemptOutcome.failed(
|
||||
stable, stable.category(), Optional.empty(), tracker.firstByteDelivered());
|
||||
stopObservation(observation, outcome);
|
||||
return outcome;
|
||||
stable, stable.category(), Optional.empty(), tracker.firstByteDelivered()));
|
||||
} catch (RuntimeException engineFailure) {
|
||||
TransportFailure classified =
|
||||
runtime.failureClassifier().classify(engineFailure, tracker.stage());
|
||||
@@ -137,14 +169,64 @@ public final class BlockingAttemptExecutor {
|
||||
.withStage(classified.stage());
|
||||
HttpClientException mapped =
|
||||
support.exceptionMapper().map(classified, metadata, engineFailure);
|
||||
AttemptOutcome<T> outcome =
|
||||
return finish(
|
||||
observation,
|
||||
scope,
|
||||
AttemptOutcome.failed(
|
||||
mapped, classified.category(), Optional.empty(), tracker.firstByteDelivered());
|
||||
stopObservation(observation, outcome);
|
||||
return outcome;
|
||||
mapped, classified.category(), Optional.empty(), tracker.firstByteDelivered()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the observation with the attempt's outcome, naming the deadline when it ended the
|
||||
* attempt.
|
||||
*
|
||||
* <p>A deadline abort reaches the executor as whatever the engine threw when its connection was
|
||||
* closed — a reset, a truncated body, a read timeout. Reported as that, a caller would see a
|
||||
* transport fault on a healthy upstream and the retry policy would judge the wrong cause. A
|
||||
* failure that ends after the deadline passed is therefore reported as the deadline. Two outcomes
|
||||
* keep their own meaning: a response that completed stays a success, and a complete error
|
||||
* response (a remote status) stays the upstream's answer — both arrived, whatever the clock says.
|
||||
*/
|
||||
private <T> AttemptOutcome<T> finish(
|
||||
AttemptObservation observation, AttemptDeadline.Scope scope, AttemptOutcome<T> outcome) {
|
||||
AttemptOutcome<T> reported = outcome;
|
||||
if (!outcome.successful()
|
||||
&& outcome.failureCategory() != FailureCategory.REMOTE_STATUS
|
||||
&& scope.expired()) {
|
||||
HttpClientException cause = outcome.failure().orElseThrow();
|
||||
reported =
|
||||
AttemptOutcome.failed(
|
||||
new HttpDeadlineExceededException(
|
||||
"effective deadline reached while the attempt was in flight",
|
||||
cause.metadata(),
|
||||
cause),
|
||||
FailureCategory.DEADLINE_EXCEEDED,
|
||||
Optional.empty(),
|
||||
outcome.firstByteDelivered());
|
||||
}
|
||||
stopObservation(observation, reported);
|
||||
return reported;
|
||||
}
|
||||
|
||||
/**
|
||||
* The failure the circuit breaker records for a returned outcome, if any.
|
||||
*
|
||||
* <p>Only a remote status that {@link CircuitBreakerStatusPolicy} counts against the upstream is
|
||||
* a breaker failure. A 404 thrown to the caller as {@code HttpRemoteErrorException} is still a
|
||||
* healthy answer for the breaker.
|
||||
*/
|
||||
private static Optional<Throwable> upstreamFailure(AttemptOutcome<?> outcome) {
|
||||
if (outcome.failureCategory() != FailureCategory.REMOTE_STATUS) {
|
||||
return Optional.empty();
|
||||
}
|
||||
boolean countsAgainstUpstream =
|
||||
outcome.status().map(CircuitBreakerStatusPolicy::countsAsUpstreamFailure).orElse(true);
|
||||
return countsAgainstUpstream
|
||||
? outcome.failure().map(failure -> (Throwable) failure)
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
private void stopObservation(AttemptObservation observation, AttemptOutcome<?> outcome) {
|
||||
if (outcome.failureCategory() == FailureCategory.RESPONSE_TIMEOUT
|
||||
|| outcome.failureCategory() == FailureCategory.POOL_ACQUIRE_TIMEOUT
|
||||
|
||||
+1
@@ -173,6 +173,7 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway {
|
||||
credentials,
|
||||
attemptNumber,
|
||||
startedAt,
|
||||
deadline,
|
||||
metadata.withAttempt(attemptNumber));
|
||||
}
|
||||
|
||||
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.transport;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* The time the physical attempt running on this thread has left before the logical call's effective
|
||||
* deadline (design D-10, §15.2).
|
||||
*
|
||||
* <p>The gateway checks the deadline before an attempt starts, but a stage timeout only bounds one
|
||||
* gap: an upstream that sends a byte every second never trips a three-second read-idle timeout and
|
||||
* can hold the caller, its virtual thread and a pooled connection indefinitely. The gateway opens a
|
||||
* {@link Scope} around each attempt and the transport — the only party that can actually stop an
|
||||
* exchange — reads it:
|
||||
*
|
||||
* <ul>
|
||||
* <li>a transport with a cancellable request registers the cancel with {@link
|
||||
* #abortOnExpiry(Runnable)}, and the scope runs it when the deadline passes;
|
||||
* <li>a transport whose engine already enforces a whole-exchange timeout bounds that timeout with
|
||||
* {@link #bound(Duration)}.
|
||||
* </ul>
|
||||
*
|
||||
* <p>The scope is thread-confined because a blocking attempt runs on the caller's thread from
|
||||
* request creation to the last body byte. When no scope is open — a transport used outside the
|
||||
* gateway — both methods leave the transport's own behaviour unchanged.
|
||||
*/
|
||||
public final class AttemptDeadline {
|
||||
|
||||
private static final ThreadLocal<Scope> CURRENT = new ThreadLocal<>();
|
||||
|
||||
private AttemptDeadline() {}
|
||||
|
||||
/**
|
||||
* Opens the deadline scope for one attempt on the current thread.
|
||||
*
|
||||
* @param remaining the time left before the logical call's effective deadline
|
||||
*/
|
||||
public static Scope open(Duration remaining) {
|
||||
Objects.requireNonNull(remaining, "remaining deadline");
|
||||
Scope scope = new Scope(remaining.isNegative() ? Duration.ZERO : remaining, CURRENT.get());
|
||||
CURRENT.set(scope);
|
||||
return scope;
|
||||
}
|
||||
|
||||
/** The current attempt's remaining time, or empty when no attempt scope is open. */
|
||||
public static Optional<Duration> remaining() {
|
||||
return Optional.ofNullable(CURRENT.get()).map(Scope::remaining);
|
||||
}
|
||||
|
||||
/** A stage timeout no longer than the current attempt's remaining time. */
|
||||
public static Duration bound(Duration stageTimeout) {
|
||||
Objects.requireNonNull(stageTimeout, "stage timeout");
|
||||
return remaining()
|
||||
.filter(remaining -> remaining.compareTo(stageTimeout) < 0)
|
||||
.orElse(stageTimeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers how to abort the exchange the current attempt is about to start.
|
||||
*
|
||||
* <p>Runs the abort at once if the deadline has already passed. Does nothing when no scope is
|
||||
* open.
|
||||
*/
|
||||
public static void abortOnExpiry(Runnable abort) {
|
||||
Objects.requireNonNull(abort, "abort");
|
||||
Scope scope = CURRENT.get();
|
||||
if (scope != null) {
|
||||
scope.register(abort);
|
||||
}
|
||||
}
|
||||
|
||||
/** One attempt's deadline; closing it cancels the pending abort and restores the outer scope. */
|
||||
public static final class Scope implements AutoCloseable {
|
||||
|
||||
private final long endNanos;
|
||||
private final Scope outer;
|
||||
private final CompletableFuture<Void> timer = new CompletableFuture<>();
|
||||
private final CompletableFuture<Void> expiry;
|
||||
private final List<Runnable> aborts = new ArrayList<>();
|
||||
private boolean fired;
|
||||
private boolean closed;
|
||||
|
||||
private Scope(Duration remaining, Scope outer) {
|
||||
this.endNanos = System.nanoTime() + remaining.toNanos();
|
||||
this.outer = outer;
|
||||
// The JDK's shared delay scheduler, the same one Spring's JDK request uses for its timeout.
|
||||
// Completing the future on close() also cancels the scheduled task, so a finished attempt
|
||||
// leaves nothing behind.
|
||||
this.expiry =
|
||||
timer
|
||||
.completeOnTimeout(null, remaining.toNanos(), TimeUnit.NANOSECONDS)
|
||||
.thenRun(this::expire);
|
||||
}
|
||||
|
||||
/** Whether the deadline passed while this attempt was running. */
|
||||
public boolean expired() {
|
||||
synchronized (this) {
|
||||
if (fired) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return System.nanoTime() - endNanos >= 0;
|
||||
}
|
||||
|
||||
Duration remaining() {
|
||||
long left = endNanos - System.nanoTime();
|
||||
return left > 0 ? Duration.ofNanos(left) : Duration.ZERO;
|
||||
}
|
||||
|
||||
private void register(Runnable abort) {
|
||||
boolean runNow;
|
||||
synchronized (this) {
|
||||
runNow = fired;
|
||||
if (!runNow && !closed) {
|
||||
aborts.add(abort);
|
||||
}
|
||||
}
|
||||
if (runNow) {
|
||||
abort.run();
|
||||
}
|
||||
}
|
||||
|
||||
private void expire() {
|
||||
List<Runnable> toRun;
|
||||
synchronized (this) {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
fired = true;
|
||||
toRun = List.copyOf(aborts);
|
||||
aborts.clear();
|
||||
}
|
||||
toRun.forEach(Runnable::run);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
synchronized (this) {
|
||||
closed = true;
|
||||
aborts.clear();
|
||||
}
|
||||
timer.complete(null);
|
||||
expiry.cancel(false);
|
||||
if (CURRENT.get() == this) {
|
||||
if (outer == null) {
|
||||
CURRENT.remove();
|
||||
} else {
|
||||
CURRENT.set(outer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.resilience;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.HttpStatus;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
class CircuitBreakerStatusPolicyTest {
|
||||
|
||||
@ParameterizedTest(name = "{0} -> {1}")
|
||||
@CsvSource({
|
||||
"400, false",
|
||||
"401, false",
|
||||
"403, false",
|
||||
"404, false",
|
||||
"409, false",
|
||||
"410, false",
|
||||
"422, false",
|
||||
"408, true",
|
||||
"429, true",
|
||||
"500, true",
|
||||
"501, true",
|
||||
"502, true",
|
||||
"503, true",
|
||||
"504, true",
|
||||
"599, true"
|
||||
})
|
||||
@DisplayName("5xx·408·429만 상대 서버 장애로 세고 나머지 4xx는 정상 응답으로 센다")
|
||||
void onlyServerSideStatusesCountAgainstTheUpstream(int status, boolean upstreamFailure) {
|
||||
// given
|
||||
HttpStatus answered = new HttpStatus(status);
|
||||
|
||||
// when
|
||||
boolean counted = CircuitBreakerStatusPolicy.countsAsUpstreamFailure(answered);
|
||||
|
||||
// then
|
||||
assertThat(counted).isEqualTo(upstreamFailure);
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.restclient;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.OperationName;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpDeadlineExceededException;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.TimeoutSettings;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
|
||||
/**
|
||||
* The total-call budget ends an attempt that is still in flight (finding 05-06, design D-10).
|
||||
*
|
||||
* <p>The upstream answers at once and then sends one body byte every 50 ms. No gap reaches the
|
||||
* read-idle (3 s) or response-header (2 s) timeout, and the whole body would take 5 s, so only the
|
||||
* one-second total budget can end the call on time.
|
||||
*/
|
||||
class AttemptDeadlineEnforcementTest {
|
||||
|
||||
private static final Duration TOTAL_CALL = Duration.ofSeconds(1);
|
||||
private static final Duration TOLERANCE = Duration.ofMillis(500);
|
||||
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@EnumSource(
|
||||
value = TransportType.class,
|
||||
names = {"APACHE", "JDK"})
|
||||
@DisplayName("바이트를 조금씩 흘리는 상대 서버라도 호출은 전체 시간 예산 안에 deadline 초과로 끝난다")
|
||||
void aSlowDripResponseIsCutOffAtTheTotalDeadline(TransportType transport) throws Exception {
|
||||
try (MockHttpServer server = MockHttpServer.start();
|
||||
TestGateways.Harness harness =
|
||||
TestGateways.forProfile(
|
||||
ClientProfiles.builder("slow")
|
||||
.baseUrl(server.uri("/"))
|
||||
.transport(transport)
|
||||
.timeout(withTotalCall(TOTAL_CALL))
|
||||
.build())) {
|
||||
// given
|
||||
server.enqueueSlowDripBody(200, 100, Duration.ofMillis(50));
|
||||
long started = System.nanoTime();
|
||||
|
||||
// when
|
||||
Throwable failure =
|
||||
catchThrowable(
|
||||
() ->
|
||||
harness
|
||||
.gateway()
|
||||
.exchange(
|
||||
harness.profile().name(),
|
||||
HttpOperation.get(new OperationName("slow-read"), "/slow", Map.of()),
|
||||
ResponseType.of(String.class)));
|
||||
|
||||
// then
|
||||
Duration elapsed = Duration.ofNanos(System.nanoTime() - started);
|
||||
assertThat(failure).isInstanceOf(HttpDeadlineExceededException.class);
|
||||
assertThat(elapsed).isLessThan(TOTAL_CALL.plus(TOLERANCE));
|
||||
}
|
||||
}
|
||||
|
||||
private static TimeoutSettings withTotalCall(Duration totalCall) {
|
||||
TimeoutSettings base = ClientProfiles.timeouts();
|
||||
return new TimeoutSettings(
|
||||
base.dns(),
|
||||
base.connect(),
|
||||
base.tlsHandshake(),
|
||||
base.proxyConnect(),
|
||||
base.requestWriteIdle(),
|
||||
base.responseHeader(),
|
||||
base.readIdle(),
|
||||
totalCall);
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.restclient;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.OperationName;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpCircuitOpenException;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRemoteErrorException;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* What the per-profile circuit breaker counts as an upstream failure, end to end (finding 05-05).
|
||||
*
|
||||
* <p>The library defaults are kept on purpose (a 100-call window, a 50% failure threshold), so 200
|
||||
* calls are enough to open the breaker twice over if a status were miscounted.
|
||||
*/
|
||||
class CircuitBreakerStatusAccountingTest {
|
||||
|
||||
private static final int CALLS = 200;
|
||||
private static final int LIBRARY_DEFAULT_WINDOW = 100;
|
||||
|
||||
@Test
|
||||
@DisplayName("정상 응답인 404가 200번 이어져도 circuit이 열리지 않고 모든 호출이 상대 서버에 닿는다")
|
||||
void aRunOfNotFoundAnswersNeverOpensTheCircuit() throws Exception {
|
||||
try (MockHttpServer server = MockHttpServer.start();
|
||||
TestGateways.Harness harness = TestGateways.apache(server.uri("/"))) {
|
||||
// given
|
||||
for (int i = 0; i < CALLS; i++) {
|
||||
server.enqueueStatus(404);
|
||||
}
|
||||
List<Throwable> failures = new ArrayList<>();
|
||||
|
||||
// when
|
||||
for (int i = 0; i < CALLS; i++) {
|
||||
failures.add(catchThrowable(() -> getUser(harness)));
|
||||
}
|
||||
|
||||
// then
|
||||
assertThat(failures)
|
||||
.hasSize(CALLS)
|
||||
.allSatisfy(
|
||||
failure ->
|
||||
assertThat(failure)
|
||||
.isExactlyInstanceOf(HttpRemoteErrorException.class)
|
||||
.isNotInstanceOf(HttpCircuitOpenException.class));
|
||||
assertThat(server.requestCount()).isEqualTo(CALLS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("503이 창 하나를 채우면 circuit이 열려 다음 호출은 상대 서버에 보내지 않고 거절한다")
|
||||
void aWindowOfServiceUnavailableAnswersOpensTheCircuit() throws Exception {
|
||||
try (MockHttpServer server = MockHttpServer.start();
|
||||
TestGateways.Harness harness = TestGateways.apache(server.uri("/"))) {
|
||||
// given
|
||||
List<Throwable> windowFailures = new ArrayList<>();
|
||||
for (int i = 0; i < LIBRARY_DEFAULT_WINDOW; i++) {
|
||||
server.enqueueStatus(503);
|
||||
windowFailures.add(catchThrowable(() -> getUser(harness)));
|
||||
}
|
||||
assertThat(windowFailures)
|
||||
.allSatisfy(f -> assertThat(f).isInstanceOf(HttpRemoteErrorException.class));
|
||||
|
||||
// when
|
||||
Throwable next = catchThrowable(() -> getUser(harness));
|
||||
|
||||
// then
|
||||
assertThat(next).isInstanceOf(HttpCircuitOpenException.class);
|
||||
assertThat(server.requestCount()).isEqualTo(LIBRARY_DEFAULT_WINDOW);
|
||||
}
|
||||
}
|
||||
|
||||
private static void getUser(TestGateways.Harness harness) {
|
||||
harness
|
||||
.gateway()
|
||||
.exchange(
|
||||
harness.profile().name(),
|
||||
HttpOperation.get(new OperationName("get-user"), "/users/1", Map.of()),
|
||||
ResponseType.of(String.class));
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.transport;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class AttemptDeadlineTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("attempt scope가 없으면 단계 timeout을 그대로 둔다")
|
||||
void withoutAScopeTheStageTimeoutIsUnchanged() {
|
||||
// given
|
||||
Duration stage = Duration.ofSeconds(2);
|
||||
|
||||
// when
|
||||
Duration bounded = AttemptDeadline.bound(stage);
|
||||
|
||||
// then
|
||||
assertThat(bounded).isEqualTo(stage);
|
||||
assertThat(AttemptDeadline.remaining()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("남은 deadline이 단계 timeout보다 짧으면 단계 timeout을 남은 시간으로 줄인다")
|
||||
void aShorterRemainingDeadlineBoundsTheStageTimeout() {
|
||||
try (AttemptDeadline.Scope scope = AttemptDeadline.open(Duration.ofMillis(300))) {
|
||||
// given
|
||||
Duration stage = Duration.ofSeconds(2);
|
||||
|
||||
// when
|
||||
Duration bounded = AttemptDeadline.bound(stage);
|
||||
|
||||
// then
|
||||
assertThat(bounded).isLessThanOrEqualTo(Duration.ofMillis(300)).isPositive();
|
||||
assertThat(scope.expired()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("deadline이 지나면 등록된 중단 동작을 실행하고 scope는 만료로 보고한다")
|
||||
void theRegisteredAbortRunsWhenTheDeadlinePasses() throws Exception {
|
||||
try (AttemptDeadline.Scope scope = AttemptDeadline.open(Duration.ofMillis(50))) {
|
||||
// given
|
||||
CountDownLatch aborted = new CountDownLatch(1);
|
||||
AttemptDeadline.abortOnExpiry(aborted::countDown);
|
||||
|
||||
// when
|
||||
boolean ran = aborted.await(2, TimeUnit.SECONDS);
|
||||
|
||||
// then
|
||||
assertThat(ran).isTrue();
|
||||
assertThat(scope.expired()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("deadline 전에 attempt가 끝나면 중단 동작은 실행되지 않고 scope도 풀린다")
|
||||
void closingTheScopeBeforeTheDeadlineCancelsTheAbort() throws Exception {
|
||||
// given
|
||||
AtomicInteger aborts = new AtomicInteger();
|
||||
AttemptDeadline.Scope scope = AttemptDeadline.open(Duration.ofMillis(100));
|
||||
AttemptDeadline.abortOnExpiry(aborts::incrementAndGet);
|
||||
|
||||
// when
|
||||
scope.close();
|
||||
|
||||
// then
|
||||
Thread.sleep(300);
|
||||
assertThat(aborts).hasValue(0);
|
||||
assertThat(AttemptDeadline.remaining()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("이미 지난 deadline에 등록한 중단 동작은 바로 실행된다")
|
||||
void anAbortRegisteredAfterExpiryRunsAtOnce() throws Exception {
|
||||
try (AttemptDeadline.Scope scope = AttemptDeadline.open(Duration.ZERO)) {
|
||||
// given
|
||||
CountDownLatch expired = new CountDownLatch(1);
|
||||
AttemptDeadline.abortOnExpiry(expired::countDown);
|
||||
assertThat(expired.await(2, TimeUnit.SECONDS)).isTrue();
|
||||
AtomicInteger late = new AtomicInteger();
|
||||
|
||||
// when
|
||||
AttemptDeadline.abortOnExpiry(late::incrementAndGet);
|
||||
|
||||
// then
|
||||
assertThat(late).hasValue(1);
|
||||
assertThat(scope.expired()).isTrue();
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -151,6 +151,21 @@ public final class MockHttpServer implements AutoCloseable {
|
||||
.setBodyDelay(delay.toMillis(), TimeUnit.MILLISECONDS));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends headers at once, then the body one byte per {@code gap}; drives total-deadline tests.
|
||||
*
|
||||
* <p>Every gap stays shorter than any idle timeout a test profile uses, so only a whole-call
|
||||
* budget can end the exchange before the body is complete.
|
||||
*/
|
||||
public void enqueueSlowDripBody(int status, int bodyBytes, Duration gap) {
|
||||
server.enqueue(
|
||||
new MockResponse()
|
||||
.setResponseCode(status)
|
||||
.setHeader("Content-Type", "text/plain")
|
||||
.setBody("x".repeat(bodyBytes))
|
||||
.throttleBody(1, gap.toMillis(), TimeUnit.MILLISECONDS));
|
||||
}
|
||||
|
||||
public RecordedHttpRequest takeRequest(Duration timeout) throws InterruptedException {
|
||||
RecordedRequest recorded = server.takeRequest(timeout.toMillis(), TimeUnit.MILLISECONDS);
|
||||
if (recorded == null) {
|
||||
|
||||
@@ -31,9 +31,16 @@ seam과 그 위의 `MessagePublisher`·`OutboxEnvelopeJson`은 outbox를 canonic
|
||||
있을 때만 생성된다. exact `ValidatedIntegrationEvent.envelopeBytes()`를 보존하고 platform의 중앙
|
||||
publish pipeline을 탄다. producer id는 host/pod/process 이름에서 추측하지 않는다.
|
||||
|
||||
`OutboxMessagePublishAdapter`는 claim된 row의 validated event를 그대로 bridge에 넘기고 platform의
|
||||
네 가지 결과(CONFIRMED·AMBIGUOUS·REJECTED_BEFORE_SEND·REJECTED_AFTER_BROKER)를 relay에 돌려준다.
|
||||
다시 직렬화하지 않는다.
|
||||
`OutboxMessagePublishAdapter`는 claim된 row의 validated event를 그대로 bridge에 넘기고 platform
|
||||
결과를 application 결과(CONFIRMED·AMBIGUOUS·REJECTED_BEFORE_SEND·REJECTED_AFTER_BROKER·
|
||||
REJECTED_RETRYABLE)로 번역해 relay에 돌려준다. 다시 직렬화하지 않는다.
|
||||
|
||||
platform `REJECTED` 중 `FailureDescriptor.retryable()`이 true인 것(종료 중 `SHUTTING_DOWN`, permit
|
||||
대기 초과, `PUBLISH_RUNTIME_UNAVAILABLE`, `KAFKA_TRANSPORT_CLOSED`, Kafka 인증·인가 실패)은
|
||||
`REJECTED_RETRYABLE`로 번역한다. relay는 이 값을 DEAD로 보내지 않고 재시도한다. 확정 거부 두 값으로
|
||||
번역하면 "같은 payload는 또 거부된다"로 읽혀 커밋된 이벤트와 그 aggregate의 뒤 이벤트가 바로
|
||||
멈춘다(2026-11-01 리뷰 06-01). `AMBIGUOUS`로 번역하지 않은 이유: 동작은 같지만 "전송됐을 수
|
||||
있음"이라는 거짓 정보가 남아 중복 경고를 오염시킨다.
|
||||
|
||||
## outbox 발행 포트에는 대역이 없다
|
||||
|
||||
|
||||
+14
@@ -15,6 +15,7 @@ import dev.caskeleton.messaging.api.TenantContext;
|
||||
import dev.caskeleton.messaging.api.TraceContext;
|
||||
import dev.caskeleton.messaging.api.destination.DestinationName;
|
||||
import dev.caskeleton.messaging.api.destination.MessageDestination;
|
||||
import dev.caskeleton.messaging.api.error.FailureDescriptor;
|
||||
import dev.caskeleton.messaging.api.header.HeaderName;
|
||||
import dev.caskeleton.messaging.api.header.HeaderValue;
|
||||
import dev.caskeleton.messaging.api.header.MessageHeaders;
|
||||
@@ -137,6 +138,16 @@ public final class PlatformIntegrationEventPublishAdapter implements Integration
|
||||
return new CausationId(canonicalMessageId(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the platform's result into the application's outcome.
|
||||
*
|
||||
* <p>A platform rejection carries a {@code retryable} flag, and the platform sets it on refusals
|
||||
* that are about the moment — shutting down, permits exhausted, transport closed, credentials
|
||||
* refused. The application reads both of its definite rejections as "the same payload is refused
|
||||
* again" and dead-letters at once, so a retryable rejection translated into one of them parks a
|
||||
* committed event, and its aggregate behind it, for a cause that clears on its own. It gets its
|
||||
* own value instead.
|
||||
*/
|
||||
private static OutboxPublishOutcome mapOutcome(PublishResult result) {
|
||||
Objects.requireNonNull(result, "publish result must not be null");
|
||||
if (result.completion() == PublishCompletion.CONFIRMED) {
|
||||
@@ -145,6 +156,9 @@ public final class PlatformIntegrationEventPublishAdapter implements Integration
|
||||
if (result.completion() == PublishCompletion.AMBIGUOUS) {
|
||||
return OutboxPublishOutcome.AMBIGUOUS;
|
||||
}
|
||||
if (result.failure().map(FailureDescriptor::retryable).orElse(false)) {
|
||||
return OutboxPublishOutcome.REJECTED_RETRYABLE;
|
||||
}
|
||||
return result.evidence().transmission() == TransmissionEvidence.NOT_TRANSMITTED
|
||||
? OutboxPublishOutcome.REJECTED_BEFORE_SEND
|
||||
: OutboxPublishOutcome.REJECTED_AFTER_BROKER;
|
||||
|
||||
+45
@@ -33,6 +33,7 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PlatformIntegrationEventPublishAdapterTest {
|
||||
@@ -102,6 +103,50 @@ class PlatformIntegrationEventPublishAdapterTest {
|
||||
.isEqualTo(OutboxPublishOutcome.REJECTED_AFTER_BROKER);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("platform이 다시 시도해도 된다고 표시한 거부는 확정 거부로 번역하지 않는다")
|
||||
void aRefusalThePlatformMarksRetryableIsNotTranslatedIntoADefiniteRejection() {
|
||||
// given: the runtime refused because it is shutting down, and said a retry may succeed
|
||||
RecordingPublisher publisher =
|
||||
new RecordingPublisher(
|
||||
PublishResult.rejected(
|
||||
Duration.ZERO,
|
||||
FailureDescriptor.of(
|
||||
FailureCategory.TRANSIENT_INFRASTRUCTURE,
|
||||
"SHUTTING_DOWN",
|
||||
"the messaging runtime stopped accepting new publishes")));
|
||||
PlatformIntegrationEventPublishAdapter bridge =
|
||||
new PlatformIntegrationEventPublishAdapter(publisher, "portfolio-service");
|
||||
|
||||
// when
|
||||
OutboxPublishOutcome outcome =
|
||||
bridge.publish(event(EVENT_ID, Optional.empty())).toCompletableFuture().join();
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_RETRYABLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("다시 시도해도 같은 결과인 거부는 지금처럼 확정 거부로 번역한다")
|
||||
void aRefusalThePlatformMarksFinalStaysADefiniteRejection() {
|
||||
// given: the runtime refused a destination this application may not publish to
|
||||
RecordingPublisher publisher =
|
||||
new RecordingPublisher(
|
||||
PublishResult.rejected(
|
||||
Duration.ZERO,
|
||||
FailureDescriptor.of(
|
||||
FailureCategory.CONFIGURATION, "PUBLISH_FORBIDDEN", "not allowed")));
|
||||
PlatformIntegrationEventPublishAdapter bridge =
|
||||
new PlatformIntegrationEventPublishAdapter(publisher, "portfolio-service");
|
||||
|
||||
// when
|
||||
OutboxPublishOutcome outcome =
|
||||
bridge.publish(event(EVENT_ID, Optional.empty())).toCompletableFuture().join();
|
||||
|
||||
// then
|
||||
assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND);
|
||||
}
|
||||
|
||||
@Test
|
||||
void incompatibleApplicationIdentityFailsClosedBeforePublisherInvocation() {
|
||||
RecordingPublisher publisher = new RecordingPublisher(confirmed());
|
||||
|
||||
+4
@@ -70,6 +70,10 @@ class NotificationPlatformWorkerConfig {
|
||||
reconciliation::reconcile,
|
||||
clock,
|
||||
properties.leaseDuration(),
|
||||
// The claim lease reuses the delivery lease rather than adding a setting. One pass asks
|
||||
// up to claimBatchSize providers in turn, so a pass slower than the lease lets another
|
||||
// instance re-ask its remaining jobs; the claim fence keeps those answers recorded once.
|
||||
properties.leaseDuration(),
|
||||
properties.claimBatchSize(),
|
||||
properties.maxAdditionalAttempts() + 1);
|
||||
}
|
||||
|
||||
+13
-1
@@ -22,6 +22,11 @@ import java.util.function.Function;
|
||||
* will not change, so the job is completed and the attempt stays visibly ambiguous for an operator
|
||||
* — a busy loop against a capability that does not exist is how a background worker burns a
|
||||
* connection pool while achieving nothing.
|
||||
*
|
||||
* <p>Every instance runs this worker, so the claim is a lease: the jobs a pass takes are this
|
||||
* instance's until {@code claimLease} has passed, and no transaction is held while the provider is
|
||||
* asked. A pass that outlives its lease may find a job taken over by another instance; the store
|
||||
* then ignores this pass's write for it, so the job is asked about twice but recorded once.
|
||||
*/
|
||||
public final class ReconciliationJobWorker {
|
||||
|
||||
@@ -32,6 +37,7 @@ public final class ReconciliationJobWorker {
|
||||
reconciler;
|
||||
private final Clock clock;
|
||||
private final Duration retryBackoff;
|
||||
private final Duration claimLease;
|
||||
private final int batchSize;
|
||||
private final int maxAttempts;
|
||||
|
||||
@@ -42,6 +48,7 @@ public final class ReconciliationJobWorker {
|
||||
* @param reconciler asks one attempt's provider
|
||||
* @param clock the clock
|
||||
* @param retryBackoff how long to wait before asking again
|
||||
* @param claimLease how long one pass owns the jobs it claimed; must cover the whole pass
|
||||
* @param batchSize how many jobs one pass handles
|
||||
* @param maxAttempts how many times one job may ask before it is left to an operator
|
||||
*/
|
||||
@@ -53,6 +60,7 @@ public final class ReconciliationJobWorker {
|
||||
reconciler,
|
||||
Clock clock,
|
||||
Duration retryBackoff,
|
||||
Duration claimLease,
|
||||
int batchSize,
|
||||
int maxAttempts) {
|
||||
this.jobs = Objects.requireNonNull(jobs, "jobs");
|
||||
@@ -62,6 +70,10 @@ public final class ReconciliationJobWorker {
|
||||
if (retryBackoff.isNegative() || retryBackoff.isZero()) {
|
||||
throw new IllegalArgumentException("retryBackoff must be positive and finite");
|
||||
}
|
||||
this.claimLease = Objects.requireNonNull(claimLease, "claimLease");
|
||||
if (claimLease.isNegative() || claimLease.isZero()) {
|
||||
throw new IllegalArgumentException("claimLease must be positive");
|
||||
}
|
||||
if (batchSize < 1) {
|
||||
throw new IllegalArgumentException("batchSize");
|
||||
}
|
||||
@@ -78,7 +90,7 @@ public final class ReconciliationJobWorker {
|
||||
* @return how many jobs reached a terminal decision
|
||||
*/
|
||||
public int reconcileOnce() {
|
||||
List<ReconciliationJob> due = jobs.claimDue(batchSize, clock.instant());
|
||||
List<ReconciliationJob> due = jobs.claimDue(batchSize, clock.instant(), claimLease);
|
||||
int settled = 0;
|
||||
for (ReconciliationJob job : due) {
|
||||
// One job's failure is not the pass's: a provider that is refusing connections would
|
||||
|
||||
+23
-3
@@ -33,12 +33,14 @@ class ReconciliationJobWorkerTest {
|
||||
|
||||
private static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z");
|
||||
private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC);
|
||||
private static final Duration CLAIM_LEASE = Duration.ofMinutes(2);
|
||||
|
||||
private final RecordingJobs jobs = new RecordingJobs();
|
||||
private final Map<DeliveryAttemptId, ReconciliationResult> answers = new java.util.HashMap<>();
|
||||
|
||||
private final ReconciliationJobWorker worker =
|
||||
new ReconciliationJobWorker(jobs, answers::get, CLOCK, Duration.ofMinutes(5), 10, 3);
|
||||
new ReconciliationJobWorker(
|
||||
jobs, answers::get, CLOCK, Duration.ofMinutes(5), CLAIM_LEASE, 10, 3);
|
||||
|
||||
@Test
|
||||
@DisplayName("a confirmed outcome completes the job")
|
||||
@@ -125,6 +127,21 @@ class ReconciliationJobWorkerTest {
|
||||
assertThat(jobs.rescheduled.get(0).getKey()).isEqualTo(failing.id());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("한 번의 pass는 설정된 lease 동안 소유하도록 job을 claim한다")
|
||||
void aPassClaimsItsJobsForTheConfiguredLease() {
|
||||
// given
|
||||
due(0);
|
||||
|
||||
// when
|
||||
worker.reconcileOnce();
|
||||
|
||||
// then
|
||||
assertThat(jobs.claimLeases)
|
||||
.as("without a lease the claim ends with the statement and every instance takes the job")
|
||||
.containsExactly(CLAIM_LEASE);
|
||||
}
|
||||
|
||||
private ReconciliationJob due(int attempts) {
|
||||
ReconciliationJob job =
|
||||
new ReconciliationJob(
|
||||
@@ -135,7 +152,8 @@ class ReconciliationJobWorkerTest {
|
||||
attempts,
|
||||
Optional.empty(),
|
||||
NOW,
|
||||
NOW);
|
||||
NOW,
|
||||
1);
|
||||
jobs.due.add(job);
|
||||
return job;
|
||||
}
|
||||
@@ -155,6 +173,7 @@ class ReconciliationJobWorkerTest {
|
||||
private final List<ReconciliationJob> due = new ArrayList<>();
|
||||
private final List<UUID> completed = new ArrayList<>();
|
||||
private final List<Map.Entry<UUID, Instant>> rescheduled = new ArrayList<>();
|
||||
private final List<Duration> claimLeases = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public ReconciliationJob schedule(
|
||||
@@ -163,7 +182,8 @@ class ReconciliationJobWorkerTest {
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ReconciliationJob> claimDue(int limit, Instant now) {
|
||||
public List<ReconciliationJob> claimDue(int limit, Instant now, Duration lease) {
|
||||
claimLeases.add(lease);
|
||||
return List.copyOf(due);
|
||||
}
|
||||
|
||||
|
||||
@@ -91,3 +91,30 @@ composition side effects/lifecycle, routing replay/read behavior, and the readin
|
||||
cd src
|
||||
./gradlew :adapter:outbound:objectstorage:check --console=plain
|
||||
```
|
||||
|
||||
### MinIO qualification lanes
|
||||
|
||||
`objectStorageMinioContractTest` and `objectStorageMinioFaultTest` (in `mainCheck`) run a real MinIO
|
||||
and Toxiproxy. Their images are read from one file,
|
||||
`src/test/resources/object-storage/minio-provider-evidence.json`, whose `image` digest is the
|
||||
release the `status`, `excludedProfiles` and `limitations` beside it were measured on.
|
||||
`MinioQualificationImage` (in `src/test`, checked by the leaf's `test` without Docker) reads it.
|
||||
|
||||
- The image is pulled before any container is built. If it cannot be pulled the lane fails with
|
||||
`pinned image unavailable: <reference>`: a supply failure, not an adapter defect. The lane does
|
||||
not skip, because a skipped vendor lane would be green with no vendor evidence.
|
||||
- A mirror of the same digest is set with `OBJECT_STORAGE_MINIO_IMAGE` or
|
||||
`-PobjectStorageMinioImage=<registry>/<repo>@sha256:<evidence digest>`. A value that does not end
|
||||
in the evidence digest is refused: a different build is a new measurement, made by re-running the
|
||||
lanes and rewriting the evidence file (image and findings together).
|
||||
- The local compose runtime (`docker-compose.infra.yml`, `LOCAL_MINIO_IMAGE`) is a different, later
|
||||
release and is not evidence; the comment there says why.
|
||||
|
||||
As of 2026-11-01 a pull of `minio/minio` from Docker Hub answers "repository does not exist", so
|
||||
these lanes fail with the message above until a mirror or a re-measured replacement is chosen
|
||||
(review 05-09; the choice is an open owner decision).
|
||||
|
||||
```bash
|
||||
cd src
|
||||
./gradlew :adapter:outbound:objectstorage:objectStorageMinioContractTest --console=plain
|
||||
```
|
||||
|
||||
@@ -35,6 +35,12 @@ testing {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The MinIO lanes read their images from the one evidence file in src/test/resources
|
||||
// (object-storage/minio-provider-evidence.json) through MinioQualificationImage in src/test, which
|
||||
// the leaf's `test` checks without Docker. The integration runtime therefore sees the test output;
|
||||
// its own tests are still only the classes each lane `requires`.
|
||||
sourceSets.integrationTest.compileClasspath += sourceSets.test.output
|
||||
sourceSets.integrationTest.runtimeClasspath += sourceSets.test.output
|
||||
configurations {
|
||||
integrationTestImplementation.extendsFrom testImplementation
|
||||
integrationTestRuntimeOnly.extendsFrom testRuntimeOnly
|
||||
@@ -82,14 +88,24 @@ tasks.named('test') {
|
||||
systemProperty 'objectstorage.readiness.registry', objectStorageReadinessRegistry.absolutePath
|
||||
}
|
||||
|
||||
// A mirror of the measured MinIO digest, for when the origin registry stops serving it (review
|
||||
// 05-09). Either spelling reaches the lanes as one system property; MinioQualificationImage refuses
|
||||
// a value that does not end in the evidence digest, because another build is a new measurement and
|
||||
// is made by editing the evidence file, not by an override.
|
||||
def minioImageOverride = (findProperty('objectStorageMinioImage')
|
||||
?: providers.environmentVariable('OBJECT_STORAGE_MINIO_IMAGE').getOrElse('')).toString()
|
||||
|
||||
strictTestLanes {
|
||||
lane('objectStorageMinioContractTest') {
|
||||
integration()
|
||||
sourceSet = 'integrationTest'
|
||||
description = 'Runs the non-skipping exact-release MinIO managed object contract.'
|
||||
description = 'Runs the non-skipping MinIO managed object contract on the evidence-pinned image.'
|
||||
requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.MinioManagedObjectContractTest'
|
||||
rejectSkipped = true
|
||||
jvmArgs '-Duser.timezone=UTC'
|
||||
if (minioImageOverride) {
|
||||
systemProperty 'objectstorage.minio.image', minioImageOverride
|
||||
}
|
||||
shouldRunAfter 'test'
|
||||
}
|
||||
lane('objectStorageMinioFaultTest') {
|
||||
@@ -99,6 +115,9 @@ strictTestLanes {
|
||||
requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.MinioManagedObjectFaultTest'
|
||||
rejectSkipped = true
|
||||
jvmArgs '-Duser.timezone=UTC'
|
||||
if (minioImageOverride) {
|
||||
systemProperty 'objectstorage.minio.image', minioImageOverride
|
||||
}
|
||||
shouldRunAfter 'objectStorageMinioContractTest'
|
||||
}
|
||||
lane('objectStorageAwsQualificationTest') {
|
||||
|
||||
+1
-4
@@ -17,7 +17,6 @@ import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.testcontainers.containers.GenericContainer;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.core.async.AsyncRequestBody;
|
||||
@@ -48,8 +47,6 @@ import software.amazon.awssdk.services.s3.model.VersioningConfiguration;
|
||||
|
||||
class MinioManagedObjectContractTest {
|
||||
|
||||
private static final String MINIO_IMAGE =
|
||||
"minio/minio@sha256:4c4a4876193f030c81f57aabb22bcb9a73462010eb61fcab66908e03e5484af8";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String BUCKET = "object-storage-contract";
|
||||
private static final String VERSIONED_BUCKET = "object-storage-versioned";
|
||||
@@ -68,7 +65,7 @@ class MinioManagedObjectContractTest {
|
||||
SECURE_RANDOM.nextBytes(keyBytes);
|
||||
String kmsKey = "contract-key:" + Base64.getEncoder().encodeToString(keyBytes);
|
||||
minio =
|
||||
new GenericContainer<>(DockerImageName.parse(MINIO_IMAGE))
|
||||
new GenericContainer<>(QualificationImages.minio())
|
||||
.withExposedPorts(9000)
|
||||
.withEnv("MINIO_ROOT_USER", accessKey)
|
||||
.withEnv("MINIO_ROOT_PASSWORD", secretKey)
|
||||
|
||||
+4
-11
@@ -34,25 +34,18 @@ class MinioManagedObjectFaultTest {
|
||||
private static final String CUT_CONNECTION_DOWNSTREAM = "CUT_CONNECTION_DOWNSTREAM";
|
||||
private static final String CUT_CONNECTION_UPSTREAM = "CUT_CONNECTION_UPSTREAM";
|
||||
|
||||
private static final DockerImageName MINIO_IMAGE =
|
||||
DockerImageName.parse(
|
||||
"minio/minio@sha256:4c4a4876193f030c81f57aabb22bcb9a73462010eb61fcab66908e03e5484af8");
|
||||
private static final DockerImageName TOXIPROXY_IMAGE =
|
||||
DockerImageName.parse(
|
||||
"ghcr.io/shopify/toxiproxy@sha256:"
|
||||
+ "9378ed52a28bc50edc1350f936f518f31fa95f0d15917d6eb40b8e376d1a214e")
|
||||
.asCompatibleSubstituteFor("shopify/toxiproxy");
|
||||
|
||||
// Every container below is declared in try-with-resources; the fluent `withX` chain returns the
|
||||
// same instance, which the compiler reads as a second, unclosed resource.
|
||||
@SuppressWarnings("resource")
|
||||
@Test
|
||||
void connectionCutProducesABoundedFailureAndRecoveryWithoutMutationReplay() throws Exception {
|
||||
DockerImageName minioImage = QualificationImages.minio();
|
||||
DockerImageName toxiproxyImage = QualificationImages.toxiproxy();
|
||||
String accessKey = "a" + UUID.randomUUID().toString().replace("-", "");
|
||||
String secretKey = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID();
|
||||
try (Network network = Network.newNetwork();
|
||||
GenericContainer<?> minio =
|
||||
new GenericContainer<>(MINIO_IMAGE)
|
||||
new GenericContainer<>(minioImage)
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases("qualified-minio")
|
||||
.withExposedPorts(9000)
|
||||
@@ -60,7 +53,7 @@ class MinioManagedObjectFaultTest {
|
||||
.withEnv("MINIO_ROOT_PASSWORD", secretKey)
|
||||
.withCommand("server", "/data");
|
||||
ToxiproxyContainer toxiproxy =
|
||||
new ToxiproxyContainer(TOXIPROXY_IMAGE)
|
||||
new ToxiproxyContainer(toxiproxyImage)
|
||||
.withNetwork(network)
|
||||
.withExposedPorts(TOXIPROXY_CONTROL_PORT, TOXIPROXY_PROXY_PORT)) {
|
||||
minio.start();
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package dev.caskeleton.adapter.outbound.objectstorage.qualification;
|
||||
|
||||
import org.testcontainers.images.RemoteDockerImage;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
|
||||
/**
|
||||
* The MinIO lanes' images, pulled before any container is built.
|
||||
*
|
||||
* <p>The references come from the evidence file through {@link MinioQualificationImage}; this class
|
||||
* only supplies the pull, Testcontainers' own image resolution, so a missing image fails here as
|
||||
* {@code pinned image unavailable: <reference>} instead of inside a container start.
|
||||
*/
|
||||
final class QualificationImages {
|
||||
|
||||
private QualificationImages() {}
|
||||
|
||||
// Loaded per call, not in a static initializer: a refused override then reads as its own
|
||||
// message instead of an ExceptionInInitializerError.
|
||||
static DockerImageName minio() {
|
||||
MinioQualificationImage images = MinioQualificationImage.load();
|
||||
return pulled(images, images.minio());
|
||||
}
|
||||
|
||||
static DockerImageName toxiproxy() {
|
||||
MinioQualificationImage images = MinioQualificationImage.load();
|
||||
return pulled(images, images.toxiproxy()).asCompatibleSubstituteFor("shopify/toxiproxy");
|
||||
}
|
||||
|
||||
private static DockerImageName pulled(MinioQualificationImage images, String reference) {
|
||||
return DockerImageName.parse(
|
||||
images.requireAvailable(
|
||||
reference, ref -> new RemoteDockerImage(DockerImageName.parse(ref)).get()));
|
||||
}
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"providerType": "s3-compatible-minio-community-release-2024-01-16t16-07-38z",
|
||||
"providerVersion": "release-2024-01-16t16-07-38z-sdk-2.30.0",
|
||||
"image": "minio/minio@sha256:4c4a4876193f030c81f57aabb22bcb9a73462010eb61fcab66908e03e5484af8",
|
||||
"toxiproxyImage": "ghcr.io/shopify/toxiproxy@sha256:9378ed52a28bc50edc1350f936f518f31fa95f0d15917d6eb40b8e376d1a214e",
|
||||
"profile": "managed-common",
|
||||
"status": "UNSUPPORTED",
|
||||
"excludedProfiles": [
|
||||
"managed-single-create-only",
|
||||
"conditional-control-create",
|
||||
"managed-multipart-create-only",
|
||||
"direct-single-create-only",
|
||||
"direct-multipart-create-only"
|
||||
],
|
||||
"limitations": [
|
||||
"PutObject If-None-Match was accepted and overwrote an existing object",
|
||||
"stale PutObject If-Match returned HTTP 412 but create-if-absent control CAS is not safe",
|
||||
"CompleteMultipartUpload accepted If-None-Match despite a pre-existing target and overwrote it",
|
||||
"managed immutable create, conditional control creation, and multipart create-only are disabled",
|
||||
"local single-node container evidence only",
|
||||
"not AWS evidence",
|
||||
"not production TLS or deployment-topology evidence"
|
||||
]
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user