From 3d435d2bc0f95c62ac21b564e494f76e4b56a78e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 12 Nov 2026 22:26:03 +0900 Subject: [PATCH 01/23] =?UTF-8?q?docs(reviews):=20round9=20=EC=A0=84?= =?UTF-8?q?=EC=B2=B4=20=EB=A6=AC=EB=B7=B0=20=EA=B8=B0=EB=A1=9D=EC=9D=84=20?= =?UTF-8?q?=EB=82=A8=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit main a7e38c10을 분야 렌즈 리뷰어 8명(두 물결)으로 전체 리뷰한 결과다. 발견 152건(Critical 0, High 2, Medium 72, Low 78)을 영역 문서 다섯에 적고, README에 색인·범위·묶음·다른 세션에 넘긴 9건·결정이 필요한 6건·멈춤 기준 상태를 적는다. 검증: python3 scripts/check-review-index.py docs/reviews/2026-11-12-round9-review rc=0(152/152), python3 scripts/check-docs.py rc=0. --- .../01-persistence-messaging-performance.md | 221 +++++++++++++ .../02-security-observability.md | 221 +++++++++++++ .../03-contract-testing.md | 207 ++++++++++++ .../2026-11-12-round9-review/04-build-docs.md | 298 ++++++++++++++++++ .../05-architecture-domain.md | 137 ++++++++ .../2026-11-12-round9-review/README.md | 250 +++++++++++++++ 6 files changed, 1334 insertions(+) create mode 100644 docs/reviews/2026-11-12-round9-review/01-persistence-messaging-performance.md create mode 100644 docs/reviews/2026-11-12-round9-review/02-security-observability.md create mode 100644 docs/reviews/2026-11-12-round9-review/03-contract-testing.md create mode 100644 docs/reviews/2026-11-12-round9-review/04-build-docs.md create mode 100644 docs/reviews/2026-11-12-round9-review/05-architecture-domain.md create mode 100644 docs/reviews/2026-11-12-round9-review/README.md diff --git a/docs/reviews/2026-11-12-round9-review/01-persistence-messaging-performance.md b/docs/reviews/2026-11-12-round9-review/01-persistence-messaging-performance.md new file mode 100644 index 00000000..5010112d --- /dev/null +++ b/docs/reviews/2026-11-12-round9-review/01-persistence-messaging-performance.md @@ -0,0 +1,221 @@ +# round9 영역 01 — 영속성·메시징·성능 + +- 대상: main `a7e38c10`(2026-11-12). 범위와 방법은 [README](README.md) 「범위」다. +- 발견마다: 출처(리뷰어), 증거 수준, 이전부터/최근 변경, 고칠 묶음(README 「묶음」). 원문의 `파일:줄`은 저장소 루트 기준이다. + +### RR9-01-01 · Medium · inbox TransactionRunner `new TransactionTemplate` timeout 없음 → 유스케이스… + +- 출처: 물결 1 영속성·메시징·성능 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B9 트랜잭션 시한·정리 +- 내용: inbound/messaging `MessagingInboxAutoConfiguration.java:76` — inbox TransactionRunner `new TransactionTemplate` timeout 없음 → 유스케이스 tx.inWrite가 합류해 30초 상한 버림(`SpringTransaction.java:200`). 근거 persistence-jpa/AGENTS.md:138, manual 09:123. 고침: setTimeout(write-timeout) + 테스트. 이전부터. + +### RR9-01-02 · Medium · heartbeat·progress·succeed·fail이 lease_owner=:workerId만 확인, fence 없음. 같은… + +- 출처: 물결 1 영속성·메시징·성능 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B8 claim·fence +- 내용: persistence-jpa `DurableOperationJpaRepository.java:121,143,168,194` — heartbeat·progress·succeed·fail이 lease_owner=:workerId만 확인, fence 없음. 같은 workerId 재claim 시 앞 실행이 true. 포트 `DurableOperationStorePort.java:14,57`은 workerId 유일 조건 안 적음. outbox lease_token·알림 lease_fence·reconciliation claim_fence·fileserver claim_token과 갈림. 고침: claimNext가 token 돌려주고 조건에 넣기 or 포트에 유일성 명시 + 계약 케이스. 이전부터. + +### RR9-01-03 · Medium · live_event_log 행 retention 지나도 안 지움, sweepExpired 호출자·스케줄 없음, 문서도 서비스 의무로 안… + +- 출처: 물결 1 영속성·메시징·성능 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B9 트랜잭션 시한·정리 +- 내용: persistence-jpa `JpaLiveEventReplay.java:142` — live_event_log 행 retention 지나도 안 지움, sweepExpired 호출자·스케줄 없음, 문서도 서비스 의무로 안 적음(inbox는 09장 179줄에 적음). 고침: reaper 조립 or 문서 의무. 이전부터. + +### RR9-01-04 · Low · 상한 없는 DELETE 한 문장(outbox는 1000행씩, OutboxEventJpaRepository.java:35-47),… + +- 출처: 물결 1 영속성·메시징·성능 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B8 claim·fence +- 내용: persistence-jpa `IdempotencyReaper.java:27-29` — 상한 없는 DELETE 한 문장(outbox는 1000행씩, OutboxEventJpaRepository.java:35-47), expires_at은 DB 시계(IdempotencyClaimGateway.java:90 clock_timestamp())인데 비교는 앱 clock. 고침: 묶음 삭제 + SQL now(). 이전부터. + +### RR9-01-05 · Low · join() 시간 상한 없음,… + +- 출처: 물결 1 영속성·메시징·성능 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B10a 발행·발송·캐시 +- 내용: messaging `OutboxMessagePublishAdapter.java:53` — join() 시간 상한 없음, longestAttempt()(PlatformIntegrationEventPublishAdapter.java:93-96) 검사가 실제 대기에 안 걸림 → lease 지나 중복 발행, 종료 대기 약속 깨짐. VerificationCoordinator.java:56은 get(timeout). 고침: orTimeout(longestAttempt) + AMBIGUOUS. 이전부터. + +### RR9-01-06 · Low · Javadoc "enqueue is an upsert"인데 UPDATE 0행이면 INSERT 두 단계, 동시 enqueue 시… + +- 출처: 물결 1 영속성·메시징·성능 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B8 claim·fence +- 내용: persistence-fileserver `JpaRecoveryQueue.java:18,43-46` — Javadoc "enqueue is an upsert"인데 UPDATE 0행이면 INSERT 두 단계, 동시 enqueue 시 uq_fs_recovery_open(V2:53) 위반·25P02, DefaultFileReconciliationService.java:242가 그대로 던짐. 고침: INSERT … ON CONFLICT (file_id) WHERE status='PENDING' DO UPDATE. 이전부터. + +### RR9-01-07 · Low · app.lock.wait-time 읽는 곳 없음(lease-ttl 교차 검사로 기동 막기만). README:559… + +- 출처: 물결 1 영속성·메시징·성능 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B9 트랜잭션 시한·정리 +- 내용: persistence-jpa `LockSettings.java:21-41` — app.lock.wait-time 읽는 곳 없음(lease-ttl 교차 검사로 기동 막기만). README:559 "@EnableConfigurationProperties가 바인딩"(실제 StrictSettingsBinder), :536 데코레이터 위치 "컴포지션 루트". 근거 manual 10 기준 3. 이전부터. + +### RR9-01-08 · Low · 408·429를 조건 없이 재시도로 적음, 코드(DefaultRetryEligibilityEngine.java:81-99,… + +- 출처: 물결 1 영속성·메시징·성능 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B10b S3·Mongo·httpclient +- 내용: `docs/httpclient/retry-and-ambiguity.md:53,55` — 408·429를 조건 없이 재시도로 적음, 코드(DefaultRetryEligibilityEngine.java:81-99, RetryEligibilityEngineTest.java:200-207)는 비멱등에서 408 결과모름·429 거부. 이전부터. + +### RR9-01-09 · Low · 주석 "retention has no default on purpose"인데… + +- 출처: 물결 1 영속성·메시징·성능 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B9 트랜잭션 시한·정리 +- 내용: persistence-jpa `JpaAdapterBeansConfig.java:124-125` — 주석 "retention has no default on purpose"인데 persistence-jpa.yml:212·env-keys.yaml:387 기본 1h. 이전부터. + +### RR9-01-10 · Low · Javadoc lane 목록에 lock timeout runbook… + +- 출처: 물결 1 영속성·메시징·성능 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B9 트랜잭션 시한·정리 +- 내용: persistence-jpa postgresqlIntegrationTest `readiness/RunbookSql.java:10-13` — Javadoc lane 목록에 lock timeout runbook lane(PostgreSqlDistributedLockIntegrationTest.java:36,137,162) 빠짐. 이전부터(ba189869). + +### RR9-01-11 · Low · Redis 같은 키 재전송 안 돌린다를 조건 없이 약속, Sentinel·Cluster failover 비동기 복제 손실… + +- 출처: 물결 1 영속성·메시징·성능 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B10b S3·Mongo·httpclient +- 내용: `docs/manual/05-idempotency.md:59` — Redis 같은 키 재전송 안 돌린다를 조건 없이 약속, Sentinel·Cluster failover 비동기 복제 손실 한계(redis-capability-incident.md:145-151) 안 적음. 이전부터. + +### RR9-01-12 · Medium · 회복이 행 잠금 없이 읽고(RecipientDeliveryJpaRepository.java:187-194) requeue 무조건… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B8 claim·fence +- 내용: `LeaseRecoveryService.java:113,157-164`, `JpaRecipientDeliveryStore.java:59-71` — 회복이 행 잠금 없이 읽고(RecipientDeliveryJpaRepository.java:187-194) requeue 무조건 read-modify-write, 인스턴스마다 돎(NotificationBackgroundWorkers.java:77) → 완료·재claim 행을 READY로. 고침: state·lease_until·lease_fence 조건부 UPDATE. + +### RR9-01-13 · Medium · UPDATE … WHERE id IN (SELECT … LIMIT), 상태 조건 subquery 안만 → READ COMMITTED 재평가 안… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B8 claim·fence +- 내용: `RecipientClaimSql.java:55-68`(EXPIRE_OVERDUE), `InboxItemJpaRepository.java:89-106`(markAllRead) — UPDATE … WHERE id IN (SELECT … LIMIT), 상태 조건 subquery 안만 → READ COMMITTED 재평가 안 함, claim된 행 EXPIRED, archive 행 READ(주석 96-97이 막겠다던 것). 고침: 바깥 WHERE 상태 조건 or FOR UPDATE SKIP LOCKED. + +### RR9-01-14 · Medium · poll마다 SQL 4개, PROJECTION_LAG WHERE 없음 → notification_provider_event 전체 스캔(지우는… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B9 트랜잭션 시한·정리 +- 내용: `JdbcNotificationServingState.java:60-69,89-118`, `NotificationSchedulerWorker.java:84-87` — poll마다 SQL 4개, PROJECTION_LAG WHERE 없음 → notification_provider_event 전체 스캔(지우는 경로 없음), Javadoc 20-22 「claim 인덱스」. 고침: backlog만 or 캐시, 부분 인덱스 조건. + +### RR9-01-15 · Medium · ThreadPoolExecutor(1,n,LinkedBlockingQueue(4n)) 큐 찰 때까지 스레드 1, limiter 4로 큐 안… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B10a 발행·발송·캐시 +- 내용: `NotificationSmtpProviderConfig.java:117-129` — ThreadPoolExecutor(1,n,LinkedBlockingQueue(4n)) 큐 찰 때까지 스레드 1, limiter 4로 큐 안 참(SmtpProviderRuntimeAssembler.java:110) → SMTP 직렬, NotificationSmtpSettings.java:22. 고침: core=max + allowCoreThreadTimeOut. + +### RR9-01-16 · Medium · RejectedExecution을 AMBIGUOUS_SUBMISSION으로(SMTP 상태 조회 없음 → 운영자 대기),… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B10a 발행·발송·캐시 +- 내용: 같은 executor + `RegistryProviderDispatchGateway.java:59-61`, `ProviderOutcomeClassifier.java:49-57` — RejectedExecution을 AMBIGUOUS_SUBMISSION으로(SMTP 상태 조회 없음 → 운영자 대기), max-concurrency > 5×dispatch-concurrency 조건, 기동 검사 없음. 고침: ProviderCallNotStartedException + 기동 검사. + +### RR9-01-17 · Medium · 캐시가 대기 예산 없는 run → lane 대기 2s + commandTimeout, @param "ceiling on one cache… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B10a 발행·발송·캐시 +- 내용: `RedisCacheRegionAdapter.java:118,131-138,161,270,346`, `SemanticRedisCall.java:115-117,134-137`, `RedisRuntimeOwner.java:171-172` — 캐시가 대기 예산 없는 run → lane 대기 2s + commandTimeout, @param "ceiling on one cache operation". rate limit은 effectWithin. 고침: effectWithin(commandTimeout). + +### RR9-01-18 · Medium · 캐시 값 크기 상한 없음(옛 키 폐기 env-keys.yaml:2686-2689, RedisKeyRules는 키만). 고침: encode 길이… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B10a 발행·발송·캐시 +- 내용: `RedisCacheRegionAdapter.java:233-341` — 캐시 값 크기 상한 없음(옛 키 폐기 env-keys.yaml:2686-2689, RedisKeyRules는 키만). 고침: encode 길이 검사. + +### RR9-01-19 · Medium · 조건부 PUT 본문 재전송 가능 → SDK 재시도가 412 → ObjectControlConflictException,… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B10b S3·Mongo·httpclient +- 내용: `S3ConditionalObjectControlStore.java:101-118`, `S3AsyncClientFactory.java:38-48` — 조건부 PUT 본문 재전송 가능 → SDK 재시도가 412 → ObjectControlConflictException, reconcileLostResponse(121) 안 돎, CAS(ObjectOperationKernel.java:112-125)는 자기 쓰기를 stale로. 조건 retry.maximum-attempts>1. 고침: 조건부 PUT 재시도 끔 or 412에서 다시 읽어 비교. + +### RR9-01-20 · Medium · getMappedResults 전부 메모리 후 셈, maxResultBytes 미집행(95), query-aggregation-guide… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B10b S3·Mongo·httpclient +- 내용: `PolicyAwareMongoAggregationExecutor.java:76-85`, `MongoOperationBudget.java:5-11` — getMappedResults 전부 메모리 후 셈, maxResultBytes 미집행(95), query-aggregation-guide 3절. 고침: $limit(max+1) + cursor 바이트 누적. + +### RR9-01-21 · Medium · heap 384m을 512m tmpfs에 dump, 같은 cgroup·swap 없음 → dump 중 OOM kill 가능,… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B19 compose·Docker 운영 +- 내용: (넘어온 2) Dockerfile:157-163, compose.yaml:113-123, docs/runbooks/internal-error-spike.md:39 — heap 384m을 512m tmpfs에 dump, 같은 cgroup·swap 없음 → dump 중 OOM kill 가능, ExitOnOutOfMemoryError로 tmpfs 사라짐. dev.yaml:25-28만 volume. 고침: named volume or runbook. + +### RR9-01-22 · Low · (넘어온 1) .env.example:193 POSITIVE_SOFT_TTL= → 빈 Duration null → setter 안 불림 →… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B2 env 계약 +- 내용: (넘어온 1) .env.example:193 POSITIVE_SOFT_TTL= → 빈 Duration null → setter 안 불림 → 필드 기본 30s(RedisCapabilitySettings.java:85), HARD_TTL<30s면 운영자가 정하지 않은 soft로 기동 실패(101-105). 고침: soft 비면 min(30s,hard). + +### RR9-01-23 · Low · max-items 100을 10분 lease로 한꺼번에 claim, lease 안에 끝나는지 검사 없음(outbox… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B8 claim·fence +- 내용: `DefaultCleanupService.java:50,96-122` — max-items 100을 10분 lease로 한꺼번에 claim, lease 안에 끝나는지 검사 없음(outbox OutboxSettings.java:68-96, notification NotificationSchedulerWorker.java:71-75와 갈림). + +### RR9-01-24 · Low · "lease > provider 호출·timeout" 주석만, 검사 없음. + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B8 claim·fence +- 내용: notification.yml:46-48, NotificationDispatchProperties.java:40-48 — "lease > provider 호출·timeout" 주석만, 검사 없음. + +### RR9-01-25 · Low · 트랜잭션 30초 상한 없음(decisions 2.5), row cap 사후 검사(inbox 건과 같은 원인). + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B9 트랜잭션 시한·정리 +- 내용: `HibernateStatelessSessionRunner.java:56-67` — 트랜잭션 30초 상한 없음(decisions 2.5), row cap 사후 검사(inbox 건과 같은 원인). + +### RR9-01-26 · Low · 새 pool 크기 모른 채 합계 미만만 봄 → 상한 초과, Javadoc "would exceed". + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B9 트랜잭션 시한·정리 +- 내용: `TenantPoolBudget.java:29-33`, `TenantDataSourceRegistry.java:54` — 새 pool 크기 모른 채 합계 미만만 봄 → 상한 초과, Javadoc "would exceed". + +### RR9-01-27 · Low · acquire void, idle 판정 마지막 acquire 시각 → 사용 중 client 닫음, 닫기 실패가 다른 tenant… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B10b S3·Mongo·httpclient +- 내용: `MongoTenantClientRegistry.java:85-128,130-156` — acquire void, idle 판정 마지막 acquire 시각 → 사용 중 client 닫음, 닫기 실패가 다른 tenant acquire에서(153). Experimental. + +### RR9-01-28 · Low · requireCurrentFence가 UNFENCED만 거름(MongoMigrationLock.java:32), refresh(166-170)… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B10b S3·Mongo·httpclient +- 내용: `MongoCollectionMigrationLedger.java:93,120,177` — requireCurrentFence가 UNFENCED만 거름(MongoMigrationLock.java:32), refresh(166-170) ISE vs MongoMigrationHeartbeat.java:22 MongoOperationRejectedException 약속. + +### RR9-01-29 · Low · lease 만료 시계 구현마다 다름: JpaRecipientLeaseStore.java:52,117,… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B8 claim·fence +- 내용: lease 만료 시계 구현마다 다름: JpaRecipientLeaseStore.java:52,117, DefaultCleanupService.java:88, MongoCollectionMigrationLock.java:76-80(JVM) vs 멱등·rate limit(서버). R1-4와 같은 원인. + +### RR9-01-30 · Low · compression=true면 Apache가 푼 스트림을 wire 계수기가 셈(ApacheClientFactory.java:114-116)… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B10b S3·Mongo·httpclient +- 내용: `RestClientResponseReader.java:112-124`, `ResponseLimits.java:8-13` — compression=true면 Apache가 푼 스트림을 wire 계수기가 셈(ApacheClientFactory.java:114-116) → 6MiB 응답 wire 초과 거절. + +### RR9-01-31 · Low · ProxyType.SOCKS를 HTTP 프록시로, capability… + +- 출처: 물결 2 outbound +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B10b S3·Mongo·httpclient +- 내용: `ApacheClientFactory.java:117-123` — ProxyType.SOCKS를 HTTP 프록시로, capability proxySupport=true(BlockingTransportCapabilities.java:33-35). diff --git a/docs/reviews/2026-11-12-round9-review/02-security-observability.md b/docs/reviews/2026-11-12-round9-review/02-security-observability.md new file mode 100644 index 00000000..7da3676a --- /dev/null +++ b/docs/reviews/2026-11-12-round9-review/02-security-observability.md @@ -0,0 +1,221 @@ +# round9 영역 02 — 보안·관측 + +- 대상: main `a7e38c10`(2026-11-12). 범위와 방법은 [README](README.md) 「범위」다. +- 발견마다: 출처(리뷰어), 증거 수준, 이전부터/최근 변경, 고칠 묶음(README 「묶음」). 원문의 `파일:줄`은 저장소 루트 기준이다. + +### RR9-02-01 · Medium · 관리 포트 기본 127.0.0.1(PR #12)인데 service-runtime/README.md:275-276·Dockerfile:221은… + +- 출처: 물결 1 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B3 공개 경로·관리 포트 +- 내용: bootstrap/app `config/observability.yml:34` — 관리 포트 기본 127.0.0.1(PR #12)인데 service-runtime/README.md:275-276·Dockerfile:221은 k8s 프로브·Prometheus가 닿는다고 약속. `MANAGEMENT_SERVER_ADDRESS`가 docs/build.md:573·.env.example·env-keys에 없음. compose.yaml:88-91·compose-lanes/dev.yaml:70 `127.0.0.1:9001:9001` publish는 컨테이너 loopback에 못 닿음(죽은 설정). 고침: 세 문서에 원격 프로브는 MANAGEMENT_SERVER_ADDRESS 필요, .env.example 행, publish 줄 정리. 최근(PR #12, 9fb5a61f). + +### RR9-02-02 · Medium · 최상위 `roles` 클레임 fallback을 권한에 합침. manual 07:51-53·decisions 2.6 「JWT… + +- 출처: 물결 1 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B4 인증·인가 +- 내용: web `auth/JwtToAuthenticatedPrincipalConverter.java:101-105` — 최상위 `roles` 클레임 fallback을 권한에 합침. manual 07:51-53·decisions 2.6 「JWT audience·role」은 realm_access·자기 client resource_access만. 고침: fallback 삭제 + 시험 "최상위 roles만 → 권한 0". 이전부터. + +### RR9-02-03 · Medium · config/security.yml 한 줄만 읽음, 문서(gates.md:63, build.md:166)는 보안 체인 전체 약속.… + +- 출처: 물결 1 보안·관측(같은 결함을 물결 1 API 계약·시험도 적음) +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B3 공개 경로·관리 포트 +- 내용: bootstrap/app test `PublicPathSnapshotTest.java:31` — config/security.yml 한 줄만 읽음, 문서(gates.md:63, build.md:166)는 보안 체인 전체 약속. profile의 public-paths(application-local.yml:161), 모듈 체인 permitAll(web-notification CallbackMvcSecurityConfiguration.java:29-35 `/internal/notification/callbacks/**`) 우회. 고침: 입력 넓히기(context 띄워 matcher 나열) or 약속 좁히기. 이전부터. + +### RR9-02-04 · Medium · runbook 둘이 없는 신호로 탐지:… + +- 출처: 물결 1 보안·관측(같은 결함을 물결 2 계약·문서도 적음) +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B7 runbook 신호 +- 내용: runbook 둘이 없는 신호로 탐지: `docs/runbooks/management-actuator-forbidden.md:15-16`(403 ACTUATOR_FORBIDDEN; 실제 404·본문없는 401 ManagementSecurityConfig.java:55-56, 코드 OperationalError.java:89 선언만), `docs/runbooks/authz-cross-tenant-violation.md:18-21,27,37`(403 AUTHZ_TENANT_MISMATCH 경보, 칸·지표 authz_denied_total 등 없음; 실제 404·로그·지표 없음). 고침: 신호 만들기(WARN+counter) 후 runbook 맞추기 or 신호 없음 명시. 이전부터. + +### RR9-02-05 · Medium · `docs/registries/metrics.yaml` 양방향 불일치: 코드 없는… + +- 출처: 물결 1 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B5 관측 registry +- 내용: `docs/registries/metrics.yaml` 양방향 불일치: 코드 없는 행(http.server.requests.latency:47, dependency.client.requests:72, db.query.duration:211, resilience4j.* 98·117·137, cache.invalidations.total:454, cache.local.* 473·492·508), 행 없는 코드(http.client.* 25개, notification.* 16, graphql.* 4, jpa.query.*, backend.redis.*, mongodb.driver.*, fileserver.*.duration), http.server.requests tag 표기(uri_template·2xx vs uri·숫자·outcome·exception), MetricsDistributionMeterFilter.java:19-24 없는 이름에 SLO, CardinalityBounds Javadoc "used by MeterFilter" 미사용, 단위 접미사 규칙 위반 lock.acquisition:308·executor.saturation:233. 고침: 행↔meter 맞추기 + "registry ⊆ 등록 meter" 시험. 이전부터. + +### RR9-02-06 · Medium · JMX 9999 무인증·무TLS, jmxremote.host 없어 모든 인터페이스. 주석 15·54 "localhost only". 고침:… + +- 출처: 물결 1 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B3 공개 경로·관리 포트 +- 내용: `src/bootstrap/app/compose-lanes/dev.yaml:62-67` — JMX 9999 무인증·무TLS, jmxremote.host 없어 모든 인터페이스. 주석 15·54 "localhost only". 고침: -Dcom.sun.management.jmxremote.host=127.0.0.1 or JMX 제거. 이전부터. + +### RR9-02-07 · Low · 18키 중 5개만 코드가 넣음(logback-spring.xml:90-94). tenant_id(77-88) required_in인데… + +- 출처: 물결 1 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B5 관측 registry +- 내용: `docs/registries/mdc-keys.yaml` — 18키 중 5개만 코드가 넣음(logback-spring.xml:90-94). tenant_id(77-88) required_in인데 없음(JwtToAuthenticatedPrincipalConverter.java:40-41 "tenant_id is also the MDC key"). method·status·duration_ms 메시지에만(RequestLoggingFilter.java:52-57). request_id·correlation_id type ulid인데 UUIDv4(WebMvcRequestIdFilter.java:159, GrpcCorrelationInterceptor.java:67, WebSocketCorrelationInterceptor.java:34). required_test contract-verification:* 시험 없음. 이전부터. + +### RR9-02-08 · Low · 전송별 correlation 규칙 다름: web(WebMvcRequestIdFilter.java:189-191),… + +- 출처: 물결 1 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B5 관측 registry +- 내용: 전송별 correlation 규칙 다름: web(WebMvcRequestIdFilter.java:189-191), gRPC(GrpcCorrelationInterceptor.java:65-74 correlation_id 없음, traceparent 없으면 trace_id 없음; Javadoc 17 "same keys"), STOMP 세션 id(WebSocketCorrelationInterceptor.java:34-37). mdc-keys.yaml:60-71. 고침: shared-contract에 결정 하나. 이전부터. + +### RR9-02-09 · Low · 401·403 WARN에 원본 getRequestURI(Javadoc 15-19 "only redacted"). 같은 모양… + +- 출처: 물결 1 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B6a 로그 내용 +- 내용: web `auth/AuthErrorResponseWriter.java:35-41` — 401·403 WARN에 원본 getRequestURI(Javadoc 15-19 "only redacted"). 같은 모양 RequestLoggingFilter.java:66-69, GlobalExceptionHandler.java:213 getDescription(false). 고침: 매칭 pattern·분류. 이전부터. + +### RR9-02-10 · Low · IP 신뢰 문서 둘: application-local.yml:120-121 "framework via… + +- 출처: 물결 1 보안·관측(같은 결함을 물결 2 계약·문서도 적음) +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B6b 비밀·IP 문서 +- 내용: IP 신뢰 문서 둘: application-local.yml:120-121 "framework via env"(server.yml:12·env-keys.yaml:133-141 금지), docs/security/rate-limiting.md:18 지운 APP_RATE_LIMIT_CLIENT_IP_MODE(capability-status.md:319 삭제). 고침: native + internal-proxies. local은 이전부터, rate-limiting은 PR #12(1444d1e0). + +### RR9-02-11 · Low · config/security.yml:23 `SECURITY_PUBLIC_PATHS`, config/runtime.yml:18… + +- 출처: 물결 1 보안·관측(같은 결함을 물결 1 API 계약·시험도 적음) +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B2 env 계약 +- 내용: config/security.yml:23 `SECURITY_PUBLIC_PATHS`, config/runtime.yml:18 `PRESENTATION_API_BASE_PATH` env-keys·.env.example 미등록(머리말 7-10 "APP_, 예외 SPRING_*"). 이전부터. + +### RR9-02-12 · Low · masking_rule full_except_last_4 구현 없음(LogMaskingPatterns.java:23-41 URI… + +- 출처: 물결 1 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B6b 비밀·IP 문서 +- 내용: `docs/registries/secrets-classification.yaml` — masking_rule full_except_last_4 구현 없음(LogMaskingPatterns.java:23-41 URI userinfo 못 가림), 죽은 행 APP_PROFILE:399·SERVER_PORT:415·APP_NOTIFICATION_SLACK_WEBHOOK_URL:330·APP_SECURITY_GOOGLE_OAUTH_CLIENT_ID:344, required_test secrets-contract:* 없음. 이전부터. + +### RR9-02-13 · Low · 로컬 비밀 기본값 `__LOCAL_DEV_` 규칙 미준수: compose.yaml:108·158, application-local.yml:55… + +- 출처: 물결 1 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B6b 비밀·IP 문서 +- 내용: 로컬 비밀 기본값 `__LOCAL_DEV_` 규칙 미준수: compose.yaml:108·158, application-local.yml:55 `ca_skeleton`, compose.yaml:337·366 `caskeleton-local`, compose.yaml:388 `admin`. SecretSourceValidator(146-161) sentinel 못 알아봄. 이전부터. + +### RR9-02-14 · Low · "The standalone sample does that." 지운 샘플(ab5982e9). 최근. + +- 출처: 물결 1 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B6b 비밀·IP 문서 +- 내용: service-runtime `management/security/ManagementSecurityConfig.java:33-35` — "The standalone sample does that." 지운 샘플(ab5982e9). 최근. + +### RR9-02-15 · Low · main 호출자 없음, WebMvcRequestIdFilter.java:182-188이 버린 규칙. 고침: 클래스·시험·README:511… + +- 출처: 물결 1 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B6a 로그 내용 +- 내용: web `observability/HeaderSanitizer.java:3-6` — main 호출자 없음, WebMvcRequestIdFilter.java:182-188이 버린 규칙. 고침: 클래스·시험·README:511 삭제. 이전부터. + +### RR9-02-16 · Medium · 인증 없는 모르는 profile POST → ISE → GlobalExceptionHandler.java:213… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B4 인증·인가 +- 내용: `ProviderCallbackIngressBridge.java:51-61`, `MapProviderCallbackAdapterRegistry.java:50`, `NotificationCallbackMvcController.java:105` — 인증 없는 모르는 profile POST → ISE → GlobalExceptionHandler.java:213 ERROR(스택·URI)+500 envelope("bare status, no body" Javadoc), 크기·content-type 검사가 profile 확인보다 먼저라 공격자 profile 문자열이 notification.security WARN. 고침: require 먼저, CallbackValidationException. + +### RR9-02-17 · Medium · root 좌표만 판정, GraphQlAuthorizationPolicy.java:11-16 builder는 User.salary 하위 좌표… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B4 인증·인가 +- 내용: `GraphQlDocumentAuthorizationHandler.java:69` — root 좌표만 판정, GraphQlAuthorizationPolicy.java:11-16 builder는 User.salary 하위 좌표 규칙 받고 버림 → 누구나 실행. 고침: 기동 거절 or 모든 필드 판정. + +### RR9-02-18 · Medium · @RequiresPermission web만: gRPC principal을… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B4 인증·인가 +- 내용: @RequiresPermission web만: gRPC principal을 Context에만(GrpcAuthenticationInterceptor.java:38), STOMP SecurityContext 전파 없음(WebSocketConfig.java:94), RequiresPermissionAuthorizationManager.java:56은 SecurityContextHolder → 항상 거부. 거부 결과도 web 403, gRPC INTERNAL+ERROR(GrpcExceptionHandlingInterceptor.java:147), STOMP ERROR(StompHandlerFailureLog.java:76), GraphQL masked INTERNAL_ERROR+ERROR(GraphQlExceptionResolver.java:66). manual 07, gRPC README AUTHZ→PERMISSION_DENIED. 고침: 전송별 SecurityContext 전달 + 같은 코드. + +### RR9-02-19 · Medium · 모든 projection을 /topic 하나로 모든 인증 세션에, tenant·소유자 판정 없음, README 「한계」 95-106 없음.… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B11b graphql·websocket 계약 +- 내용: `LiveEventStompBroadcaster.java:89-92` — 모든 projection을 /topic 하나로 모든 인증 세션에, tenant·소유자 판정 없음, README 「한계」 95-106 없음. 고침: 목적지 분리 or 규칙·시험. + +### RR9-02-20 · Medium · SPRING_PROFILES_ACTIVE=test면 배포 jar 통과 → prod 검사 모두 꺼짐(SecretSourceValidator… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B4 인증·인가 +- 내용: `RuntimeEnvironmentProfileValidator.java:50` — SPRING_PROFILES_ACTIVE=test면 배포 jar 통과 → prod 검사 모두 꺼짐(SecretSourceValidator __LOCAL_DEV_·fixture-, fileserver unenforced, GraphQL 모드), JpaSafetySettings.java:32-33 local 편의 켜짐. RuntimeEnvironment.java:52 "test는 배포 환경 아님" 장치 없음. 고침: 배포 jar + test 표지 없음 → 기동 실패. + +### RR9-02-21 · Medium · INFO 이하 로거 구분 없이 버림, 감사 로거 INFO(LoggingNotificationAudit.java:31,… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B6a 로그 내용 +- 내용: `SamplingTurboFilter.java:46-56` — INFO 이하 로거 구분 없이 버림, 감사 로거 INFO(LoggingNotificationAudit.java:31, StructuredAdminAudit.java:25, StructuredFileserverAudit.java:21), prod 0.1 권장(app README:349, env-keys.yaml:838) → 감사 90% 손실. 고침: 감사 로거·marker 제외 + 시험. + +### RR9-02-22 · Medium · 예외 통째 로그 → SQL·제약·값, 전송은 ServerFailureLog.of(ServerFailureLog.java:59-63). 고침:… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B6a 로그 내용 +- 내용: `OutboxRelayScheduler.java:115-121`, `FileserverCleanupWorker.java:79-85,110-116` — 예외 통째 로그 → SQL·제약·값, 전송은 ServerFailureLog.of(ServerFailureLog.java:59-63). 고침: carrier면 ServerFailureLog 줄. + +### RR9-02-23 · Medium · sub 없는 토큰 idpUserId=null → FileAccessSubject.java:24,… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B4 인증·인가 +- 내용: `JwtToAuthenticatedPrincipalConverter.java:57` — sub 없는 토큰 idpUserId=null → FileAccessSubject.java:24, EdgeRateLimitSubject.java:25 NPE 500. AUTH_CLAIM_MAPPING_FAILED(OperationalError.java:33) 안 던짐, tenant claim 틀리면(:78) 문자열 매칭으로 AUTH_TOKEN_MALFORMED(SecurityErrorClassifier.java:110). 고침: 변환기에서 AUTH_CLAIM_MAPPING_FAILED 구조화. 구조적 위험. + +### RR9-02-24 · Low · 금지 값; auth-kid-unknown.md:25, auth-token-rotation-failure.md:29 없는 JWKS 손잡이;… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B7 runbook 신호 +- 내용: auth runbook(R2-4와 같은 원인): auth-claim-mapping-failed.md:20 토큰 payload, auth-token-malformed.md:20 Authorization 원문, auth-token-missing.md:20 — 금지 값; auth-kid-unknown.md:25, auth-token-rotation-failure.md:29 없는 JWKS 손잡이; auth-token-rotation-failure.md:16,33,64 없는 경보·지표; auth-issuer-mismatch.md:20 키 이름(app.security.issuer-uri / APP_SECURITY_JWT_ISSUER). + +### RR9-02-25 · Low · `WebSocketConfig.java:93` 주석 틀림(거부 preSend… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B6a 로그 내용 +- 내용: `WebSocketConfig.java:93` 주석 틀림(거부 preSend WebSocketInboundAuthorizationInterceptor.java:49, request_id는 beforeHandle WebSocketCorrelationInterceptor.java:34), 플랫폼 거부 로그 없음, Spring StompSubProtocolHandler가 거부 SEND만 ERROR, SUBSCRIBE 흔적 없음(A8). 고침: 거부 WARN, Spring 로거 레벨, 주석. + +### RR9-02-26 · Low · 컨텍스트 속성만 바꿈, logback-spring.xml:89,122 ${APP_PROFILE}은 이미 치환 → JSON profile 칸… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B6a 로그 내용 +- 내용: `ResolvedProfileLoggingContextListener.java:56` — 컨텍스트 속성만 바꿈, logback-spring.xml:89,122 ${APP_PROFILE}은 이미 치환 → JSON profile 칸 그대로, LogProfileDriftCharacterizationTest:38 속성만. 구조적 위험. + +### RR9-02-27 · Low · in-process lock 미계량 → lock.acquisition 0, metrics.yaml:307 "1:1",… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B5 관측 registry +- 내용: `DistributedLockPersistenceConfig.java:48-50` — in-process lock 미계량 → lock.acquisition 0, metrics.yaml:307 "1:1", persistence-jpa README:563-564 "호출마다". + +### RR9-02-28 · Low · "서버 허용 목록 이름이라 echo 안전"인데 요청 값 echo(PatchFieldAuthorization.java:59,… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B4 인증·인가 +- 내용: `PatchAuthorizationException.java:15,25` — "서버 허용 목록 이름이라 echo 안전"인데 요청 값 echo(PatchFieldAuthorization.java:59, JsonPointerAuthorization.java:76) → details·메시지. + +### RR9-02-29 · Low · tenant 규칙 갈림: WebTenantContextResolver.java:19-20 거부 목록에 tenant_id 없음,… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B4 인증·인가 +- 내용: tenant 규칙 갈림: WebTenantContextResolver.java:19-20 거부 목록에 tenant_id 없음, GraphQlTenantIsolationPolicy.java:59 호출자 목록·대소문자, :41 source()==null 죽은 코드, 익명에 SYSTEM tenant(GraphQlRequestContextConfiguration.java:128, TenantContext.java:25), GraphQlContextPropagator.java:14 "모든 스레드 이동" 호출 0. + +### RR9-02-30 · Low · `compose/redis/acl/README.md:43` advanced 계정 pub/sub 더함, 실제… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B19 compose·Docker 운영 +- 내용: `compose/redis/acl/README.md:43` advanced 계정 pub/sub 더함, 실제 application-advanced.acl:1에 @pubsub 없음, redis-sdk README:58 "pub/sub 없음". + +### RR9-02-31 · Low · `GraphQlClientPolicy.java:24` maxInputListElements "한 input list 상한"인데… + +- 출처: 물결 2 보안·관측 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B11b graphql·websocket 계약 +- 내용: `GraphQlClientPolicy.java:24` maxInputListElements "한 input list 상한"인데 variables·extensions만(GraphQlJsonStructurePolicy.java:54). diff --git a/docs/reviews/2026-11-12-round9-review/03-contract-testing.md b/docs/reviews/2026-11-12-round9-review/03-contract-testing.md new file mode 100644 index 00000000..42394306 --- /dev/null +++ b/docs/reviews/2026-11-12-round9-review/03-contract-testing.md @@ -0,0 +1,207 @@ +# round9 영역 03 — API 계약·시험 + +- 대상: main `a7e38c10`(2026-11-12). 범위와 방법은 [README](README.md) 「범위」다. +- 발견마다: 출처(리뷰어), 증거 수준, 이전부터/최근 변경, 고칠 묶음(README 「묶음」). 원문의 `파일:줄`은 저장소 루트 기준이다. + +### RR9-03-01 · Medium · 부분 실패 batch가 success:true + data.results. fullySucceeded() 미사용. 약속 충돌: web… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B12 fileserver·notification HTTP +- 내용: web-fileserver `FileUploadController.java:128-136`, `dto/BatchUploadResponse.java:18` — 부분 실패 batch가 success:true + data.results. fullySucceeded() 미사용. 약속 충돌: web AGENTS B8·docs/web/http-contract.md:29(success:false+BATCH_PARTIAL_FAILURE) vs docs/fileserver/http-contract.md:12,100·upgrade-guide:65(200+results[].error). → 소유자 결정 필요(약속끼리 다름). 이전부터. + +### RR9-03-02 · Medium · partial() error.message 영어 고정, BulkItemResult 호출자 문구 그대로·null 키 남김(mix-in 아님,… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B12 fileserver·notification HTTP +- 내용: shared-contract `response/BulkEnvelope.java:28`, `BulkItemResult.java:13-21` — partial() error.message 영어 고정, BulkItemResult 호출자 문구 그대로·null 키 남김(mix-in 아님, EnvelopeWireFormatConfig.java:34-37). 근거 http-contract.md:44, error-codes.yaml:15-16(ClientErrorMessages). 고침: ClientErrorMessages.of(BATCH_PARTIAL_FAILURE), 항목 message 정리, mix-in. 이전부터. + +### RR9-03-03 · Medium · 실제 long maxAgeSeconds(CorsSettings.java:19-20, config/security.yml:54) → 예시 그대로… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B2 env 계약 +- 내용: `.env.example:79` APP_SECURITY_CORS_MAX_AGE=600s, env-keys.yaml:941-948(duration, 600s) — 실제 long maxAgeSeconds(CorsSettings.java:19-20, config/security.yml:54) → 예시 그대로 쓰면 기동 실패. 고침: int(초)·600. 이전부터. + +### RR9-03-04 · Medium · env-keys.yaml:2563-2577·2670-2684… + +- 출처: 물결 1 API 계약·시험(같은 결함을 물결 2 outbound도 적음) +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B2 env 계약 +- 내용: env-keys.yaml:2563-2577·2670-2684 APP_CACHE_REDIS_COMMAND_TIMEOUT·SEMANTIC_REGION "닿지 않음, 2026-11-30 제거"인데 cache-redis.yml:32,35 바인딩(기본 200ms vs registry 2s). 기본값 불일치: APP_RATE_LIMIT_REDIS_COMMAND_TIMEOUT 1s/200ms(cache-redis.yml:69), APP_LOG_LEVEL_SQL WARN/INFO(observability.yml:117), APP_CACHE_REDIS_POSITIVE_SOFT_TTL null/30s(cache-redis.yml:36). 이전부터. + +### RR9-03-05 · Medium · docs/registries/headers.yaml:16,154 X-Request-Id·X-Correlation-Id type ulid(코드… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B5 관측 registry +- 내용: docs/registries/headers.yaml:16,154 X-Request-Id·X-Correlation-Id type ulid(코드 UUID, WebMvcRequestIdFilter.java:159,163,191; correlation [A-Za-z0-9._-]{1,128}). ETag·Location·Allow·Cache-Control·Vary·Content-Range·tus·Upload-* 행 없음. web README.md:487-490 "코드 미러, 맞추는 시험 있음", 없는 X-Api-Version "여기서 생산". HeaderRegistryRuntimeAlignmentTest 행 3개만. 고침: 타입·행·ApiHeaders 대조 시험. 이전부터. + +### RR9-03-06 · Medium · 서버 포화를 전송마다 다른 코드: gRPC GrpcCallAdmission.java:82-83 RATE_LIMIT_EXCEEDED("요청이… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B13 전송 오류 코드 +- 내용: 서버 포화를 전송마다 다른 코드: gRPC GrpcCallAdmission.java:82-83 RATE_LIMIT_EXCEEDED("요청이 너무 잦습니다"), web-advanced WebAdvancedError.java:23 ADMISSION_REFUSED 503, fileserver FileserverErrorCode.java:45 429 RATE_LIMIT, 공용 OperationalError.java:81 JOB_EXECUTOR_REJECTED. decisions 2.3 행 없음 → 소유자 결정(wire 바뀜). 이전부터. + +### RR9-03-07 · Medium · 27개 중 23개 계약 문서에 없음, docs/fileserver/http-contract.md:79 예시 "data":… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B12 fileserver·notification HTTP +- 내용: application/fileserver `api/error/FileserverErrorCode.java` — 27개 중 23개 계약 문서에 없음, docs/fileserver/http-contract.md:79 예시 "data": null(NON_NULL 결정과 다름). 고침: 코드 표 + 예시. 이전부터. + +### RR9-03-08 · Medium · grpc README.md:26-28 "전용 APP_* 키 registry에 없다"인데 APP_GRPC_SERVER_ENABLED… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B2 env 계약 +- 내용: grpc README.md:26-28 "전용 APP_* 키 registry에 없다"인데 APP_GRPC_SERVER_ENABLED 등록(env-keys.yaml:4059). APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL registry·.env.example 없음. 이전부터. + +### RR9-03-09 · Medium · Content-Range(MvcDownloadResponseWriter.java:43,… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B12 fileserver·notification HTTP +- 내용: FileserverHttpSurfaceConfiguration.java:43-56, http-contract.md:178-180 — Content-Range(MvcDownloadResponseWriter.java:43, FileserverProblemHeaders.java:55) 노출 헤더 목록 없음 → CORS 이어받기 못 함. 이전부터. + +### RR9-03-10 · Low · MANAGEMENT_SERVER_ADDRESS registry 있음·.env.example 없음(R2-1 일부). 최근(#12). + +- 출처: 물결 1 API 계약·시험(같은 결함을 물결 2 계약·문서도 적음) +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B2 env 계약 +- 내용: observability.yml:34, .env.example:22 — MANAGEMENT_SERVER_ADDRESS registry 있음·.env.example 없음(R2-1 일부). 최근(#12). + +### RR9-03-11 · Low · OPERATION_NOT_FOUND(operation/OperationErrorCode.java) §4에 없음(decisions 2.3 「새… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B13 전송 오류 코드 +- 내용: docs/web/http-contract.md:184-193 — OPERATION_NOT_FOUND(operation/OperationErrorCode.java) §4에 없음(decisions 2.3 「새 오류 코드 소유」). 이전부터. + +### RR9-03-12 · Low · 모든 503이 REQUEST_TIMEOUT(retryable). §4는 비동기 시간 초과에만. 이전부터. + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B13 전송 오류 코드 +- 내용: web `error/HttpStatusErrorCodes.java:31` — 모든 503이 REQUEST_TIMEOUT(retryable). §4는 비동기 시간 초과에만. 이전부터. + +### RR9-03-13 · Low · 모르는 channel·slot·locale이 details 없는 BAD_PARAMETER(주석은 validation error, S4는… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B12 fileserver·notification HTTP +- 내용: NotificationSubmissionController.java:98-104,114-121, NotificationTemplateController.java:85,119-131 — 모르는 channel·slot·locale이 details 없는 BAD_PARAMETER(주석은 validation error, S4는 VALIDATION_FAILED), 201에 Location 없음, 경로 /notification-templates lowerCamel 아님(manual 11:37). 이전부터. + +### RR9-03-14 · Low · ERROR frame code만(category·retryable 없음), 원인 사슬 어디 IAE든 BAD_PARAMETER(다른 전송은 실패… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B11b graphql·websocket 계약 +- 내용: websocket `SafeStompSubProtocolErrorHandler.java:51-58,62-67` — ERROR frame code만(category·retryable 없음), 원인 사슬 어디 IAE든 BAD_PARAMETER(다른 전송은 실패 자신만), Javadoc:16-17 "다른 전송과 같은 코드". 이전부터. + +### RR9-03-15 · Low · Retry-After를 occurrence만 보고 붙임, 본문은 코드 값으로 좁힘(ErrorResponseFactory.java:42) →… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B12 fileserver·notification HTTP +- 내용: FileserverProblemHeaders.java:51 — Retry-After를 occurrence만 보고 붙임, 본문은 코드 값으로 좁힘(ErrorResponseFactory.java:42) → ATOMIC_PUBLISH_UNSUPPORTED 행 어긋남. 이전부터. + +### RR9-03-16 · Low · 낡은 문서: GrpcStatusMapper.java:21 WORKLOG_NOT_FOUND 예시(ab5982e95 이후), graphql 스냅숏… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B13 전송 오류 코드 +- 내용: 낡은 문서: GrpcStatusMapper.java:21 WORKLOG_NOT_FOUND 예시(ab5982e95 이후), graphql 스냅숏 머리말 없는 spi 패키지(graphql/build.gradle:149). + +### RR9-03-17 · Medium · test에서 태그 없이 env-keys.yaml 읽음, modules.json 거슬러 ca.repository.root 가드 우회, 입력… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B16 시험 품질 +- 내용: GraphQlDeploymentModeRegistryParityTest.java:26-46 — test에서 태그 없이 env-keys.yaml 읽음, modules.json 거슬러 ca.repository.root 가드 우회, 입력 미선언 → 캐시가 registry 변경 놓침. 근거 build-logic/AGENTS.md:14-17. 고침: document-contract로. 이전부터. + +### RR9-03-18 · Medium · "값을 싣지 않는다" 단언에 예외 타입 없음 → 메시지 null NPE로 바꿔도 통과. 이전부터. + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B16 시험 품질 +- 내용: WebSecurityContextBridgeTest.java:39-43, GraphQlScalarContractTest.java:83-89, GraphQlScalarSymmetryTest.java:80-85 — "값을 싣지 않는다" 단언에 예외 타입 없음 → 메시지 null NPE로 바꿔도 통과. 이전부터. + +### RR9-03-19 · Low · 빈 목록이면 통과, GWT 없음. 고침: 메서드 목록 고정. 최근(#12 bb8bb31b9). + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B16 시험 품질 +- 내용: FileserverAdminControllerRequestBodyValidationTest.java:27-41 — 빈 목록이면 통과, GWT 없음. 고침: 메서드 목록 고정. 최근(#12 bb8bb31b9). + +### RR9-03-20 · Low · MvcUploadExecutorSaturationTest.java:112-121(이름 timeout인데 타입만), :45 sleep(200),… + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B16 시험 품질 +- 내용: MvcUploadExecutorSaturationTest.java:112-121(이름 timeout인데 타입만), :45 sleep(200), GraphQlRequestDeadlineTest.java:101-104 sleep(500) 뒤 부재 단언. 이전부터. + +### RR9-03-21 · Low · EnvelopeWireShapeTest + +- 출처: 물결 1 API 계약·시험 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B16 시험 품질 +- 내용: EnvelopeWireShapeTest — http-contract.md:9가 §1 증거로 대는데 data null 키 없음(:32), String→Envelope(:33), sort:null(:55), 부분 실패 message 안 봄. EnvelopeTest.java:34 when 둘. 이전부터. + +### RR9-03-22 · Low · 영어 @DisplayName 381/940, // when 없는 3문장+ 테스트 약 890/1550(휴리스틱). 규칙은 "손댈 때 고침" →… + +- 출처: 물결 1 API 계약·시험(같은 결함을 물결 2 arch-reviewer도 적음) +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B16 시험 품질 +- 내용: 영어 @DisplayName 381/940, // when 없는 3문장+ 테스트 약 890/1550(휴리스틱). 규칙은 "손댈 때 고침" → 일괄 전환은 소유자 결정. 표 입력 반복문·when 둘: WebSecurityContextBridgeTest.everySpelling…, HmacGraphQlCursorCodecTest:232, GraphQlMutationResultMapperTest:44. + +### RR9-03-23 · Medium · web-advanced patch 위반이 세 코드(PATCH_REJECTED 400 / BAD_PARAMETER 400 IAE /… + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B11a web-advanced 계약 +- 내용: web-advanced patch 위반이 세 코드(PATCH_REJECTED 400 / BAD_PARAMETER 400 IAE / PATCH_PATH_FORBIDDEN 403), 비JSON 본문 → readTree JacksonException → GlobalExceptionHandler.java:207 500 INTERNAL_ERROR. JsonPatchDocument.java:151-155,175, JsonPatchOperation.java:28-53, JsonMergePatchDocument.java:55-62,92, JsonPointerAuthorization.java:128-130. 근거 WebAdvancedError.java:26, README:61. 고침: JsonPatchRejectedException 통일 + 파싱 감쌈 + upgrade 행. + +### RR9-03-24 · Medium · "결과를 문서 전체로 검증 후 적용" 약속, 검증기 안 받음. + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B11a web-advanced 계약 +- 내용: JsonMergePatchApplier.java:42-44, JsonPatchApplier.java:14-16, patch-contract.md:43-44,62-64 — "결과를 문서 전체로 검증 후 적용" 약속, 검증기 안 받음. + +### RR9-03-25 · Medium · sequence 엄격 증가·heartbeat·idle·max-age·버퍼 상한·drain 재연결 약속, writer 아무것도 안… + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B11a web-advanced 계약 +- 내용: streaming-contract.md:25,58-62,66-67,71-72 vs MvcStreamWriter.java:52-77 — sequence 엄격 증가·heartbeat·idle·max-age·버퍼 상한·drain 재연결 약속, writer 아무것도 안 함(GapAndDuplicateGuard·WebStreamSession·WebStreamDrainCoordinator main에 없음, IDLE_TIMEOUT·MAX_AGE 안 냄). + +### RR9-03-26 · Medium · commit 뒤 실패 코드 DEPENDENCY_FAILURE 고정(registry·WebAdvancedError·§4 없음),… + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B11a web-advanced 계약 +- 내용: MvcStreamWriter.java:97-100 — commit 뒤 실패 코드 DEPENDENCY_FAILURE 고정(registry·WebAdvancedError·§4 없음), StreamItemTooLargeException(README:67)·carrier 코드 버림. + +### RR9-03-27 · Medium · 503+Retry-After 약속, guard bean만, 요청 경로에서 run 안 부름(manual 10 기준 3). + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B11a web-advanced 계약 +- 내용: virtual-thread-profile.md:16-17,36-40, advanced-capabilities.md:13 vs VirtualThreadMvcConfiguration.java:53-58 — 503+Retry-After 약속, guard bean만, 요청 경로에서 run 안 부름(manual 10 기준 3). + +### RR9-03-28 · Medium · 정본 충돌 → 소유자 결정. + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B11a web-advanced 계약 +- 내용: web AGENTS.md:65 B2 "merge-patch+json 안 씀" vs patch-contract.md:22 "필드 변경은 merge patch" — 정본 충돌 → 소유자 결정. + +### RR9-03-29 · Medium · Javadoc "Stable request-error code GRAPHQL_CURSOR_REJECTED"인데 플랫폼 거부·carrier 아님… + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B11b graphql·websocket 계약 +- 내용: GraphQlCursorException.java:10-15, GraphQlConnectionException.java:8-13 — Javadoc "Stable request-error code GRAPHQL_CURSOR_REJECTED"인데 플랫폼 거부·carrier 아님 → resolver 안에서 INTERNAL_ERROR+ERROR(GraphQlErrorCodeCatalogTest:58-61). diff --git a/docs/reviews/2026-11-12-round9-review/04-build-docs.md b/docs/reviews/2026-11-12-round9-review/04-build-docs.md new file mode 100644 index 00000000..3a263304 --- /dev/null +++ b/docs/reviews/2026-11-12-round9-review/04-build-docs.md @@ -0,0 +1,298 @@ +# round9 영역 04 — 빌드·문서 + +- 대상: main `a7e38c10`(2026-11-12). 범위와 방법은 [README](README.md) 「범위」다. +- 발견마다: 출처(리뷰어), 증거 수준, 이전부터/최근 변경, 고칠 묶음(README 「묶음」). 원문의 `파일:줄`은 저장소 루트 기준이다. + +### RR9-04-01 · Medium · #12가 줄 더해 151/150, check-work-docs rc=1 → verify.sh docs·라운드 끝 실패. 같은 줄 "(W4… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · E2(실행) · 최근 변경 +- 묶음: B1 문서·지침 +- 내용: `docs/work/operate.md:120` — #12가 줄 더해 151/150, check-work-docs rc=1 → verify.sh docs·라운드 끝 실패. 같은 줄 "(W4 BE-OBS-A)" 묶음 ID(docs/work 금지), --history가 못 잡음. 고침: 문장 옮기고 ID 삭제, `W\d BE-` 패턴 검사에. E2. 최근 #12(1444d1e0). + +### RR9-04-02 · Medium · `cd ~/workspace/<작업>/src` 뒤 ./gradlew(#10 뒤 src에 gradlew 없음). desktop-gates… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B1 문서·지침 +- 내용: `docs/work/operate.md:57,87` — `cd ~/workspace/<작업>/src` 뒤 ./gradlew(#10 뒤 src에 gradlew 없음). desktop-gates 6단계가 이 절차로 보냄. 최근 #10. + +### RR9-04-03 · Medium · "Gradle 루트가 src/라 두 단계 위", `--include-build ../../messaging-library` →… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B1 문서·지침 +- 내용: `docs/work/reference/related-repos.md:19,22` — "Gradle 루트가 src/라 두 단계 위", `--include-build ../../messaging-library` → `../messaging-library`. 최근 #10. + +### RR9-04-04 · Medium · 이름 바꾸기 `git grep -l 'dev\.caskeleton' -- src scripts`가 build.gradle:26,… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B18a 스크립트 +- 내용: `README.md:122` — 이름 바꾸기 `git grep -l 'dev\.caskeleton' -- src scripts`가 build.gradle:26, JavaConventionsPlugin.java:67, config/spotbugs/exclude.xml(69줄)·exclude-test.xml(8줄) 놓침 → qualityCheck 실패. 고침: pathspec 넓힘. 최근 #10. + +### RR9-04-05 · Medium · 없는 PublicPathSnapshotPlugin.java·updatePublicPathSnapshot, 없는 CI step. 고침:… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B3 공개 경로·관리 포트 +- 내용: `docs/build.md:156,160,169` — 없는 PublicPathSnapshotPlugin.java·updatePublicPathSnapshot, 없는 CI step. 고침: `./gradlew verifyPublicPathSnapshot -PapprovePublicPathChange`. 이전부터. (R2-3·R3-7 문서 부분과 같은 자리) + +### RR9-04-06 · Medium · `:app-bootstrap:test --tests '*CleanArchitectureTest'` 고르는 클래스… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B17 빌드 +- 내용: `scripts/verify-mongodb-platform.sh:130` — `:app-bootstrap:test --tests '*CleanArchitectureTest'` 고르는 클래스 없음(architectureTest source set) → 항상 FAILED. persistence-mongo/AGENTS.md:155·docs/mongodb/repository-adaptation.md:123가 시킴. :156 태그 증거. 고침: :app-bootstrap:architectureTest, 이미지는 카탈로그 mongo-8. 이전부터. + +### RR9-04-07 · Medium · `docs/work/experts.md:56-66` 3절 표가 스킬 paths와 갈림(be-build-ci… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B1 문서·지침 +- 내용: `docs/work/experts.md:56-66` 3절 표가 스킬 paths와 갈림(be-build-ci settings.gradle·gradle.properties·Dockerfile·renovate.json, be-api-contract .env.example·docs/upgrade/**, be-security .trivyignore.yaml, be-testing docs/testing/**·container-images.properties, be-observability docs/runbooks/**, be-persistence docs/jpa/**·docs/mongodb/**, be-docs **/CLAUDE.md). test_claude_setup.py:158 이름만. 고침: 표가 paths 가리키게 or 대조 시험. 최근 #14(c611b06f). + +### RR9-04-08 · Medium · 행이 코드와 다르고 「바뀜」 표시 없음: 64 docs-check workflow 없음, 193 build-logic 잠그지 않음 vs… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B1 문서·지침 +- 내용: `docs/work/reference/decisions.md:64,193,194,199` — 행이 코드와 다르고 「바뀜」 표시 없음: 64 docs-check workflow 없음, 193 build-logic 잠그지 않음 vs build-logic/build.gradle:35-38 STRICT, 194 cosign keyless vs release.yml:8-11 키 쌍(11-07), 199 cd 따라감 vs 11-08 형식 검사 셸 거절(StrictLaneStagesPlugin.java:46-48). 193 이전부터, 나머지 최근 #7. + +### RR9-04-09 · Medium · 단계 구성표 네 곳: docs/testing/TESTING_STRATEGY.md:146-148(틀림,… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B18b 문서 본문 +- 내용: 단계 구성표 네 곳: docs/testing/TESTING_STRATEGY.md:146-148(틀림, build.gradle:175-181,269-274), docs/build.md:28,34(testQualityCheck·verifyFeatureScaffold·graphqlStableTest 빠짐), gates.md:42, build.gradle:62-85 주석. 고침: gates.md 1절만 남기고 가리킴. 이전부터. + +### RR9-04-10 · Medium · 33·36 지운… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B18b 문서 본문 +- 내용: `docs/capability-status.md:16,33,35,36` — 33·36 지운 redis-sdk-topology.yml·notification-platform.yml·verifyNotificationEvidence, 35 relay가 app-bootstrap OutboxConfig(지금 :composition:outbox-relay, 같은 문서 :439), 없는 lane postgresqlLegacyOutboxConcurrentRelayIntegrationTest. HISTORY_HOLDERS라 reference 검사 안 봄. 최근 #7·이전부터. + +### RR9-04-11 · Medium · nightly jpa-postgresql·release jpa-release-gate. 고침: digest. 이전부터. + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B17 빌드 +- 내용: `gradle/container-images.properties:27-30` postgres-17·18 태그만(머리말 :8, gates.md:193, 함정 12와 다름) — nightly jpa-postgresql·release jpa-release-gate. 고침: digest. 이전부터. + +### RR9-04-12 · Medium · 모든 ca.spring-library leaf(30) testImplementation에… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B17 빌드 +- 내용: build-logic `SpringLibraryConventionPlugin.java:12-15` — 모든 ca.spring-library leaf(30) testImplementation에 spring-boot-starter-webmvc-test(Tomcat 포함), MockMvc 쓰는 leaf 5개. 예 identifier/gradle.lockfile:68-131, Tomcat 테스트 classpath lockfile 14개. 고침: 쓰는 leaf만. 이전부터(60b6a319). + +### RR9-04-13 · Low · `gradle/libs.versions.toml` 미사용 칸: 120 errorprone-core, 121 findsecbugs-plugin,… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B17 빌드 +- 내용: `gradle/libs.versions.toml` 미사용 칸: 120 errorprone-core, 121 findsecbugs-plugin, 123 jackson3-core, 125·126 jmh, 130 junit-platform-launcher(+70), 142 protobuf-java-legacy(+91 주석), 148·149 spock(+97-98, 머리말 12-18), 플러그인 174-177 spring-dependency-management·spotless·spotbugs·errorprone(루트 미적용 build.gradle:5-9), 167-170 주석의 libs.errorprone.core. 이전부터. + +### RR9-04-14 · Low · "쓰는 lane만 다시 돈다"인데 JavaConventionsPlugin.java:279-288이 파일 전체를 모든 leaf 모든 Test… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B17 빌드 +- 내용: `gradle/container-images.properties:3-5` — "쓰는 lane만 다시 돈다"인데 JavaConventionsPlugin.java:279-288이 파일 전체를 모든 leaf 모든 Test 입력으로 → 이미지 하나 바꿔도 domain-core 캐시 무효. postgres-16-4(:24-26) 미사용. 이전부터. + +### RR9-04-15 · Low · 없는 클래스… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B17 빌드 +- 내용: `config/spotbugs/exclude.xml:62-70` — 없는 클래스 ...bootstrap.autoconfigure.notification.observation.NotificationObservationTest, exclude-test.xml:102-109에 이미 있음. 이전부터. + +### RR9-04-16 · Low · `src/adapter/outbound/notification/build.gradle:104` additionalSourceRoots 상대… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B17 빌드 +- 내용: `src/adapter/outbound/notification/build.gradle:104` additionalSourceRoots 상대 경로 `../../../application/notification/src/main/java`(함정 10), JavaPublicTypes.java:35-37 없는 폴더 말없이 건너뜀 → 승인 update 시 줄어든 surface 기록. 고침: project(':application-notification').file(...), 없으면 실패. 이전부터. + +### RR9-04-17 · Low · 검사 스크립트 정비: check-repo-layout.py:90-96 HISTORY_PREFIXES 없는 폴더… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B18a 스크립트 +- 내용: 검사 스크립트 정비: check-repo-layout.py:90-96 HISTORY_PREFIXES 없는 폴더 셋(superpowers·evidence·study), docs/history/·docs/design/ 빠짐; 머리 주석에 부르는 쪽 없음(check-repo-layout, check-docs, check-work-docs, verify-httpclient-docs, verify-compose-profile-contracts); scripts/tests 시험 없음(check-repo-layout, check-review-index, verify-httpclient-docs). 이전부터·#10. + +### RR9-04-18 · Low · docstring 낡음: check-docs.py:2,18,41 "검사 여섯"(여덟), check-work-docs.py:31 lychee… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B18a 스크립트 +- 내용: docstring 낡음: check-docs.py:2,18,41 "검사 여섯"(여덟), check-work-docs.py:31 lychee "PR workflow"(main). 이전부터·#7. + +### RR9-04-19 · Low · `docs/README.md:187` "PR마다 workflow docs-check" → pr.yml done → :prCheck →… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B1 문서·지침 +- 내용: `docs/README.md:187` "PR마다 workflow docs-check" → pr.yml done → :prCheck → documentCheck. 최근 #7. + +### RR9-04-20 · Low · 기본 조립: docs/build.md:50-56·scripts/bootstrap-local.sh:12-14,42 "app 기동(Flyway… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B18b 문서 본문 +- 내용: 기본 조립: docs/build.md:50-56·scripts/bootstrap-local.sh:12-14,42 "app 기동(Flyway 포함)"(기본 web만, build.md:254), build.md:279 알림 키 "8종"(7개). 이전부터. + +### RR9-04-21 · Low · `docs/roadmap/messaging-r2.md:45,48` 지운… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B18b 문서 본문 +- 내용: `docs/roadmap/messaging-r2.md:45,48` 지운 VerifyMessagingEvidenceTask·MessagingQualificationPlugin. 이전부터. + +### RR9-04-22 · Low · #13이 합친 integration job을 가리킴: cache-redis/README.md:332,… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B18b 문서 본문 +- 내용: #13이 합친 integration job을 가리킴: cache-redis/README.md:332, cache-redis/build.gradle:74, httpclient/build.gradle:233. 최근 #13. + +### RR9-04-23 · Low · bootstrap-local.sh를 flock으로 직접(:33 ./gradlew --no-daemon 없음), "4.1절의 정리법"… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B1 문서·지침 +- 내용: `.claude/agents/verify-api.md:21,23` — bootstrap-local.sh를 flock으로 직접(:33 ./gradlew --no-daemon 없음), "4.1절의 정리법" operate.md에 없음. 고침: scripts/verify.sh app --on here. 최근 c67c7131. + +### RR9-04-24 · Low · `CLAUDE.md:8` "분야 지식 be-* 10개" 개수 복사(함정 6). 최근 #14. + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B1 문서·지침 +- 내용: `CLAUDE.md:8` "분야 지식 be-* 10개" 개수 복사(함정 6). 최근 #14. + +### RR9-04-25 · Low · `renovate.json:9,17` "either bot"·GitHub vulnerability alerts 전제, Gitea에서… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B18b 문서 본문 +- 내용: `renovate.json:9,17` "either bot"·GitHub vulnerability alerts 전제, Gitea에서 Renovate 근거 없음, .github/dependency-vulnerability-policy.md:7,95 정책 수단으로 듦. 최근 #7. + +### RR9-04-26 · Low · `scripts/run-compose-runtime-smoke.sh:388` lane마다 정적 계약 전체 재실행(compose config… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B18a 스크립트 +- 내용: `scripts/run-compose-runtime-smoke.sh:388` lane마다 정적 계약 전체 재실행(compose config ~650회/nightly), PR이 verifyComposeProfiles로 이미 함. 고침: 루프 전 한 번. 이전부터. + +### RR9-04-27 · Low · handoff --force-recreate가 1단계 재시작 수 지움, ps -a -q 빈 결과면 restarts.txt 비고 || true로… + +- 출처: 물결 1 빌드·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B18a 스크립트 +- 내용: `run-compose-runtime-smoke.sh:533-537,602-606` — handoff --force-recreate가 1단계 재시작 수 지움, ps -a -q 빈 결과면 restarts.txt 비고 || true로 통과. 최근 50cd7154. + +### RR9-04-28 · Medium · graphql AGENTS·README가 「모듈별 yml 금지」라 하지만 모듈이 config/graphql.yml을 읽는다 + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B18b 문서 본문 +- 내용: graphql AGENTS.md:116, README.md:126,152,166-168 — "모듈별 yml 금지·없음"인데 config/graphql.yml 직접 읽음(GraphQlActivationEnvironmentPostProcessor:55, manual 10:67 예외), app.graphql.console.*, 지운 "execution profile". + +### RR9-04-29 · Medium · `.env.example`의 APP_DATASOURCE_CONNECTION_TIMEOUT=5s는 registry가 기동 실패라 적은 값이다 + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B2 env 계약 +- 내용: .env.example:45 APP_DATASOURCE_CONNECTION_TIMEOUT=5s(registry가 기동 실패라 적은 값) — B2 묶음. + +### RR9-04-30 · Medium · `.env.example`의 FORWARD_HEADERS_STRATEGY=native가 registry 기본 none과 다르다 + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B2 env 계약 +- 내용: .env.example:25 FORWARD_HEADERS_STRATEGY=native — registry 기본 none·"기본은 닫힘"(env-keys.yaml:135-140). 고침: 비우거나 none. — B2 묶음(기존 안은 example: native였음 → 리뷰어는 none 권함). + +### RR9-04-31 · Low · `.env.example` 머리말 「Seven values」가 여섯만 나열하고, 폐기 키 48개에 값이 들어 있다 + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B2 env 계약 +- 내용: .env.example:12-15 "Seven values" 여섯, deprecated 48개 — B2 묶음. + +### RR9-04-32 · Medium · cache-redis README가 운영 비밀로 폐기 키 넷을 넣으라고 한다 + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B2 env 계약 +- 내용: cache-redis/README.md:49-50 운영 비밀로 deprecated_orphaned 키 넷(APP_CACHE_REDIS_PASSWORD·_KEY_HMAC_SECRET, APP_IDEMPOTENCY_/LEASE_REDIS_KEY_HMAC_SECRET). 고침: APP_REDIS_AUTHENTICATION_*. + +### RR9-04-33 · Medium · 지식 스킬 넷이 재배치 뒤에도 「명령은 src/에서」라고 한다 + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B1 문서·지침 +- 내용: 스킬 넷 "명령은 src/에서" — PR #16에서 고침(2249d442). + +### RR9-04-34 · Low · docs/web/runbook.md:37,49,56-58 TTL "연산마다"(전역 APP_IDEMPOTENCY_TTL),… + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B7 runbook 신호 +- 내용: docs/web/runbook.md:37,49,56-58 TTL "연산마다"(전역 APP_IDEMPOTENCY_TTL), GracefulShutdownProbe(testFixtures)를 운영 장치로, routeTemplate tag 없음. + +### RR9-04-35 · Low · docs/web/repository-adaptation.md:146-162 "앱은 애플리케이션 칸 강제 안 함" vs… + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B18c 낡은 이름·leaf 안내 +- 내용: docs/web/repository-adaptation.md:146-162 "앱은 애플리케이션 칸 강제 안 함" vs app.web.mvc.max-json-body-size 1MB 413(WebMvcPlatformSettings.java:31). + +### RR9-04-36 · Low · openapi-32-compatibility.md가 아무도 만들지 않는 3.1.2 산출물·snapshot 불변식을 적는다 + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B18c 낡은 이름·leaf 안내 +- 내용: docs/web/openapi-32-compatibility.md:10,14,26 "3.1.2 릴리스 산출물", "3.1 snapshot" 불변식 — 만드는·대조하는 build 없음(샘플 삭제 뒤). + +### RR9-04-37 · Low · 없는 metric·행 가리키는 runbook: authz-cross-tenant-violation.md:38,67,… + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B7 runbook 신호 +- 내용: 없는 metric·행 가리키는 runbook: authz-cross-tenant-violation.md:38,67, rate-limit-exceeded.md:38,68(gateway_rate_limit_*, 헤더 X-RateLimit-Remaining), dependency-unavailable.md:75(CACHE_UNAVAILABLE). + +### RR9-04-38 · Low · 옮기거나 바꾼 타입: persistence-jpa/README.md:43 OutboxConfig,… + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B18c 낡은 이름·leaf 안내 +- 내용: 옮기거나 바꾼 타입: persistence-jpa/README.md:43 OutboxConfig, :220·application/core/README.md:287 IdempotencyProviderSelectionConfig→IdempotencyAutoConfiguration, docs/build.md:413 TracingProperties→TracingSettings, bootstrap/app/README.md:88 SecretSource→SecretSourcePort, web/README.md:472 JsonNullableModule, graphql AGENTS.md:104·README.md:130 GraphQlPlatformProperties→Settings, web/AGENTS.md:139 PeriodTest, application/core/AGENTS.md:80 OutboxEventIdFactory. + +### RR9-04-39 · Low · 지운 샘플: defect-patterns.md:68 SampleDemoProfilesStartupSystemTest,… + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B18c 낡은 이름·leaf 안내 +- 내용: 지운 샘플: defect-patterns.md:68 SampleDemoProfilesStartupSystemTest, TESTING_STRATEGY.md:292, IdempotencyAutoConfiguration.java:24, ManagementSecurityConfig.java:35 Javadoc. + +### RR9-04-40 · Low · graphql AGENTS.md:23-33·README.md:186 "messaging leaf registry 등록, 두 패턴… + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B18c 낡은 이름·leaf 안내 +- 내용: graphql AGENTS.md:23-33·README.md:186 "messaging leaf registry 등록, 두 패턴 공존"(#8), grpc AGENTS.md:44-45·README.md:62 "vendored 플랫폼 starter"(#6), docs/websocket/runbook.md:5·defect-patterns.md:20 leaf CLAUDE.md(지금 AGENTS.md). + +### RR9-04-41 · Low · graphql AGENTS.md:19·README.md:183 "366개 java 파일"(246), AGENTS.md:160 "23… + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B18c 낡은 이름·leaf 안내 +- 내용: graphql AGENTS.md:19·README.md:183 "366개 java 파일"(246), AGENTS.md:160 "23 tests"(34), manual 06:58 registry 머리말 옛 영어 인용. + +### RR9-04-42 · Low · leaf 안내 공백: application-notification·-fileserver·-objectstorage 가장 가까운 AGENTS가… + +- 출처: 물결 2 계약·문서 +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 최근 변경 +- 묶음: B18c 낡은 이름·leaf 안내 +- 내용: leaf 안내 공백: application-notification·-fileserver·-objectstorage 가장 가까운 AGENTS가 루트뿐·README 없음, web-notification·web-fileserver·redis-runtime 자기 AGENTS·README 없음, docs/README.md 지도 security/ 행이 rate-limiting.md 안 덮음(#12). diff --git a/docs/reviews/2026-11-12-round9-review/05-architecture-domain.md b/docs/reviews/2026-11-12-round9-review/05-architecture-domain.md new file mode 100644 index 00000000..ed46d6b8 --- /dev/null +++ b/docs/reviews/2026-11-12-round9-review/05-architecture-domain.md @@ -0,0 +1,137 @@ +# round9 영역 05 — 계층·도메인·SRP + +- 대상: main `a7e38c10`(2026-11-12). 범위와 방법은 [README](README.md) 「범위」다. +- 발견마다: 출처(리뷰어), 증거 수준, 이전부터/최근 변경, 고칠 묶음(README 「묶음」). 원문의 `파일:줄`은 저장소 루트 기준이다. + +### RR9-05-01 · High · controller가 domain `Repository` 포트를 주입해도 안 걸림(HARD-STOP 2). 생성 명령이… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B14 아키텍처 규칙 +- 내용: architectureTest `AdapterBoundaryArchitectureTest.java:410-421`, `WebForbiddenTypeCatalog.java:23` — controller가 domain `Repository` 포트를 주입해도 안 걸림(HARD-STOP 2). 생성 명령이 포트를 `dev.caskeleton.domain.`에 둠(Create__Feature__UseCase.java.tmpl:13), 규칙은 `..repository..`만, web testkit은 Spring Data·JPA만. gRPC 서비스는 ARE_CONTROLLERS 밖. 고침: inbound가 domain *Repository·*IdFactory, application *StorePort·*QueryPort 못 쓰게 + fixture. 현재 inbound import 0건. + +### RR9-05-02 · High · inbound 밖 사용자 전송(bootstrap·composition controller, JWT converter)이… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B14 아키텍처 규칙 +- 내용: `ApplicationBoundaryArchitectureTest.java:759-774,736-747,822-826` — inbound 밖 사용자 전송(bootstrap·composition controller, JWT converter)이 @SystemInvoked 유스케이스에 닿아도 통과, `new`·비@SystemCaller 중간 클래스 경유도 통과(OutboxRelayScheduler.java:51). manual 07:75 "빌드 실패" 약속. "bootstrap에 controller 금지"(app AGENTS) 규칙 없음. 고침: USER_TRANSPORTS 전이 대상에 @SystemInvoked, controller는 ..adapter.inbound.. 규칙. + +### RR9-05-03 · Medium · web 밖 JWT… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B14 아키텍처 규칙 +- 내용: (a) `ApplicationBoundaryArchitectureTest.java:472-494,523-558` — web 밖 JWT converter·JwtDecoder·OAuth2TokenValidator·AuthenticationProvider·AuthorizationManager·HttpSecurity 람다 설정 못 잡음(Filter·EntryPoint·AccessDeniedHandler·BearerTokenResolver는 잡힘). 고침: spring security web·oauth2 resource server·jwt 패키지와 두 타입을 목록에 + fixture. + +### RR9-05-04 · Medium · `registration.interceptors(x)`에서 x가 구체 클래스 필드·생성자·new, ChannelInterceptor 지역… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B14 아키텍처 규칙 +- 내용: (b) `:584-587,626-627` — `registration.interceptors(x)`에서 x가 구체 클래스 필드·생성자·new, ChannelInterceptor 지역 변수, 구체 반환 @Bean이면 설정 자신 안 잡힘(ArchUnit 1.3.0 anewarray 미기록). manual 07:107 과대 약속. 고침: assignable 검사 or 문서 한계. + +### RR9-05-05 · Medium · capabilityProjects에 :adapter:inbound:messaging 없음 → 전체 ArchUnit이… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B14 아키텍처 규칙 +- 내용: `src/bootstrap/app/build.gradle:131-143` — capabilityProjects에 :adapter:inbound:messaging 없음 → 전체 ArchUnit이 MessagingInboxAutoConfiguration 안 읽음. 125줄 주석 "모든 모듈". 고침: 목록·주석 runtimeOnly 줄. + +### RR9-05-06 · Medium · 시스템 호출 쓰기가 유스케이스 계약 밖: fileserver DefaultCleanupService.java:32,… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B15a application 구조 +- 내용: `FileserverUseCaseContractDeviationTest.java:22-30,42-43` — 시스템 호출 쓰기가 유스케이스 계약 밖: fileserver DefaultCleanupService.java:32, DefaultFileReconciliationService.java:28; notification NotificationDispatchService.java:49, LeaseRecoveryService.java:36, ReconciliationService.java:32, ProviderEventProjectionService.java:17. 사용자·시스템이 같은 서비스(CleanupUploadsApplicationUseCase·FileserverCleanupWorker, admin·LeaseRecoveryService). 고침: @SystemInvoked 분리 or 결정 기록 + notification freeze 시험. + +### RR9-05-07 · Medium · 연산 4개 inbound 포트, UseCase·capability·@RequiresPermission 없음, 쓰는 전송… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B15a application 구조 +- 내용: `NotificationAdminService.java:9`, `NotificationAdminApplicationService.java:45` — 연산 4개 inbound 포트, UseCase·capability·@RequiresPermission 없음, 쓰는 전송 없음(NotificationDeliveryConfiguration.java:167-169), 협력 객체 12. 고침: 유스케이스 4개 or 삭제. + +### RR9-05-08 · Medium · `FileserverMaintenanceServiceConfiguration.java:27-63`(outbound adapter가… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B15a application 구조 +- 내용: `FileserverMaintenanceServiceConfiguration.java:27-63`(outbound adapter가 application 서비스 조립), NotificationPlatformPolicyConfig.java:79·89-92·140(retry ofMinutes(1)·jitter를 설정에서), NotificationPlatformDispatchConfig.java:65, notification worker가 adapter.outbound.notification(NotificationSchedulerWorker.java:31). 고침: composition으로, retry 값 settings. + +### RR9-05-09 · Medium · 전송 4곳이 "upload.bin" 기본 이름(HARD-STOP 4·중복), application… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B12 fileserver·notification HTTP +- 내용: `RawUploadRequestMapper.java:23,44` 외 MultipartUploadRequestMapper.java:16, Draft12UploadController.java:244, TusController.java:115 — 전송 4곳이 "upload.bin" 기본 이름(HARD-STOP 4·중복), application OriginalFilenamePolicy.java:16은 "file". 고침: 전송은 없음으로, 정책 한 곳. + +### RR9-05-10 · Medium · web이 outbound LiveEventReplayPort 직접 읽음(application-core AGENTS 「읽기·query 경로」).… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B15a application 구조 +- 내용: `MessagingReplayBridge.java:31,68` — web이 outbound LiveEventReplayPort 직접 읽음(application-core AGENTS 「읽기·query 경로」). 고침: 조회 유스케이스 + 1번 규칙. + +### RR9-05-11 · Medium · operation id 문법 셋, owner token 64 hex(IdempotencyClaimAttempt.java:19) vs… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B15b application 작은 것 +- 내용: `OperationId.java:24`·`LeaseValidation.java:16-20`·`DurableOperationId.java:16` — operation id 문법 셋, owner token 64 hex(IdempotencyClaimAttempt.java:19) vs base64url. 고침: 값 타입 통일 or 이유. + +### RR9-05-12 · Medium · 표시·문서만), notification… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B15b application 작은 것 +- 내용: 멱등 판정 세 벌: durable operation SubmitDurableOperationUseCase.java:54 KEYED인데 executor 안 씀(결정 15·26 지문 방식 — 표시·문서만), notification AcceptNotificationApplicationUseCase.java:140-155·NotificationRequestRecord.java:17·NotificationRequestStorePort.java:36 원본 키 저장·자체 판정(결정 없음). 고침: executor or 결정. + +### RR9-05-13 · Low · durable operation이 core 공통 타입 안 따름: tenant·principal… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B15b application 작은 것 +- 내용: durable operation이 core 공통 타입 안 따름: tenant·principal String(OperationCommand.java:31-32, GetDurableOperationQuery.java:14, CancelDurableOperationCommand.java:14, DurableOperationAccessPolicy.java:25), DurableOperationIdFactory·Id가 IdFactory·ResourceId 아님(AGENTS:80 예외 없음), id를 controller에서 만듦. + +### RR9-05-14 · Low · `SubmitDurableOperationUseCase.java:177-190` UUIDv7 파생을 유스케이스가 →… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B15b application 작은 것 +- 내용: `SubmitDurableOperationUseCase.java:177-190` UUIDv7 파생을 유스케이스가 → IntegrationIdentity로. + +### RR9-05-15 · Low · 미사용 추상화: ReadConsistency.java:4(참조 0, persistence-jpa에 다른 모양 동명),… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B15b application 작은 것 +- 내용: 미사용 추상화: ReadConsistency.java:4(참조 0, persistence-jpa에 다른 모양 동명), FileserverSpans.java(span 안 냄), ProviderEventId.java, NotificationExpiredException.java, BatchNotificationProviderAdapter.java, CollapseCapability.java(시험만). + +### RR9-05-16 · Low · application-core README.md:780 "final이 아니다", be-domain 함정 12. + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B15b application 작은 것 +- 내용: GetDurableOperationUseCase.java:18, PublishPendingOutboxEventsUseCase.java:43 final — application-core README.md:780 "final이 아니다", be-domain 함정 12. + +### RR9-05-17 · Low · FileMetadataPort(insert·transition·markDeleting·relocate),… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B15b application 작은 것 +- 내용: FileMetadataPort(insert·transition·markDeleting·relocate), UploadSessionPort(acquireLease·commitOffset) 실패 결과 Javadoc 없음(어댑터 JpaFileMetadata.java:146-168만). + +### RR9-05-18 · Low · `CanonicalNotificationPlanEncoder.java:73,78,262,264,265,282,299` 문자열에 NUL 바이트… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B15b application 작은 것 +- 내용: `CanonicalNotificationPlanEncoder.java:73,78,262,264,265,282,299` 문자열에 NUL 바이트 → git·grep 바이너리. 고침: "\u0000". + +### RR9-05-19 · Low · `FileserverAdminController.java:151-152,164-176` orphan apply·cleanup… + +- 출처: 물결 2 arch-reviewer +- 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 +- 묶음: B12 fileserver·notification HTTP +- 내용: `FileserverAdminController.java:151-152,164-176` orphan apply·cleanup 기본값(maxBytes 1<<30, reasonCode, dryRun)을 controller가 → application command 팩터리. diff --git a/docs/reviews/2026-11-12-round9-review/README.md b/docs/reviews/2026-11-12-round9-review/README.md new file mode 100644 index 00000000..bd3aeae0 --- /dev/null +++ b/docs/reviews/2026-11-12-round9-review/README.md @@ -0,0 +1,250 @@ +# round9 전체 리뷰 (2026-11-12) + +## 1. 결론 + +main `a7e38c10`(Gradle 루트 재배치, gRPC·메시징 플랫폼 분리, 분야 전문가 스킬, CI 재편, red team 수정이 들어간 뒤)을 +새 눈으로 전체 리뷰했다. 발견 152건: Critical 0, High 2, Medium 72, Low 78. 이 밖에 CI workflow·`build.gradle`·`gates.md`처럼 +백엔드 CI 세션이 고치는 중인 파일의 발견 9건은 그 세션에 넘겼다(5절). + +- High 둘은 아키텍처 규칙의 사각지대다(HARD-STOP 2). controller가 domain repository 포트를 들어도, inbound 밖 사용자 + 전송이 `@SystemInvoked` 유스케이스에 닿아도 빌드가 통과한다(RR9-05-01·02). +- Medium의 큰 덩어리: env 계약이 registry·`.env.example`·배포 설정 사이에서 갈렸다(예시를 그대로 복사하면 JPA 배포가 + 기동하지 않는 값 포함), 공개 경로 게이트가 모듈 chain을 못 본다, 관측 registry와 코드의 지표·MDC 이름이 어긋난다, + claim·lease의 fence가 구현마다 갈렸다, 문서가 재배치 뒤 낡은 경로·명령을 가리킨다. +- 결함은 모두 고친다(`docs/work/improve.md` 4.5절). 원인 묶음마다 PR 하나다(4절). + +## 2. 범위 + +- 대상: main `a7e38c10`, 작업 트리 깨끗함, 2026-11-12. 기준 게이트: `scripts/verify.sh pr --no-cache` rc=0(desktop, 21:06~21:39). + `main` 단계는 6절에 결과를 적는다. +- 방법: `docs/work/experts.md`의 분야 렌즈로 `reviewer` 서브에이전트를 두 물결에 나눠 띄웠다(lead 스킬, 한 물결 4명). + 모든 발견은 E1(현재 커밋 코드·문서 정적 확인)이고, 고칠 때 RED 시험(수정 전 실패)으로 다시 확인한다. + +| 물결 | 렌즈 | 경로 | +| --- | --- | --- | +| 1 | be-persistence + be-messaging + be-performance | `src/adapter/outbound/**`, inbound messaging, outbox·멱등·durable operation 조립, 마이그레이션·runbook | +| 1 | be-security + be-observability | `src/bootstrap/app`, service-runtime, inbound 보안·필터, 보안·관측 registry, Dockerfile·compose | +| 1 | be-api-contract + be-testing | inbound 전송 계약, shared-contract, 계약 registry·스냅숏, 시험 품질 | +| 1 | be-build-ci + be-docs | build-logic, gradle, config, scripts, 진입 문서·`docs/**`·`.claude/**` | +| 2 | be-domain(`arch-reviewer`) | domain·application·shared-contract, HARD-STOP 1~5 전체, ArchUnit 사각지대 | +| 2 | be-persistence + be-performance + be-messaging | 물결 1이 못 본 outbound(mongo, redis-sdk, httpclient, objectstorage, notification, fileserver 등) | +| 2 | be-security + be-observability | 물결 1이 못 본 web-advanced·graphql·grpc·websocket·web-fileserver 보안, 조립 모듈, logback, auth runbook | +| 2 | be-api-contract + be-docs | web-advanced·graphql·websocket·tus 계약, 매뉴얼·runbook·모듈 README 본문 | + +- 못 본 것(두 물결이 모두 「못 본 하위 경로」로 적은 곳): redis-sdk의 programmability·cluster·reactive, persistence-mongo의 + csfle·qe·sharding, httpclient의 auth·dynamic·http3, objectstorage publication kernel 본문, web-advanced의 codec·openapi· + versioning, graphql의 cost scorer 내부. 다음 확인 리뷰가 표본으로 본다. +- 지난 라운드가 넘긴 항목: 동시 인덱스 `_ccold`(결함 아님, E1), 멱등 Redis Lua의 cluster 원자성(결함 아님, 남는 것은 + failover 내구성 RR9-01-11), `RunbookSql` lane 목록(RR9-01-10), 메시징 인증 증거 대조(이 repo에서 닫힘, 라이브러리 + repo의 일), compose smoke OOM(고쳐짐, 남은 틈 RR9-04-27), STOMP 밖 Spring Security 확장점·`registration.interceptors(x)` + 사각지대(RR9-05-03·04). + +## 3. 색인 + +| ID | 심각도 | 영역 | 내용 | 묶음 | +| --- | --- | --- | --- | --- | +| RR9-01-01 | Medium | 영속성·메시징·성능 | inbox TransactionRunner `new TransactionTemplate` timeout 없음 → 유스케이스… | B9 트랜잭션 시한·정리 | +| RR9-01-02 | Medium | 영속성·메시징·성능 | heartbeat·progress·succeed·fail이 lease_owner=:workerId만 확인, fence 없음. 같은… | B8 claim·fence | +| RR9-01-03 | Medium | 영속성·메시징·성능 | live_event_log 행 retention 지나도 안 지움, sweepExpired 호출자·스케줄 없음, 문서도 서비스 의무로 안… | B9 트랜잭션 시한·정리 | +| RR9-01-04 | Low | 영속성·메시징·성능 | 상한 없는 DELETE 한 문장(outbox는 1000행씩, OutboxEventJpaRepository.java:35-47),… | B8 claim·fence | +| RR9-01-05 | Low | 영속성·메시징·성능 | join() 시간 상한 없음,… | B10a 발행·발송·캐시 | +| RR9-01-06 | Low | 영속성·메시징·성능 | Javadoc "enqueue is an upsert"인데 UPDATE 0행이면 INSERT 두 단계, 동시 enqueue 시… | B8 claim·fence | +| RR9-01-07 | Low | 영속성·메시징·성능 | app.lock.wait-time 읽는 곳 없음(lease-ttl 교차 검사로 기동 막기만). README:559… | B9 트랜잭션 시한·정리 | +| RR9-01-08 | Low | 영속성·메시징·성능 | 408·429를 조건 없이 재시도로 적음, 코드(DefaultRetryEligibilityEngine.java:81-99,… | B10b S3·Mongo·httpclient | +| RR9-01-09 | Low | 영속성·메시징·성능 | 주석 "retention has no default on purpose"인데… | B9 트랜잭션 시한·정리 | +| RR9-01-10 | Low | 영속성·메시징·성능 | Javadoc lane 목록에 lock timeout runbook… | B9 트랜잭션 시한·정리 | +| RR9-01-11 | Low | 영속성·메시징·성능 | Redis 같은 키 재전송 안 돌린다를 조건 없이 약속, Sentinel·Cluster failover 비동기 복제 손실… | B10b S3·Mongo·httpclient | +| RR9-01-12 | Medium | 영속성·메시징·성능 | 회복이 행 잠금 없이 읽고(RecipientDeliveryJpaRepository.java:187-194) requeue 무조건… | B8 claim·fence | +| RR9-01-13 | Medium | 영속성·메시징·성능 | UPDATE … WHERE id IN (SELECT … LIMIT), 상태 조건 subquery 안만 → READ COMMITTED 재평가 안… | B8 claim·fence | +| RR9-01-14 | Medium | 영속성·메시징·성능 | poll마다 SQL 4개, PROJECTION_LAG WHERE 없음 → notification_provider_event 전체 스캔(지우는… | B9 트랜잭션 시한·정리 | +| RR9-01-15 | Medium | 영속성·메시징·성능 | ThreadPoolExecutor(1,n,LinkedBlockingQueue(4n)) 큐 찰 때까지 스레드 1, limiter 4로 큐 안… | B10a 발행·발송·캐시 | +| RR9-01-16 | Medium | 영속성·메시징·성능 | RejectedExecution을 AMBIGUOUS_SUBMISSION으로(SMTP 상태 조회 없음 → 운영자 대기),… | B10a 발행·발송·캐시 | +| RR9-01-17 | Medium | 영속성·메시징·성능 | 캐시가 대기 예산 없는 run → lane 대기 2s + commandTimeout, @param "ceiling on one cache… | B10a 발행·발송·캐시 | +| RR9-01-18 | Medium | 영속성·메시징·성능 | 캐시 값 크기 상한 없음(옛 키 폐기 env-keys.yaml:2686-2689, RedisKeyRules는 키만). 고침: encode 길이… | B10a 발행·발송·캐시 | +| RR9-01-19 | Medium | 영속성·메시징·성능 | 조건부 PUT 본문 재전송 가능 → SDK 재시도가 412 → ObjectControlConflictException,… | B10b S3·Mongo·httpclient | +| RR9-01-20 | Medium | 영속성·메시징·성능 | getMappedResults 전부 메모리 후 셈, maxResultBytes 미집행(95), query-aggregation-guide… | B10b S3·Mongo·httpclient | +| RR9-01-21 | Medium | 영속성·메시징·성능 | heap 384m을 512m tmpfs에 dump, 같은 cgroup·swap 없음 → dump 중 OOM kill 가능,… | B19 compose·Docker 운영 | +| RR9-01-22 | Low | 영속성·메시징·성능 | (넘어온 1) .env.example:193 POSITIVE_SOFT_TTL= → 빈 Duration null → setter 안 불림 →… | B2 env 계약 | +| RR9-01-23 | Low | 영속성·메시징·성능 | max-items 100을 10분 lease로 한꺼번에 claim, lease 안에 끝나는지 검사 없음(outbox… | B8 claim·fence | +| RR9-01-24 | Low | 영속성·메시징·성능 | "lease > provider 호출·timeout" 주석만, 검사 없음. | B8 claim·fence | +| RR9-01-25 | Low | 영속성·메시징·성능 | 트랜잭션 30초 상한 없음(decisions 2.5), row cap 사후 검사(inbox 건과 같은 원인). | B9 트랜잭션 시한·정리 | +| RR9-01-26 | Low | 영속성·메시징·성능 | 새 pool 크기 모른 채 합계 미만만 봄 → 상한 초과, Javadoc "would exceed". | B9 트랜잭션 시한·정리 | +| RR9-01-27 | Low | 영속성·메시징·성능 | acquire void, idle 판정 마지막 acquire 시각 → 사용 중 client 닫음, 닫기 실패가 다른 tenant… | B10b S3·Mongo·httpclient | +| RR9-01-28 | Low | 영속성·메시징·성능 | requireCurrentFence가 UNFENCED만 거름(MongoMigrationLock.java:32), refresh(166-170)… | B10b S3·Mongo·httpclient | +| RR9-01-29 | Low | 영속성·메시징·성능 | lease 만료 시계 구현마다 다름: JpaRecipientLeaseStore.java:52,117,… | B8 claim·fence | +| RR9-01-30 | Low | 영속성·메시징·성능 | compression=true면 Apache가 푼 스트림을 wire 계수기가 셈(ApacheClientFactory.java:114-116)… | B10b S3·Mongo·httpclient | +| RR9-01-31 | Low | 영속성·메시징·성능 | ProxyType.SOCKS를 HTTP 프록시로, capability… | B10b S3·Mongo·httpclient | +| RR9-02-01 | Medium | 보안·관측 | 관리 포트 기본 127.0.0.1(PR #12)인데 service-runtime/README.md:275-276·Dockerfile:221은… | B3 공개 경로·관리 포트 | +| RR9-02-02 | Medium | 보안·관측 | 최상위 `roles` 클레임 fallback을 권한에 합침. manual 07:51-53·decisions 2.6 「JWT… | B4 인증·인가 | +| RR9-02-03 | Medium | 보안·관측 | config/security.yml 한 줄만 읽음, 문서(gates.md:63, build.md:166)는 보안 체인 전체 약속.… | B3 공개 경로·관리 포트 | +| RR9-02-04 | Medium | 보안·관측 | runbook 둘이 없는 신호로 탐지:… | B7 runbook 신호 | +| RR9-02-05 | Medium | 보안·관측 | `docs/registries/metrics.yaml` 양방향 불일치: 코드 없는… | B5 관측 registry | +| RR9-02-06 | Medium | 보안·관측 | JMX 9999 무인증·무TLS, jmxremote.host 없어 모든 인터페이스. 주석 15·54 "localhost only". 고침:… | B3 공개 경로·관리 포트 | +| RR9-02-07 | Low | 보안·관측 | 18키 중 5개만 코드가 넣음(logback-spring.xml:90-94). tenant_id(77-88) required_in인데… | B5 관측 registry | +| RR9-02-08 | Low | 보안·관측 | 전송별 correlation 규칙 다름: web(WebMvcRequestIdFilter.java:189-191),… | B5 관측 registry | +| RR9-02-09 | Low | 보안·관측 | 401·403 WARN에 원본 getRequestURI(Javadoc 15-19 "only redacted"). 같은 모양… | B6a 로그 내용 | +| RR9-02-10 | Low | 보안·관측 | IP 신뢰 문서 둘: application-local.yml:120-121 "framework via… | B6b 비밀·IP 문서 | +| RR9-02-11 | Low | 보안·관측 | config/security.yml:23 `SECURITY_PUBLIC_PATHS`, config/runtime.yml:18… | B2 env 계약 | +| RR9-02-12 | Low | 보안·관측 | masking_rule full_except_last_4 구현 없음(LogMaskingPatterns.java:23-41 URI… | B6b 비밀·IP 문서 | +| RR9-02-13 | Low | 보안·관측 | 로컬 비밀 기본값 `__LOCAL_DEV_` 규칙 미준수: compose.yaml:108·158, application-local.yml:55… | B6b 비밀·IP 문서 | +| RR9-02-14 | Low | 보안·관측 | "The standalone sample does that." 지운 샘플(ab5982e9). 최근. | B6b 비밀·IP 문서 | +| RR9-02-15 | Low | 보안·관측 | main 호출자 없음, WebMvcRequestIdFilter.java:182-188이 버린 규칙. 고침: 클래스·시험·README:511… | B6a 로그 내용 | +| RR9-02-16 | Medium | 보안·관측 | 인증 없는 모르는 profile POST → ISE → GlobalExceptionHandler.java:213… | B4 인증·인가 | +| RR9-02-17 | Medium | 보안·관측 | root 좌표만 판정, GraphQlAuthorizationPolicy.java:11-16 builder는 User.salary 하위 좌표… | B4 인증·인가 | +| RR9-02-18 | Medium | 보안·관측 | @RequiresPermission web만: gRPC principal을… | B4 인증·인가 | +| RR9-02-19 | Medium | 보안·관측 | 모든 projection을 /topic 하나로 모든 인증 세션에, tenant·소유자 판정 없음, README 「한계」 95-106 없음.… | B11b graphql·websocket 계약 | +| RR9-02-20 | Medium | 보안·관측 | SPRING_PROFILES_ACTIVE=test면 배포 jar 통과 → prod 검사 모두 꺼짐(SecretSourceValidator… | B4 인증·인가 | +| RR9-02-21 | Medium | 보안·관측 | INFO 이하 로거 구분 없이 버림, 감사 로거 INFO(LoggingNotificationAudit.java:31,… | B6a 로그 내용 | +| RR9-02-22 | Medium | 보안·관측 | 예외 통째 로그 → SQL·제약·값, 전송은 ServerFailureLog.of(ServerFailureLog.java:59-63). 고침:… | B6a 로그 내용 | +| RR9-02-23 | Medium | 보안·관측 | sub 없는 토큰 idpUserId=null → FileAccessSubject.java:24,… | B4 인증·인가 | +| RR9-02-24 | Low | 보안·관측 | 금지 값; auth-kid-unknown.md:25, auth-token-rotation-failure.md:29 없는 JWKS 손잡이;… | B7 runbook 신호 | +| RR9-02-25 | Low | 보안·관측 | `WebSocketConfig.java:93` 주석 틀림(거부 preSend… | B6a 로그 내용 | +| RR9-02-26 | Low | 보안·관측 | 컨텍스트 속성만 바꿈, logback-spring.xml:89,122 ${APP_PROFILE}은 이미 치환 → JSON profile 칸… | B6a 로그 내용 | +| RR9-02-27 | Low | 보안·관측 | in-process lock 미계량 → lock.acquisition 0, metrics.yaml:307 "1:1",… | B5 관측 registry | +| RR9-02-28 | Low | 보안·관측 | "서버 허용 목록 이름이라 echo 안전"인데 요청 값 echo(PatchFieldAuthorization.java:59,… | B4 인증·인가 | +| RR9-02-29 | Low | 보안·관측 | tenant 규칙 갈림: WebTenantContextResolver.java:19-20 거부 목록에 tenant_id 없음,… | B4 인증·인가 | +| RR9-02-30 | Low | 보안·관측 | `compose/redis/acl/README.md:43` advanced 계정 pub/sub 더함, 실제… | B19 compose·Docker 운영 | +| RR9-02-31 | Low | 보안·관측 | `GraphQlClientPolicy.java:24` maxInputListElements "한 input list 상한"인데… | B11b graphql·websocket 계약 | +| RR9-03-01 | Medium | API 계약·시험 | 부분 실패 batch가 success:true + data.results. fullySucceeded() 미사용. 약속 충돌: web… | B12 fileserver·notification HTTP | +| RR9-03-02 | Medium | API 계약·시험 | partial() error.message 영어 고정, BulkItemResult 호출자 문구 그대로·null 키 남김(mix-in 아님,… | B12 fileserver·notification HTTP | +| RR9-03-03 | Medium | API 계약·시험 | 실제 long maxAgeSeconds(CorsSettings.java:19-20, config/security.yml:54) → 예시 그대로… | B2 env 계약 | +| RR9-03-04 | Medium | API 계약·시험 | env-keys.yaml:2563-2577·2670-2684… | B2 env 계약 | +| RR9-03-05 | Medium | API 계약·시험 | docs/registries/headers.yaml:16,154 X-Request-Id·X-Correlation-Id type ulid(코드… | B5 관측 registry | +| RR9-03-06 | Medium | API 계약·시험 | 서버 포화를 전송마다 다른 코드: gRPC GrpcCallAdmission.java:82-83 RATE_LIMIT_EXCEEDED("요청이… | B13 전송 오류 코드 | +| RR9-03-07 | Medium | API 계약·시험 | 27개 중 23개 계약 문서에 없음, docs/fileserver/http-contract.md:79 예시 "data":… | B12 fileserver·notification HTTP | +| RR9-03-08 | Medium | API 계약·시험 | grpc README.md:26-28 "전용 APP_* 키 registry에 없다"인데 APP_GRPC_SERVER_ENABLED… | B2 env 계약 | +| RR9-03-09 | Medium | API 계약·시험 | Content-Range(MvcDownloadResponseWriter.java:43,… | B12 fileserver·notification HTTP | +| RR9-03-10 | Low | API 계약·시험 | MANAGEMENT_SERVER_ADDRESS registry 있음·.env.example 없음(R2-1 일부). 최근(#12). | B2 env 계약 | +| RR9-03-11 | Low | API 계약·시험 | OPERATION_NOT_FOUND(operation/OperationErrorCode.java) §4에 없음(decisions 2.3 「새… | B13 전송 오류 코드 | +| RR9-03-12 | Low | API 계약·시험 | 모든 503이 REQUEST_TIMEOUT(retryable). §4는 비동기 시간 초과에만. 이전부터. | B13 전송 오류 코드 | +| RR9-03-13 | Low | API 계약·시험 | 모르는 channel·slot·locale이 details 없는 BAD_PARAMETER(주석은 validation error, S4는… | B12 fileserver·notification HTTP | +| RR9-03-14 | Low | API 계약·시험 | ERROR frame code만(category·retryable 없음), 원인 사슬 어디 IAE든 BAD_PARAMETER(다른 전송은 실패… | B11b graphql·websocket 계약 | +| RR9-03-15 | Low | API 계약·시험 | Retry-After를 occurrence만 보고 붙임, 본문은 코드 값으로 좁힘(ErrorResponseFactory.java:42) →… | B12 fileserver·notification HTTP | +| RR9-03-16 | Low | API 계약·시험 | 낡은 문서: GrpcStatusMapper.java:21 WORKLOG_NOT_FOUND 예시(ab5982e95 이후), graphql 스냅숏… | B13 전송 오류 코드 | +| RR9-03-17 | Medium | API 계약·시험 | test에서 태그 없이 env-keys.yaml 읽음, modules.json 거슬러 ca.repository.root 가드 우회, 입력… | B16 시험 품질 | +| RR9-03-18 | Medium | API 계약·시험 | "값을 싣지 않는다" 단언에 예외 타입 없음 → 메시지 null NPE로 바꿔도 통과. 이전부터. | B16 시험 품질 | +| RR9-03-19 | Low | API 계약·시험 | 빈 목록이면 통과, GWT 없음. 고침: 메서드 목록 고정. 최근(#12 bb8bb31b9). | B16 시험 품질 | +| RR9-03-20 | Low | API 계약·시험 | MvcUploadExecutorSaturationTest.java:112-121(이름 timeout인데 타입만), :45 sleep(200),… | B16 시험 품질 | +| RR9-03-21 | Low | API 계약·시험 | EnvelopeWireShapeTest | B16 시험 품질 | +| RR9-03-22 | Low | API 계약·시험 | 영어 @DisplayName 381/940, // when 없는 3문장+ 테스트 약 890/1550(휴리스틱). 규칙은 "손댈 때 고침" →… | B16 시험 품질 | +| RR9-03-23 | Medium | API 계약·시험 | web-advanced patch 위반이 세 코드(PATCH_REJECTED 400 / BAD_PARAMETER 400 IAE /… | B11a web-advanced 계약 | +| RR9-03-24 | Medium | API 계약·시험 | "결과를 문서 전체로 검증 후 적용" 약속, 검증기 안 받음. | B11a web-advanced 계약 | +| RR9-03-25 | Medium | API 계약·시험 | sequence 엄격 증가·heartbeat·idle·max-age·버퍼 상한·drain 재연결 약속, writer 아무것도 안… | B11a web-advanced 계약 | +| RR9-03-26 | Medium | API 계약·시험 | commit 뒤 실패 코드 DEPENDENCY_FAILURE 고정(registry·WebAdvancedError·§4 없음),… | B11a web-advanced 계약 | +| RR9-03-27 | Medium | API 계약·시험 | 503+Retry-After 약속, guard bean만, 요청 경로에서 run 안 부름(manual 10 기준 3). | B11a web-advanced 계약 | +| RR9-03-28 | Medium | API 계약·시험 | 정본 충돌 → 소유자 결정. | B11a web-advanced 계약 | +| RR9-03-29 | Medium | API 계약·시험 | Javadoc "Stable request-error code GRAPHQL_CURSOR_REJECTED"인데 플랫폼 거부·carrier 아님… | B11b graphql·websocket 계약 | +| RR9-04-01 | Medium | 빌드·문서 | #12가 줄 더해 151/150, check-work-docs rc=1 → verify.sh docs·라운드 끝 실패. 같은 줄 "(W4… | B1 문서·지침 | +| RR9-04-02 | Medium | 빌드·문서 | `cd ~/workspace/<작업>/src` 뒤 ./gradlew(#10 뒤 src에 gradlew 없음). desktop-gates… | B1 문서·지침 | +| RR9-04-03 | Medium | 빌드·문서 | "Gradle 루트가 src/라 두 단계 위", `--include-build ../../messaging-library` →… | B1 문서·지침 | +| RR9-04-04 | Medium | 빌드·문서 | 이름 바꾸기 `git grep -l 'dev\.caskeleton' -- src scripts`가 build.gradle:26,… | B18a 스크립트 | +| RR9-04-05 | Medium | 빌드·문서 | 없는 PublicPathSnapshotPlugin.java·updatePublicPathSnapshot, 없는 CI step. 고침:… | B3 공개 경로·관리 포트 | +| RR9-04-06 | Medium | 빌드·문서 | `:app-bootstrap:test --tests '*CleanArchitectureTest'` 고르는 클래스… | B17 빌드 | +| RR9-04-07 | Medium | 빌드·문서 | `docs/work/experts.md:56-66` 3절 표가 스킬 paths와 갈림(be-build-ci… | B1 문서·지침 | +| RR9-04-08 | Medium | 빌드·문서 | 행이 코드와 다르고 「바뀜」 표시 없음: 64 docs-check workflow 없음, 193 build-logic 잠그지 않음 vs… | B1 문서·지침 | +| RR9-04-09 | Medium | 빌드·문서 | 단계 구성표 네 곳: docs/testing/TESTING_STRATEGY.md:146-148(틀림,… | B18b 문서 본문 | +| RR9-04-10 | Medium | 빌드·문서 | 33·36 지운… | B18b 문서 본문 | +| RR9-04-11 | Medium | 빌드·문서 | nightly jpa-postgresql·release jpa-release-gate. 고침: digest. 이전부터. | B17 빌드 | +| RR9-04-12 | Medium | 빌드·문서 | 모든 ca.spring-library leaf(30) testImplementation에… | B17 빌드 | +| RR9-04-13 | Low | 빌드·문서 | `gradle/libs.versions.toml` 미사용 칸: 120 errorprone-core, 121 findsecbugs-plugin,… | B17 빌드 | +| RR9-04-14 | Low | 빌드·문서 | "쓰는 lane만 다시 돈다"인데 JavaConventionsPlugin.java:279-288이 파일 전체를 모든 leaf 모든 Test… | B17 빌드 | +| RR9-04-15 | Low | 빌드·문서 | 없는 클래스… | B17 빌드 | +| RR9-04-16 | Low | 빌드·문서 | `src/adapter/outbound/notification/build.gradle:104` additionalSourceRoots 상대… | B17 빌드 | +| RR9-04-17 | Low | 빌드·문서 | 검사 스크립트 정비: check-repo-layout.py:90-96 HISTORY_PREFIXES 없는 폴더… | B18a 스크립트 | +| RR9-04-18 | Low | 빌드·문서 | docstring 낡음: check-docs.py:2,18,41 "검사 여섯"(여덟), check-work-docs.py:31 lychee… | B18a 스크립트 | +| RR9-04-19 | Low | 빌드·문서 | `docs/README.md:187` "PR마다 workflow docs-check" → pr.yml done → :prCheck →… | B1 문서·지침 | +| RR9-04-20 | Low | 빌드·문서 | 기본 조립: docs/build.md:50-56·scripts/bootstrap-local.sh:12-14,42 "app 기동(Flyway… | B18b 문서 본문 | +| RR9-04-21 | Low | 빌드·문서 | `docs/roadmap/messaging-r2.md:45,48` 지운… | B18b 문서 본문 | +| RR9-04-22 | Low | 빌드·문서 | #13이 합친 integration job을 가리킴: cache-redis/README.md:332,… | B18b 문서 본문 | +| RR9-04-23 | Low | 빌드·문서 | bootstrap-local.sh를 flock으로 직접(:33 ./gradlew --no-daemon 없음), "4.1절의 정리법"… | B1 문서·지침 | +| RR9-04-24 | Low | 빌드·문서 | `CLAUDE.md:8` "분야 지식 be-* 10개" 개수 복사(함정 6). 최근 #14. | B1 문서·지침 | +| RR9-04-25 | Low | 빌드·문서 | `renovate.json:9,17` "either bot"·GitHub vulnerability alerts 전제, Gitea에서… | B18b 문서 본문 | +| RR9-04-26 | Low | 빌드·문서 | `scripts/run-compose-runtime-smoke.sh:388` lane마다 정적 계약 전체 재실행(compose config… | B18a 스크립트 | +| RR9-04-27 | Low | 빌드·문서 | handoff --force-recreate가 1단계 재시작 수 지움, ps -a -q 빈 결과면 restarts.txt 비고 || true로… | B18a 스크립트 | +| RR9-04-28 | Medium | 빌드·문서 | graphql AGENTS·README가 「모듈별 yml 금지」라 하지만 모듈이 config/graphql.yml을 읽는다 | B18b 문서 본문 | +| RR9-04-29 | Medium | 빌드·문서 | `.env.example`의 APP_DATASOURCE_CONNECTION_TIMEOUT=5s는 registry가 기동 실패라 적은 값이다 | B2 env 계약 | +| RR9-04-30 | Medium | 빌드·문서 | `.env.example`의 FORWARD_HEADERS_STRATEGY=native가 registry 기본 none과 다르다 | B2 env 계약 | +| RR9-04-31 | Low | 빌드·문서 | `.env.example` 머리말 「Seven values」가 여섯만 나열하고, 폐기 키 48개에 값이 들어 있다 | B2 env 계약 | +| RR9-04-32 | Medium | 빌드·문서 | cache-redis README가 운영 비밀로 폐기 키 넷을 넣으라고 한다 | B2 env 계약 | +| RR9-04-33 | Medium | 빌드·문서 | 지식 스킬 넷이 재배치 뒤에도 「명령은 src/에서」라고 한다 | B1 문서·지침 | +| RR9-04-34 | Low | 빌드·문서 | docs/web/runbook.md:37,49,56-58 TTL "연산마다"(전역 APP_IDEMPOTENCY_TTL),… | B7 runbook 신호 | +| RR9-04-35 | Low | 빌드·문서 | docs/web/repository-adaptation.md:146-162 "앱은 애플리케이션 칸 강제 안 함" vs… | B18c 낡은 이름·leaf 안내 | +| RR9-04-36 | Low | 빌드·문서 | openapi-32-compatibility.md가 아무도 만들지 않는 3.1.2 산출물·snapshot 불변식을 적는다 | B18c 낡은 이름·leaf 안내 | +| RR9-04-37 | Low | 빌드·문서 | 없는 metric·행 가리키는 runbook: authz-cross-tenant-violation.md:38,67,… | B7 runbook 신호 | +| RR9-04-38 | Low | 빌드·문서 | 옮기거나 바꾼 타입: persistence-jpa/README.md:43 OutboxConfig,… | B18c 낡은 이름·leaf 안내 | +| RR9-04-39 | Low | 빌드·문서 | 지운 샘플: defect-patterns.md:68 SampleDemoProfilesStartupSystemTest,… | B18c 낡은 이름·leaf 안내 | +| RR9-04-40 | Low | 빌드·문서 | graphql AGENTS.md:23-33·README.md:186 "messaging leaf registry 등록, 두 패턴… | B18c 낡은 이름·leaf 안내 | +| RR9-04-41 | Low | 빌드·문서 | graphql AGENTS.md:19·README.md:183 "366개 java 파일"(246), AGENTS.md:160 "23… | B18c 낡은 이름·leaf 안내 | +| RR9-04-42 | Low | 빌드·문서 | leaf 안내 공백: application-notification·-fileserver·-objectstorage 가장 가까운 AGENTS가… | B18c 낡은 이름·leaf 안내 | +| RR9-05-01 | High | 계층·도메인·SRP | controller가 domain `Repository` 포트를 주입해도 안 걸림(HARD-STOP 2). 생성 명령이… | B14 아키텍처 규칙 | +| RR9-05-02 | High | 계층·도메인·SRP | inbound 밖 사용자 전송(bootstrap·composition controller, JWT converter)이… | B14 아키텍처 규칙 | +| RR9-05-03 | Medium | 계층·도메인·SRP | web 밖 JWT… | B14 아키텍처 규칙 | +| RR9-05-04 | Medium | 계층·도메인·SRP | `registration.interceptors(x)`에서 x가 구체 클래스 필드·생성자·new, ChannelInterceptor 지역… | B14 아키텍처 규칙 | +| RR9-05-05 | Medium | 계층·도메인·SRP | capabilityProjects에 :adapter:inbound:messaging 없음 → 전체 ArchUnit이… | B14 아키텍처 규칙 | +| RR9-05-06 | Medium | 계층·도메인·SRP | 시스템 호출 쓰기가 유스케이스 계약 밖: fileserver DefaultCleanupService.java:32,… | B15a application 구조 | +| RR9-05-07 | Medium | 계층·도메인·SRP | 연산 4개 inbound 포트, UseCase·capability·@RequiresPermission 없음, 쓰는 전송… | B15a application 구조 | +| RR9-05-08 | Medium | 계층·도메인·SRP | `FileserverMaintenanceServiceConfiguration.java:27-63`(outbound adapter가… | B15a application 구조 | +| RR9-05-09 | Medium | 계층·도메인·SRP | 전송 4곳이 "upload.bin" 기본 이름(HARD-STOP 4·중복), application… | B12 fileserver·notification HTTP | +| RR9-05-10 | Medium | 계층·도메인·SRP | web이 outbound LiveEventReplayPort 직접 읽음(application-core AGENTS 「읽기·query 경로」).… | B15a application 구조 | +| RR9-05-11 | Medium | 계층·도메인·SRP | operation id 문법 셋, owner token 64 hex(IdempotencyClaimAttempt.java:19) vs… | B15b application 작은 것 | +| RR9-05-12 | Medium | 계층·도메인·SRP | 표시·문서만), notification… | B15b application 작은 것 | +| RR9-05-13 | Low | 계층·도메인·SRP | durable operation이 core 공통 타입 안 따름: tenant·principal… | B15b application 작은 것 | +| RR9-05-14 | Low | 계층·도메인·SRP | `SubmitDurableOperationUseCase.java:177-190` UUIDv7 파생을 유스케이스가 →… | B15b application 작은 것 | +| RR9-05-15 | Low | 계층·도메인·SRP | 미사용 추상화: ReadConsistency.java:4(참조 0, persistence-jpa에 다른 모양 동명),… | B15b application 작은 것 | +| RR9-05-16 | Low | 계층·도메인·SRP | application-core README.md:780 "final이 아니다", be-domain 함정 12. | B15b application 작은 것 | +| RR9-05-17 | Low | 계층·도메인·SRP | FileMetadataPort(insert·transition·markDeleting·relocate),… | B15b application 작은 것 | +| RR9-05-18 | Low | 계층·도메인·SRP | `CanonicalNotificationPlanEncoder.java:73,78,262,264,265,282,299` 문자열에 NUL 바이트… | B15b application 작은 것 | +| RR9-05-19 | Low | 계층·도메인·SRP | `FileserverAdminController.java:151-152,164-176` orphan apply·cleanup… | B12 fileserver·notification HTTP | + +같은 결함을 두 리뷰어가 적은 것은 하나로 셌다(영역 문서 「출처」에 둘 다 적음). + +## 4. 묶음 + +원인 묶음마다 브랜치 하나·PR 하나다. 묶음의 발견 목록은 위 색인의 「묶음」 칸이다. + +| 묶음 | 브랜치 | 상태 | +| --- | --- | --- | +| B1 문서·지침 | `claude/r9-docs-work` | PR #16 | +| B2 env 계약 | `claude/r9-env-keys` | 진행 | +| B3 공개 경로·관리 포트 | `claude/r9-public-surface` | 진행 | +| B9 트랜잭션 시한·정리 | `claude/r9-tx-timeouts` | 진행(R1-1 먼저) | +| B14 아키텍처 규칙 | `claude/r9-arch-rules` | 진행 | +| B18c 낡은 이름·leaf 안내 | `claude/r9-stale-names` | 진행 | +| 나머지(B4~B8, B10~B13, B15~B19) | — | 대기 | + +## 5. 다른 세션에 넘긴 것 + +백엔드 CI 세션(workflow·루트 `build.gradle`·`gates.md`·`verify.sh`·`scripts/ci/**`·`template-vs-consumer.md`·redis-sdk +compose README를 고치는 중)에 9건을 넘겼다(2026-11-12). 그 세션 PR이 병합되면 확인 리뷰가 본다. + +1. [Medium] docs 단계(`check-work-docs.py`)가 어느 workflow에서도 돌지 않는데 문서는 「`prCheck` 안」이라 한다 + (`gates.md:17`, `verify.sh:7`, `build.gradle:196-198·218-233`). +2. [Low] `verify.sh:9`의 PR job 이름(`gradle` → `done`). +3. [Low] `build.gradle:11`「JMH leaf 셋」, `:147-150`「leaf 다섯 중첩 빌드」. +4. [Low] `release.yml:31-32`「ci를 다시 돌리지 않는다」와 재실행 job들. +5. [Low] `main.yml:100` lychee 범위(`src/**/CLAUDE.md`만, `AGENTS.md` 빠짐), `gates.md:86`. +6. [Low] `gates.md:115`의 desktop 직접 실행과 `redis-topology.sh:88` `--no-daemon` 없음, `gates.md:193` digest 문장. +7. [Low] `redis-sdk/compose/README.md:94-96` 필수 클래스 수. +8. [Low] `template-vs-consumer.md:20`(object-storage-aws를 nightly로), `:39`. +9. [Low] (1과 같은 원인의 문서 쪽 `operate.md`는 B1이 고침) + +## 6. 결정이 필요한 것 + +소유자 결정이 필요한 항목은 소유자 지시(중간 승인 없이 권하는 안으로 진행)대로 권하는 안을 적용하고, PR 본문 +「정한 기본값」과 여기에 남긴다. 소유자가 뒤집을 수 있다. + +| # | 항목 | 권하는 안 | +| --- | --- | --- | +| ① | RR9-03-01 batch 부분 실패 응답: web AGENTS B8·http-contract(`success:false`+`BATCH_PARTIAL_FAILURE`) vs fileserver 계약(200+`results[].error`) | 공용 B8로 맞춘다. upgrade 안내 행 | +| ② | RR9-03-06 서버 포화 오류 코드가 전송마다 다르다 | 서버 포화는 공용 코드 하나(503, retryable, `Retry-After`), 호출자 빈도 초과만 429 | +| ③ | RR9-03-28 merge patch: web AGENTS B2 「쓰지 않는다」 vs patch-contract 「필드 변경은 merge patch」 | patch-contract를 정본으로, web AGENTS B2가 그쪽을 가리킨다 | +| ④ | RR9-03-22 영어 `@DisplayName`·`// when` 없는 시험의 일괄 전환 | 규칙 그대로(고치는 시험에 적용). 일괄 전환하지 않고 결정 색인에 적는다 | +| ⑤ | RR9-05-12 notification 멱등 판정이 executor와 다르다 | 근거를 보고 executor로 옮기거나 결정으로 기록 — 묶음이 고른다 | +| ⑥ | env 이름 `SECURITY_PUBLIC_PATHS`·`PRESENTATION_API_BASE_PATH`의 `APP_` 접두 | 지금 이름 그대로 registry에 등록(바꾸면 파생 서비스 배포 env가 소리 없이 무시됨). 이름 변경은 소유자 결정 | + +## 7. 멈춤 기준 상태 (`docs/work/improve.md` 4.5절) + +1. 마지막 확인 리뷰 발견 0: 아님. 이 라운드 152건을 고친 뒤 확인 리뷰(독립 리뷰어 둘)가 판정한다. +2. 열린 「Declined to judge」 0: 참. 판정을 미룬 항목은 없다. 못 본 경로는 2절에 적었다. +3. 합친 트리의 라운드 끝 게이트: 아직. 묶음을 합친 뒤 돈다. +4. README의 남은 항목 0: 아님. 4절의 대기 묶음과 6절의 결정이 남았다. -- 2.54.0 From f4d832dfaf8bb661e0387a78896333033937a6c3 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 00:28:00 +0900 Subject: [PATCH 02/23] =?UTF-8?q?fix(arch):=20=EC=95=84=ED=82=A4=ED=85=8D?= =?UTF-8?q?=EC=B2=98=20=EA=B7=9C=EC=B9=99=EC=9D=B4=20=EB=86=93=EC=B9=9C=20?= =?UTF-8?q?HARD-STOP=202=20=EC=82=AC=EA=B0=81=EC=A7=80=EB=8C=80=20?= =?UTF-8?q?=EB=8B=A4=EC=84=AF=EC=9D=84=20=EB=8B=AB=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 저장소 전체 ArchUnit suite가 약속한 것을 막지 못하는 길이 다섯이다. 1. controller가 domain repository 포트(생성 명령이 aggregate 옆 dev.caskeleton.domain.에 두는 Repository)를 주입해도 걸리지 않는다. 규칙은 ..repository.. 패키지와 Spring Data·JPA 타입만 본다. gRPC 서비스는 controller 판정에 들지 않는다(HARD-STOP 2). 2. ..adapter.inbound.. 밖의 사용자 전송(조립 모듈의 controller 등)이 @SystemInvoked 유스케이스를 new로 만들어 부르거나, 표시 없는 중간 클래스를 거쳐 부르면 통과한다. 매뉴얼 07은 이것을 "빌드 실패"라고 약속한다. app AGENTS의 "bootstrap에 controller 금지"도 검사가 없다. 3. web 패키지 밖에 둔 Spring Security 요청 경로 확장점(JWT converter, AuthorizationManager, AuthenticationProvider, 필터 chain DSL)은 servlet 타입을 쓰지 않아 사용자 전송으로 보이지 않는다. 4. 설정이 interceptor를 자기 클래스 타입 필드로 쥐고 registration.interceptors(x)로 넘기면, ArchUnit 1.3은 ChannelRegistration (설정용 타입)만 기록해 설정이 사용자 전송이 되지 않는다. 5. capabilityProjects에 :adapter:inbound:messaging이 없어 저장소 전체 suite가 MessagingInboxAutoConfiguration을 읽지 않는다("suite가 모든 모듈을 본다"는 주석과 다름). 고른 방법: 1. ENDPOINTS_DO_NOT_HOLD_PERSISTENCE_PORTS: controller와 gRPC 서비스는 ..domain..·..application..의 *Repository·*StorePort·*QueryPort에 의존하지 않는다. 2. CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS, 그리고 USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS의 전이 대상에 @SystemInvoked 유스케이스 자신을 더한다. 3. org.springframework.security.web·config.annotation.web· oauth2.server.resource·oauth2.jwt 패키지와 AuthenticationProvider· AuthorizationManager를 사용자 전송·요청 처리기 목록에 더한다. 4. 설정이 의존하는 프로젝트 클래스가 요청 처리기 타입을 상속·구현하면 그 설정도 사용자 전송으로 본다. 5. capabilityProjects와 주석 처리된 runtimeOnly 줄에 inbound messaging을 더한다. 매뉴얼 07 표와 app AGENTS를 같이 고쳤다. 지금 운영 코드에 걸리는 곳은 없다(inbound가 그런 포트를 import한 곳 0, 조립 모듈 controller 0). 버린 대안: inbound가 application *Port 전부를 못 쓰게 하기 — web이 AuthorizationPort·CorrelationIdPort를 구현하고 쓰므로 맞는 코드가 걸린다. IdFactory는 지금 DurableOperationController가 쓰고 있어 이번 규칙에서 뺐다 (그 controller의 id 생성은 리뷰 RR9-05-13로 따로 고친다). 위험·한계: 규칙 3·4는 목록·클래스 의존 방식이라, 목록에 없는 보안 타입이나 타입 이름이 남지 않는 길(bean 이름 조회, 함수로 감싸 넘기기)은 여전히 못 본다(매뉴얼 07 「규칙이 못 보는 길」). gRPC 서비스 fixture는 io.grpc가 architectureTest 컴파일 classpath에 없어 두지 않았다 — 판정은 BindableService 이름으로 한다. 검증(desktop, --no-build-cache): - RED: 기준 a7e38c10 + 새 fixture와 시험(새 규칙 대신 기존 규칙을 부르는 변형)만으로 ArchitectureViolationFixtureTest 204건 중 5건 실패 — 다섯 위반 모두 기존 규칙에 안 걸림. 허용 시험은 통과. - GREEN: :app-bootstrap:resolveAndLockAll --write-locks(잠금 변화 없음), spotlessApply 뒤 :app-bootstrap:architectureTest 259건 실패 0, :app-bootstrap:testQualityCheck, :app-bootstrap:spotlessCheck, :verifyDependencyLocks, :architectureCheck rc=0. 로그 desktop ~/r9-be-logs/b14-{red,green2}.log. Refs: docs/reviews/2026-11-12-round9-review RR9-05-01~05 --- docs/manual/07-authorization.md | 5 +- src/bootstrap/app/AGENTS.md | 2 +- src/bootstrap/app/build.gradle | 2 + .../AdapterBoundaryArchitectureTest.java | 61 +++++++++ .../ApplicationBoundaryArchitectureTest.java | 66 ++++++++- .../ArchRuleDiscoveryContractTest.java | 2 + .../ArchitectureViolationFixtureTest.java | 129 +++++++++++++++++- ...ainRepositoryHoldingControllerFixture.java | 26 ++++ ...UnmarkedRelayCallingControllerFixture.java | 16 +++ ...sideASystemCallerConfigurationFixture.java | 33 +++++ .../domain/order/OrderRepository.java | 10 ++ ...ontrollerReachingSystemInvokedFixture.java | 20 +++ .../ops/UnmarkedSystemWorkRelayFixture.java | 17 +++ ...ionManagerReachingSystemCallerFixture.java | 26 ++++ 14 files changed, 404 insertions(+), 11 deletions(-) create mode 100644 src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/DomainRepositoryHoldingControllerFixture.java create mode 100644 src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/UnmarkedRelayCallingControllerFixture.java create mode 100644 src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/InterceptorFieldBesideASystemCallerConfigurationFixture.java create mode 100644 src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/domain/order/OrderRepository.java create mode 100644 src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/OpsControllerReachingSystemInvokedFixture.java create mode 100644 src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/UnmarkedSystemWorkRelayFixture.java create mode 100644 src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/security/AuthorizationManagerReachingSystemCallerFixture.java diff --git a/docs/manual/07-authorization.md b/docs/manual/07-authorization.md index c8127597..71cfd8cf 100644 --- a/docs/manual/07-authorization.md +++ b/docs/manual/07-authorization.md @@ -102,9 +102,10 @@ client가 같은 이름의 역할을 정의해도 이 서비스 권한이 되지 | 규칙 | 무엇을 막나 | 어디 | | --- | --- | --- | | bean 금지 | `@SystemInvoked` 유스케이스가 bean이면 기동 실패. 호출자가 `new`로 만들어 혼자 들고 있는 것만 허용한다 | `src/bootstrap/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java` | -| 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스와 그 안에 중첩된 클래스만 예외 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) | +| 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스와 그 안에 중첩된 클래스만 예외. inbound 밖 사용자 전송과 중간 클래스를 거친 길은 아래 「전송 → 시스템 호출자 금지」가 잡는다 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) | +| controller 위치 | Spring controller는 `..adapter.inbound..`에만 둔다. 조립 루트나 조립 모듈에 둔 controller는 빌드 실패 | `CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS`(`AdapterBoundaryArchitectureTest`) | | 표시 검사 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·JAX-RS·GraphQL·STOMP mapping과 channel interceptor·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) | -| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`나, 그 클래스가 구현·상속하는 프로젝트 타입(작업의 인터페이스 등)에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 클래스는 넷이다. ① 사용자 전송 패키지에 있는 클래스. ② 설정(`@Configuration`·`@AutoConfiguration`) 클래스 자신이 요청 처리기 타입(함수형 `RouterFunction`·`HandlerFunction`, `@RestController`·`@RequestMapping`, servlet·`Filter`·`HandlerInterceptor`, `WebSocketHandler`, GraphQL `DataFetcher`·`RuntimeWiringConfigurer`, gRPC `BindableService`·`ServerInterceptor`, STOMP `ChannelInterceptor`·`ExecutorChannelInterceptor` 등)에 의존하는 것. 요청 처리 코드를 설정에 직접 쓴 경우와 등록만 한 경우가 모두 든다. channel interceptor를 구현한 설정은 프레임마다 자기 메서드가 돈다. interceptor를 `@Bean`으로 내놓는 설정은 route를 등록하는 설정과 같다. 함수형 route나 data fetcher를 람다로 쓰면 그 코드가 설정 클래스의 메서드로 컴파일되어 설정이 곧 endpoint다. 처리 코드를 다른 클래스에 두고 메서드 참조로 등록만 해도(`route().GET("/orders", orders::list)`) 설정은 route builder에 의존한다. 클래스 의존으로는 등록과 처리 코드를 가를 수 없어서 둘 다 사용자 전송으로 센다. ③ 설정 안에 중첩된 클래스 가운데 사용자 전송 타입에 의존하는 것. 중첩된 JAX-RS 자원·`@ServerEndpoint`, `configureClientInboundChannel`에서 등록하는 STOMP channel interceptor(익명 클래스여도, STOMP 헤더를 읽지 않아도)도 여기서 잡힌다. 설정용 타입(`WebMvcConfigurer`·`WebSocketConfigurer`·STOMP broker 설정과 그 registry, CORS 설정, `RequestMethod`)에만 의존하는 중첩 클래스는 설정의 일부로 본다. inbound channel의 thread 수만 정하는 설정도 설정용이다. ④ 그 밖의 클래스 가운데 사용자 전송 타입에 의존하는 것. 사용자 전송 패키지 밖에 둔 channel interceptor가 여기에 든다. 그래서 handler를 bean으로 등록하는 설정은 같은 클래스에서 `WebMvcConfigurer`(설정 필드를 읽는 익명 클래스여도)·CORS 설정·controller bean을 함께 만들어도 걸리지 않는다. 같은 클래스에 "지금 실행" route·data fetcher·interceptor를 쓰거나, route를 등록하거나, 안에 중첩한 endpoint가 작업을 부르면(설정의 메서드를 거쳐 불러도) 걸린다. route·data fetcher·interceptor 등록은 handler bean을 만드는 설정과 다른 설정에 둔다. 설정이 만드는 controller는 controller 자신이 검사받는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) | +| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`나, 그 클래스가 구현·상속하는 프로젝트 타입(작업의 인터페이스 등), 또는 `@SystemInvoked` 유스케이스 자신에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 타입에는 Spring Security의 요청 경로 확장점(`org.springframework.security.web`·`.config.annotation.web`·`.oauth2.server.resource`·`.oauth2.jwt` 패키지, `AuthenticationProvider`, `AuthorizationManager`)이 든다. 그래서 web 패키지 밖에 둔 JWT converter나 authorization manager도 사용자 전송이다. 사용자 전송 클래스는 넷이다. ① 사용자 전송 패키지에 있는 클래스. ② 설정(`@Configuration`·`@AutoConfiguration`) 클래스 자신이 요청 처리기 타입(함수형 `RouterFunction`·`HandlerFunction`, `@RestController`·`@RequestMapping`, servlet·`Filter`·`HandlerInterceptor`, `WebSocketHandler`, GraphQL `DataFetcher`·`RuntimeWiringConfigurer`, gRPC `BindableService`·`ServerInterceptor`, STOMP `ChannelInterceptor`·`ExecutorChannelInterceptor` 등)에 의존하는 것. 요청 처리 코드를 설정에 직접 쓴 경우와 등록만 한 경우가 모두 든다. 요청 처리기 타입을 구현·상속한 프로젝트 클래스(예: `ChannelInterceptor`를 구현한 interceptor)를 필드·생성자 인자·`new`로 쥔 설정도 든다. `registration.interceptors(frameCounter)`는 클래스 의존으로 `ChannelRegistration`만 남기므로 그 필드의 타입이 설정을 사용자 전송으로 만든다. channel interceptor를 구현한 설정은 프레임마다 자기 메서드가 돈다. interceptor를 `@Bean`으로 내놓는 설정은 route를 등록하는 설정과 같다. 함수형 route나 data fetcher를 람다로 쓰면 그 코드가 설정 클래스의 메서드로 컴파일되어 설정이 곧 endpoint다. 처리 코드를 다른 클래스에 두고 메서드 참조로 등록만 해도(`route().GET("/orders", orders::list)`) 설정은 route builder에 의존한다. 클래스 의존으로는 등록과 처리 코드를 가를 수 없어서 둘 다 사용자 전송으로 센다. ③ 설정 안에 중첩된 클래스 가운데 사용자 전송 타입에 의존하는 것. 중첩된 JAX-RS 자원·`@ServerEndpoint`, `configureClientInboundChannel`에서 등록하는 STOMP channel interceptor(익명 클래스여도, STOMP 헤더를 읽지 않아도)도 여기서 잡힌다. 설정용 타입(`WebMvcConfigurer`·`WebSocketConfigurer`·STOMP broker 설정과 그 registry, CORS 설정, `RequestMethod`)에만 의존하는 중첩 클래스는 설정의 일부로 본다. inbound channel의 thread 수만 정하는 설정도 설정용이다. ④ 그 밖의 클래스 가운데 사용자 전송 타입에 의존하는 것. 사용자 전송 패키지 밖에 둔 channel interceptor가 여기에 든다. 그래서 handler를 bean으로 등록하는 설정은 같은 클래스에서 `WebMvcConfigurer`(설정 필드를 읽는 익명 클래스여도)·CORS 설정·controller bean을 함께 만들어도 걸리지 않는다. 같은 클래스에 "지금 실행" route·data fetcher·interceptor를 쓰거나, route를 등록하거나, 안에 중첩한 endpoint가 작업을 부르면(설정의 메서드를 거쳐 불러도) 걸린다. route·data fetcher·interceptor 등록은 handler bean을 만드는 설정과 다른 설정에 둔다. 설정이 만드는 controller는 controller 자신이 검사받는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) | | 프로젝트 밖 상위 타입 금지 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스(익명·지역 클래스와 예외 제외)는 프로젝트(`dev.caskeleton..`와 소유자의 별도 repo 라이브러리 `dev.cakit..`) 밖의 클래스·인터페이스를 상속·구현하지 않는다. `Runnable`은 누구나 의존하는 타입이라, endpoint가 작업을 `Runnable`로 주입받아도 위 규칙이 다른 사용과 구별하지 못하기 때문이다. 메시지 handler의 `MessageHandler`(메시징 라이브러리 `dev.cakit.messaging`)는 프로젝트 타입으로 쳐서 된다. record·enum은 언어가 붙이는 상위 타입(`Record`, `Enum`과 `Enum`이 구현하는 `Comparable`·`Serializable`·`Constable`)만은 가져도 된다. 그래서 handler 안의 파싱 결과 record, 결과 enum, 독(poison) 메시지 예외, record로 쓴 handler는 통과하고, `Runnable`을 구현한 record는 걸린다 | `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`(같은 파일) | 규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 이 성질은 **패키지** 쪽에서만 온다. diff --git a/src/bootstrap/app/AGENTS.md b/src/bootstrap/app/AGENTS.md index 175c9045..201001a6 100644 --- a/src/bootstrap/app/AGENTS.md +++ b/src/bootstrap/app/AGENTS.md @@ -27,7 +27,7 @@ ## 금지 - 구체적인 업무 정책. -- bootstrap 아래에 직접 쓴 controller, 유스케이스, repository 어댑터, mapper. +- bootstrap 아래에 직접 쓴 controller, 유스케이스, repository 어댑터, mapper. controller는 `CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS`가 빌드에서 막는다. - 업무 로직을 구현하는 설정 클래스. - `application-core`나 `domain-core` 포트를 구현하기. 포트를 구현하는 클래스는 의존성을 어떻게 설정했든 outbound 어댑터이고 `adapter/outbound/*` leaf에 둔다 — diff --git a/src/bootstrap/app/build.gradle b/src/bootstrap/app/build.gradle index e0697407..1ed7df74 100644 --- a/src/bootstrap/app/build.gradle +++ b/src/bootstrap/app/build.gradle @@ -138,6 +138,7 @@ def capabilityProjects = [ ':adapter:outbound:objectstorage', ':adapter:inbound:websocket', ':adapter:inbound:grpc', + ':adapter:inbound:messaging', ':composition:fileserver-platform', ':composition:notification-platform', ] @@ -164,6 +165,7 @@ dependencies { // runtimeOnly project(':adapter:outbound:objectstorage') // 객체 저장소 (S3/로컬) // runtimeOnly project(':adapter:inbound:websocket') // WebSocket (STOMP push) // runtimeOnly project(':adapter:inbound:grpc') // gRPC 서버 + // runtimeOnly project(':adapter:inbound:messaging') // Kafka 소비 inbox (handler가 있을 때만) // runtimeOnly project(':composition:fileserver-platform') // 파일 서버 // runtimeOnly project(':composition:notification-platform') // 알림 (persistence-jpa·persistence-notification을 함께 가져온다) diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java index 10371835..17516da9 100644 --- a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java @@ -406,6 +406,67 @@ class AdapterBoundaryArchitectureTest { + "notification) are peers: none may depend on a sibling; shared outbound code " + "lives in :adapter:outbound:support (Task 7 adapter topology)"); + /** + * The endpoints a user request lands on: a Spring controller wherever it is filed, and a gRPC + * service, which carries no controller annotation (review 2026-11-12). + */ + static final DescribedPredicate ARE_ENDPOINTS = + CleanArchitectureRuleSupport.ARE_CONTROLLERS.or( + DescribedPredicate.describe( + "are gRPC services", type -> type.isAssignableTo("io.grpc.BindableService"))); + + /** + * A domain repository port, an application store port or a read-model query port: the ports a use + * case owns to reach persistence. The generator files the repository port beside its aggregate in + * {@code dev.caskeleton.domain.}, not in a {@code ..repository..} package, so the + * package rule below never saw it. + */ + static final DescribedPredicate ARE_PERSISTENCE_PORTS = + JavaClass.Predicates.resideInAnyPackage("..domain..", "..application..") + .and( + DescribedPredicate.describe( + "named *Repository, *StorePort or *QueryPort", + type -> + type.getName().startsWith("dev.caskeleton.") + && (type.getSimpleName().endsWith("Repository") + || type.getSimpleName().endsWith("StorePort") + || type.getSimpleName().endsWith("QueryPort")))) + .as("domain repository, application store and query ports"); + + /** + * HARD-STOP 2 for the ports themselves: an endpoint reaches persistence only through a use case. + * A controller handed {@code OrderRepository} compiles (web depends on domain-core) and passed + * every rule until 2026-11-12, because the rules below look for repository packages and Spring + * Data types. + */ + @ArchTest + static final ArchRule ENDPOINTS_DO_NOT_HOLD_PERSISTENCE_PORTS = + noClasses() + .that(ARE_ENDPOINTS) + .should() + .dependOnClassesThat(ARE_PERSISTENCE_PORTS) + .as( + "ENDPOINTS_DO_NOT_HOLD_PERSISTENCE_PORTS: a controller or gRPC service calls a use" + + " case; it does not hold a domain repository port, an application store port" + + " or a query port (AGENTS.md HARD-STOP 2)") + .allowEmptyShould(true); + + /** + * A controller is an inbound adapter, so it lives in one. One filed in the composition root or a + * composition module is reached by no transport rule that names inbound packages (app {@code + * AGENTS.md}: no controller in bootstrap). + */ + @ArchTest + static final ArchRule CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS = + classes() + .that(CleanArchitectureRuleSupport.ARE_CONTROLLERS) + .should() + .resideInAPackage("..adapter.inbound..") + .as( + "CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS: a Spring controller lives in an inbound" + + " adapter package (..adapter.inbound..), not in bootstrap or a composition module") + .allowEmptyShould(true); + @ArchTest static final ArchRule CONTROLLERS_DO_NOT_ACCESS_REPOSITORIES_OR_JPA_ENTITIES = noClasses() diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java index 77ae0111..2bd3a769 100644 --- a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java @@ -478,7 +478,14 @@ class ApplicationBoundaryArchitectureTest { "jakarta.servlet", "jakarta.websocket", "jakarta.ws.rs", - "graphql"); + "graphql", + // Spring Security's request-path extension points: a bearer token resolver, an entry + // point, a JWT converter or decoder, the filter-chain DSL. One filed outside the web + // package depends on no servlet type and was no transport (review 2026-11-12). + "org.springframework.security.web", + "org.springframework.security.config.annotation.web", + "org.springframework.security.oauth2.server.resource", + "org.springframework.security.oauth2.jwt"); /** * The single user-transport types named beside the framework packages. A STOMP client-inbound @@ -491,7 +498,9 @@ class ApplicationBoundaryArchitectureTest { "org.springframework.stereotype.Controller", "org.springframework.messaging.handler.annotation.MessageMapping", "org.springframework.messaging.support.ChannelInterceptor", - "org.springframework.messaging.support.ExecutorChannelInterceptor"); + "org.springframework.messaging.support.ExecutorChannelInterceptor", + "org.springframework.security.authentication.AuthenticationProvider", + "org.springframework.security.authorization.AuthorizationManager"); /** * What makes a class a way in for a user request: a user-transport adapter package, or the @@ -529,7 +538,11 @@ class ApplicationBoundaryArchitectureTest { "org.springframework.graphql.data.method.annotation", "org.springframework.graphql.server", "jakarta.servlet.http", - "graphql.schema"); + "graphql.schema", + "org.springframework.security.web", + "org.springframework.security.config.annotation.web", + "org.springframework.security.oauth2.server.resource", + "org.springframework.security.oauth2.jwt"); /** The single request-handler types {@code ARE_REQUEST_HANDLER_TYPES} names beside packages. */ static final Set REQUEST_HANDLER_TYPE_NAMES = @@ -555,7 +568,9 @@ class ApplicationBoundaryArchitectureTest { "io.grpc.ServerCall", "io.grpc.stub.StreamObserver", "org.springframework.messaging.support.ChannelInterceptor", - "org.springframework.messaging.support.ExecutorChannelInterceptor"); + "org.springframework.messaging.support.ExecutorChannelInterceptor", + "org.springframework.security.authentication.AuthenticationProvider", + "org.springframework.security.authorization.AuthorizationManager"); /** * The framework types request-handling code is written against or registered with: an annotated @@ -622,9 +637,35 @@ class ApplicationBoundaryArchitectureTest { .or(namedAnyOf("transport setup values", TRANSPORT_SETUP_TYPE_NAMES)) .as("transport setup types (configurers, registries, CORS settings)"); - /** What makes a configuration a way in: a request-handler type that is no setup type. */ + /** + * A project class that is a request-handler type by what it extends or implements: an + * interceptor, a filter or a handler the configuration holds by its own class. {@code + * registration.interceptors(frameCounter)} with a field of the interceptor's own class records + * only {@code ChannelRegistration}, a setup type, and the varargs array it builds is no class + * dependency ArchUnit 1.3 records (review 2026-11-12), so the field type has to make the + * configuration a way in by itself. + */ + private static final DescribedPredicate ARE_PROJECT_REQUEST_HANDLERS = + DescribedPredicate.describe( + "project classes that extend or implement a request-handler type", + type -> + type.getName().startsWith("dev.caskeleton.") + && java.util.stream.Stream.concat( + type.getAllRawSuperclasses().stream(), + type.getAllRawInterfaces().stream()) + .anyMatch( + supertype -> + ARE_REQUEST_HANDLER_TYPES.test(supertype) + && !ARE_TRANSPORT_SETUP_TYPES.test(supertype))); + + /** + * What makes a configuration a way in: a request-handler type that is no setup type, or a project + * class that is one. + */ private static final DescribedPredicate MAKE_A_CONFIGURATION_A_WAY_IN = - ARE_REQUEST_HANDLER_TYPES.and(DescribedPredicate.not(ARE_TRANSPORT_SETUP_TYPES)); + ARE_REQUEST_HANDLER_TYPES + .and(DescribedPredicate.not(ARE_TRANSPORT_SETUP_TYPES)) + .or(ARE_PROJECT_REQUEST_HANDLERS); /** What makes a class nested in a configuration a way in: any user-transport type but setup. */ private static final DescribedPredicate MAKE_A_NESTED_CLASS_A_WAY_IN = @@ -746,6 +787,16 @@ class ApplicationBoundaryArchitectureTest { } }; + /** + * A {@link SystemInvoked} use case itself, as a target of the transitive rule below: a user + * transport outside {@code ..adapter.inbound..} (a controller in a composition module, a JWT + * converter) or one that reaches the use case through an unmarked class in between is no + * dependency the direct rule here sees (review 2026-11-12). + */ + private static final DescribedPredicate ARE_SYSTEM_INVOKED_USE_CASES = + DescribedPredicate.describe( + "@SystemInvoked use cases", type -> type.isAnnotatedWith(SystemInvoked.class)); + /** * A {@link SystemInvoked} use case is a write with no permission check, so no user request may * reach it. A user comes in through a transport; the system comes in through a delivery or a tick @@ -823,7 +874,8 @@ class ApplicationBoundaryArchitectureTest { noClasses() .that(ARE_USER_TRANSPORTS) .should() - .transitivelyDependOnClassesThat(ARE_TYPES_A_SYSTEM_CALLER_IS_HANDED_AS) + .transitivelyDependOnClassesThat( + ARE_TYPES_A_SYSTEM_CALLER_IS_HANDED_AS.or(ARE_SYSTEM_INVOKED_USE_CASES)) .as( "USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS: a class a user request comes in " + "through (a user-transport package; a configuration that holds or registers " diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java index b559a106..3c5fc54f 100644 --- a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java @@ -95,9 +95,11 @@ class ArchRuleDiscoveryContractTest { "CONFIGURATION_PROPERTIES_END_WITH_SETTINGS_OR_POLICY", "CONTACT_POINT_VALUES_ARE_IMMUTABLE_RECORDS", "CONTROLLERS_DO_NOT_ACCESS_REPOSITORIES_OR_JPA_ENTITIES", + "CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS", "CONTROLLERS_DO_NOT_RETURN_DOMAIN_OR_ENTITY_TYPES", "CONTROLLER_REQUEST_MAPPINGS_FOLLOW_AIP122", "DOMAIN_CONTEXT_PROPAGATION_PRIMITIVES_STAY_UNSHIPPED", + "ENDPOINTS_DO_NOT_HOLD_PERSISTENCE_PORTS", "DOMAIN_ENTITIES_DO_NOT_CARRY_AUDIT_FIELDS", "DOMAIN_EVENTS_ARE_RECORDS", "DOMAIN_EVENTS_ARE_TRANSPORT_FREE", diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java index 5f9be05a..de48d4ea 100644 --- a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java @@ -36,12 +36,14 @@ import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.schedule import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.ScheduledWorkFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.SystemCallerWithNestedEndpointFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.SystemJobLauncherFixture; +import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.DomainRepositoryHoldingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.MessageHandlerInjectingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerInvokingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerRelayingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemInvokedCallingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemJobInterfaceInvokingControllerFixture; +import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.UnmarkedRelayCallingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.outbound.RawExternalResponseFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.outbound.messaging.GenericTypeLeakingAdapterFixture; import dev.caskeleton.bootstrap.architecture.violations.application.BulkWriteWithoutWriteAccessUseCase; @@ -60,11 +62,15 @@ import dev.caskeleton.bootstrap.architecture.violations.configuration.RunNowRout import dev.caskeleton.bootstrap.architecture.violations.domain.AnnotatedPublicNoArgValueObjectFixture; import dev.caskeleton.bootstrap.architecture.violations.domain.JakartaValidationDomainFixture; import dev.caskeleton.bootstrap.architecture.violations.domain.entity.FakeDomainEntity; +import dev.caskeleton.bootstrap.architecture.violations.domain.order.OrderRepository; import dev.caskeleton.bootstrap.architecture.violations.domain.vo.PackagePublicNoArgValueObjectFixture; +import dev.caskeleton.bootstrap.architecture.violations.ops.OpsControllerReachingSystemInvokedFixture; +import dev.caskeleton.bootstrap.architecture.violations.ops.UnmarkedSystemWorkRelayFixture; import dev.caskeleton.bootstrap.architecture.violations.persistence.flyway.ClassicConfigurationFlywayFixture; import dev.caskeleton.bootstrap.architecture.violations.persistence.flyway.ConfigureCallingFlywayFixture; import dev.caskeleton.bootstrap.architecture.violations.persistence.flyway.FluentConfigurationFlywayFixture; import dev.caskeleton.bootstrap.architecture.violations.persistence.flyway.ReferencedConfigurationFlywayFixture; +import dev.caskeleton.bootstrap.architecture.violations.security.AuthorizationManagerReachingSystemCallerFixture; import dev.caskeleton.bootstrap.architecture.violations.streaming.JakartaWebSocketEndpointFixture; import dev.caskeleton.bootstrap.architecture.violations.streaming.SpringWebSocketHandlerFixture; import org.junit.jupiter.api.DisplayName; @@ -840,7 +846,8 @@ class ArchitectureViolationFixtureTest { "RunNowOnFrameConfigurationFixture$RunNowAfterHandling", "RunNowOnFrameInterceptorFixture", "RunNowInterceptingConfigurationFixture", - "InterceptorBesideASystemCallerConfigurationFixture" + "InterceptorBesideASystemCallerConfigurationFixture", + "InterceptorFieldBesideASystemCallerConfigurationFixture" }) void aStompChannelInterceptorThatCallsASystemCallerIsCaughtWhereverItIsKept(String interceptor) { // when @@ -1726,4 +1733,124 @@ class ArchitectureViolationFixtureTest { // then assertThat(result.getFailureReport().getDetails()).isEmpty(); } + + @Test + @DisplayName("inbound 밖에 둔 controller가 @SystemInvoked 유스케이스를 만들어 부르면 전송 규칙과 배치 규칙에 걸린다") + void aControllerOutsideTheInboundPackagesThatRunsASystemInvokedUseCaseIsCaught() { + // given + JavaClasses fixtureOnly = + new ClassFileImporter() + .importClasses( + OpsControllerReachingSystemInvokedFixture.class, SystemInvokedFixtureUseCase.class); + + // when + EvaluationResult transport = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + fixtureOnly); + EvaluationResult placement = + AdapterBoundaryArchitectureTest.CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS.evaluate(fixtureOnly); + + // then + assertThat(transport.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains(OpsControllerReachingSystemInvokedFixture.class.getName()) + .contains(SystemInvokedFixtureUseCase.class.getName())); + assertThat(placement.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains(OpsControllerReachingSystemInvokedFixture.class.getName())); + } + + @Test + @DisplayName("controller가 표시 없는 중간 클래스를 거쳐 @SystemInvoked 유스케이스에 닿아도 걸린다") + void aControllerThatReachesASystemInvokedUseCaseThroughAnUnmarkedClassIsCaught() { + // given + JavaClasses fixtureOnly = + new ClassFileImporter() + .importClasses( + UnmarkedRelayCallingControllerFixture.class, + UnmarkedSystemWorkRelayFixture.class, + SystemInvokedFixtureUseCase.class); + + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + fixtureOnly); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains(UnmarkedRelayCallingControllerFixture.class.getName()) + .contains(SystemInvokedFixtureUseCase.class.getName())); + } + + @Test + @DisplayName("controller가 domain repository 포트를 직접 들면 endpoint 포트 규칙에 걸린다") + void aControllerHoldingADomainRepositoryPortIsCaught() { + // given + JavaClasses fixtureOnly = + new ClassFileImporter() + .importClasses(DomainRepositoryHoldingControllerFixture.class, OrderRepository.class); + + // when + EvaluationResult result = + AdapterBoundaryArchitectureTest.ENDPOINTS_DO_NOT_HOLD_PERSISTENCE_PORTS.evaluate( + fixtureOnly); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains(DomainRepositoryHoldingControllerFixture.class.getName()) + .contains(OrderRepository.class.getName())); + } + + @Test + @DisplayName("포트를 들지 않고 inbound 패키지에 있는 controller는 endpoint 포트 규칙과 배치 규칙을 통과한다") + void anInboundControllerHoldingNoPersistencePortPasses() { + // given + JavaClasses fixtureOnly = new ClassFileImporter().importClasses(PingControllerFixture.class); + + // when + EvaluationResult ports = + AdapterBoundaryArchitectureTest.ENDPOINTS_DO_NOT_HOLD_PERSISTENCE_PORTS.evaluate( + fixtureOnly); + EvaluationResult placement = + AdapterBoundaryArchitectureTest.CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS.evaluate(fixtureOnly); + + // then + assertThat(ports.getFailureReport().getDetails()).isEmpty(); + assertThat(placement.getFailureReport().getDetails()).isEmpty(); + } + + @Test + @DisplayName("web 패키지 밖의 Spring Security AuthorizationManager가 시스템 호출자에 닿으면 걸린다") + void aSecurityExtensionPointOutsideTheWebPackageThatReachesASystemCallerIsCaught() { + // given + JavaClasses fixtureOnly = + new ClassFileImporter() + .importClasses( + AuthorizationManagerReachingSystemCallerFixture.class, + SystemCallerHandlerFixture.class, + SystemInvokedFixtureUseCase.class); + + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + fixtureOnly); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains(AuthorizationManagerReachingSystemCallerFixture.class.getName()) + .contains(SystemCallerHandlerFixture.class.getName())); + } } diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/DomainRepositoryHoldingControllerFixture.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/DomainRepositoryHoldingControllerFixture.java new file mode 100644 index 00000000..70a7dda2 --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/DomainRepositoryHoldingControllerFixture.java @@ -0,0 +1,26 @@ +package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller; + +import dev.caskeleton.bootstrap.architecture.violations.domain.order.OrderRepository; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * Negative fixture for {@code ENDPOINTS_DO_NOT_HOLD_PERSISTENCE_PORTS}: a controller handed the + * domain repository port instead of a use case (HARD-STOP 2). The repository port lives in a {@code + * ..domain..} package, not a {@code ..repository..} one, so the package rule missed it (review + * 2026-11-12). + */ +@RestController +public class DomainRepositoryHoldingControllerFixture { + + private final OrderRepository orders; + + public DomainRepositoryHoldingControllerFixture(OrderRepository orders) { + this.orders = orders; + } + + @PostMapping("/orders") + public void create() { + orders.save("order"); + } +} diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/UnmarkedRelayCallingControllerFixture.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/UnmarkedRelayCallingControllerFixture.java new file mode 100644 index 00000000..2684cace --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/UnmarkedRelayCallingControllerFixture.java @@ -0,0 +1,16 @@ +package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller; + +import dev.caskeleton.bootstrap.architecture.violations.ops.UnmarkedSystemWorkRelayFixture; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a controller that + * reaches a {@code @SystemInvoked} use case through a plain class in between (review 2026-11-12). + */ +public class UnmarkedRelayCallingControllerFixture { + + private final UnmarkedSystemWorkRelayFixture relay = new UnmarkedSystemWorkRelayFixture(); + + public void trigger() { + relay.run(); + } +} diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/InterceptorFieldBesideASystemCallerConfigurationFixture.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/InterceptorFieldBesideASystemCallerConfigurationFixture.java new file mode 100644 index 00000000..69e16857 --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/InterceptorFieldBesideASystemCallerConfigurationFixture.java @@ -0,0 +1,33 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.stomp; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.FrameCountingInterceptorFixture; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.simp.config.ChannelRegistration; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: the configuration + * registers an interceptor held in a field of the interceptor's own class and builds the message + * handler. {@code registration.interceptors(frameCounter)} records only {@code + * ChannelRegistration}, a setup type, and the varargs array is no dependency ArchUnit records, so + * the configuration was no way in (review 2026-11-12). The interceptor's own class makes it one. + */ +@Configuration(proxyBeanMethods = false) +public class InterceptorFieldBesideASystemCallerConfigurationFixture + implements WebSocketMessageBrokerConfigurer { + + private final FrameCountingInterceptorFixture frameCounter = + new FrameCountingInterceptorFixture(); + + @Override + public void configureClientInboundChannel(ChannelRegistration registration) { + registration.interceptors(frameCounter); + } + + @Bean + SystemCallerHandlerFixture systemCallerHandler() { + return new SystemCallerHandlerFixture(); + } +} diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/domain/order/OrderRepository.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/domain/order/OrderRepository.java new file mode 100644 index 00000000..6bbbdd4b --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/domain/order/OrderRepository.java @@ -0,0 +1,10 @@ +package dev.caskeleton.bootstrap.architecture.violations.domain.order; + +/** + * A domain repository port where the generator files one, beside its aggregate. Not a violation on + * its own: {@code DomainRepositoryHoldingControllerFixture} holds it. + */ +public interface OrderRepository { + + void save(String order); +} diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/OpsControllerReachingSystemInvokedFixture.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/OpsControllerReachingSystemInvokedFixture.java new file mode 100644 index 00000000..2de444cf --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/OpsControllerReachingSystemInvokedFixture.java @@ -0,0 +1,20 @@ +package dev.caskeleton.bootstrap.architecture.violations.ops; + +import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS} and {@code + * CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS}: an operations endpoint filed outside {@code + * ..adapter.inbound..}, as a composition module might, that builds a {@code @SystemInvoked} use + * case and runs it. The direct rule reads inbound packages only, so it passed (review 2026-11-12). + */ +@RestController +public class OpsControllerReachingSystemInvokedFixture { + + @PostMapping("/ops/run") + public void run() { + new SystemInvokedFixtureUseCase().handle(); + } +} diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/UnmarkedSystemWorkRelayFixture.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/UnmarkedSystemWorkRelayFixture.java new file mode 100644 index 00000000..ddf5e240 --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/UnmarkedSystemWorkRelayFixture.java @@ -0,0 +1,17 @@ +package dev.caskeleton.bootstrap.architecture.violations.ops; + +import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; + +/** + * An unmarked class between a user transport and a {@code @SystemInvoked} use case: it is no + * {@code @SystemCaller}, so a controller that calls it named neither the use case nor a system + * caller (review 2026-11-12). + */ +public final class UnmarkedSystemWorkRelayFixture { + + private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase(); + + public void run() { + useCase.handle(); + } +} diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/security/AuthorizationManagerReachingSystemCallerFixture.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/security/AuthorizationManagerReachingSystemCallerFixture.java new file mode 100644 index 00000000..37660282 --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/security/AuthorizationManagerReachingSystemCallerFixture.java @@ -0,0 +1,26 @@ +package dev.caskeleton.bootstrap.architecture.violations.security; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import java.util.function.Supplier; +import org.springframework.security.authorization.AuthorizationDecision; +import org.springframework.security.authorization.AuthorizationManager; +import org.springframework.security.authorization.AuthorizationResult; +import org.springframework.security.core.Authentication; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a method-security + * authorization manager filed outside the web package runs on every request it guards, but names no + * servlet type, so it was no transport (review 2026-11-12). + */ +public final class AuthorizationManagerReachingSystemCallerFixture + implements AuthorizationManager { + + private final SystemCallerHandlerFixture handler = new SystemCallerHandlerFixture(); + + @Override + public AuthorizationResult authorize( + Supplier authentication, Object object) { + handler.handle(); + return new AuthorizationDecision(true); + } +} -- 2.54.0 From bd17bf1f0087529431e31b128108c9df48a2a655 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 01:48:48 +0900 Subject: [PATCH 03/23] =?UTF-8?q?fix(env)!:=20env=20=EA=B3=84=EC=95=BD?= =?UTF-8?q?=EC=9D=84=20=EB=B0=B0=ED=8F=AC=20=EC=84=A4=EC=A0=95=20=EB=8F=99?= =?UTF-8?q?=EC=9E=91=EC=97=90=20=EB=A7=9E=EC=B6=94=EA=B3=A0=20verifyEnvKey?= =?UTF-8?q?s=EA=B0=80=20=EA=B7=B8=20=EC=B0=A8=EC=9D=B4=EB=A5=BC=20?= =?UTF-8?q?=EC=9E=A1=EA=B2=8C=20=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: docs/registries/env-keys.yaml·.env.example·배포 설정(profile 밖의 application.yml, config/*.yml, 모듈 module-defaults)이 서로 갈렸고 verifyEnvKeys는 그 차이를 보지 못했다. - .env.example을 복사하면 기동이 실패하는 값이 있었다: APP_DATASOURCE_CONNECTION_TIMEOUT=5s(Hikari long ms, registry 주석이 "기동 실패"라고 적은 그 값), APP_SECURITY_CORS_MAX_AGE=600s(long 초). - 기본값과 다른 예시 값: cache·rate-limit Redis command timeout(2s·1s vs 200ms), APP_LOG_LEVEL_SQL(WARN vs INFO), FORWARD_HEADERS_STRATEGY(native vs none — 프록시 없는 배포에서 forwarded 헤더를 믿게 된다), POSITIVE_SOFT_TTL(빈 줄 — 빈 문자열이 기본값을 덮는다). - registry가 폐기(deprecated_orphaned)로 적은 키 셋을 cache-redis 모듈 설정이 읽는다(COMMAND_TIMEOUT, SEMANTIC_REGION, KEY_HMAC_SECRET 참조). - 폐기 키 45개가 .env.example에 값과 함께 남아, 복사하면 아무 일도 하지 않는 값을 켠 것으로 믿는다. 검사가 오히려 registry의 모든 APP_ 행을 예시에 요구해 폐기 행도 넣게 했다. - 배포 설정이 읽는 APP_ 밖 placeholder 11개(SECURITY_PUBLIC_PATHS, PRESENTATION_API_BASE_PATH, SPRING_JACKSON_DESER_* 등)에 registry 행이 없었다. 검사가 APP_ 이름만 보고, registry 파서도 APP_ 행만 읽어 MANAGEMENT_SERVER_ADDRESS 같은 행이 보이지 않았다. - .env.example 머리말은 "빈 키는 기본값을 쓴다", "Seven values"라고 적었다. 고른 방법: 런타임 동작은 바꾸지 않고 registry와 예시를 배포 설정에 맞춘다. 그리고 verifyEnvKeys가 다섯을 더 본다. 1. registry 행은 접두어와 상관없이 읽는다. 2. 배포 설정의 placeholder는 접두어와 상관없이 행이 있어야 한다. 3. deprecated_orphaned 행은 배포 설정이 읽지 않고 .env.example에 없다. 4. .env.example 값은 registry default(행에 example이 있으면 그 값)와 같다. 빈 줄은 빈 문자열로 본다. 5. profile 밖 배포 설정의 placeholder 기본값은 registry default와 같다. registry에 example 칸을 두었다(SMTP 587·timeout처럼 기본값이 아닌 권장값). APP_ 밖 이름 11개는 지금 이름 그대로 등록했다. 바꾸면 파생 서비스의 배포 env가 소리 없이 무시된다. 이름 변경은 소유자 결정이다. registry 머리말을 실제 규칙(SPRING_·MANAGEMENT_·SERVER_·OTEL_ 이름공간과 옛 이름 둘)으로 고쳤다. gRPC를 켜려면 꼭 두는 APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL과 .env.example의 MANAGEMENT_SERVER_ADDRESS를 더했다. 버린 대안: SECURITY_PUBLIC_PATHS·PRESENTATION_API_BASE_PATH를 APP_로 바꾸고 옛 이름을 fallback으로 두기 — 공개 경로 기본값이 4중 placeholder가 되고 공개 경로 스냅숏 파서까지 바꿔야 한다. 이름 정리는 따로 정한다. 위험·한계: 파생 서비스가 자기 placeholder를 등록하지 않았거나 예시 값이 기본값과 다르면 이제 verifyEnvKeys(mainCheck)가 실패한다(upgrade 안내 5·6). 예시 값이 바뀌어 옛 예시를 복사한 .env는 그대로 둔다 — 안내 1~4가 고칠 값을 적는다. 검증(desktop, --no-build-cache): - RED: 기준 a7e38c10 + 시험만으로 EnvContractVerifierTest 22건 중 7건 실패 (새 검사 6건 + 메시지를 바꾼 기존 1건). 새 지킴 시험(example 행 통과)은 기준에서도 통과. - GREEN: -p build-logic test, :app-bootstrap:verifyEnvKeys(314 env keys, 6 required placeholders, 370 rows), :app-bootstrap:test·repositoryContractTest· documentContractTest, registry·예시를 읽는 leaf 시험(httpclient env manifest, notification mode, redis-runtime required_when, support, fileserver·notification platform, graphql registry parity, web CORS) 682건 실패 0, skip 5. rc=0. BREAKING CHANGE: verifyEnvKeys가 접두어 밖 placeholder, 폐기 행의 사용, 예시·기본값 차이를 실패로 본다. .env.example에서 폐기 키가 빠지고 값 여덟이 기본값으로 바뀌었다. 할 일은 docs/upgrade/2026-11-round9-env-keys.md. --- .env.example | 77 ++---- .../config/EnvContractVerifier.java | 133 ++++++++-- .../buildlogic/config/EnvRegistryRow.java | 25 +- .../config/EnvContractVerifierTest.java | 171 ++++++++++++- docs/registries/env-keys.yaml | 230 ++++++++++++++++-- docs/upgrade/2026-11-round9-env-keys.md | 45 ++++ 6 files changed, 581 insertions(+), 100 deletions(-) create mode 100644 docs/upgrade/2026-11-round9-env-keys.md diff --git a/.env.example b/.env.example index 91afa010..1c68b40e 100644 --- a/.env.example +++ b/.env.example @@ -9,10 +9,13 @@ # is a credential in the repository, and the fact that it is 'only an example' is not something a # scanner, a fork, or a hurried operator can tell. # -# A key left blank here uses the inline default in application.yml. Seven values have no default -# at all — the datasource URL, username and password, the application name, and the JWT issuer and -# audience — because a default for any of them is a deployment running against something nobody -# chose. +# Every value here is the registry default (or the row's `example:`, a recommended production +# value such as the SMTP submission port). A blank line is not "use the default": Compose env_file +# and bootRun both set the variable to an empty string, which replaces the default. So a key is left +# blank only when it has no default — secrets, and the values a deployment must choose itself (the +# profile, the application name, the datasource URL and username, the JWT issuer and audience), +# because a default for any of them is a deployment running against something nobody chose. +# Keys the registry marks deprecated_orphaned are not listed: nothing reads them. # ============================================================================= # ---- Configuration ----------------------------------------------------------- @@ -20,9 +23,13 @@ SPRING_PROFILES_ACTIVE= APP_NAME= APP_SERVER_PORT=8080 MANAGEMENT_SERVER_PORT=9001 +# Loopback by default, so the actuator is reachable only from inside the container. Kubernetes +# probes and a Prometheus scrape reach the pod IP: set the address they use (for example 0.0.0.0 +# behind a NetworkPolicy) or run them as a sidecar. +MANAGEMENT_SERVER_ADDRESS=127.0.0.1 APP_SERVER_SHUTDOWN=graceful APP_SERVER_SHUTDOWN_TIMEOUT=30s -APP_SERVER_FORWARD_HEADERS_STRATEGY=native +APP_SERVER_FORWARD_HEADERS_STRATEGY=none APP_SERVER_TOMCAT_MAX_THREADS=200 APP_SERVER_TOMCAT_MIN_SPARE_THREADS=10 APP_SERVER_TOMCAT_ACCEPT_COUNT=100 @@ -42,7 +49,7 @@ APP_DATASOURCE_URL= APP_DATASOURCE_USERNAME= APP_DATASOURCE_POOL_MAX_SIZE=10 APP_DATASOURCE_POOL_MIN_IDLE=2 -APP_DATASOURCE_CONNECTION_TIMEOUT=5s +APP_DATASOURCE_CONNECTION_TIMEOUT=5000 APP_DATASOURCE_DRIVER=org.postgresql.Driver APP_DATASOURCE_DDL_AUTO=validate APP_DATASOURCE_SHOW_SQL=false @@ -57,7 +64,7 @@ APP_LOG_LEVEL_ROOT=INFO APP_LOG_LEVEL_APP=INFO APP_LOG_LEVEL_SPRING=INFO APP_LOG_LEVEL_WEB=INFO -APP_LOG_LEVEL_SQL=WARN +APP_LOG_LEVEL_SQL=INFO APP_LOG_FILE_ENABLED=false APP_LOG_FILE_PATH=logs/ca-skeleton.json APP_LOG_FILE_MAX_SIZE=100MB @@ -76,7 +83,7 @@ APP_SECURITY_CORS_ENABLED=false APP_SECURITY_CORS_ALLOWED_METHODS= APP_SECURITY_CORS_ALLOWED_HEADERS=* APP_SECURITY_CORS_ALLOW_CREDENTIALS=false -APP_SECURITY_CORS_MAX_AGE=600s +APP_SECURITY_CORS_MAX_AGE=600 APP_SECURITY_AUTH_MODE=jwt APP_SESSION_COOKIE_NAME=CA_SESSION APP_SESSION_COOKIE_SECURE=true @@ -85,33 +92,16 @@ APP_SESSION_COOKIE_SAME_SITE=Lax APP_SESSION_COOKIE_PATH=/ APP_SESSION_CSRF_COOKIE_NAME=XSRF-TOKEN APP_SESSION_CSRF_HEADER_NAME=X-XSRF-TOKEN -APP_SESSION_REDIS_NAMESPACE_ENVIRONMENT=local -APP_SESSION_IDLE_TIMEOUT=30m -APP_SESSION_ABSOLUTE_LIFETIME=8h -APP_SESSION_TOUCH_INTERVAL=1m -APP_SESSION_TOMBSTONE_TTL=5m -APP_SESSION_MAXIMUM_ENVELOPE_BYTES=32768 -APP_SESSION_MAXIMUM_ATTRIBUTES=64 -APP_SESSION_MAXIMUM_SCALAR_BYTES=8192 APP_SECURITY_JWT_ISSUER= APP_SECURITY_JWT_AUDIENCE= APP_RATE_LIMIT_ENABLED=false -APP_RATE_LIMIT_REDIS_ENABLED=false APP_RATE_LIMIT_PROVIDER=disabled APP_RATE_LIMIT_FAILURE_POLICY=fail-closed APP_RATE_LIMIT_DEFAULT_POLICY_ID=api-default APP_RATE_LIMIT_FAILURE_RETRY_AFTER=100ms APP_RATE_LIMIT_HASH_KEY_VERSION=1 APP_RATE_LIMIT_KEY_VERSION=1 -APP_RATE_LIMIT_REDIS_HOST= -APP_RATE_LIMIT_REDIS_PORT=6379 -APP_RATE_LIMIT_REDIS_TRUST_PEM= -APP_SESSION_REDIS_TRUST_PEM= -APP_RATE_LIMIT_REDIS_COMMAND_TIMEOUT=1s -APP_RATE_LIMIT_REDIS_MAXIMUM_COMMAND_BYTES=16384 -APP_RATE_LIMIT_REDIS_MAXIMUM_QUEUED_COMMANDS=32 -APP_RATE_LIMIT_REDIS_MAXIMUM_IN_FLIGHT_BYTES=1048576 -APP_RATE_LIMIT_REDIS_NAMESPACE_ENVIRONMENT=local +APP_RATE_LIMIT_REDIS_COMMAND_TIMEOUT=200ms APP_RATE_LIMIT_POLICY_REVISION=v1 APP_RATE_LIMIT_ALGORITHM=sliding-counter APP_RATE_LIMIT_LIMIT=100 @@ -127,12 +117,10 @@ APP_IDEMPOTENCY_TTL=24h # disabled | redis | postgresql. postgresql refuses a non-PostgreSQL data source, so bootRunH2 # runs with disabled or redis. APP_IDEMPOTENCY_PROVIDER=disabled -APP_IDEMPOTENCY_REDIS_NAMESPACE_ENVIRONMENT=local APP_IDEMPOTENCY_PROCESSING_LEASE=30s # Failure retention: at most 30d and not shorter than APP_IDEMPOTENCY_TTL (startup fails). APP_IDEMPOTENCY_FAILURE_RETENTION=24h APP_LEASE_PROVIDER=disabled -APP_LEASE_REDIS_NAMESPACE_ENVIRONMENT=local APP_LEASE_REDIS_DRIFT_BUDGET=10ms APP_CACHE_CANONICAL_DEFAULT_PROVIDER=disabled APP_REDIS_ENABLED=true @@ -179,32 +167,10 @@ APP_REDIS_TLS_CLIENT_KEY_REFERENCE= APP_REDIS_TLS_ENABLED=false APP_REDIS_TLS_HOSTNAME_VERIFICATION=true APP_REDIS_TLS_TRUST_MATERIAL_RESOURCE= -APP_CACHE_REDIS_ENABLED=false -APP_CACHE_REDIS_CLIENT_MODE=managed -APP_CACHE_REDIS_HOST= -APP_CACHE_REDIS_PORT=6379 -APP_CACHE_REDIS_TRUST_PEM= -APP_REDIS_SEMANTIC_PROBE_MINIMUM_INTERVAL=5s -APP_REDIS_SENTINEL_DISCOVERY_REFRESH_PERIOD=30s -APP_REDIS_SEMANTIC_PROBE_MAXIMUM_STALENESS=15s -APP_CACHE_REDIS_COMMAND_TIMEOUT=2s -APP_CACHE_REDIS_MAXIMUM_QUEUED_COMMANDS=8 -APP_CACHE_REDIS_MAXIMUM_IN_FLIGHT_BYTES=16777216 -APP_CACHE_REDIS_POSITIVE_SOFT_TTL= -APP_CACHE_REDIS_TTL_JITTER=0.10 +APP_CACHE_REDIS_COMMAND_TIMEOUT=200ms +APP_CACHE_REDIS_POSITIVE_SOFT_TTL=30s APP_CACHE_REDIS_MINIMUM_HARD_TTL=1s -APP_CACHE_REDIS_NAMESPACE_ENVIRONMENT=local APP_CACHE_REDIS_SEMANTIC_REGION=default -APP_CACHE_REDIS_MAXIMUM_VALUE_BYTES=1048576 -APP_CACHE_REDIS_L1_ENABLED=false -APP_CACHE_REDIS_L1_MAXIMUM_ENTRIES=10000 -APP_CACHE_REDIS_L1_MAXIMUM_WEIGHT_BYTES=67108864 -APP_CACHE_REDIS_L1_MAXIMUM_ENTRY_WEIGHT_BYTES=1048576 -APP_CACHE_REDIS_L1_TTL=30s -APP_CACHE_REDIS_L1_GENERATION_RECHECK_INTERVAL=5s -APP_CACHE_REDIS_L1_INVALIDATION_QUEUE_CAPACITY=1024 -APP_CACHE_DEFAULT_TTL=300s -APP_CACHE_NEGATIVE_TTL=60s APP_MESSAGING_BROKER=kafka APP_MESSAGING_PRODUCER_ID= APP_MESSAGING_KAFKA_BROKERS= @@ -301,6 +267,9 @@ APP_WEBSOCKET_ENABLED=true # `false` is the explicit off the Compose lanes set. APP_OBJECTSTORAGE_ENABLED=true APP_GRPC_SERVER_ENABLED=true +# The listener is loopback plaintext only; a deployment that selects the gRPC module sets this to +# true or startup refuses. +APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL=false APP_WEBSOCKET_ENDPOINT=/ws APP_WEBSOCKET_ALLOWED_ORIGINS=http://localhost:3000 APP_WEBSOCKET_BROADCAST_DESTINATION=/topic/events @@ -384,10 +353,6 @@ APP_PRIVACY_PSEUDONYMIZATION_SALT= APP_RATE_LIMIT_REDIS_PASSWORD= APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET= APP_SESSION_REDIS_PASSWORD= -APP_SESSION_REDIS_KEY_HMAC_SECRET= -APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET= -APP_LEASE_REDIS_KEY_HMAC_SECRET= -APP_CACHE_REDIS_PASSWORD= APP_CACHE_REDIS_KEY_HMAC_SECRET= APP_FILESERVER_PLATFORM_OBSERVABILITY_FINGERPRINT_KEY= # The notification platform's seven key purposes. Each is base64 of at least 32 bytes and must diff --git a/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java b/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java index c1f1892e..f917534f 100644 --- a/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java +++ b/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java @@ -9,21 +9,28 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Repository policy for the operator-facing environment contract. No Gradle API. */ public final class EnvContractVerifier { - private static final Pattern ENV_LINE = Pattern.compile("^([A-Z][A-Z0-9_]*)=.*"); + private static final Pattern ENV_LINE = Pattern.compile("^([A-Z][A-Z0-9_]*)=(.*)$"); private static final Pattern PLACEHOLDER = Pattern.compile("\\$\\{([A-Z][A-Z0-9_]*)(:[^}]*)?}"); private static final Pattern SECRET_REFERENCE = Pattern.compile("secret://environment/(APP_[A-Z][A-Z0-9_]*)"); + /** + * A registry row of any name. It used to match {@code APP_} rows only, so the framework-named + * rows ({@code MANAGEMENT_SERVER_ADDRESS}, {@code SPRING_MAIL_*}) were invisible to every rule + * below and a placeholder outside {@code APP_} needed no row at all. + */ private static final Pattern REGISTRY_NAME = - Pattern.compile("^\\s*- name: (APP_[A-Z0-9_]+)"); + Pattern.compile("^\\s*- name: ([A-Z][A-Z0-9_]*)\\s*$"); private static final Pattern REGISTRY_FIELD = Pattern.compile("^\\s*([a-z_]+):\\s*(\\S.*)?$"); private static final Pattern APP_KEY = Pattern.compile("APP_[A-Z][A-Z0-9_]*"); @@ -114,23 +121,34 @@ public final class EnvContractVerifier { requireFile(registryFile, "missing " + registryFile); Set envKeys = new TreeSet<>(); + Map envValues = new TreeMap<>(); for (String line : readLines(envFile)) { Matcher matcher = ENV_LINE.matcher(line); if (matcher.matches()) { envKeys.add(matcher.group(1)); + envValues.put(matcher.group(1), matcher.group(2).trim()); } } Set requiredPlaceholders = new TreeSet<>(); Set allPlaceholders = new TreeSet<>(); Set environmentSecretReferences = new TreeSet<>(); + // name -> the literal defaults the non-profile shipped files give it ("" for ${KEY:}). A + // profile file (application-.yml) overrides on purpose and is not compared; a default + // that nests another placeholder is not a literal and is not compared either. + Map> shippedDefaults = new TreeMap<>(); for (File configurationFile : configurationFiles) { String configuration = read(configurationFile); + boolean profileFile = configurationFile.getName().startsWith("application-"); Matcher placeholderMatcher = PLACEHOLDER.matcher(configuration); while (placeholderMatcher.find()) { allPlaceholders.add(placeholderMatcher.group(1)); if (placeholderMatcher.group(2) == null) { requiredPlaceholders.add(placeholderMatcher.group(1)); + } else if (!profileFile && !placeholderMatcher.group(2).contains("${")) { + shippedDefaults + .computeIfAbsent(placeholderMatcher.group(1), name -> new TreeSet<>()) + .add(normalizedValue(placeholderMatcher.group(2).substring(1))); } } Matcher secretMatcher = SECRET_REFERENCE.matcher(configuration); @@ -139,10 +157,9 @@ public final class EnvContractVerifier { } } - Set applicationAppReferences = new TreeSet<>(); - allPlaceholders.stream() - .filter(name -> name.startsWith("APP_")) - .forEach(applicationAppReferences::add); + // Every name the shipped configuration reads, whatever its prefix: a placeholder outside APP_ + // (SECURITY_PUBLIC_PATHS opens paths to anonymous callers) needs a row as much as an APP_ one. + Set applicationAppReferences = new TreeSet<>(allPlaceholders); applicationAppReferences.addAll(environmentSecretReferences); failUnlessEmpty( @@ -152,26 +169,80 @@ public final class EnvContractVerifier { List registryRows = parseRegistryRows(registryFile); Set registryAppKeys = new TreeSet<>(); Set registryProperties = new TreeSet<>(); + Set liveAppRows = new TreeSet<>(); + Set deprecatedRows = new TreeSet<>(); for (EnvRegistryRow row : registryRows) { registryAppKeys.add(row.name()); row.property().ifPresent(registryProperties::add); + if (row.deprecatedOrphaned()) { + deprecatedRows.add(row.name()); + } else if (row.name().startsWith("APP_")) { + liveAppRows.add(row.name()); + } } failUnlessEmpty( - difference(registryAppKeys, envKeys), + difference(liveAppRows, envKeys), "docs/registries/env-keys.yaml registers APP_ keys absent from .env.example, so an " + "adopter copying the example never sees them: "); - - Set envAppKeys = new TreeSet<>(); - envKeys.stream().filter(name -> name.startsWith("APP_")).forEach(envAppKeys::add); failUnlessEmpty( - difference(envAppKeys, registryAppKeys), - ".env.example declares APP_ keys absent from docs/registries/env-keys.yaml " - + "(registry is the SSOT for APP_ keys): "); + intersection(deprecatedRows, envKeys), + ".env.example sets keys the registry marks deprecated_orphaned — an adopter who copies it" + + " sets a variable nothing reads and believes it is in force: ", + " — take the line out; the registry row stays to tell a deployment that still sets it."); + failUnlessEmpty( + intersection(deprecatedRows, applicationAppReferences), + "docs/registries/env-keys.yaml marks keys deprecated_orphaned that the shipped" + + " configuration still reads: ", + " — the row says nothing reads them and tells deployments to stop setting them; restore" + + " the row (and its default) or remove the placeholder."); + + failUnlessEmpty( + difference(envKeys, registryAppKeys), + ".env.example declares keys absent from docs/registries/env-keys.yaml " + + "(registry is the SSOT): "); failUnlessEmpty( difference(applicationAppReferences, registryAppKeys), - "shipped configuration references APP_ keys absent from docs/registries/env-keys.yaml " - + "(optional defaults and environment secret references are included): "); + "shipped configuration references env keys absent from docs/registries/env-keys.yaml " + + "(any prefix; optional defaults and environment secret references are included): "); + + List valueMismatches = new ArrayList<>(); + for (EnvRegistryRow row : registryRows) { + String expected = row.exampleValue(); + String written = envValues.get(row.name()); + if (written != null && !normalizedValue(written).equals(expected)) { + valueMismatches.add( + row.name() + + ": .env.example writes '" + + written + + "', the registry " + + (row.example().isPresent() ? "example" : "default") + + " is '" + + expected + + "'" + + (written.isEmpty() + ? " (a blank line sets an empty string, which replaces the default)" + : "")); + } + Set defaults = shippedDefaults.getOrDefault(row.name(), Set.of()); + String registered = row.defaultValue().orElse(""); + for (String shipped : defaults) { + if (!shipped.equals(registered)) { + valueMismatches.add( + row.name() + + ": the shipped configuration defaults to '" + + shipped + + "', the registry default is '" + + registered + + "'"); + } + } + } + failUnlessEmpty( + valueMismatches, + "env values disagree with docs/registries/env-keys.yaml: ", + " — the registry default is what the shipped configuration falls back to, and" + + " .env.example writes that default (or the row's example:)."); Set declared = ConfigurationMetadataClasspath.propertiesUnder(metadataClasspath, ""); Set typedProperties = new TreeSet<>(); @@ -351,6 +422,10 @@ public final class EnvContractVerifier { current.property = value; } else if (key.equals("deprecated_orphaned")) { current.deprecatedOrphaned = Boolean.parseBoolean(value); + } else if (key.equals("default")) { + current.defaultValue = normalizedValue(value); + } else if (key.equals("example")) { + current.example = normalizedValue(value); } } if (current != null) { @@ -391,6 +466,25 @@ public final class EnvContractVerifier { } } + private static Set intersection(Collection left, Collection right) { + Set result = new TreeSet<>(left); + result.retainAll(new HashSet<>(right)); + return result; + } + + /** A registry or env value without YAML quotes; {@code null}, {@code ~} and blank are "". */ + private static String normalizedValue(String raw) { + String value = raw.trim(); + if (value.length() >= 2 + && (value.startsWith("\"") && value.endsWith("\"") + || value.startsWith("'") && value.endsWith("'"))) { + value = value.substring(1, value.length() - 1); + } else if (value.equals("null") || value.equals("~")) { + value = ""; + } + return value; + } + private static Set difference(Collection left, Collection right) { Set result = new TreeSet<>(left); result.removeAll(new HashSet<>(right)); @@ -417,13 +511,20 @@ public final class EnvContractVerifier { private final String name; private String property; private boolean deprecatedOrphaned; + private String defaultValue; + private String example; private RowBuilder(String name) { this.name = name; } private EnvRegistryRow build() { - return new EnvRegistryRow(name, Optional.ofNullable(property), deprecatedOrphaned); + return new EnvRegistryRow( + name, + Optional.ofNullable(property), + deprecatedOrphaned, + Optional.ofNullable(defaultValue).filter(value -> !value.isEmpty()), + Optional.ofNullable(example)); } } } diff --git a/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvRegistryRow.java b/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvRegistryRow.java index 77ffd3fc..8b1f6810 100644 --- a/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvRegistryRow.java +++ b/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvRegistryRow.java @@ -3,10 +3,33 @@ package dev.caskeleton.buildlogic.config; import java.util.Objects; import java.util.Optional; +/** + * One {@code env-keys.yaml} row as the environment contract reads it. + * + * @param defaultValue the row's {@code default:}, empty when it is {@code null} or blank — the + * value the shipped configuration falls back to and {@code .env.example} writes + * @param example the row's {@code example:}, the value {@code .env.example} writes instead of the + * default (a recommended production value such as the SMTP submission port) + */ public record EnvRegistryRow( - String name, Optional property, boolean deprecatedOrphaned) { + String name, + Optional property, + boolean deprecatedOrphaned, + Optional defaultValue, + Optional example) { public EnvRegistryRow { Objects.requireNonNull(name, "name"); property = property == null ? Optional.empty() : property; + defaultValue = defaultValue == null ? Optional.empty() : defaultValue; + example = example == null ? Optional.empty() : example; + } + + public EnvRegistryRow(String name, Optional property, boolean deprecatedOrphaned) { + this(name, property, deprecatedOrphaned, Optional.empty(), Optional.empty()); + } + + /** What {@code .env.example} must write for this row: the example, else the default. */ + public String exampleValue() { + return example.or(() -> defaultValue).orElse(""); } } diff --git a/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java b/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java index f3c4f9d1..4cb1250d 100644 --- a/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java +++ b/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java @@ -102,7 +102,7 @@ class EnvContractVerifierTest { Files.readString(fixture.registry()) + "- name: APP_REDIS_UNUSED\n" + " type: string\n" - + " default: null\n"); + + " default: present-but-unread\n"); IllegalStateException failure = assertThrows( @@ -142,7 +142,7 @@ class EnvContractVerifierTest { List.of("APP_REDIS_"), List.of())); - assertTrue(failure.getMessage().contains("shipped configuration references APP_ keys")); + assertTrue(failure.getMessage().contains("shipped configuration references env keys")); assertTrue(failure.getMessage().contains("APP_SECONDARY_ONLY")); } @@ -356,7 +356,7 @@ class EnvContractVerifierTest { Files.writeString( fixture.registry(), Files.readString(fixture.registry()) - + "- name: APP_GHOST_ENABLED\n property: app.ghost.enabled\n type: boolean\n"); + + "- name: APP_GHOST_ENABLED\n property: app.ghost.enabled\n type: boolean\n default: true\n"); Path compose = fixture.repositoryRoot().resolve("compose.yaml"); Files.writeString( compose, "services:\n app:\n environment:\n APP_GHOST_ENABLED: \"true\"\n"); @@ -381,7 +381,7 @@ class EnvContractVerifierTest { Files.writeString( fixture.registry(), Files.readString(fixture.registry()) - + "- name: APP_GHOST_ENABLED\n property: app.ghost.enabled\n type: boolean\n"); + + "- name: APP_GHOST_ENABLED\n property: app.ghost.enabled\n type: boolean\n default: true\n"); Path ghostClasses = fixture.repositoryRoot().resolve("adapter/ghost/build/classes/java/main"); Files.createDirectories(ghostClasses.resolve("META-INF")); Files.writeString( @@ -398,6 +398,167 @@ class EnvContractVerifierTest { assertEquals(3, result.envKeyCount()); } + @Test + @DisplayName("APP_ 밖 이름의 placeholder도 레지스트리에 없으면 실패한다") + void aPlaceholderOutsideTheAppPrefixMustBeRegistered(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString( + fixture.applicationYaml(), + Files.readString(fixture.applicationYaml()) + "paths: ${SECURITY_PUBLIC_PATHS:/v1/health}\n"); + + // when + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> verify(fixture)); + + // then + assertTrue(failure.getMessage().contains("shipped configuration references env keys absent")); + assertTrue(failure.getMessage().contains("SECURITY_PUBLIC_PATHS")); + } + + @Test + @DisplayName("APP_ 밖 이름의 레지스트리 행도 placeholder를 등록한 것으로 친다") + void aFrameworkNamedRegistryRowRegistersItsPlaceholder(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString( + fixture.applicationYaml(), + Files.readString(fixture.applicationYaml()) + + "address: ${MANAGEMENT_SERVER_ADDRESS:127.0.0.1}\n"); + Files.writeString( + fixture.registry(), + Files.readString(fixture.registry()) + + "- name: MANAGEMENT_SERVER_ADDRESS\n type: string\n default: 127.0.0.1\n"); + + // when + EnvContractResult result = verify(fixture); + + // then + assertEquals(3, result.applicationReferenceCount()); + } + + @Test + @DisplayName("deprecated_orphaned 행의 키를 .env.example이 아직 쓰면 실패한다") + void aDeprecatedKeyTheExampleStillSetsFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString( + fixture.envFile(), Files.readString(fixture.envFile()) + "APP_REDIS_OLD=2s\n"); + Files.writeString( + fixture.registry(), + Files.readString(fixture.registry()) + + "- name: APP_REDIS_OLD\n deprecated_orphaned: true\n type: duration\n default: 2s\n"); + + // when + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> verify(fixture)); + + // then + assertTrue(failure.getMessage().contains("marks deprecated_orphaned")); + assertTrue(failure.getMessage().contains("APP_REDIS_OLD")); + } + + @Test + @DisplayName("deprecated_orphaned 행의 키를 배포 설정이 아직 읽으면 실패한다") + void aDeprecatedKeyTheConfigurationStillReadsFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString( + fixture.applicationYaml(), + Files.readString(fixture.applicationYaml()) + "timeout: ${APP_REDIS_OLD:200ms}\n"); + Files.writeString( + fixture.registry(), + Files.readString(fixture.registry()) + + "- name: APP_REDIS_OLD\n deprecated_orphaned: true\n type: duration\n default: 200ms\n"); + + // when + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> verify(fixture)); + + // then + assertTrue(failure.getMessage().contains("that the shipped configuration still reads")); + assertTrue(failure.getMessage().contains("APP_REDIS_OLD")); + } + + @Test + @DisplayName(".env.example 값이 레지스트리 기본값과 다르면 실패하고, 빈 줄은 빈 문자열로 친다") + void anExampleValueThatIsNotTheRegistryDefaultFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString(fixture.envFile(), "APP_REQUIRED=required\nAPP_REDIS_HOST=\n"); + + // when + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> verify(fixture)); + + // then + assertTrue(failure.getMessage().contains("APP_REDIS_HOST: .env.example writes ''")); + assertTrue(failure.getMessage().contains("a blank line sets an empty string")); + } + + @Test + @DisplayName("행의 example 값을 .env.example이 쓰면 기본값과 달라도 통과한다") + void anExampleValueTheRowNamesPasses(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString( + fixture.envFile(), Files.readString(fixture.envFile()) + "SPRING_MAIL_PORT=587\n"); + Files.writeString( + fixture.registry(), + Files.readString(fixture.registry()) + + "- name: SPRING_MAIL_PORT\n type: integer\n default: null\n example: 587\n"); + + // when + EnvContractResult result = verify(fixture); + + // then + assertEquals(3, result.envKeyCount()); + } + + @Test + @DisplayName("배포 설정의 기본값이 레지스트리 기본값과 다르면 실패하고, profile 파일은 비교하지 않는다") + void aShippedDefaultThatIsNotTheRegistryDefaultFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Path profile = fixture.applicationYaml().resolveSibling("application-local.yml"); + Files.writeString(profile, "redis: ${APP_REDIS_HOST:127.0.0.1}\n"); + Files.writeString( + fixture.applicationYaml(), + "required: ${APP_REQUIRED}\nredis: ${APP_REDIS_HOST:redis.internal}\n"); + + // when + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> + EnvContractVerifier.verify( + fixture.envFile().toFile(), + List.of(fixture.applicationYaml().toFile(), profile.toFile()), + fixture.registry().toFile(), + List.of(), + fixture.metadataClasspath(), + List.of("app.redis."), + List.of("APP_REDIS_"), + List.of())); + + // then + assertTrue( + failure + .getMessage() + .contains( + "APP_REDIS_HOST: the shipped configuration defaults to 'redis.internal', the" + + " registry default is 'localhost'")); + assertTrue(!failure.getMessage().contains("127.0.0.1"), failure.getMessage()); + } + + private static EnvContractResult verify(Fixture fixture) { + return EnvContractVerifier.verify( + fixture.envFile().toFile(), + List.of(fixture.applicationYaml().toFile()), + fixture.registry().toFile(), + List.of(), + fixture.metadataClasspath(), + List.of("app.redis."), + List.of("APP_REDIS_"), + List.of()); + } + private static EnvContractResult verifyWithOperatorFiles( Fixture fixture, Path operatorFile, Path... otherModuleClasses) { List classpath = new ArrayList<>(fixture.metadataClasspath()); @@ -435,7 +596,7 @@ class EnvContractVerifierTest { applicationYaml, "required: ${APP_REQUIRED}\nredis: ${APP_REDIS_HOST:localhost}\n"); Files.writeString( registry, - "- name: APP_REQUIRED\n type: string\n default: none\n" + "- name: APP_REQUIRED\n type: string\n default: required\n" + "- name: APP_REDIS_HOST\n property: app.redis.host\n type: string\n default: localhost\n"); Files.writeString(metadata, "{\"properties\":[{\"name\":\"app.redis.host\"}]}"); return new Fixture(repositoryRoot, envFile, applicationYaml, registry, redisClasses, metadata); diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 8d362b5a..3df26fc2 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -1,13 +1,18 @@ # Registry: Env Keys # Schema owner: feature-contract-registry-governance # Owner branch: feature-env-driven-runtime-configuration -# Last updated: 2026-09-25 +# Last updated: 2026-11-12 # # 표기 규칙 # - 애플리케이션이 가진 env는 모두 `APP_` 접두어를 쓴다(D2, 2026-06-05). Spring 속성으로 이어지는 # datasource·server 등의 키도 APP_*로 바꿨다(예: SERVER_PORT -> APP_SERVER_PORT). -# - Spring 런타임이 직접 읽는 env만 원래 이름으로 둔다: SPRING_*와 SPRING_PROFILES_ACTIVE -# (D6 — profile 선택자는 APP_가 아니라 Spring 자체 이름이다). +# - 원래 이름으로 두는 것: Spring Boot 이름공간(SPRING_*·MANAGEMENT_*·SERVER_*, profile 선택자 SPRING_PROFILES_ACTIVE +# 포함 — D6), OpenTelemetry 규격 이름(OTEL_*), 그리고 APP_ 통일 전에 퍼진 두 이름(SECURITY_PUBLIC_PATHS, +# PRESENTATION_API_BASE_PATH, 맨 아래 절). 새 키는 APP_를 쓴다. +# - 배포 설정의 placeholder는 접두어와 상관없이 모두 행이 있어야 한다(verifyEnvKeys, 2026-11-12부터). +# - `default`는 배포 설정의 placeholder 기본값과 같고, .env.example은 그 값을 쓴다. 기본값이 아닌 권장값을 쓰는 +# 행은 `example`에 그 값을 둔다. 빈 줄은 빈 문자열로 들어가 기본값을 덮으므로, 빈 칸은 기본값이 없는 키뿐이다. +# - `deprecated_orphaned: true` 행은 배포 설정이 읽지 않고 .env.example에도 없다(둘 다 verifyEnvKeys가 본다). # - `classification: secret` 행은 secrets-classification.yaml을 가리키기만 한다. 행 전체는 그 파일이 가진다. # - reload_policy 기본값 = `restart-only` (env-driven branch "config reload: no runtime reload" — 실행 중 # 다시 읽지 않는다). @@ -666,7 +671,7 @@ env_keys: - name: APP_LOG_LEVEL_SQL # source: feature-log-management-contract — JPA/JDBC SQL 패키지 레벨 (DEBUG면 SQL을 찍는다) type: enum - default: WARN + default: INFO allowed_values: [TRACE, DEBUG, INFO, WARN, ERROR, OFF] classification: public-config required: false @@ -938,14 +943,16 @@ env_keys: - name: APP_SECURITY_CORS_MAX_AGE # source: feature-security-operational-baseline 2026-05-22 # "preflight max-age 600s default" - type: duration - default: 600s + # 단위: 초. 이 값은 app.cors.max-age-seconds(CorsSettings의 long)로 간다 — "600s"는 바인딩되지 않아 + # dev·prod 기동이 실패한다. 이 행이 duration / 600s라 했고 .env.example이 그 값을 복사했다(2026-11-12 리뷰). + type: integer + default: 600 allowed_values: null classification: public-config required: false reload_policy: restart-only owner_branch: feature-security-operational-baseline - validation: spring_duration_shorthand + validation: non_negative_integer_seconds compatibility_impact: behavior-change required_test: security-contract:cors-preflight-max-age @@ -1425,7 +1432,7 @@ env_keys: - name: APP_RATE_LIMIT_REDIS_COMMAND_TIMEOUT type: duration - default: 1s + default: 200ms allowed_values: null classification: public-config required: false @@ -2545,10 +2552,9 @@ env_keys: required_test: redis-contract:semantic-probe-staleness-bounded - name: APP_CACHE_REDIS_KEY_HMAC_SECRET - # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 - # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. - deprecated_orphaned: true - removal_deadline: 2026-11-30 + # 2026-09-25 capability 포장 때 cache-redis 모듈 기본 설정(config/module-defaults/cache-redis.yml)이 + # app.capabilities.cache.*에 이 키를 다시 묶었다. 2026-08-10 폐기 표시가 그 뒤로 틀린 채 남아 있었다 + # (2026-11-12 리뷰, verifyEnvKeys가 이제 폐기 행을 읽는 placeholder를 잡는다). type: string default: null allowed_values: null @@ -2561,12 +2567,11 @@ env_keys: required_test: cache-contract:redis-hmac-secret-bounded - name: APP_CACHE_REDIS_COMMAND_TIMEOUT - # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 - # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. - deprecated_orphaned: true - removal_deadline: 2026-11-30 + # 2026-09-25 capability 포장 때 cache-redis 모듈 기본 설정(config/module-defaults/cache-redis.yml)이 + # app.capabilities.cache.*에 이 키를 다시 묶었다. 2026-08-10 폐기 표시가 그 뒤로 틀린 채 남아 있었다 + # (2026-11-12 리뷰, verifyEnvKeys가 이제 폐기 행을 읽는 placeholder를 잡는다). type: duration - default: 2s + default: 200ms allowed_values: null classification: public-config required: false @@ -2610,7 +2615,7 @@ env_keys: - name: APP_CACHE_REDIS_POSITIVE_SOFT_TTL type: duration - default: null + default: 30s allowed_values: null classification: public-config required: false @@ -2668,10 +2673,9 @@ env_keys: required_test: cache-contract:redis-namespace-environment-bound - name: APP_CACHE_REDIS_SEMANTIC_REGION - # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 - # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. - deprecated_orphaned: true - removal_deadline: 2026-11-30 + # 2026-09-25 capability 포장 때 cache-redis 모듈 기본 설정(config/module-defaults/cache-redis.yml)이 + # app.capabilities.cache.*에 이 키를 다시 묶었다. 2026-08-10 폐기 표시가 그 뒤로 틀린 채 남아 있었다 + # (2026-11-12 리뷰, verifyEnvKeys가 이제 폐기 행을 읽는 placeholder를 잡는다). type: string default: default allowed_values: null @@ -3860,6 +3864,8 @@ env_keys: # source: persistence-mongo techlead review C1. Spring Boot 4는 이 자체 키를 spring.mongodb.uri로 쓴다. # 유효한 연결 출처 둘 중 하나다. 다른 하나는 고른 typed profile의 uri-secret을 MongoCredentialResolver로 푼 # 값이다. + property: spring.mongodb.uri + owner_module: adapter-outbound-persistence-mongo type: string default: null allowed_values: null @@ -4072,6 +4078,22 @@ env_keys: validation: boolean compatibility_impact: none required_test: off-state-zero-side-effects-and-env-round-trip + - name: APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL + # 2026-11-12 등록: 지금 구현이 여는 listener는 loopback plaintext뿐이라, 모듈을 켠 배포는 이 값을 true로 + # 명시해야 기동한다(GrpcServerSettings, grpc README 「켜기와 끄기」). registry에 없어 운영자가 찾을 곳이 없었다. + property: app.grpc.server.allow-insecure-local + owner_module: adapter-inbound-grpc + type: boolean + default: false + allowed_values: [true, false] + classification: security-relevant + required: false + required_when: gRPC 모듈이 런타임에 있고 app.grpc.server.enabled가 true일 때 + reload_policy: restart-only + owner_branch: refactor/maturity-review-2026-11 + validation: boolean + compatibility_impact: none + required_test: adapter-contract:grpc-plaintext-requires-explicit-opt-in - name: APP_GRAPHQL_ENABLED # 2026-09-25 capability 포장: 모듈은 있으면 켜진다(모듈 자신의 설정 yml이 이 키를 기본 true로 잇는다). # false가 명시적으로 끄는 값이다. 빌드에 모듈이 없는 것이 보통의 꺼진 상태다. @@ -4846,6 +4868,7 @@ env_keys: owner_module: adapter-outbound-notification type: integer default: null + example: 587 allowed_values: null classification: public-config required: false @@ -4897,6 +4920,7 @@ env_keys: owner_module: adapter-outbound-notification type: boolean default: null + example: true allowed_values: null classification: public-config required: false @@ -4914,6 +4938,7 @@ env_keys: owner_module: adapter-outbound-notification type: boolean default: null + example: true allowed_values: null classification: public-config required: false @@ -4931,6 +4956,7 @@ env_keys: owner_module: adapter-outbound-notification type: integer default: null + example: 5000 allowed_values: null classification: public-config required: false @@ -4948,6 +4974,7 @@ env_keys: owner_module: adapter-outbound-notification type: integer default: null + example: 10000 allowed_values: null classification: public-config required: false @@ -4965,6 +4992,7 @@ env_keys: owner_module: adapter-outbound-notification type: integer default: null + example: 10000 allowed_values: null classification: public-config required: false @@ -5270,3 +5298,161 @@ env_keys: validation: positive_duration compatibility_impact: behavior-change required_test: adapter-contract:notification-callback-replay + + # === 원래 이름으로 읽는 placeholder (2026-11-12 등록) === + # 배포 설정이 읽는데 행이 없던 이름이다. verifyEnvKeys가 APP_ 밖 placeholder를 보지 않아 빠졌다. 이름을 APP_로 + # 바꾸면 파생 서비스의 배포 env가 소리 없이 무시되므로 지금 이름 그대로 등록한다(바꾸는 것은 소유자 결정). + # SPRING_JACKSON_DESER_*·SPRING_JACKSON_SER_*·SPRING_BANNER_MODE는 Spring relaxed 이름이 아니라 application.yml + # placeholder가 만든 이름이다. relaxed 이름(예: SPRING_JACKSON_DESERIALIZATION_FAIL_ON_UNKNOWN_PROPERTIES, + # SPRING_MAIN_BANNER_MODE)도 같은 속성을 덮고, 둘 다 있으면 relaxed 이름이 이긴다(환경 변수 소스가 yml보다 앞선다). + + - name: SECURITY_PUBLIC_PATHS + # 인증을 건너뛰는 경로 CSV(app.security.public-paths). 기본값은 API base path 뒤의 healthcheck 하나이고 + # docs/security/public-paths-snapshot.txt가 그 기본값을 고정한다. 운영자 값은 스냅숏 밖이다. + property: app.security.public-paths + type: csv + default: /v1/healthcheck + allowed_values: null + classification: security-relevant + required: false + reload_policy: restart-only + owner_branch: feature-security-operational-baseline + validation: csv_of_absolute_paths + compatibility_impact: behavior-change + required_test: security-contract:public-path-snapshot + + - name: PRESENTATION_API_BASE_PATH + # 모든 controller 앞에 붙는 경로(presentation.api-base-path). 빈 값이면 접두어 없음. SECURITY_PUBLIC_PATHS의 + # 기본값도 이 값에서 나온다. + type: string + default: /v1 + allowed_values: null + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-api-contract-baseline + validation: leading_slash_path_or_empty + compatibility_impact: behavior-change + required_test: web-contract:api-base-path-prefix + + - name: SPRING_BANNER_MODE + property: spring.main.banner-mode + type: enum + default: console + allowed_values: [off, console, log] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: enum_in_allowed_values + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_MAIN_LAZY_INITIALIZATION + property: spring.main.lazy-initialization + type: boolean + default: false + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_MAIN_LOG_STARTUP_INFO + property: spring.main.log-startup-info + type: boolean + default: true + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_THREADS_VIRTUAL_ENABLED + property: spring.threads.virtual.enabled + type: boolean + default: true + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_JACKSON_DESER_FAIL_ON_UNKNOWN_PROPERTIES + # 요청 경계 Jackson 정책(web AGENTS B1). 끄면 잘못된 본문을 조용히 받아들인다. + property: spring.jackson.deserialization.fail-on-unknown-properties + type: boolean + default: true + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_JACKSON_DESER_FAIL_ON_NULL_FOR_PRIMITIVES + # 요청 경계 Jackson 정책(web AGENTS B1). 끄면 잘못된 본문을 조용히 받아들인다. + property: spring.jackson.deserialization.fail-on-null-for-primitives + type: boolean + default: true + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_JACKSON_DESER_FAIL_ON_IGNORED_PROPERTIES + # 요청 경계 Jackson 정책(web AGENTS B1). 끄면 잘못된 본문을 조용히 받아들인다. + property: spring.jackson.deserialization.fail-on-ignored-properties + type: boolean + default: true + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_JACKSON_DESER_READ_UNKNOWN_ENUM_VALUES_AS_NULL + # 요청 경계 Jackson 정책(web AGENTS B1). 끄면 잘못된 본문을 조용히 받아들인다. + property: spring.jackson.datatype.enum.read-unknown-enum-values-as-null + type: boolean + default: false + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_JACKSON_SER_WRITE_DATES_AS_TIMESTAMPS + # 요청 경계 Jackson 정책(web AGENTS B1). 끄면 잘못된 본문을 조용히 받아들인다. + property: spring.jackson.datatype.datetime.write-dates-as-timestamps + type: boolean + default: false + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder diff --git a/docs/upgrade/2026-11-round9-env-keys.md b/docs/upgrade/2026-11-round9-env-keys.md new file mode 100644 index 00000000..02ead116 --- /dev/null +++ b/docs/upgrade/2026-11-round9-env-keys.md @@ -0,0 +1,45 @@ +# 업그레이드 안내 — 2026-11 env 키 계약 정리 + +- 범위: `docs/registries/env-keys.yaml`·`.env.example`·`verifyEnvKeys`를 배포 설정의 실제 동작에 맞춘 변경. 앱이 읽는 키와 + 그 기본값은 바뀌지 않았다. 바뀐 것은 예시 파일의 값, registry 행, 그리고 검사가 실패로 보는 범위다. +- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 env 계약 발견 + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 예전 `.env.example`을 복사해 `.env`나 +배포 env를 만든 서비스, 자기 배포 설정에 placeholder를 더한 서비스다. + +## 2. 할 일 + +| # | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | +| 1 | 옛 `.env.example`에서 복사한 `APP_DATASOURCE_CONNECTION_TIMEOUT=5s`를 `5000`(밀리초)으로 바꾼다 | JPA를 켠 배포가 Hikari 바인딩 실패로 기동하지 않는다 | persistence-jpa 선택 | +| 2 | 옛 예시의 `APP_SECURITY_CORS_MAX_AGE=600s`를 `600`(초)으로 바꾼다 | dev·prod 기동이 `app.cors.max-age-seconds` 바인딩 실패로 멈춘다(local은 profile 리터럴이 덮어 안 보인다) | 예시를 복사한 서비스 | +| 3 | 옛 예시에서 복사한 값 다섯을 확인한다: `APP_CACHE_REDIS_COMMAND_TIMEOUT=2s`, `APP_RATE_LIMIT_REDIS_COMMAND_TIMEOUT=1s`, `APP_LOG_LEVEL_SQL=WARN`, `APP_SERVER_FORWARD_HEADERS_STRATEGY=native`, `APP_CACHE_REDIS_POSITIVE_SOFT_TTL=`(빈 값). 새 예시는 기본값(`200ms`, `200ms`, `INFO`, `none`, `30s`)을 쓴다 | 그 값들이 env가 없을 때와 다르게 동작한다. 특히 `native`는 프록시를 거치지 않는 배포에서 호출자가 보낸 forwarded 헤더를 믿는다 | 예시를 복사한 서비스 | +| 4 | `.env`·배포 env에 남은 `deprecated_orphaned` 키(예: `APP_CACHE_REDIS_TTL_JITTER`, `APP_SESSION_IDLE_TIMEOUT`, `APP_CACHE_REDIS_L1_*`)를 지운다. 무엇이 대신하는지는 registry 행 주석에 있다 | 아무 일도 하지 않는 값을 켠 것으로 믿는다 | 예시를 복사한 서비스 | +| 5 | 서비스가 배포 설정(profile 파일 밖의 `application.yml`, `config/*.yml`, 모듈 `config/module-defaults/*.yml`)에 더한 placeholder는 접두어와 상관없이 registry에 행을 더하고, 행의 `default`를 placeholder 기본값과 같게 둔다 | `:app-bootstrap:verifyEnvKeys`(`mainCheck` 안)가 실패한다 | 자기 placeholder를 더한 서비스 | +| 6 | `.env.example`의 값을 registry `default`(또는 행의 `example`)와 같게 둔다. 기본값이 있는 키를 빈 줄로 두지 않는다 | 같은 검사가 실패한다 | 자기 키를 예시에 더한 서비스 | + +## 3. 다시 살린 registry 행 + +아래 셋은 2026-08-10 폐기로 적혀 있었지만, 2026-09-25 capability 포장 뒤로 cache-redis 모듈 설정이 다시 읽는다. +`deprecated_orphaned`를 지우고 기본값을 모듈 설정에 맞췄다. + +| 키 | 읽는 곳 | 기본값 | +| --- | --- | --- | +| `APP_CACHE_REDIS_COMMAND_TIMEOUT` | `app.capabilities.cache.command-timeout` | `200ms`(registry가 `2s`라고 적었다) | +| `APP_CACHE_REDIS_SEMANTIC_REGION` | `app.capabilities.cache.semantic-region` | `default` | +| `APP_CACHE_REDIS_KEY_HMAC_SECRET` | `secret://environment/APP_CACHE_REDIS_KEY_HMAC_SECRET` 참조 | 없음(비밀) | + +## 4. 새로 등록한 이름 + +배포 설정이 읽는데 registry에 없던 이름이다. 이름은 그대로이고 동작도 같다. + +- `SECURITY_PUBLIC_PATHS`, `PRESENTATION_API_BASE_PATH` — APP_ 통일 전에 퍼진 이름이다. 바꾸면 파생 서비스의 배포 env가 + 소리 없이 무시되어 그대로 둔다. +- `SPRING_BANNER_MODE`, `SPRING_JACKSON_DESER_*` 넷, `SPRING_JACKSON_SER_WRITE_DATES_AS_TIMESTAMPS`, + `SPRING_MAIN_LAZY_INITIALIZATION`, `SPRING_MAIN_LOG_STARTUP_INFO`, `SPRING_THREADS_VIRTUAL_ENABLED` — `application.yml` + placeholder 이름이다. Spring relaxed 이름도 같은 속성을 덮고, 둘 다 있으면 relaxed 이름이 이긴다. +- `APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL` — gRPC 모듈을 켠 배포가 기동하려면 `true`로 명시하는 값이다. +- `.env.example`에 `MANAGEMENT_SERVER_ADDRESS=127.0.0.1`을 더했다. Kubernetes 프로브와 Prometheus는 pod IP로 붙으므로 + 원격에서 읽으려면 이 값을 바꾼다. -- 2.54.0 From ebbfafe4549e6448c531b54813200202f642cefa Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 01:48:48 +0900 Subject: [PATCH 04/23] =?UTF-8?q?docs(adapter):=20grpc=C2=B7cache-redis=20?= =?UTF-8?q?README=EC=9D=98=20env=20=ED=82=A4=20=EC=95=88=EB=82=B4=EB=A5=BC?= =?UTF-8?q?=20registry=EC=97=90=20=EB=A7=9E=EC=B6=98=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit grpc README는 "전용 APP_* 키는 registry에 없다"고 했지만 끄는 값 APP_GRPC_SERVER_ENABLED가 있고, 기동에 꼭 두라는 APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL은 registry에 없었다(앞 커밋이 등록). cache-redis README는 운영 비밀로 읽는 곳 없는 폐기 키 셋 (APP_CACHE_REDIS_PASSWORD, APP_IDEMPOTENCY_/LEASE_REDIS_KEY_HMAC_SECRET)을 넣으라고 했다. 자격 증명은 APP_REDIS_AUTHENTICATION_*의 secret 참조다. 검증: python3 scripts/check-docs.py rc=0. --- src/adapter/inbound/grpc/README.md | 7 ++++--- src/adapter/outbound/cache-redis/README.md | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/adapter/inbound/grpc/README.md b/src/adapter/inbound/grpc/README.md index e713d0cf..81ecdc3e 100644 --- a/src/adapter/inbound/grpc/README.md +++ b/src/adapter/inbound/grpc/README.md @@ -23,9 +23,10 @@ 이 줄을 지우면 서버, 포트, 설정 바인딩이 모두 함께 빠진다. - 켜기와 끄기: 모듈이 있으면 켜진다. `app.grpc.server.enabled=false`로만 끈다. -- 필요한 설정: 전용 `APP_*` env 키는 registry에 없다. 켜진 상태에서 지금 구현이 받는 listener는 - loopback plaintext뿐이라 `app.grpc.server.allow-insecure-local=true`(env - `APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL=true`)를 명시해야 기동한다. 선택: `app.grpc.server.port` +- 필요한 설정: registry 행은 끄는 값 `APP_GRPC_SERVER_ENABLED`와 `APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL` 둘이다. + 켜진 상태에서 지금 구현이 받는 listener는 loopback plaintext뿐이라 + `APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL=true`(`app.grpc.server.allow-insecure-local`)를 명시해야 기동한다. 나머지 + `app.grpc.server.*`는 registry 행 없이 Spring relaxed 이름(`APP_GRPC_SERVER_PORT` 등)으로 받는다. 선택: `app.grpc.server.port` (기본 9090), `.bind-address`(기본 127.0.0.1), `.reflection-enabled`, `.shutdown-grace-seconds`, `.shutdown-drain-seconds`, 그리고 아래 「서버 한도」 절의 전송 한도 키. diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index 51cb4fab..265934b3 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -47,7 +47,7 @@ runtimeOnly project(':adapter:outbound:cache-redis') // brings :adapter:outbou | namespace | `APP_REDIS_NAMESPACE_ENVIRONMENT`, `APP_REDIS_NAMESPACE_SERVICE`, `APP_REDIS_NAMESPACE_DOMAIN` | | role | `APP_CACHE_CANONICAL_DEFAULT_PROVIDER`, `APP_RATE_LIMIT_PROVIDER`, `APP_LEASE_PROVIDER`, `APP_IDEMPOTENCY_PROVIDER=redis` | | role 조정 | `APP_CACHE_REDIS_*`, `APP_RATE_LIMIT_*`, `APP_LEASE_REDIS_*`, `APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT` | -| 운영 비밀 값(고른 role마다) | `APP_CACHE_REDIS_PASSWORD`, `APP_CACHE_REDIS_KEY_HMAC_SECRET`, `APP_RATE_LIMIT_REDIS_PASSWORD`, `APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET`, `APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET`, `APP_LEASE_REDIS_KEY_HMAC_SECRET` | +| 운영 비밀 값(고른 role마다) | Redis 접속 자격 증명은 `APP_REDIS_AUTHENTICATION_*`가 가리키는 `secret://` 참조다. 캐시 key HMAC은 `APP_CACHE_REDIS_KEY_HMAC_SECRET`, rate limit은 `APP_RATE_LIMIT_REDIS_PASSWORD`·`APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET`. 멱등·lease는 호출자가 준 digest를 써서 비밀이 없다. role마다 따로 두던 `APP_CACHE_REDIS_PASSWORD`, `APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET`, `APP_LEASE_REDIS_KEY_HMAC_SECRET`는 읽는 곳이 없다(registry `deprecated_orphaned`) | ## 켜기와 조립 -- 2.54.0 From 703af1bac03f0401fdc009fe92f70579675d35cf Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 03:23:02 +0900 Subject: [PATCH 05/23] =?UTF-8?q?fix(messaging):=20inbox=20=ED=8A=B8?= =?UTF-8?q?=EB=9E=9C=EC=9E=AD=EC=85=98=20runner=EA=B0=80=20=EC=93=B0?= =?UTF-8?q?=EA=B8=B0=EC=99=80=20=EA=B0=99=EC=9D=80=2030=EC=B4=88=20?= =?UTF-8?q?=EC=83=81=ED=95=9C=EC=9C=BC=EB=A1=9C=20=ED=8A=B8=EB=9E=9C?= =?UTF-8?q?=EC=9E=AD=EC=85=98=EC=9D=84=20=EC=97=B0=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: inbound messaging의 IdempotentConsumer.TransactionRunner는 new TransactionTemplate(transactionManager)를 상한 없이 썼다. handler의 유스케이스가 부르는 TransactionPort.inWrite는 이 트랜잭션에 합류하고, 합류한 쓰기는 자기 상한(app.persistence-jpa.transaction.write-timeout 30s)을 걸지 않는다. 그래서 막힌 문장이나 잠금 대기가 연결과 partition을 그 시간 내내 쥐었다. docs/work/reference/decisions.md 2.5 JPA 기본값 「트랜잭션 제한 30초」와 다르다. 고른 방법: TransactionTemplate에 쓰기와 같은 30초를 건다. 값은 상수 하나 (TRANSACTION_TIMEOUT_SECONDS)이고, 설정 키는 더하지 않았다 — 쓰기 상한과 따로 움직일 이유가 아직 없고, 키를 더하면 env 계약도 늘어난다. 버린 대안: 쓰기 상한 설정(write-timeout)을 읽어 쓰기 — 이 leaf가 persistence-jpa 설정에 기대게 되어 registry edge가 생긴다. 위험·한계: 30초를 넘기던 handler는 이제 롤백되고 재전달된다. 그런 handler는 원래 쓰기 상한도 넘긴 것이다. 검증(desktop, --no-build-cache): - RED: 기준 a7e38c10 + 시험만으로 MessagingInboxAutoConfigurationTest 8건 중 새 시험 1건 실패(상한이 걸리지 않음). - GREEN: :adapter:inbound:messaging:check rc=0. --- src/adapter/inbound/messaging/README.md | 2 ++ .../MessagingInboxAutoConfiguration.java | 10 ++++++++ .../MessagingInboxAutoConfigurationTest.java | 24 ++++++++++++++++++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/adapter/inbound/messaging/README.md b/src/adapter/inbound/messaging/README.md index 21b9d6c2..adce8338 100644 --- a/src/adapter/inbound/messaging/README.md +++ b/src/adapter/inbound/messaging/README.md @@ -27,6 +27,8 @@ Kafka ─▶ platform consumer (starter-kafka) - `IdempotentConsumer.TransactionRunner`(애플리케이션 `PlatformTransactionManager` 위의 `TransactionTemplate`). inbox 예약과 use case의 JPA 쓰기가 한 트랜잭션에서 함께 커밋되거나 함께 롤백된다. handler가 실패하면 예약도 롤백되어 재전달이 효과를 다시 적용한다. + 이 트랜잭션은 30초 상한(`TransactionPort` 쓰기와 같은 값)으로 열린다. handler의 유스케이스 `inWrite`는 이 + 트랜잭션에 합류해 자기 상한을 쓰지 않으므로, 막힌 문장이나 잠금 대기는 이 상한에서 끊긴다. - platform starter(`MessagingReliabilityAutoConfiguration`)가 이 두 bean으로 `IdempotentConsumer`를 만든다. platform은 애플리케이션의 datasource·트랜잭션을 스스로 고르지 않는다는 기존 설계를 그대로 둔다. - 애플리케이션의 handler(`MessageHandler` 구현)는 이 leaf에 둔다. 컨트롤러가 HTTP 요청을 use case diff --git a/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfiguration.java b/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfiguration.java index 52dae485..7c2f92e6 100644 --- a/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfiguration.java +++ b/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfiguration.java @@ -68,12 +68,22 @@ public class MessagingInboxAutoConfiguration { return new MessagingInboxSchemaStream(dataSource); } + /** + * The upper bound on one delivery's transaction, in whole seconds: the same 30 s as one {@code + * TransactionPort} write ({@code app.persistence-jpa.transaction.write-timeout}). The handler's + * use case joins this transaction, and a joined {@code inWrite} leaves the deadline to the call + * that began it, so without one here a blocked statement or lock wait held the connection and the + * partition for as long as it lasted (review 2026-11-12). + */ + static final int TRANSACTION_TIMEOUT_SECONDS = 30; + /** Runs the inbox reservation and the handler in one application transaction. */ @Bean @ConditionalOnMissingBean(IdempotentConsumer.TransactionRunner.class) public IdempotentConsumer.TransactionRunner messagingInboxTransactions( PlatformTransactionManager transactionManager) { TransactionTemplate template = new TransactionTemplate(transactionManager); + template.setTimeout(TRANSACTION_TIMEOUT_SECONDS); return new IdempotentConsumer.TransactionRunner() { @Override public T inTransaction(java.util.function.Supplier work) { diff --git a/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfigurationTest.java b/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfigurationTest.java index 2a144703..c82b8d7e 100644 --- a/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfigurationTest.java +++ b/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfigurationTest.java @@ -164,6 +164,25 @@ class MessagingInboxAutoConfigurationTest { assertThat(transactions.outcomes).containsExactly("commit", "rollback"); } + @Test + @DisplayName("트랜잭션 runner는 TransactionPort 쓰기와 같은 30초 상한으로 트랜잭션을 연다") + void theRunnerOpensItsTransactionWithTheWriteTimeout() { + // given + RecordingTransactions transactions = new RecordingTransactions(); + IdempotentConsumer.TransactionRunner runner = + new MessagingInboxAutoConfiguration().messagingInboxTransactions(transactions); + + // when + runner.inTransaction(() -> "applied"); + + // then + assertThat(transactions.timeouts) + .as( + "the handler's use case joins this transaction, and a joined inWrite leaves the deadline" + + " to the call that began it") + .containsExactly(30); + } + @Test @DisplayName("같은 메시지가 두 번 전달돼도 handler의 부작용은 한 번만 일어난다") void theSameMessageDeliveredTwiceRunsTheSideEffectOnce() { @@ -232,6 +251,7 @@ class MessagingInboxAutoConfigurationTest { private static final long serialVersionUID = 1L; private final transient List outcomes = new ArrayList<>(); + private final transient List timeouts = new ArrayList<>(); @Override protected Object doGetTransaction() { @@ -239,7 +259,9 @@ class MessagingInboxAutoConfigurationTest { } @Override - protected void doBegin(Object transaction, TransactionDefinition definition) {} + protected void doBegin(Object transaction, TransactionDefinition definition) { + timeouts.add(definition.getTimeout()); + } @Override protected void doCommit(DefaultTransactionStatus status) { -- 2.54.0 From f2d2267e2eb4bdeb95403b81c3c76217010e3928 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 03:23:03 +0900 Subject: [PATCH 06/23] =?UTF-8?q?docs:=20=EC=98=AE=EA=B8=B0=EA=B1=B0?= =?UTF-8?q?=EB=82=98=20=EC=A7=80=EC=9A=B4=20=ED=83=80=EC=9E=85=C2=B7?= =?UTF-8?q?=EC=83=98=ED=94=8C=C2=B7=ED=94=8C=EB=9E=AB=ED=8F=BC=EC=9D=84=20?= =?UTF-8?q?=EA=B0=80=EB=A6=AC=ED=82=A4=EB=8D=98=20=EC=95=88=EB=82=B4?= =?UTF-8?q?=EB=A5=BC=20=EC=A7=80=EA=B8=88=20=EC=9D=B4=EB=A6=84=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EA=B3=A0=EC=B9=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 모듈 README·AGENTS·매뉴얼·Javadoc이 옮기거나 이름을 바꾼 타입, 지운 샘플, 다른 repo로 옮긴 플랫폼을 그대로 가리켰다. - 옮기거나 바꾼 타입: OutboxConfig(지금 :composition:outbox-relay의 OutboxRelayAutoConfiguration), IdempotencyProviderSelectionConfig(지금 :composition:idempotency의 IdempotencyAutoConfiguration), TracingProperties·GraphQlPlatformProperties(지금 *Settings), SecretSource (지금 application-core SecretSourcePort), JsonNullableModule(지금 JsonNullableJackson3Module), PeriodTest·OutboxEventIdFactory(샘플과 함께 지움). - 지운 샘플: SampleDemoProfilesStartupSystemTest, 「sample 테스트」, IdempotencyAutoConfiguration·ManagementSecurityConfig Javadoc의 샘플. - 옮긴 플랫폼: graphql AGENTS·README가 messaging 플랫폼과 「두 패턴 공존」을 적었지만 그 플랫폼은 2026-11-08 messaging-library로 옮겼다. gRPC 문서는 grpc-library로 옮긴 플랫폼을 「vendored」·「벤더 starter」로 불렀다. - leaf CLAUDE.md를 가리키던 곳(지금 AGENTS.md), 복사한 숫자(httpclient java 파일 수, graphql systemTest 수), manual 06의 registry 머리말 옛 영어 인용. 고른 방법: 문장이 가리키는 대상만 지금 이름으로 바꾼다. 동작 설명은 그대로 둔다. 숫자는 지운다(레지스트리·빌드가 정한다). 검증: - 노트북: check-docs.py rc=0. check-work-docs.py는 main의 operate.md 151줄 때문에만 rc=1. - desktop(--no-build-cache, 트리 310eb524): 이 문서들을 읽는 시험 (:app-bootstrap:documentContractTest, repositoryContractTest — DeveloperExperienceContractTest 포함, MongoNamespaceContractTest, AwsQualificationClaimHonestyTest)과 Javadoc을 고친 두 leaf의 compileJava·spotlessCheck. 134건 실패 0, skip 1. --- docs/build.md | 2 +- docs/manual/06-errors.md | 4 ++-- docs/testing/TESTING_STRATEGY.md | 2 +- docs/websocket/runbook.md | 2 +- docs/work/reference/defect-patterns.md | 4 ++-- src/adapter/inbound/graphql/AGENTS.md | 22 +++++++------------ src/adapter/inbound/graphql/README.md | 13 +++++------ src/adapter/inbound/grpc/AGENTS.md | 4 ++-- src/adapter/inbound/grpc/README.md | 2 +- src/adapter/inbound/web/AGENTS.md | 2 +- src/adapter/inbound/web/README.md | 2 +- .../outbound/persistence-jpa/README.md | 4 ++-- src/application/core/AGENTS.md | 2 +- src/application/core/README.md | 2 +- src/bootstrap/app/README.md | 15 +++++++------ .../IdempotencyAutoConfiguration.java | 2 +- .../security/ManagementSecurityConfig.java | 2 +- 17 files changed, 40 insertions(+), 46 deletions(-) diff --git a/docs/build.md b/docs/build.md index f23d30eb..66083ac2 100644 --- a/docs/build.md +++ b/docs/build.md @@ -410,7 +410,7 @@ app: ### 분산 추적 - **`OTEL_EXPORTER_OTLP_ENDPOINT`** — OTLP exporter endpoint. 빈 값 = exporter off(스켈레톤에서 OTel - SEAM 미활성). 값이 있으면 유효한 URL 이어야 하며 기동 시 `TracingProperties` 가 검증한다. + SEAM 미활성). 값이 있으면 유효한 URL 이어야 하며 기동 시 `TracingSettings` 가 검증한다. - **`APP_TRACING_ENABLED`** — `false` 면 tracing seam 은 꺼지지만, `meta.traceId` 는 `WebMvcRequestIdFilter` 가 W3C `traceparent` 로 여전히 생성한다(D4 disabled-fallback 보장). - **`APP_TRACING_SAMPLE_RATE`** — per-profile 기본값을 덮어쓰는 샘플 비율. [0.0, 1.0] float. diff --git a/docs/manual/06-errors.md b/docs/manual/06-errors.md index febe2b59..cf69867c 100644 --- a/docs/manual/06-errors.md +++ b/docs/manual/06-errors.md @@ -55,8 +55,8 @@ gRPC/GraphQL/WebSocket: 같은 ApiErrorCarrier를 자기 status 모양으로 - 템플릿 운영 코드: `OperationalError` + `docs/registries/error-codes.yaml`을 같은 변경에서 고친다. `ErrorCodeRegistryMappingTest`(app-bootstrap)가 status 일치를 검사한다. -- 서비스 기능 코드: 그 registry에 넣지 않는다(registry 머리말 "Product/fork ApiErrorCode enums own local - registries"). 서비스 자기 registry를 만들고 같은 모양의 대조 테스트를 둔다. 모양은 위 +- 서비스 기능 코드: 그 registry에 넣지 않는다(registry 머리말 「제품·fork의 ApiErrorCode enum은 자기 레지스트리·계약을 + 가진다」). 서비스 자기 registry를 만들고 같은 모양의 대조 테스트를 둔다. 모양은 위 `ErrorCodeRegistryMappingTest`(`src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/contract/ErrorCodeRegistryMappingTest.java`)다. ## 지금 이해하면 되는 것 diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index b8a0b20f..af863e27 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -289,7 +289,7 @@ source set에서 태그 `jpa-contract`로 `jpaPlatformContractTest` lane이 돌 케이스 3건이 실패함을 확인했다. - `OutboxAggregateSequenceContract`는 포트 Javadoc의 세 약속 중 둘을 보지 않았다(RR-01-06). "쓰기 트랜잭션 밖 거부"와 "롤백된 번호는 다시 준다"를 넣었다. fake는 `DirectTransactionPort`를 받으면 같은 - 규칙으로 동작한다(인자 없이 만들면 예전처럼 트랜잭션을 보지 않는다 — sample 테스트가 쓰는 방식). + 규칙으로 동작한다(인자 없이 만들면 예전처럼 트랜잭션을 보지 않는다). `CacheRegionContract`에는 2^53 위 revision 한 자리 차이 경우를 넣었다. fake가 revision을 double로 비교하게 바꾼 변이가 이제 실패한다(전에는 통과). diff --git a/docs/websocket/runbook.md b/docs/websocket/runbook.md index cda6966c..0a6a1e6e 100644 --- a/docs/websocket/runbook.md +++ b/docs/websocket/runbook.md @@ -2,7 +2,7 @@ > **범위:** 내보내는 조립은 WebSocket 런타임을 조립하지 않는다. 이 runbook은 `PlatformWebSocketHandler`를 스스로 등록한 > 서비스에 적용한다(`src/adapter/inbound/websocket/README.md` 「라이브러리 API」). STOMP channel의 규칙은 leaf -> `CLAUDE.md`에 있다. +> `AGENTS.md`에 있다. 무엇을 보았는지로 나눴다. 장애 중에 손에 있는 것이 그것이기 때문이다. diff --git a/docs/work/reference/defect-patterns.md b/docs/work/reference/defect-patterns.md index ab58e17d..4f306a9b 100644 --- a/docs/work/reference/defect-patterns.md +++ b/docs/work/reference/defect-patterns.md @@ -17,7 +17,7 @@ - **모양**: 계약·runbook·매뉴얼·README·Javadoc·실패 메시지가 현재 동작과 다르다. - **막는 기준**: 동작을 바꾸는 변경은 그 동작을 설명하는 모든 문서를 같은 변경에서 고친다. 대상: `docs/web/http-contract.md`, `docs/registries/`, runbook, 매뉴얼, leaf README·`CLAUDE.md`, Javadoc, 업그레이드 안내. 고친 뒤 옛 표현을 grep으로 찾아 남은 곳을 없앤다. -- **볼 것**: diff가 바꾼 동작의 키워드(오류 코드, 설정 키, 상태 이름)로 `docs/`, `src/**/README.md`, `src/**/CLAUDE.md`를 grep. +- **볼 것**: diff가 바꾼 동작의 키워드(오류 코드, 설정 키, 상태 이름)로 `docs/`, `src/**/README.md`, `src/**/AGENTS.md`를 grep. - **장치**: 일부만 있다. runbook 숫자와 상수를 비교하는 document-contract lane, runbook SQL을 실 PostgreSQL에서 그대로 실행하는 lane. 나머지는 리뷰가 본다. 이 repo는 문서 전체를 파싱하는 검사를 일부러 두지 않는다(`docs/testing/TESTING_STRATEGY.md` 8절). ### A3. 선언과 실행이 떨어져 있다 @@ -65,7 +65,7 @@ - **모양**: 프로필·환경 이름 하나가 다르면 위험한 기능이 열린다. 허용한 값으로는 실제로 동작하지 않는다. - **막는 기준**: 위험한 기능(데모 계정, 비밀 검사 면제 등)은 거부 목록이 아니라 허용 목록으로 연다. 허용 목록의 값마다 실제로 그 값으로 동작해야 한다. - **볼 것**: 프로필·환경 이름 문자열 비교, 허용 값마다 실제로 기동하는 테스트가 있는지. -- **장치**: `SampleDemoProfilesStartupSystemTest`(허용 프로필마다 기동). +- **장치**: 기동 때 profile 값을 검사하는 `RuntimeEnvironmentProfileValidator`와 그 시험. 허용 프로필마다 실제로 기동해 보던 시험은 샘플과 함께 지웠다(2026-11-07). ### A10. 글로만 있는 규칙 diff --git a/src/adapter/inbound/graphql/AGENTS.md b/src/adapter/inbound/graphql/AGENTS.md index 608c3e39..7e2f8099 100644 --- a/src/adapter/inbound/graphql/AGENTS.md +++ b/src/adapter/inbound/graphql/AGENTS.md @@ -16,21 +16,15 @@ Package root: `dev.caskeleton.adapter.inbound.graphql`. ## 플랫폼 모듈 = sub-package (Gradle 모듈 아님) GraphQL 플랫폼 설계서는 Stable 16개 + Advanced 12개 "모듈"을 말하지만, 이 구현은 그 28개를 이 -leaf 안의 **bounded sub-package** 로 매핑한다(선례: httpclient leaf 가 366개 java 파일을 같은 +leaf 안의 **bounded sub-package** 로 매핑한다(선례: httpclient leaf 가 여러 기능 package를 같은 방식으로 담는다). GraphQL 표면은 하나의 인바운드 전송 경계이고, 그 내부 분할을 leaf 정체성 SSOT(`gradle/modules.json`)까지 밀어올리지 않는다는 선택이다. -**이는 레지스트리가 닫혀 있어서가 아니다.** `modules.json` 은 확장 가능하며, 실제로 자매 -플랫폼인 messaging 은 **정반대 선택**을 해서 자기 leaf 들을 레지스트리에 개별 등록했다. 개수는 -`modules.json` 이 소유하며 여기서 되풀이하지 않는다 — 산문에 적힌 숫자는 leaf 가 하나 추가되는 순간 -낡는다. 즉 이 레포에는 두 패턴이 공존한다: - -| | 방식 | 경계 강제 | -| --- | --- | --- | -| messaging | 레지스트리에 leaf 등록 | Gradle 의존 게이트 | -| graphql | 단일 leaf 내 sub-package | 아래 ArchUnit 테스트 (전송 경계만) | - -어느 쪽으로 통일할지는 **미결 아키텍처 결정**이다. +**이는 레지스트리가 닫혀 있어서가 아니다.** `modules.json` 은 확장 가능하다. 자매 플랫폼 messaging 은 +한때 **정반대 선택**을 해서 자기 leaf 들을 레지스트리에 개별 등록했다. 그 플랫폼은 2026-11-08 별도 repo +`messaging-library`로 옮겨 버전으로 받는다(`docs/work/reference/related-repos.md`). 그래서 이 repo 안에는 비교할 다른 +패턴이 없다. GraphQL 내부를 leaf로 나누는 일은 레지스트리에 leaf를 더하는 변경이고, 경계 강제는 지금 +아래 ArchUnit 테스트(전송 경계만)다. sub-package 사이의 경계(Stable↔Advanced 방향, 모듈 레코드)를 값으로 선언하던 `moduleboundary/` 모델과 부팅 때마다 컨트롤러를 리플렉션으로 검사하던 `architecture/` 는 2026-09-25 에 삭제했다 @@ -101,7 +95,7 @@ required-class 검사가 이 테스트가 조용히 사라지는 것을 막는 고정한다(`spring-boot-starter-web`·`spring-webmvc`·`spring-webflux`·`tomcat-embed-*` 전부 `testCompileClasspath,testRuntimeClasspath` 만). 템플릿은 servlet 단일 스택이라 실행 프로파일(`execution-profile`)·reactive 런타임 감지·blocking bridge 는 2026-09-25 에 삭제했다. -- `annotationProcessor` 로 `spring-boot-configuration-processor` — `GraphQlPlatformProperties` 가 +- `annotationProcessor` 로 `spring-boot-configuration-processor` — `GraphQlPlatformSettings` 가 `@ConfigurationProperties` 이므로 `ca.spring-config` convention plugin이 주는 패리티 게이트가 이 선언을 요구한다. @@ -157,7 +151,7 @@ health 스키마만 소유한다. ```bash ./gradlew :adapter:inbound:graphql:graphqlStableTest --console=plain # GraphQlTransportBoundaryArchitectureTest만, skip 금지 -./gradlew :adapter:inbound:graphql:systemTest --console=plain # 23 tests (실제 HTTP 서버) +./gradlew :adapter:inbound:graphql:systemTest --console=plain # 실제 HTTP 서버 ``` `graphqlStableTest` 는 `GraphQlTransportBoundaryArchitectureTest` 가 실행되지 않거나 skip 되면 diff --git a/src/adapter/inbound/graphql/README.md b/src/adapter/inbound/graphql/README.md index c7db8089..70f606b0 100644 --- a/src/adapter/inbound/graphql/README.md +++ b/src/adapter/inbound/graphql/README.md @@ -127,7 +127,7 @@ gRPC 와 달리 spring-graphql / graphql-java 는 Spring Boot BOM 이 관리한 플랫폼 정책은 `spring.graphql.*` 로 표현할 수 없다 — cost/page 한계, preparsed 캐시 경계, 관측 label 로 허용할 operation 이름은 전부 이 leaf 의 결정이다. 그래서 -`GraphQlPlatformProperties` 가 **`app.graphql`** prefix 로 `@ConfigurationProperties` 를 +`GraphQlPlatformSettings` 가 **`app.graphql`** prefix 로 `@ConfigurationProperties` 를 바인딩한다(`spring.graphql.platform.*` 이 아니다 — 그 prefix 는 존재한 적이 없다). ```yaml @@ -180,16 +180,15 @@ composition root 는 이 leaf 를 채택할 때 인증/인가 및 CORS 정책을 (`gradle/modules.json`)에 추가하는 것은 레지스트리· `settings.gradle` fail-closed 검증·의존 게이트를 동시에 건드리는 변경이다. GraphQL 표면은 하나의 인바운드 전송 경계이므로 그 **내부** 분할을 레포 전역 SSOT 까지 밀어올리지 않기로 하고, -**모듈 = bounded sub-package** 로 매핑했다(선례: httpclient leaf 가 366개 java 파일을 같은 방식으로 +**모듈 = bounded sub-package** 로 매핑했다(선례: httpclient leaf 가 여러 기능 package를 같은 방식으로 담는다). -**정직하게 기록해 둘 반례:** 이후 main 에 통합된 자매 플랫폼 messaging 은 정반대로 -**자기 leaf 를 레지스트리에 하나씩 등록**했다(지금의 leaf 목록과 수는 레지스트리가 정한다). 즉 레지스트리는 닫혀 있지 않았고, -"확장하면 게이트가 깨진다"는 전제는 과했다. 두 플랫폼이 서로 다른 패턴을 쓰고 있으므로 -**어느 쪽으로 통일할지는 미결 아키텍처 결정**이다. +**정직하게 기록해 둘 반례:** 자매 플랫폼 messaging 은 정반대로 **자기 leaf 를 레지스트리에 하나씩 +등록**했다. 즉 레지스트리는 닫혀 있지 않았고, "확장하면 게이트가 깨진다"는 전제는 과했다. 그 플랫폼은 +2026-11-08 별도 repo `messaging-library`로 옮겼으므로 지금 이 repo에서 두 패턴이 공존하지는 않는다. sub-package 경계를 값으로 선언하던 `moduleboundary/` 모델(소스 텍스트 스캐너 포함)은 -2026-09-25 에 삭제했다. 두 플랫폼 중 어느 패턴으로 통일할지 정할 때 다시 설계한다. +2026-09-25 에 삭제했다. GraphQL 내부를 leaf로 나누기로 정할 때 다시 설계한다. ## 전송 경계 규칙은 빌드 때 ArchUnit 으로 검사한다 diff --git a/src/adapter/inbound/grpc/AGENTS.md b/src/adapter/inbound/grpc/AGENTS.md index 0eb3956a..b5e6b947 100644 --- a/src/adapter/inbound/grpc/AGENTS.md +++ b/src/adapter/inbound/grpc/AGENTS.md @@ -42,8 +42,8 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`. 타입드 `@ConfigurationProperties` 만 두고, 값은 composition-root `application.yml` 에 산다 (모듈별 `yml` 없음). prefix가 `app.grpc`가 아니라 `.server`까지인 이유: 바인딩이 -`ignoreUnknownFields = false`라서, 부모 prefix를 쓰면 벤더 starter의 `app.grpc.platform.*` -키가 들어오는 순간 기동이 실패한다(`GrpcSafeActivationTest`). +`ignoreUnknownFields = false`라서, 부모 prefix를 쓰면 `grpc-library` starter를 함께 받은 서비스의 +`app.grpc.platform.*` 키가 들어오는 순간 기동이 실패한다(`GrpcSafeActivationTest`). | key | default | 의미 | |---|---|---| diff --git a/src/adapter/inbound/grpc/README.md b/src/adapter/inbound/grpc/README.md index e713d0cf..57b8b82b 100644 --- a/src/adapter/inbound/grpc/README.md +++ b/src/adapter/inbound/grpc/README.md @@ -59,7 +59,7 @@ io.grpc 기본값은 메시지 4 MiB, 연결당 동시 호출 무제한, 호출마다 스레드를 늘리는 cached executor, 서버 deadline 없음, 연결 수명 무제한이다. 어댑터 서버는 이 값을 모두 명시한다. -| 키 (`app.grpc.server.*`) | 기본값 | 같은 값의 출처 (vendored 플랫폼) | +| 키 (`app.grpc.server.*`) | 기본값 | 같은 값의 출처 (`grpc-library` 플랫폼) | |---|---|---| | `max-inbound-message-bytes` | 1048576 (1 MiB) | `GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES` | | `max-inbound-metadata-bytes` | 8192 (8 KiB) | `GrpcTransportLimits.DEFAULT_MAX_METADATA_BYTES` | diff --git a/src/adapter/inbound/web/AGENTS.md b/src/adapter/inbound/web/AGENTS.md index fbc2fd8a..3983047a 100644 --- a/src/adapter/inbound/web/AGENTS.md +++ b/src/adapter/inbound/web/AGENTS.md @@ -136,7 +136,7 @@ B2)가 이미 inbound 쪽을 덮고, 아래 규칙이 outbound 쪽을 덮는다. |---|---|---|---|---| | 문법·모양 | `adapter:inbound:web` 요청 DTO(`@Valid` / `jakarta.validation`) | 요청 모양, 타입, 필수 필드 | `VALIDATION` | ArchUnit 규칙 `VALIDATION_CONSTRAINTS_STAY_AT_WEB_BOUNDARY` | | 유스케이스 정책 | `application-core` | 인가, aggregate를 가로지르는 정책, 상태 전제 조건 | `AUTHZ` / `CONFLICT` | `BusinessRuleValidationContractTest` | -| 도메인 불변식 | `domain-core` 모델·값 객체 **생성자** | 업무 불변식(예: end ≥ start) | `CONFLICT` / `VALIDATION` | 도메인 단위 시험(예: `PeriodTest`) — 생성자가 유일하고 바뀌지 않는 생성 경로다 | +| 도메인 불변식 | `domain-core` 모델·값 객체 **생성자** | 업무 불변식(예: end ≥ start) | `CONFLICT` / `VALIDATION` | 도메인 단위 시험(생성 명령이 만드는 aggregate의 시험) — 생성자가 유일하고 바뀌지 않는 생성 경로다 | | 영속 무결성 | `adapter:outbound:persistence-jpa`(번역기는 `feature-persistence-failure-baseline`의 것) | unique / FK / check / serialization | `DATA_INTEGRITY` / `CONFLICT` | `BusinessRuleValidationContractTest` + 누출 시험 | - **C1 — 검증 애너테이션은 web 경계에 머문다.** `jakarta.validation`(`@NotNull`, `@Valid`, …)은 diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 9173bad1..62439653 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -469,7 +469,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML (/api 없이) 계속 접근 가능하게 유지. ### JacksonNullableConfig -- `JsonNullableModule` 을 Spring 관리 `ObjectMapper` 에 등록. 없으면 PATCH 요청 DTO 의 `JsonNullable`(B2)를 +- `JacksonNullableConfig`가 `JsonNullable` 처리기 모듈(`JsonNullableJackson3Module`)을 Spring 관리 `ObjectMapper` 에 등록. 없으면 PATCH 요청 DTO 의 `JsonNullable`(B2)를 Jackson 이 역직렬화하지 못해 absent / explicit-null 구분이 조용히 붕괴된다. - 스켈레톤 전역 web 관심사(공유 `Patch` 타입과 짝)라 기능 모듈이 아니라 adapter-web 에 위치. diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index 581c36df..403e60e6 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -40,7 +40,7 @@ bean과 함께 Boot의 JDBC·Hibernate·Spring Data JPA·Flyway 자동 설정도 `ModuleDefaultsEnvironmentPostProcessor`가 가장 낮은 우선순위로 읽으므로 애플리케이션 설정과 환경변수가 언제나 이긴다. -outbox **relay**(스케줄러)는 이 모듈이 아니라 합성 루트의 `OutboxConfig`가 조립한다. use case를 +outbox **relay**(스케줄러)는 이 모듈이 아니라 조립 모듈 `:composition:outbox-relay`의 `OutboxRelayAutoConfiguration`이 조립한다. use case를 만들고 구동하는 일은 driven adapter의 몫이 아니기 때문이다. 그 설정은 이 모듈이 주는 `OutboxStorePort`와 messaging이 주는 `OutboxMessagePublishPort`가 모두 있을 때만 켜진다. @@ -217,7 +217,7 @@ Spring Boot 메인 클래스는 `dev.caskeleton.bootstrap` 에 있어서, `@Auto `app.capabilities.idempotency.provider=postgresql` 일 때만 켜진다 (`autoconfigure/PostgreSqlIdempotencyStoreConfig`). 이 leaf 는 `IdempotencyStorePort` 구현 (`PostgreSqlIdempotencyStore`) 하나만 내놓고, executor 는 app-bootstrap -`IdempotencyProviderSelectionConfig` 가 만든다. V1 JDBC store 와 `jdbc` provider 값은 없다. +조립 모듈 `:composition:idempotency`의 `IdempotencyAutoConfiguration`이 만든다. V1 JDBC store 와 `jdbc` provider 값은 없다. - **스키마**: 기본 테이블은 primary Flyway(`db/migration/postgresql/V1__idempotency_record.sql`)가, owner-safe 컬럼은 `db/migration/jpa/idempotency` stream 이 소유한다. 기동 시 diff --git a/src/application/core/AGENTS.md b/src/application/core/AGENTS.md index e321756b..9d5e5859 100644 --- a/src/application/core/AGENTS.md +++ b/src/application/core/AGENTS.md @@ -77,7 +77,7 @@ architectureTest)가 강제한다. 나머지는 리뷰 규칙이고, 리뷰가 | 애플리케이션이 가진 기술 저장소(outbox, 멱등성, operation 행) | `StorePort` | application 패키지 | `*WritePort`(옛 onboarding fixture, 지움) | | aggregate가 아니라 projection을 돌려주는 읽기 모델 | `QueryPort` | application 패키지. projection만 돌려준다(ArchUnit) | — | | 그 밖의 outbound 포트 | `Port` | application 패키지 | — | -| 서버가 정하는 id 생성 | `IdFactory extends IdFactory<Id>` | domain 패키지. id record는 `implements ResourceId` | `OutboxEventIdFactory`(샘플. event id는 resource id가 아니다) | +| 서버가 정하는 id 생성 | `IdFactory extends IdFactory<Id>` | domain 패키지. id record는 `implements ResourceId` | `DurableOperationIdFactory`(durable operation id는 aggregate의 resource id가 아니라 `IdFactory`를 따르지 않는다) | | 설정 바인딩 | `*Settings`(운영) 또는 `*Policy`(인가·도메인 정책), ArchUnit이 강제 | 그것을 바인딩하는 leaf | — | | Throwable | `*Exception`, ArchUnit이 강제 | — | — | | 포트의 계약 시험 키트 | 포트 소유자의 testFixtures에 둔 추상 `Contract`. fake의 시험과 각 어댑터의 시험이 상속한다 | testFixtures | 값 타입 시험의 이름이 한때 `*ContractTest`였다. 지금은 `*ValueTypesTest`다 | diff --git a/src/application/core/README.md b/src/application/core/README.md index ade67b6d..83132c58 100644 --- a/src/application/core/README.md +++ b/src/application/core/README.md @@ -284,7 +284,7 @@ application 계층이 claim·replay·복구 **정책** 을 소유하고, 저장 `LEASE_EXPIRED` 를 받는다. 이 값은 `NOT_OWNER`(기록이 남에게 넘어감)와 다르다: 시작 전이면 아무것도 돌지 않았고 다음 claim 이 넘겨받으며, executor 는 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거부)로 답한다. 실행 중이면 주인은 여전히 `complete`·`markFailed` 할 수 있다(RR5-01-02). -- 생성은 app-bootstrap `IdempotencyProviderSelectionConfig` 가 한 번 한다(`IdempotencySettings`: +- 생성은 조립 모듈 `:composition:idempotency`의 `IdempotencyAutoConfiguration`이 한 번 한다(`IdempotencySettings`: processing lease 30s, replay TTL 24h(최대 72h), failure retention 24h(replay TTL 이상), codec id `json-v2`, policy revision 2). 유스케이스나 서비스 설정이 직접 만들지 않는다. - 이 계약은 요청 재생(replay) 근거를 남길 뿐이다. store 와 비즈니스 DB 사이의 exactly-once 를 diff --git a/src/bootstrap/app/README.md b/src/bootstrap/app/README.md index f5134be7..0acfa9f7 100644 --- a/src/bootstrap/app/README.md +++ b/src/bootstrap/app/README.md @@ -85,11 +85,12 @@ README의 "startup" 절에 있다. 시크릿을 어디서 읽을지(env / Vault / 클라우드 시크릿 매니저)를 인터페이스 뒤로 숨기고, 위험한 런타임 설정값은 기동 시점에 막는다. -### SecretSource -- **시크릿 해석을 인터페이스 한 겹 뒤로 숨긴 backend seam 이다.** 시크릿이 필요한 코드는 이 - 인터페이스에만 의존하고, 실제 백엔드(env / Vault / AWS Secrets Manager / GCP Secret Manager)는 +### SecretSourcePort +- **시크릿 해석을 인터페이스 한 겹 뒤로 숨긴 backend seam 이다.** 포트는 application-core + `dev.caskeleton.application.secret`에 있다. 시크릿이 필요한 코드는 이 인터페이스에만 의존하고, + 실제 백엔드(env / Vault / AWS Secrets Manager / GCP Secret Manager)는 `SecretSourceFactory`가 설정값으로 고른다. 설정과 구현 선택을 한 factory에 모으는 패턴이다. - 백엔드를 추가하는 비용이 "새 `SecretSource` 구현 1개 + `SecretSourceStrategy` enum 값 1개 + + 백엔드를 추가하는 비용이 "새 `SecretSourcePort` 구현 1개 + `SecretSourceStrategy` enum 값 1개 + factory case 1개"로 고정되고, 소비자(`SecretSourceValidator`, 향후 어댑터)는 전혀 손대지 않는다. - **빈 문자열은 "없음"으로 취급한다.** `resolve`가 blank 값을 `Optional.empty()`로 돌려주지 않으면, "값은 존재하지만 비어 있는" 시크릿이 존재 검사(presence check)를 통과해 버려 prod 부팅을 막을 수 @@ -98,7 +99,7 @@ README의 "startup" 절에 있다. ### SecretSourceStrategy - **enum 값 하나가 곧 백엔드 하나라는 확장 규약을 못 박는다.** `app.secret-source.strategy`로 바인딩되며 `ENVIRONMENT`만 기본 제공한다. 미래 백엔드(VAULT, AWS_SECRETS_MANAGER, - GCP_SECRET_MANAGER)는 주석으로만 남겨 두어, 추가 절차가 "enum 값 + `SecretSource` 구현 + factory + GCP_SECRET_MANAGER)는 주석으로만 남겨 두어, 추가 절차가 "enum 값 + `SecretSourcePort` 구현 + factory case"임을 코드에서 바로 읽히게 했다(rate-limit algorithm enum 패턴과 동일). ### SecretSourceSettings @@ -108,7 +109,7 @@ README의 "startup" 절에 있다. ### SecretSourceConfig - **시크릿 백엔드와 그 시작 가드를 composition root 에서만 와이어링한다.** `SecretSourceFactory`로 - 선택된 `SecretSource`(기본 `ENVIRONMENT`)와, 그것을 통해 필수 시크릿을 검증하는 + 선택된 `SecretSourcePort` 구현(기본 `ENVIRONMENT`)과, 그것을 통해 필수 시크릿을 검증하는 `SecretSourceValidator`를 빈으로 노출한다. 검증기를 Spring 스테레오타입 없는 일반 클래스로 둔 이유는 단위 테스트 가능성을 지키기 위함이고, 이 config 가 유일한 production 와이어링이다. - **`RuntimeSafetyConfig`와 일부러 분리했다.** 시크릿 계약은 secrets-config-source-contract 가 @@ -117,7 +118,7 @@ README의 "startup" 절에 있다. ### SecretSourceFactory - **유일한 확장 지점을 `switch` 하나로 모았다.** 새 백엔드는 `SecretSourceStrategy` 값 + - `SecretSource` 구현 + 이 `switch`의 case 추가로 끝나고 소비자는 바뀌지 않는다. + `SecretSourcePort` 구현 + 이 `switch`의 case 추가로 끝나고 소비자는 바뀌지 않는다. factory 한곳에 "확장 비용이 어디에 있는가"를 보이게 했다. ### EnvironmentSecretSource diff --git a/src/bootstrap/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfiguration.java b/src/bootstrap/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfiguration.java index 1a26e96f..28339218 100644 --- a/src/bootstrap/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfiguration.java +++ b/src/bootstrap/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfiguration.java @@ -21,7 +21,7 @@ import org.springframework.core.env.Environment; * replay TTL, retention, codec id, policy revision — is the same whichever store holds the records, * so it lives in one {@link IdempotencySettings} record and the executor is built here from it. * Every composition root that serves idempotent requests takes this module rather than a copy of - * it: the application and the sample build the same executor from the same checks. + * it, so every one builds the same executor from the same checks. * *

A selected provider must yield exactly one store. None means the provider's module is not on * the runtime classpath or its switch is off; two means something else registered one (a scan-found diff --git a/src/bootstrap/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java b/src/bootstrap/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java index 24551983..1677eb5d 100644 --- a/src/bootstrap/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java +++ b/src/bootstrap/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java @@ -32,7 +32,7 @@ import org.springframework.security.web.authentication.HttpStatusEntryPoint; * *

A composition root that deliberately wants another actuator posture declares its own bean * named {@code actuatorSecurityFilterChain}; this one then steps aside instead of putting two - * chains with the same matcher in front of the same requests. The standalone sample does that. + * chains with the same matcher in front of the same requests. */ @AutoConfiguration( before = { -- 2.54.0 From db819944907a663ca9674b4bad8fd5cdd18e0032 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 03:47:30 +0900 Subject: [PATCH 07/23] =?UTF-8?q?fix(security)!:=20=EA=B3=B5=EA=B0=9C=20?= =?UTF-8?q?=EA=B2=BD=EB=A1=9C=20=EC=8A=A4=EB=83=85=EC=88=8F=EC=9D=B4=20pro?= =?UTF-8?q?file=20=EB=8D=AE=EC=96=B4=EC=93=B0=EA=B8=B0=EC=99=80=20?= =?UTF-8?q?=EB=AA=A8=EB=93=88=20chain=EC=9D=98=20permitAll=EA=B9=8C?= =?UTF-8?q?=EC=A7=80=20=EA=B3=A0=EC=A0=95=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 공개 경로 스냅숏(publicPathSnapshotTest)은 config/security.yml의 기본값 한 줄만 읽었다. 문서(docs/build.md, gates.md 「공개 경로·보안 체인」)는 보안 체인 전체를 지킨다고 했다. 그래서 둘이 검사를 지나갔다. - application-local.yml이 public-paths를 /api/healthcheck로 덮는다. - web-notification의 callback chain이 /internal/notification/callbacks/**를 anyRequest().permitAll()로 연다. actuator chain의 health·info·prometheus도 같다. docs/build.md는 지운 PublicPathSnapshotPlugin.java와 없는 updatePublicPathSnapshot 태스크를 승인 방법으로 적었다. 관리 포트도 문서와 compose가 갈렸다. 관리 포트가 컨테이너 loopback에 묶인 뒤(MANAGEMENT_SERVER_ADDRESS 기본 127.0.0.1) compose.yaml·dev lane의 127.0.0.1:9001 publish는 아무것도 답하지 않는 줄이 됐고, service-runtime README·Dockerfile은 Kubernetes 프로브가 닿는다고 적었다. dev lane은 원격 JMX(9999)를 인증·TLS 없이, jmxremote.host 없이 열었다(주석은 「localhost only」). 고른 방법: - 스냅숏에 두 절을 더한다. profile 파일이 public-paths를 리터럴로 덮으면 그 값, 모든 leaf 운영 코드에서 Spring Security를 import한 파일의 permitAll·securityMatcher 문장(파일 경로와 함께, 정렬). 그 소스와 baseline을 lane 입력으로 선언해 캐시가 변경을 놓치지 않게 했다. - 기동한 SecurityFilterChain의 matcher를 reflection으로 읽는 안은 버렸다. matcher가 Spring의 private 필드에 있어 버전마다 깨진다. 문장 글자만 보므로 상수로 만든 matcher의 값은 못 본다. 그 한계를 docs/build.md에 적었다. - 관리 포트 publish 줄과 dev lane JMX를 지웠다. 컨테이너 안에서 읽는 명령 (docker compose exec app wget …, jcmd)을 주석에 적었다. Kubernetes는 MANAGEMENT_SERVER_ADDRESS를 바꾸거나 sidecar로 읽어야 한다고 service-runtime README·Dockerfile·docs/build.md에 적었다. 위험·한계: 파생 서비스가 자기 chain이나 profile 덮어쓰기를 두었다면 merge 뒤 스냅숏이 실패한다. 읽고 승인하면 된다(upgrade 안내 1). dev lane에서 원격 JMX로 보던 사람은 jcmd로 바꾼다(안내 4). 검증(desktop, --no-build-cache): - RED: 기준 a7e38c10에 permitAll chain을 더한 탐침 트리에서 기존 publicPathSnapshotTest가 통과했다(rc=0) — 틈이 있다. - GREEN: spotlessApply 뒤 :app-bootstrap:test --tests '*PublicPathSnapshotTest' (새 렌더링 시험 둘), :app-bootstrap:publicPathSnapshotTest, repositoryContractTest, spotlessCheck, :verifyComposeProfiles(18 lane) — 67건 실패 0, skip 1, rc=0. - 변이: 새 스냅숏을 커밋한 트리에서 callback chain의 securityMatcher를 "/internal/**"로 넓히면 publicPathSnapshotTest가 실패한다. BREAKING CHANGE: 공개 경로 스냅숏이 profile 덮어쓰기와 모든 모듈의 permitAll·securityMatcher 문장을 본다. compose가 관리 포트 9001과 dev lane JMX 9999를 publish하지 않는다. 할 일은 docs/upgrade/2026-11-round9-public-surface.md. --- Dockerfile | 4 +- compose.yaml | 9 +- docs/build.md | 41 +++-- docs/security/public-paths-snapshot.txt | 9 ++ docs/upgrade/2026-11-round9-public-surface.md | 28 ++++ src/bootstrap/app/build.gradle | 8 + src/bootstrap/app/compose-lanes/dev.yaml | 18 +-- .../security/PublicPathSnapshotTest.java | 151 +++++++++++++++++- src/bootstrap/service-runtime/README.md | 9 +- 9 files changed, 236 insertions(+), 41 deletions(-) create mode 100644 docs/upgrade/2026-11-round9-public-surface.md diff --git a/Dockerfile b/Dockerfile index e8205522..0eef5d1a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -219,7 +219,9 @@ EXPOSE 8080 9001 # connection adds its own indicator when it is selected — the JPA module adds the datasource — so a # container started without that dependency reachable is genuinely not ready. # Kubernetes ignores HEALTHCHECK and uses its own probes against the same path; this exists for -# docker and Compose. +# docker and Compose. A kubelet probe reaches the pod IP, and the management port binds loopback +# by default (MANAGEMENT_SERVER_ADDRESS=127.0.0.1): a Kubernetes deployment sets that address, or +# its probes fail (src/bootstrap/service-runtime/README.md 「management/security」). # # wget is present in eclipse-temurin:21-jre-noble, so nothing is installed for it. HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \ diff --git a/compose.yaml b/compose.yaml index bb145c2e..31d24860 100644 --- a/compose.yaml +++ b/compose.yaml @@ -85,10 +85,11 @@ services: required: false ports: - "${APP_SERVER_PORT:-8080}:8080" - # Management (health, info, prometheus — answered without authentication) on loopback only: - # published on every interface it reaches the whole LAN (07-13). The smoke lanes read it from - # inside the container, so they need no host port at all. - - "127.0.0.1:9001:9001" + # Management (health, info, prometheus — answered without authentication) is not published. + # It binds the container's loopback (MANAGEMENT_SERVER_ADDRESS, default 127.0.0.1), so a host + # port mapped to it would answer nothing, and binding 0.0.0.0 to publish it would open it to + # every container on the network as well. The healthcheck and the smoke lanes read it from + # inside the container: `docker compose exec app wget -qO- http://localhost:9001/actuator/health`. environment: # Explicit, not inherited. A Compose profile selects services; it says nothing about which # environment the application believes it is in. The dev and prod-smoke lane overlays set diff --git a/docs/build.md b/docs/build.md index f23d30eb..ffb4bfd8 100644 --- a/docs/build.md +++ b/docs/build.md @@ -147,28 +147,22 @@ Checkstyle은 파싱된 파일에 같은 질문을 하고, leaf 단위로 돈다 ### `verifyPublicPathSnapshot` -- **하는 일.** deny-by-default public path 표면이 승인 없이 바뀌면 빌드를 실패시킨다. -- **배경.** 이 앱은 deny-by-default이다. 즉 `SECURITY_PUBLIC_PATHS` 가 먹이는 명시적 `permitAll()` - 경로를 **제외한** 모든 요청은 인증을 요구한다 - (`src/bootstrap/app/src/main/resources/config/security.yml` → `SecuritySettings.publicPaths()` → - `SecurityConfig`). 설정 분할 이전에는 이 SSOT 가 `.env` 였고 문서만 그대로 남아 있었다. - 스냅샷 플러그인이 실제로 읽는 파일은 `config/security.yml`이다 - (`build-logic/.../publicpath/PublicPathSnapshotPlugin.java`). - 이 public 표면이 바뀌는 순간이 곧 보호되던 엔드포인트가 조용히 공개로 노출되는 지점이다. - 그래서 그 표면을 snapshot 으로 떠 두고, 미승인 변경에 빌드를 실패시킨다. -- **승인 방법.** `verifyPublicPathSnapshot` 은 항상 읽기 전용이다. reviewer 가 변경을 승인한 뒤 - `./gradlew updatePublicPathSnapshot -PapprovePublicPathChange` 로 snapshot 을 명시적으로 다시 - 생성한다. 공개 경로 변경은 보안 리뷰 대상으로 보고 재생성된 snapshot 을 함께 커밋한다. -- **결정 — 무엇을 snapshot 했나 (프로젝트 선택).** 초기안은 기동 시 - `SecurityFilterChain.getFilters()` 를 introspection 하는 방식이었다. 하지만 그 reflection - 은 Spring 버전마다 깨지기 쉽다(`permitAll` matcher 가 - `RequestMatcherDelegatingAuthorizationManager` 의 private 필드에 숨어 있음). 그래서 `permitAll()` - 을 실제로 먹이는 결정적 SSOT 인 `SECURITY_PUBLIC_PATHS` 자체를 snapshot 한다. 탐지 목표(공개 경로 - 변경은 무조건 게이트를 실패시킨다)는 같고, 메커니즘은 더 견고하다. -- **snapshot 위치.** `docs/security/public-paths-snapshot.txt`. 이 파일은 커밋된 필수 보안 - baseline이다. CI 는 Gradle 실행 전에 파일이 비어 있지 않고 Git에 추적되는지 검사하므로 fresh - checkout 에서 누락되거나 untracked 상태면 즉시 실패한다. 승인된 변경만 update task로 재생성한 - 뒤 보안 리뷰와 함께 커밋한다. +- **하는 일.** 인증 없이 들어올 수 있는 표면이 승인 없이 바뀌면 빌드를 실패시킨다. main 단계(`mainCheck`)와 + `releaseCheck`의 lane `:app-bootstrap:publicPathSnapshotTest`다. +- **스냅숏에 드는 셋.** `docs/security/public-paths-snapshot.txt`의 세 절이다. + - 기본 공개 경로: `src/bootstrap/app/src/main/resources/config/security.yml`의 `app.security.public-paths` 기본값 + (`SecuritySettings.publicPaths()` → web `SecurityConfig`의 `permitAll()`). + - profile이 덮는 값: `application-.yml`이 `public-paths`를 리터럴로 덮으면 그 값. + - 모듈 chain: 모든 leaf의 운영 코드에서 Spring Security를 쓰는 파일의 `permitAll` 문장과 chain 범위 + (`securityMatcher`) 문장. 알림 callback chain, actuator chain이 여기에 든다. 문장 글자가 바뀌면(새 matcher, + 넓어진 pattern) 스냅숏이 바뀐다. +- **못 보는 것.** 운영자가 배포 env(`SECURITY_PUBLIC_PATHS`)로 준 값, 그리고 matcher를 상수나 변수로 다른 줄에서 + 만든 경우의 그 값(문장 글자만 본다). 그런 변경은 리뷰가 본다. +- **승인 방법.** 리뷰가 변경을 받은 뒤 `./gradlew verifyPublicPathSnapshot -PapprovePublicPathChange`로 스냅숏을 다시 + 쓰고 함께 커밋한다. 플래그 없이 돌리면 비교만 한다. +- **결정 — 무엇을 스냅숏하나.** 기동한 `SecurityFilterChain`의 matcher를 reflection으로 읽는 안은 Spring 버전마다 + 깨진다(`permitAll` matcher가 `RequestMatcherDelegatingAuthorizationManager`의 private 필드에 있다). 그래서 설정의 + 기본값과 소스의 `permitAll` 문장을 글자로 고정한다. ### Trivy suppression과 플래키 격리 — 정책은 유지, 파서는 삭제 @@ -575,3 +569,6 @@ docker compose up -d --wait db - **결정 — management 포트 분리.** actuator 엔드포인트를 앱 API 와 **같은 소켓에 노출하지 않으려고** 별도 management 포트를 둔다. - **`MANAGEMENT_SERVER_PORT`** — 1~65535 정수. **`APP_SERVER_PORT`(8080)와 달라야 한다.** +- **`MANAGEMENT_SERVER_ADDRESS`** — 관리 커넥터가 묶이는 주소. 기본 `127.0.0.1`(컨테이너 안 loopback). 그래서 + 컨테이너 밖에서는 닿지 않고, compose도 이 포트를 publish하지 않는다. Kubernetes 프로브와 Prometheus처럼 pod IP로 + 읽는 배포는 이 값을 바꾸거나(`0.0.0.0`과 NetworkPolicy) 같은 pod의 sidecar로 읽는다. diff --git a/docs/security/public-paths-snapshot.txt b/docs/security/public-paths-snapshot.txt index 73632d25..a75b6f16 100644 --- a/docs/security/public-paths-snapshot.txt +++ b/docs/security/public-paths-snapshot.txt @@ -4,3 +4,12 @@ # overrides it at run time and is outside this snapshot. # Update only after review with: ./gradlew verifyPublicPathSnapshot -PapprovePublicPathChange /v1/healthcheck +# Profile overrides of app.security.public-paths +profile local: /api/healthcheck +# Filter-chain statements that permit requests without authentication +src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackMvcSecurityConfiguration.java: .authorizeHttpRequests(requests -> requests.anyRequest().permitAll()) +src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackMvcSecurityConfiguration.java: return http.securityMatcher("/internal/notification/callbacks/**") +src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java: auth.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll(); +src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java: auth.requestMatchers(publicPaths).permitAll(); +src/bootstrap/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java: .requestMatchers(EndpointRequest.to("health", "info", "prometheus")) .permitAll() +src/bootstrap/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java: http.securityMatcher(EndpointRequest.toAnyEndpoint()) diff --git a/docs/upgrade/2026-11-round9-public-surface.md b/docs/upgrade/2026-11-round9-public-surface.md new file mode 100644 index 00000000..2400bfe8 --- /dev/null +++ b/docs/upgrade/2026-11-round9-public-surface.md @@ -0,0 +1,28 @@ +# 업그레이드 안내 — 2026-11 공개 경로 스냅숏과 관리 포트 + +- 범위: 공개 경로 스냅숏(`docs/security/public-paths-snapshot.txt`)이 보는 범위를 넓힌 변경과, compose가 관리 포트·JMX를 + publish하던 줄을 지운 변경. 앱이 여는 경로와 기본 설정은 바뀌지 않았다. +- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 공개 경로·관리 포트 발견 + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 자기 모듈에 Spring Security filter +chain을 둔 서비스, profile 파일에서 `app.security.public-paths`를 덮은 서비스, Kubernetes에 배포하는 서비스, dev +compose lane으로 JVM을 원격 JMX로 보던 사람이다. + +## 2. 할 일 + +| # | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | +| 1 | merge 뒤 `./gradlew verifyPublicPathSnapshot`을 돌린다. 실패하면 스냅숏에 새로 든 두 절(profile이 덮는 값, filter chain의 `permitAll`·`securityMatcher` 문장)을 읽고, 의도한 공개면 `./gradlew verifyPublicPathSnapshot -PapprovePublicPathChange`로 다시 쓴 파일을 보안 리뷰와 함께 커밋한다 | `mainCheck`·`releaseCheck`의 `:app-bootstrap:publicPathSnapshotTest`가 실패한다 | 자기 chain이나 profile 덮어쓰기가 있는 서비스 | +| 2 | Kubernetes 배포는 `MANAGEMENT_SERVER_ADDRESS`를 pod IP에서 닿는 주소(예: `0.0.0.0`과 NetworkPolicy)로 두거나 같은 pod의 sidecar로 읽는다. 기본값 `127.0.0.1`은 2026-11-12 main 병합(관리 포트 loopback 고정)부터다 | kubelet 프로브가 관리 포트에 닿지 않아 liveness 실패로 재시작하고 readiness가 오지 않는다. Prometheus도 못 읽는다 | Kubernetes 배포 | +| 3 | compose에서 관리 포트를 호스트로 읽던 명령(`curl localhost:9001/...`)을 `docker compose exec app wget -qO- http://localhost:9001/actuator/health`로 바꾼다 | 호스트 포트가 없어 연결이 거절된다. 지운 publish 줄도 컨테이너 loopback에 닿지 않아 원래 아무것도 답하지 않았다 | compose로 띄우는 사람 | +| 4 | dev lane에서 원격 JMX(9999) 대신 `docker compose exec app jcmd 1 <명령>`(`VM.flags`, `Thread.print`, `JFR.start`)을 쓴다 | 9999 연결이 거절된다 | dev lane으로 JVM을 보던 사람 | + +## 3. 바뀐 것 + +- 스냅숏은 세 절이다: 기본 공개 경로(`config/security.yml`), profile이 덮는 값(`application-.yml`), 모든 leaf + 운영 코드의 `permitAll`·`securityMatcher` 문장. 알림 callback chain과 actuator chain이 셋째 절에 든다. +- 스냅숏이 못 보는 것은 운영자가 배포 env(`SECURITY_PUBLIC_PATHS`)로 준 값과, matcher를 상수나 변수로 다른 줄에서 + 만든 경우의 그 값이다. 그런 변경은 리뷰가 본다(`docs/build.md` 「`verifyPublicPathSnapshot`」). +- dev lane의 원격 JMX는 인증·TLS 없이 열려 있었고 `jmxremote.host`가 없어 모든 인터페이스에 묶였다. 그래서 지웠다. diff --git a/src/bootstrap/app/build.gradle b/src/bootstrap/app/build.gradle index e0697407..90133b56 100644 --- a/src/bootstrap/app/build.gradle +++ b/src/bootstrap/app/build.gradle @@ -459,6 +459,14 @@ strictTestLanes { systemProperty 'publicpath.snapshot.write', project.hasProperty('approvePublicPathChange') ? 'true' : 'false' } } +// The snapshot also lists every filter-chain statement that permits requests, in any leaf, and the +// committed baseline it compares with: both are files outside this project's own inputs. +tasks.named('publicPathSnapshotTest', Test) { + inputs.files(fileTree(rootProject.projectDir) { + include 'src/**/src/main/java/**/*.java', 'docs/security/public-paths-snapshot.txt' + exclude repositoryContractExcludes + }).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('securitySourcesAndBaseline') +} tasks.register('stageDockerJar', Sync) { dependsOn tasks.named('bootJar') diff --git a/src/bootstrap/app/compose-lanes/dev.yaml b/src/bootstrap/app/compose-lanes/dev.yaml index 0be7e6ad..cb0d05ec 100644 --- a/src/bootstrap/app/compose-lanes/dev.yaml +++ b/src/bootstrap/app/compose-lanes/dev.yaml @@ -12,7 +12,11 @@ # can hot-swap files without image rebuilds. # - Increases memory allowance for dev/debugging workloads. # - Disables restart-unless-stopped so crash loops don't mask startup errors. -# - Enables JMX remote port (local only, never in prod). +# - No remote JMX. The JVM's JMX connector without authentication runs code for anyone who +# reaches it, and a port published to the host's loopback still answers every container on the +# Compose network (the reason the management port binds the container's loopback). Inspect the +# JVM from inside the container instead: `docker compose exec app jcmd 1 VM.flags`, `Thread.print`, +# `JFR.start` (2026-11-12 review). # - Mounts a local source volume for fast iteration (optional; mount when IDE # attaches to the running container). # ============================================================================= @@ -51,7 +55,6 @@ services: # Use a shorter drain timeout in dev so restarts are faster. APP_SERVER_SHUTDOWN_TIMEOUT: "5s" APP_SERVER_SHUTDOWN: "graceful" - # Remote JMX — bind to localhost only; NEVER expose in production. JAVA_TOOL_OPTIONS: >- -XX:MaxRAMPercentage=75 -XX:+UseContainerSupport @@ -59,16 +62,11 @@ services: -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/tmp/heap -Dserver.tomcat.basedir=/tmp - -Dcom.sun.management.jmxremote - -Dcom.sun.management.jmxremote.port=9999 - -Dcom.sun.management.jmxremote.rmi.port=9999 - -Dcom.sun.management.jmxremote.authenticate=false - -Dcom.sun.management.jmxremote.ssl=false - -Djava.rmi.server.hostname=127.0.0.1 + # The management port is not published: it binds the container's loopback + # (MANAGEMENT_SERVER_ADDRESS), so a host port mapped to it answers nothing. Read it from inside + # the container: `docker compose exec app wget -qO- http://localhost:9001/actuator/health`. ports: - "8080:8080" - - "127.0.0.1:9001:9001" # management — localhost only (07-13) - - "127.0.0.1:9999:9999" # JMX — localhost only # No health check constraint in dev; let the app start at its own pace. healthcheck: disable: true diff --git a/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/security/PublicPathSnapshotTest.java b/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/security/PublicPathSnapshotTest.java index d71cebd4..712351fd 100644 --- a/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/security/PublicPathSnapshotTest.java +++ b/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/security/PublicPathSnapshotTest.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -30,6 +31,10 @@ class PublicPathSnapshotTest { private static final Path SECURITY_CONFIGURATION = Path.of("src/main/resources/config/security.yml"); private static final Path SNAPSHOT = Path.of("../../../docs/security/public-paths-snapshot.txt"); + private static final Path RESOURCES = Path.of("src/main/resources"); + private static final Path REPOSITORY = Path.of("../../.."); + private static final Pattern PROFILE_FILE = Pattern.compile("application-([a-z0-9-]+)\\.yml"); + private static final String SECURITY_IMPORT = "org.springframework.security"; private static final Pattern BINDING = Pattern.compile("^\\s*public-paths:\\s*(\\S.*?)\\s*$"); private static final Pattern DEFAULTED_PLACEHOLDER = Pattern.compile("\\$\\{[A-Za-z0-9_.]+:([^{}]*)}"); @@ -47,7 +52,10 @@ class PublicPathSnapshotTest { @DisplayName("배포되는 public path 기본값이 검토된 기준선과 같다") void theShippedPublicPathDefaultMatchesTheReviewedBaseline() throws IOException { // given - String rendered = render(Files.readAllLines(SECURITY_CONFIGURATION, StandardCharsets.UTF_8)); + String rendered = + render(Files.readAllLines(SECURITY_CONFIGURATION, StandardCharsets.UTF_8)) + + renderProfiles(profileFiles()) + + renderPermitAllSites(REPOSITORY, securitySources()); if (Boolean.getBoolean("publicpath.snapshot.write")) { Files.writeString(SNAPSHOT, rendered, StandardCharsets.UTF_8); } @@ -112,6 +120,61 @@ class PublicPathSnapshotTest { .hasMessageContaining("expected exactly one 'public-paths:' binding, found 0"); } + @Test + @DisplayName("보안 설정의 permitAll 문장과 chain 범위를 파일 경로와 함께 정렬해 적고, 보안 import가 없는 파일은 건너뛴다") + void permitAllStatementsAreListedWithTheirChainScope(@org.junit.jupiter.api.io.TempDir Path root) + throws IOException { + // given + Path chain = root.resolve("src/a/src/main/java/ChainConfig.java"); + Path other = root.resolve("src/b/src/main/java/Policy.java"); + Files.createDirectories(chain.getParent()); + Files.createDirectories(other.getParent()); + Files.writeString( + chain, + """ + import org.springframework.security.config.annotation.web.builders.HttpSecurity; + class ChainConfig { + // .permitAll() in a comment is not a statement + void chain(HttpSecurity http) { + http.securityMatcher("/hooks/**") + .authorizeHttpRequests(a -> a + .requestMatchers("/hooks/ping") + .permitAll()); + } + }"""); + Files.writeString(other, "class Policy { static Policy permitAll() { return null; } }"); + + // when + String rendered = renderPermitAllSites(root, List.of(chain, other)); + + // then + assertThat(rendered) + .isEqualTo( + "# Filter-chain statements that permit requests without authentication\n" + + "src/a/src/main/java/ChainConfig.java: .requestMatchers(\"/hooks/ping\")" + + " .permitAll());\n" + + "src/a/src/main/java/ChainConfig.java: http.securityMatcher(\"/hooks/**\")\n"); + } + + @Test + @DisplayName("profile 파일이 public-paths를 덮으면 profile 이름과 값을 적는다") + void aProfileThatOverridesThePublicPathsIsListed(@org.junit.jupiter.api.io.TempDir Path root) + throws IOException { + // given + Path local = root.resolve("application-local.yml"); + Path prod = root.resolve("application-prod.yml"); + Files.writeString(local, "app:\n security:\n public-paths: /api/healthcheck\n"); + Files.writeString(prod, "app:\n security:\n audience: x\n"); + + // when + String rendered = renderProfiles(List.of(local, prod)); + + // then + assertThat(rendered) + .isEqualTo( + "# Profile overrides of app.security.public-paths\nprofile local: /api/healthcheck\n"); + } + private static String render(List configuration) { List bindings = new ArrayList<>(); for (String line : configuration) { @@ -150,4 +213,90 @@ class PublicPathSnapshotTest { .toList(); return HEADER + (paths.isEmpty() ? "" : String.join("\n", paths) + "\n"); } + + /** + * A profile file that sets {@code app.security.public-paths} to a literal overrides the default + * in that runtime, so the snapshot pins it too. The check used to read security.yml only, and + * application-local.yml opened its own path past it (review 2026-11-12). + */ + static String renderProfiles(List profiles) throws IOException { + List lines = new ArrayList<>(); + for (Path profile : profiles) { + Matcher name = PROFILE_FILE.matcher(profile.getFileName().toString()); + if (!name.matches()) { + continue; + } + for (String line : Files.readAllLines(profile, StandardCharsets.UTF_8)) { + Matcher binding = BINDING.matcher(line); + if (binding.matches()) { + lines.add("profile " + name.group(1) + ": " + binding.group(1)); + } + } + } + return lines.isEmpty() + ? "" + : "# Profile overrides of app.security.public-paths\n" + + String.join("\n", lines.stream().sorted().toList()) + + "\n"; + } + + /** + * Every filter chain that lets a request through unauthenticated, wherever its module is: the + * statement that permits and the matcher that scopes its chain. The default list above feeds one + * chain; a module's own chain (the notification callback, the actuator) opened paths the old + * snapshot never saw. A statement whose text changes — a new matcher, a wider pattern — changes + * the snapshot. + */ + static String renderPermitAllSites(Path root, List sources) throws IOException { + List sites = new ArrayList<>(); + for (Path source : sources) { + List lines = Files.readAllLines(source, StandardCharsets.UTF_8); + if (lines.stream().noneMatch(line -> line.contains(SECURITY_IMPORT))) { + continue; + } + String file = root.relativize(source).toString().replace('\\', '/'); + String previous = ""; + for (String raw : lines) { + String line = raw.trim(); + if (line.isEmpty() + || line.startsWith("//") + || line.startsWith("*") + || line.startsWith("/*")) { + continue; + } + if (line.contains("securityMatcher(")) { + sites.add(file + ": " + line); + } + if (line.contains(".permitAll(")) { + sites.add(file + ": " + (line.startsWith(".permitAll") ? previous + " " + line : line)); + } + previous = line; + } + } + return sites.isEmpty() + ? "" + : "# Filter-chain statements that permit requests without authentication\n" + + String.join("\n", sites.stream().sorted().toList()) + + "\n"; + } + + private static List profileFiles() throws IOException { + try (Stream files = Files.list(RESOURCES)) { + return files + .filter(path -> PROFILE_FILE.matcher(path.getFileName().toString()).matches()) + .sorted() + .toList(); + } + } + + private static List securitySources() throws IOException { + try (Stream files = Files.walk(REPOSITORY.resolve("src"))) { + return files + .filter(path -> path.toString().endsWith(".java")) + .filter(path -> path.toString().replace('\\', '/').contains("/src/main/java/")) + .filter(path -> !path.toString().replace('\\', '/').contains("/build/")) + .sorted() + .toList(); + } + } } diff --git a/src/bootstrap/service-runtime/README.md b/src/bootstrap/service-runtime/README.md index dbcab88f..d7081f94 100644 --- a/src/bootstrap/service-runtime/README.md +++ b/src/bootstrap/service-runtime/README.md @@ -272,9 +272,12 @@ runtimeOnly project(':composition:service-runtime') 앞서 실행된다.** 그래서 액추에이터 엔드포인트에 매칭되는 요청은 앱 체인이 아니라 이 체인이 처리한다. 보안 매처는 `EndpointRequest.toAnyEndpoint()`로, 관리 포트의 `/actuator/**` 경로만 이 체인 범위에 든다. -- **접근 정책.** `health`, `info`, `prometheus`는 permit-all 이다. 자격 증명 없이 Kubernetes 프로브와 - Prometheus 스크레이프가 접근할 수 있어야 하고, 이 엔드포인트들은 민감 데이터를 노출하지 않기 - 때문이다(health 상세는 `never`). 나머지(`/actuator` 링크 등)는 모두 인증이 필요하다. +- **접근 정책.** `health`, `info`, `prometheus`는 permit-all 이다. 자격 증명 없이 프로브와 스크레이프가 + 읽을 수 있어야 하고, 이 엔드포인트들은 민감 데이터를 노출하지 않기 때문이다(health 상세는 `never`). + 관리 포트는 기본으로 loopback(`MANAGEMENT_SERVER_ADDRESS=127.0.0.1`)에만 묶인다. Kubernetes kubelet + 프로브와 Prometheus는 pod IP로 붙으므로, 그 배포는 `MANAGEMENT_SERVER_ADDRESS`를 그 주소(예: `0.0.0.0`과 + NetworkPolicy)로 바꾸거나 같은 pod의 sidecar로 읽는다. 기본값 그대로면 liveness가 실패해 재시작하고 + readiness가 오지 않는다. 나머지(`/actuator` 링크 등)는 모두 인증이 필요하다. - **`loggers`는 노출하지 않는다.** 이 체인에는 인증 수단(`httpBasic`·`oauth2ResourceServer`)이 없어 `authenticated()`에 걸리는 엔드포인트는 어떤 자격 증명으로도 도달할 수 없다. 그래서 `loggers` 노출과 `show-details: when-authorized`를 뺐다. 로그 레벨을 런타임에 보거나 바꿔야 하면 인증 -- 2.54.0 From 23139722e8e5384faa5d0dc597d70fef7c45cb93 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 03:55:38 +0900 Subject: [PATCH 08/23] =?UTF-8?q?fix(compose):=20heap=20dump=20=EA=B2=BD?= =?UTF-8?q?=EB=A1=9C=EB=A5=BC=20=EC=BB=A8=ED=85=8C=EC=9D=B4=EB=84=88=20?= =?UTF-8?q?=EB=A9=94=EB=AA=A8=EB=A6=AC=20=ED=95=9C=EA=B3=84=20=EC=95=88?= =?UTF-8?q?=EC=9D=98=20tmpfs=EC=97=90=20=EB=91=90=EC=A7=80=20=EC=95=8A?= =?UTF-8?q?=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 기본 compose.yaml은 -XX:HeapDumpPath=/var/tmp/heap을 512m tmpfs로 붙였다. 컨테이너는 mem_limit 512m·swap 없음이고 힙은 그 75%(384m)다. tmpfs에 쓴 페이지는 같은 컨테이너 메모리 한계에 잡힌다. 그래서 OutOfMemoryError 때 덤프를 쓰는 동안 컨테이너가 OOM kill(137)될 수 있었고, runbook이 기대하는 깨끗한 끝(코드 3, ExitOnOutOfMemoryError)이 사라졌다. 덤프가 끝까지 써져도 tmpfs는 컨테이너가 끝나면 함께 사라져 읽을 수 없었다. Dockerfile 주석은 오케스트레이터에 그 경로를 tmpfs로 붙이라고 했고, internal-error-spike runbook은 없는 파일 이름(heapdump-.hprof)을 적었다. 고른 방법: - 기본 compose.yaml은 그 경로에 아무것도 붙이지 않는다. 루트가 읽기 전용이라 JVM은 파일을 만들지 못하고 바로 코드 3으로 끝난다. 덤프를 남기는 dev lane(named volume heap-dumps)은 그대로다. - scripts/verify-compose-profile-contracts.sh(prCheck의 verifyComposeProfiles)가 모든 lane에서 그 경로의 tmpfs를 거절한다. 경로는 Dockerfile의 -XX:HeapDumpPath에서 읽는다. - Dockerfile 주석과 runbook 둘(runtime-jvm-oom 「진단」, internal-error-spike)에 덤프를 남기는 법(Kubernetes emptyDir without medium: Memory·PV, dev lane volume)과 실제 파일 이름(java_pid.hprof)을 적었다. - 버린 대안: 기본 compose에 named volume을 붙이기 — 기본 조립은 디스크에 아무것도 남기지 않는다는 결정(compose.yaml 「No volume」 주석)과 다르다. - 고치며 찾은 것(RR9-03-30): ComposeMergeCharacterizationTest는 어느 lane에서도 돌지 않았다. integrationTest lane은 requires로 적은 클래스 넷만 고른다 (StrictTestLanePlugin). 그 시험이 보던 기본·dev 조합 렌더링과 계약 스크립트는 verifyComposeProfiles가 18개 lane으로 이미 본다. 시험과, 그 lane에 compose 파일을 입력으로 선언하던 블록을 지웠다. 검증(desktop): - RED: 기준 ca1fbfde + 검사 스크립트만으로 :verifyComposeProfiles 실패 (기본 compose를 쓰는 lane마다 「heap dump path ... as a tmpfs」). - 탐침(eclipse-temurin:21-jdk, 읽기 전용 루트, 메모리 192m·swap 없음, -Xmx96m으로 OutOfMemoryError): 경로에 아무것도 없음 → "Unable to create /var/tmp/heap: Read-only file system", 코드 3. tmpfs → 덤프를 쓰다 코드 137(OOM kill). 디스크 마운트 → 덤프 101MB가 남고 코드 3. - GREEN: :verifyComposeProfiles(18 lane), :app-bootstrap:integrationTest, repositoryContractTest, spotlessCheck — 71건 실패 0, skip 1, rc=0. --- Dockerfile | 15 ++- compose.yaml | 10 +- docs/runbooks/internal-error-spike.md | 2 +- docs/runbooks/runtime-jvm-oom.md | 9 +- scripts/verify-compose-profile-contracts.sh | 19 ++- src/bootstrap/app/build.gradle | 12 +- src/bootstrap/app/compose-lanes/dev.yaml | 15 +-- .../ComposeMergeCharacterizationTest.java | 119 ------------------ 8 files changed, 50 insertions(+), 151 deletions(-) delete mode 100644 src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/compose/ComposeMergeCharacterizationTest.java diff --git a/Dockerfile b/Dockerfile index e8205522..840c0851 100644 --- a/Dockerfile +++ b/Dockerfile @@ -152,8 +152,8 @@ ENV HOME=/tmp # -XX:MaxRAMPercentage=75 — use up to 75% of the container memory limit for heap. # -XX:+UseContainerSupport — respect cgroup memory limits (default on JDK 10+, explicit here). # -XX:+ExitOnOutOfMemoryError — terminate immediately on OOM so the orchestrator can restart. -# -XX:+HeapDumpOnOutOfMemoryError / -XX:HeapDumpPath — write a heap dump to the writable -# /var/tmp/heap mount (see tmpfs mounts in compose files, D2). +# -XX:+HeapDumpOnOutOfMemoryError / -XX:HeapDumpPath — write a heap dump to /var/tmp/heap when a +# disk-backed volume is mounted there (see below). # -Dserver.tomcat.basedir=/tmp — redirect Tomcat temp files to /tmp (D2: read-only root fs). ENV JAVA_TOOL_OPTIONS="\ -XX:MaxRAMPercentage=75 \ @@ -164,10 +164,13 @@ ENV JAVA_TOOL_OPTIONS="\ -Dserver.tomcat.basedir=/tmp" # ---- Filesystem layout (D2: read-only root filesystem) ---------------------- -# /var/tmp/heap — heap dump landing zone; must be a writable mount at runtime. -# /tmp — Tomcat working directory (see JAVA_TOOL_OPTIONS above). -# Both directories are declared here so tooling is aware of them; at runtime they -# MUST be mounted as tmpfs (or host volumes) by the orchestrator (see compose files). +# /tmp — Tomcat working directory (see JAVA_TOOL_OPTIONS above); a tmpfs at runtime. +# /var/tmp/heap — heap dump landing zone. To keep dumps, mount a disk-backed volume there: in +# Kubernetes an emptyDir without `medium: Memory` (it survives a container restart) +# or a PersistentVolume. Never a tmpfs: it is charged to the container's memory +# limit and vanishes on exit, so the dump only risks an OOM kill. With nothing +# mounted the read-only root refuses the file and the JVM exits 3 at once (compose.yaml). +# Both directories are declared here so tooling is aware of them. RUN mkdir -p /var/tmp/heap && chmod 1777 /var/tmp/heap # ---- Non-root user (D3) ----------------------------------------------------- diff --git a/compose.yaml b/compose.yaml index bb145c2e..0ebba1dc 100644 --- a/compose.yaml +++ b/compose.yaml @@ -107,13 +107,17 @@ services: APP_DATASOURCE_USERNAME: "${APP_DATASOURCE_USERNAME:-ca_skeleton}" APP_DATASOURCE_PASSWORD: "${APP_DATASOURCE_PASSWORD:-ca_skeleton}" # ---- Read-only root filesystem (D2) ------------------------------------- - # The application must write only to the tmpfs mounts declared below. + # The application must write only to the tmpfs mount declared below. # /tmp — Tomcat basedir (see -Dserver.tomcat.basedir=/tmp in Dockerfile). - # /var/tmp/heap — heap dump landing zone (see -XX:HeapDumpPath=/var/tmp/heap). + # /var/tmp/heap — the heap dump path (-XX:HeapDumpPath) — is deliberately not a tmpfs. A tmpfs is + # charged to this container's mem_limit and is gone once the container exits, so a dump written + # there at an OutOfMemoryError could only turn the clean exit 3 into an OOM kill, and was never + # there to read. On the read-only root the JVM cannot create the file and exits 3 at once. The + # dev lane mounts a volume there to keep dumps; scripts/verify-compose-profile-contracts.sh + # refuses a tmpfs at that path in every lane. read_only: true tmpfs: - /tmp:mode=1777,size=128m - - /var/tmp/heap:mode=1777,size=512m # No volume: the shipped composition keeps nothing on disk. A capability that does brings its # mount in its own overlay, added with -f when the capability is selected, so this file never # names one (07-08). diff --git a/docs/runbooks/internal-error-spike.md b/docs/runbooks/internal-error-spike.md index 2822a4ab..de04cdfe 100644 --- a/docs/runbooks/internal-error-spike.md +++ b/docs/runbooks/internal-error-spike.md @@ -36,7 +36,7 @@ status: 초안 - log query: `{service="app"} | http.status>=500 | stats count by error.code` - metric panel: `jvm_memory_used_bytes{area="heap"}`, `jvm_gc_pause_seconds`, `process_cpu_seconds_total`, `http_server_requests_seconds_count{status=~"5.."}` - trace: 실패 request의 `traceId`로 span chain 확인 → stack trace에서 root exception 추출 -- heap dump 위치: `/var/tmp/heap/heapdump-.hprof` (JVM ergonomics: `-XX:MaxRAMPercentage=75 -XX:+HeapDumpOnOutOfMemoryError`) +- heap dump 위치: `/var/tmp/heap/java_pid.hprof`(`-XX:HeapDumpPath=/var/tmp/heap`). 그 경로에 디스크 볼륨을 붙인 배포에만 남는다. 읽는 법은 `docs/runbooks/runtime-jvm-oom.md` 「진단」 - 가능한 원인: - 직전 deploy의 회귀 버그 → rollback - JVM OOM (메모리 leak 또는 부하 증가) → heap dump 분석 diff --git a/docs/runbooks/runtime-jvm-oom.md b/docs/runbooks/runtime-jvm-oom.md index 8dba2923..3f9635e0 100644 --- a/docs/runbooks/runtime-jvm-oom.md +++ b/docs/runbooks/runtime-jvm-oom.md @@ -22,7 +22,14 @@ status: 초안 ## 진단 - 힙 덤프를 본다. 이미지의 `JAVA_TOOL_OPTIONS`가 `-XX:+HeapDumpOnOutOfMemoryError`와 - `-XX:HeapDumpPath=/var/tmp/heap`을 켠다(`Dockerfile`). + `-XX:HeapDumpPath=/var/tmp/heap`을 켠다(`Dockerfile`). 파일은 `/var/tmp/heap/java_pid.hprof`다. +- 덤프는 그 경로에 디스크 볼륨을 붙였을 때만 남는다. + - Kubernetes: `medium: Memory`가 없는 emptyDir나 PersistentVolume. emptyDir는 컨테이너가 다시 떠도 남는다. + `kubectl cp :/var/tmp/heap/java_pid1.hprof .`로 꺼낸다. + - compose dev lane: named volume `heap-dumps`. `docker compose cp app:/var/tmp/heap/<파일> .`로 꺼낸다. + - 기본 `compose.yaml`: 그 경로에 아무것도 붙이지 않는다. 루트가 읽기 전용이라 JVM이 파일을 못 만들고 바로 + 코드 3으로 끝난다. tmpfs는 쓰지 않는다. 컨테이너 메모리 한계에 함께 잡혀 덤프 중 OOM kill(코드 137)이 나고, + 컨테이너가 끝나면 함께 사라진다. - 죽기 전 메모리 사용 추세를 본다. - 메모리 누수를 찾는다: 커지기만 하는 캐시, 상한 없는 목록, 쌓이는 세션. diff --git a/scripts/verify-compose-profile-contracts.sh b/scripts/verify-compose-profile-contracts.sh index 459431eb..3e47131d 100755 --- a/scripts/verify-compose-profile-contracts.sh +++ b/scripts/verify-compose-profile-contracts.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # The static half of the Compose contract: every lane renders, and renders exactly what it claims. # -# Nine things are checked, and each exists because assuming it cost something: +# Ten things are checked, and each exists because assuming it cost something: # # 1. the Compose version, because `!override` is what stops the dev overlay's tmpfs merging with # the base's and colliding with a bind mount, and it needs 2.24.4; @@ -24,7 +24,11 @@ # would hide the same trade in production; the lane has to look like a deployment instead. # 8. a lane's appMemoryLimit, when it has one, is a Compose memory size, because the smoke wrapper # writes it into the application's mem_limit and a malformed one fails only at `up`. -# 9. the Keycloak realm artifact carries no key Keycloak refuses (below the lane loop). +# 9. the application's heap dump path (-XX:HeapDumpPath in the Dockerfile) is not a tmpfs, because a +# tmpfs is charged to the container's memory limit and is gone once the container exits: the +# dump written at an OutOfMemoryError could only push the container into an OOM kill and was +# never there to read (2026-11-12 review). +# 10. the Keycloak realm artifact carries no key Keycloak refuses (below the lane loop). # # Static only. Nothing starts here; scripts/run-compose-runtime-smoke.sh owns that. set -euo pipefail @@ -103,6 +107,8 @@ redis_authentication_problems() { } command -v jq >/dev/null 2>&1 || { echo "jq is required" >&2; exit 78; } +HEAP_DUMP_PATH="$(sed -n 's/.*-XX:HeapDumpPath=\([^ \\"]*\).*/\1/p' "${REPO_ROOT}/Dockerfile" | head -1)" +[[ -n "${HEAP_DUMP_PATH}" ]] || { echo "the Dockerfile sets no -XX:HeapDumpPath" >&2; exit 78; } command -v docker >/dev/null 2>&1 || { echo "docker is required" >&2; exit 78; } [[ -r "${CONTRACTS}" ]] || { echo "missing ${CONTRACTS}" >&2; exit 78; } @@ -233,10 +239,17 @@ for index in $(seq 0 $((lane_count - 1))); do fail "${id}: appMemoryLimit '${memory_limit}' is not a Compose memory size such as 1g" fi + # 9. the heap dump path is not a tmpfs. + heap_tmpfs="$(jq -r --arg path "${HEAP_DUMP_PATH}" \ + '.services.app.tmpfs // [] | .[] | split(":")[0] | select(. == $path)' <<<"${model}")" + if [[ -n "${heap_tmpfs}" ]]; then + fail "${id}: app mounts the heap dump path ${HEAP_DUMP_PATH} as a tmpfs, which counts against its memory limit and is gone when it exits" + fi + [[ ${FAILURES} -eq 0 ]] && echo "${id}: ${expected} @ ${runtime}" done -# 9. the Keycloak realm artifact deserializes into Keycloak's own representation. +# 10. the Keycloak realm artifact deserializes into Keycloak's own representation. # # Keycloak rejects unknown fields rather than ignoring them, so one annotation key anywhere in the # tree fails the whole import, the container exits 1, and every lane that needs an identity provider diff --git a/src/bootstrap/app/build.gradle b/src/bootstrap/app/build.gradle index e0697407..78bb88ce 100644 --- a/src/bootstrap/app/build.gradle +++ b/src/bootstrap/app/build.gradle @@ -399,9 +399,9 @@ tasks.named('check') { } // The other suites find the repository themselves and read what Gradle cannot otherwise see: the -// architecture suite scans every leaf's production sources and its own rule sources as text, the -// opt-in classpath contract reads this build script, and the Compose characterization reads the -// Compose files. +// architecture suite scans every leaf's production sources and its own rule sources as text, and the +// opt-in classpath contract reads this build script. The Compose files are rendered by +// :verifyComposeProfiles (pull-request stage), not by a test here. tasks.named('architectureTest', Test) { inputs.files(fileTree(rootProject.projectDir) { include 'src/**/src/main/java/**/*.java', 'build-logic/src/main/java/**/*.java', @@ -412,12 +412,6 @@ tasks.named('architectureTest', Test) { tasks.named('conditionalTransportBuildContractTest', Test) { inputs.file('build.gradle').withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('buildScript') } -tasks.named('integrationTest', Test) { - inputs.files(fileTree(repositoryRootForContractTests) { - include 'compose.yaml', 'compose/**', 'scripts/*compose*.sh', 'src/bootstrap/app/compose-lanes/**' - exclude repositoryContractExcludes - }).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('composeFiles') -} // Fast developer test lane. Whole-repository ArchUnit graphs and full composition-root boot // characterizations have their own source sets, so the ordinary lane does not compile or execute diff --git a/src/bootstrap/app/compose-lanes/dev.yaml b/src/bootstrap/app/compose-lanes/dev.yaml index 0be7e6ad..579cd9b9 100644 --- a/src/bootstrap/app/compose-lanes/dev.yaml +++ b/src/bootstrap/app/compose-lanes/dev.yaml @@ -22,10 +22,9 @@ services: # Relax read-only constraint for local development. read_only: false # `!override`, not a plain empty list. An empty sequence merges with the base sequence rather - # than replacing it, so the base's /var/tmp/heap tmpfs survived and collided with the bind mount - # below — Compose refuses to have the same target twice and will not silently pick one. That is - # the right refusal: a heap dump written into a tmpfs dies with the container that produced it, - # which is the one moment somebody wants the file. + # than replacing it; the writable root needs no tmpfs at all. The base once declared a tmpfs at + # /var/tmp/heap too, and the merge collided with the volume below — Compose refuses to have the + # same target twice and will not silently pick one. # # `!override` needs Compose >= 2.24.4. Whether the collision is actually gone is checked in the # merged model rather than assumed from this line. @@ -74,11 +73,9 @@ services: disable: true # Do not restart automatically so crash loops stay visible. restart: "no" - # Heap dumps survive the container that wrote them. - # The base declares /var/tmp/heap as a tmpfs, which is right for an ephemeral runtime and wrong - # for dev: a heap dump written into a tmpfs dies with the container that produced it, which is - # the one moment somebody wants the file. Compose refuses to have both, and correctly — it will - # not silently pick one — so the tmpfs list is replaced rather than appended to. + # Heap dumps survive the container that wrote them. The base mounts nothing at /var/tmp/heap, so + # there the JVM cannot write a dump at all; a tmpfs would not do instead, since it dies with the + # container that produced it, which is the one moment somebody wants the file. # # A named volume, not a bind mount of ./tmp/heap-dumps: Docker created that folder as root inside # the checkout, and a git worktree holding it could not be removed without root. Copy a dump out diff --git a/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/compose/ComposeMergeCharacterizationTest.java b/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/compose/ComposeMergeCharacterizationTest.java deleted file mode 100644 index 7024f756..00000000 --- a/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/compose/ComposeMergeCharacterizationTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package dev.caskeleton.bootstrap.compose; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Every shipped Compose file stack must at least render. - * - *

A stack that cannot merge has no failure mode short of total: nothing starts, and the error - * arrives at the moment somebody most wants the environment. The dev stack was in exactly that - * state — the base declares {@code /var/tmp/heap} as a tmpfs, the dev overlay mounts a volume at - * the same target so heap dumps survive the container, and the overlay\'s {@code tmpfs: []} merged - * with the base list instead of replacing it. {@code !override} replaces it, and the merged model - * is checked for duplicate mount targets rather than the fix being assumed from the syntax. - */ -class ComposeMergeCharacterizationTest { - - private static final Path REPOSITORY_ROOT = repositoryRoot(); - - @Test - @DisplayName("the development stack renders") - void developmentStackRenders() { - assertStackRenders("compose.yaml"); - } - - @Test - @DisplayName("the dev lane stack renders") - void devStackRenders() { - assertStackRenders("compose.yaml", "src/bootstrap/app/compose-lanes/dev.yaml"); - } - - /** - * The lane contract, checked by the script that owns it. - * - *

Delegating rather than reimplementing: the script is the entry point CI calls, and a test - * that re-derived the same checks in Java would be a second opinion that can agree with the - * contract while the script disagrees. What this adds is that the check runs in the explicit - * integration lane, where Docker Compose and companion CLI tools are environment prerequisites - * rather than hidden unit-test dependencies. - */ - @Test - @DisplayName("every lane renders exactly the services its contract names") - void everyLaneMatchesItsContract() { - Assumptions.assumeTrue(dockerComposeIsAvailable(), "docker compose is not on this machine"); - ProcessResult result = run(List.of("./scripts/verify-compose-profile-contracts.sh")); - assertThat(result.exitCode()) - .as("verify-compose-profile-contracts.sh said:%n%s", result.output()) - .isZero(); - } - - private static void assertStackRenders(String... files) { - Assumptions.assumeTrue(dockerComposeIsAvailable(), "docker compose is not on this machine"); - List command = new ArrayList<>(List.of("docker", "compose")); - for (String file : files) { - command.add("-f"); - command.add(file); - } - command.add("config"); - ProcessResult result = run(command); - assertThat(result.exitCode()) - .as( - "the %s stack must render; docker compose said:%n%s", - String.join(" + ", files), result.output()) - .isZero(); - } - - private static boolean dockerComposeIsAvailable() { - try { - return run(List.of("docker", "compose", "version", "--short")).exitCode() == 0; - } catch (RuntimeException failure) { - return false; - } - } - - private static ProcessResult run(List command) { - try { - Process process = - new ProcessBuilder(command) - .directory(REPOSITORY_ROOT.toFile()) - .redirectErrorStream(true) - .start(); - String output = - new String( - process.getInputStream().readAllBytes(), java.nio.charset.StandardCharsets.UTF_8); - if (!process.waitFor(120, TimeUnit.SECONDS)) { - process.destroyForcibly(); - throw new IllegalStateException("docker compose did not finish within 120s"); - } - return new ProcessResult(process.exitValue(), output); - } catch (IOException failure) { - throw new IllegalStateException("could not run " + command, failure); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("interrupted while running " + command, interrupted); - } - } - - private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null && !Files.isRegularFile(candidate.resolve("compose.yaml"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("could not locate the repository root from the test cwd"); - } - return candidate; - } - - private record ProcessResult(int exitCode, String output) {} -} -- 2.54.0 From 10751b4279c593dedc6a186385da8158433b4b19 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 03:49:39 +0900 Subject: [PATCH 09/23] =?UTF-8?q?docs(reviews):=20round9=20=EA=B8=B0?= =?UTF-8?q?=EB=A1=9D=EC=97=90=20=EA=B8=B0=EC=A4=80=20=EA=B2=8C=EC=9D=B4?= =?UTF-8?q?=ED=8A=B8=20=EA=B2=B0=EA=B3=BC=C2=B7=EB=AC=B6=EC=9D=8C=20PR?= =?UTF-8?q?=C2=B7=EA=B3=A0=EC=B9=98=EB=A9=B0=20=EC=B0=BE=EC=9D=80=20?= =?UTF-8?q?=EB=B0=9C=EA=B2=AC=EC=9D=84=20=EB=8D=94=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 2절: 기준 main 단계 결과(rc=0, 시험 1867건 실패 0, skip 19)와 pr 단계 시험 수를 적고, 「6절에 적는다」던 잘못된 가리킴을 지웠다. nightly·release 기준 실행을 접은 이유를 적었다. - 4절: 열린 PR 번호(#16 #19 #20 #21 #22 #23 #24)와 병렬 그룹 A·B·C 표. - RR9-03-30(Medium): compose 병합 특성 시험이 어느 lane에서도 돌지 않았다(integrationTest lane이 requires 클래스 넷만 고른다). B19(PR #24)가 고친다. 색인과 03-contract-testing.md에 더해 모두 153건이다. 검증: check-review-index.py(153/153), check-docs.py, check-work-docs.py rc=0. --- .../03-contract-testing.md | 7 +++++ .../2026-11-12-round9-review/README.md | 31 +++++++++++++------ 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/docs/reviews/2026-11-12-round9-review/03-contract-testing.md b/docs/reviews/2026-11-12-round9-review/03-contract-testing.md index 42394306..2074348d 100644 --- a/docs/reviews/2026-11-12-round9-review/03-contract-testing.md +++ b/docs/reviews/2026-11-12-round9-review/03-contract-testing.md @@ -205,3 +205,10 @@ - 증거: E1(현재 커밋 코드·문서 정적 확인) · 이전부터 - 묶음: B11b graphql·websocket 계약 - 내용: GraphQlCursorException.java:10-15, GraphQlConnectionException.java:8-13 — Javadoc "Stable request-error code GRAPHQL_CURSOR_REJECTED"인데 플랫폼 거부·carrier 아님 → resolver 안에서 INTERNAL_ERROR+ERROR(GraphQlErrorCodeCatalogTest:58-61). + +### RR9-03-30 · Medium · compose 병합 특성 시험이 어느 lane에서도 돌지 않았다 + +- 출처: 고치며 찾음(B19, 2026-11-13) +- 증거: E2(desktop 실행: `:app-bootstrap:integrationTest --tests '*ComposeMergeCharacterizationTest'`가 「No tests found」) · 이전부터 +- 묶음: B19 compose·Docker 운영 +- 내용: `src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/compose/ComposeMergeCharacterizationTest.java` — `integrationTest` lane은 `requires`로 적은 클래스 넷만 고른다(`StrictTestLanePlugin.java:228-232`). `src/bootstrap/app/build.gradle`은 그 lane 입력에 compose 파일을 선언해 이 시험이 돈다고 적었다. 시험이 보던 것(기본·dev 조합 렌더링, 계약 스크립트)은 PR 단계 `verifyComposeProfiles`가 18개 lane으로 이미 본다. 고침: 시험과 입력 선언을 지운다. diff --git a/docs/reviews/2026-11-12-round9-review/README.md b/docs/reviews/2026-11-12-round9-review/README.md index bd3aeae0..92745392 100644 --- a/docs/reviews/2026-11-12-round9-review/README.md +++ b/docs/reviews/2026-11-12-round9-review/README.md @@ -3,7 +3,7 @@ ## 1. 결론 main `a7e38c10`(Gradle 루트 재배치, gRPC·메시징 플랫폼 분리, 분야 전문가 스킬, CI 재편, red team 수정이 들어간 뒤)을 -새 눈으로 전체 리뷰했다. 발견 152건: Critical 0, High 2, Medium 72, Low 78. 이 밖에 CI workflow·`build.gradle`·`gates.md`처럼 +새 눈으로 전체 리뷰했다. 발견 152건: Critical 0, High 2, Medium 72, Low 78. 고치며 1건(Medium)을 더 찾아 모두 153건이다. 이 밖에 CI workflow·`build.gradle`·`gates.md`처럼 백엔드 CI 세션이 고치는 중인 파일의 발견 9건은 그 세션에 넘겼다(5절). - High 둘은 아키텍처 규칙의 사각지대다(HARD-STOP 2). controller가 domain repository 포트를 들어도, inbound 밖 사용자 @@ -15,8 +15,9 @@ main `a7e38c10`(Gradle 루트 재배치, gRPC·메시징 플랫폼 분리, 분 ## 2. 범위 -- 대상: main `a7e38c10`, 작업 트리 깨끗함, 2026-11-12. 기준 게이트: `scripts/verify.sh pr --no-cache` rc=0(desktop, 21:06~21:39). - `main` 단계는 6절에 결과를 적는다. +- 대상: main `a7e38c10`, 작업 트리 깨끗함, 2026-11-12. 기준 게이트(desktop, `--no-cache`): `scripts/verify.sh pr` rc=0 + (21:06~21:39, 시험 6724건 실패 0, skip 28), `scripts/verify.sh main` rc=0(시험 1867건 실패 0, skip 19). `nightly`·`release` + 기준 실행은 desktop 잠금을 수정 검증에 쓰려고 접었다. 라운드 끝 게이트가 합친 트리에서 돈다(7절). - 방법: `docs/work/experts.md`의 분야 렌즈로 `reviewer` 서브에이전트를 두 물결에 나눠 띄웠다(lead 스킬, 한 물결 4명). 모든 발견은 E1(현재 커밋 코드·문서 정적 확인)이고, 고칠 때 RED 시험(수정 전 실패)으로 다시 확인한다. @@ -134,6 +135,7 @@ main `a7e38c10`(Gradle 루트 재배치, gRPC·메시징 플랫폼 분리, 분 | RR9-03-27 | Medium | API 계약·시험 | 503+Retry-After 약속, guard bean만, 요청 경로에서 run 안 부름(manual 10 기준 3). | B11a web-advanced 계약 | | RR9-03-28 | Medium | API 계약·시험 | 정본 충돌 → 소유자 결정. | B11a web-advanced 계약 | | RR9-03-29 | Medium | API 계약·시험 | Javadoc "Stable request-error code GRAPHQL_CURSOR_REJECTED"인데 플랫폼 거부·carrier 아님… | B11b graphql·websocket 계약 | +| RR9-03-30 | Medium | API 계약·시험 | compose 병합 특성 시험이 어느 lane에서도 돌지 않았다 | B19 compose·Docker 운영 | | RR9-04-01 | Medium | 빌드·문서 | #12가 줄 더해 151/150, check-work-docs rc=1 → verify.sh docs·라운드 끝 실패. 같은 줄 "(W4… | B1 문서·지침 | | RR9-04-02 | Medium | 빌드·문서 | `cd ~/workspace/<작업>/src` 뒤 ./gradlew(#10 뒤 src에 gradlew 없음). desktop-gates… | B1 문서·지침 | | RR9-04-03 | Medium | 빌드·문서 | "Gradle 루트가 src/라 두 단계 위", `--include-build ../../messaging-library` →… | B1 문서·지침 | @@ -205,12 +207,21 @@ main `a7e38c10`(Gradle 루트 재배치, gRPC·메시징 플랫폼 분리, 분 | 묶음 | 브랜치 | 상태 | | --- | --- | --- | | B1 문서·지침 | `claude/r9-docs-work` | PR #16 | -| B2 env 계약 | `claude/r9-env-keys` | 진행 | -| B3 공개 경로·관리 포트 | `claude/r9-public-surface` | 진행 | -| B9 트랜잭션 시한·정리 | `claude/r9-tx-timeouts` | 진행(R1-1 먼저) | -| B14 아키텍처 규칙 | `claude/r9-arch-rules` | 진행 | -| B18c 낡은 이름·leaf 안내 | `claude/r9-stale-names` | 진행 | -| 나머지(B4~B8, B10~B13, B15~B19) | — | 대기 | +| B2 env 계약 | `claude/r9-env-keys` | PR #20 | +| B3 공개 경로·관리 포트 | `claude/r9-public-surface` | PR #23 | +| B9a inbox 트랜잭션 상한(RR9-01-01) | `claude/r9-tx-timeouts` | PR #21 | +| B14 아키텍처 규칙 | `claude/r9-arch-rules` | PR #19 | +| B18c 낡은 이름(RR9-04-38~41) | `claude/r9-stale-names` | PR #22 | +| B19 compose·Docker 운영(RR9-01-21, RR9-03-30) | `claude/r9-compose-ops` | PR #24 | +| 그룹 A 보안·관측·전송: B4, B5, B6a, B6b, B7, B11b | 그룹 세션 | 대기 | +| 그룹 B 영속성·outbound·application: B8, B9 나머지, B10a, B10b, B15a, B15b, B16 일부 | 그룹 세션 | 대기 | +| 그룹 C 계약·시험·빌드·문서: B11a, B12, B13, B16, B17, B18a, B18b, B18c 나머지(RR9-04-35·36·42) | 그룹 세션 | 대기 | + +그룹은 서로 파일이 겹치지 않게 나눴다. 묶음과 경로는 위 색인의 「묶음」 칸과 같다. + +### 고치며 찾은 것 + +- RR9-03-30(Medium): 고치는 중에 찾은 발견이다. 색인과 `03-contract-testing.md`에 더했다. ## 5. 다른 세션에 넘긴 것 @@ -244,7 +255,7 @@ compose README를 고치는 중)에 9건을 넘겼다(2026-11-12). 그 세션 PR ## 7. 멈춤 기준 상태 (`docs/work/improve.md` 4.5절) -1. 마지막 확인 리뷰 발견 0: 아님. 이 라운드 152건을 고친 뒤 확인 리뷰(독립 리뷰어 둘)가 판정한다. +1. 마지막 확인 리뷰 발견 0: 아님. 이 라운드 153건을 고친 뒤 확인 리뷰(독립 리뷰어 둘)가 판정한다. 2. 열린 「Declined to judge」 0: 참. 판정을 미룬 항목은 없다. 못 본 경로는 2절에 적었다. 3. 합친 트리의 라운드 끝 게이트: 아직. 묶음을 합친 뒤 돈다. 4. README의 남은 항목 0: 아님. 4절의 대기 묶음과 6절의 결정이 남았다. -- 2.54.0 From 18188f78c90b04ab51b5df1a8fd0e01fcf3aaa61 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 04:08:16 +0900 Subject: [PATCH 10/23] =?UTF-8?q?fix(web-advanced)!:=20patch=C2=B7stream?= =?UTF-8?q?=C2=B7virtual=20thread=EA=B0=80=20=EC=95=BD=EC=86=8D=ED=95=9C?= =?UTF-8?q?=20=EA=B3=84=EC=95=BD=EB=8C=80=EB=A1=9C=20=EB=8B=B5=ED=95=9C?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: web-advanced의 계약 문서와 코드가 다섯 곳에서 갈렸다. - patch 거부가 세 코드로 갈렸다. 형식 오류는 PATCH_REJECTED(400), 빈 문서·연산 모양 오류·merge 깊이 초과는 IllegalArgumentException이라 BAD_PARAMETER(400), 너무 깊은 pointer는 권한 거절 PATCH_PATH_FORBIDDEN(403) 이었다. JSON이 아닌 본문과 결과가 대상 타입으로 읽히지 않는 patch는 Jackson 예외로 catch-all에 닿아 500 INTERNAL_ERROR였다. - patch-contract.md는 결과를 문서 전체로 검증한다고 했지만 두 applier는 검증기를 받지 않았다. - streaming-contract.md는 서버가 위치 증가를 강제하고 heartbeat·idle·max age·버퍼 상한·drain 재연결을 한다고 했다. MvcStreamWriter는 그 어느 것도 하지 않았다. - commit 뒤 Failure 기록이 어디에도 등록되지 않은 DEPENDENCY_FAILURE로 고정이라, STREAM_ITEM_TOO_LARGE 같은 carrier 코드가 사라졌다. - virtual thread profile은 503 + Retry-After를 약속했지만 admission guard는 bean만 있었고 요청 경로에서 아무도 부르지 않았다. - web AGENTS B2는 merge patch를 쓰지 않는다고 했고 patch-contract는 필드 변경에 merge patch를 쓰라고 했다(정본 충돌). 고른 방법: - 형식이 틀린 patch 문서는 모두 JsonPatchRejectedException(PATCH_REJECTED) 이다. 본문 파싱과 결과 변환은 PatchBodies가 감싼다. 너무 깊은 pointer는 권한 검사 앞에서 400으로 거절한다. 대상 타입이 객체가 아닌 것은 서버 결함이라 IllegalStateException이다. - 두 applier가 Bean Validation Validator를 받아 결과 객체 전체를 검증한다. 위반은 @Valid 본문과 같은 ConstraintViolationException → VALIDATION_FAILED. - writer는 위치가 앞 항목보다 크지 않으면 그 항목을 쓰지 않고 INTERNAL_ERROR Failure 기록으로 끝낸다. Failure 기록은 cause 사슬의 carrier 코드, 없으면 INTERNAL_ERROR, 문구는 category 고정 문구다. - writer가 할 수 없는 것(heartbeat, idle·max age, 버퍼, drain)은 계약 문서를 고쳐 누가 하는지(WebStreamPolicy·Registry·DrainCoordinator를 쓰는 서비스) 적었다. 요청 thread의 동기 writer라 heartbeat를 넣으려면 thread 모델을 바꿔야 해서 버렸다. - VirtualThreadAdmissionFilter가 모든 요청을 guard 아래 둔다(request-id filter 바로 뒤). async 요청은 async가 끝날 때 permit을 돌려준다. guard에 Permit API를 더했다. - 정본 충돌은 리뷰 README 6절 ③대로 patch-contract를 정본으로 두고 web AGENTS B2가 그쪽을 가리킨다. 위험·한계: patch를 쓰는 서비스는 applier 생성자에 Validator를 넘겨야 컴파일된다. client가 보는 patch·stream 오류 코드가 바뀐다. virtual thread profile을 켠 배포는 처음으로 상한에 걸릴 수 있다(upgrade 안내 1~5). BREAKING CHANGE: JsonMergePatchApplier·JsonPatchApplier 생성자가 Validator를 받는다. patch 거부는 모두 PATCH_REJECTED(400), 결과 제약 위반은 VALIDATION_FAILED, stream Failure 코드는 실패의 코드나 INTERNAL_ERROR다. 할 일은 docs/upgrade/2026-11-round9-contracts.md. Refs: RR9-03-23, RR9-03-24, RR9-03-25, RR9-03-26, RR9-03-27, RR9-03-28 --- docs/upgrade/2026-11-round9-contracts.md | 19 +++ docs/web/advanced-capabilities.md | 2 +- docs/web/patch-contract.md | 9 ++ docs/web/streaming-contract.md | 27 +++-- docs/web/virtual-thread-profile.md | 6 +- src/adapter/inbound/web-advanced/README.md | 2 +- .../web/advanced/mvc/MvcStreamWriter.java | 36 +++++- .../mvc/VirtualThreadAdmissionFilter.java | 111 ++++++++++++++++++ .../mvc/VirtualThreadMvcConfiguration.java | 12 ++ .../advanced/patch/JsonMergePatchApplier.java | 13 +- .../patch/JsonMergePatchDocument.java | 8 +- .../web/advanced/patch/JsonPatchApplier.java | 12 +- .../web/advanced/patch/JsonPatchDocument.java | 5 +- .../advanced/patch/JsonPatchOperation.java | 10 +- .../patch/JsonPointerAuthorization.java | 13 +- .../web/advanced/patch/PatchBodies.java | 53 +++++++++ .../VirtualThreadAdmissionGuard.java | 36 +++++- .../mvc/MvcAdvancedConfigurationTest.java | 2 + .../advanced/mvc/MvcStreamingWiringTest.java | 57 ++++++++- .../mvc/VirtualThreadAdmissionFilterTest.java | 87 ++++++++++++++ .../patch/JsonMergePatchApplierTest.java | 48 +++++++- .../advanced/patch/JsonPatchApplierTest.java | 88 +++++++++++++- src/adapter/inbound/web/AGENTS.md | 8 +- 23 files changed, 610 insertions(+), 54 deletions(-) create mode 100644 docs/upgrade/2026-11-round9-contracts.md create mode 100644 src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java create mode 100644 src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java create mode 100644 src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java diff --git a/docs/upgrade/2026-11-round9-contracts.md b/docs/upgrade/2026-11-round9-contracts.md new file mode 100644 index 00000000..8f89e0c3 --- /dev/null +++ b/docs/upgrade/2026-11-round9-contracts.md @@ -0,0 +1,19 @@ +# 업그레이드 안내 — 2026-11 HTTP 계약·오류 코드 정리 + +- 범위: web-advanced(patch·stream·virtual thread), fileserver·notification HTTP, 전송 오류 코드를 약속한 계약에 맞춘 + 변경. 응답 코드·모양이 바뀐 곳이 있다. 아래 표가 그 목록이다. +- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 계약·오류 코드 발견 + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스와, 그 서비스의 HTTP 응답을 읽는 client 팀이 읽는다. + +## 2. 할 일 + +| # | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | +| 1 | `JsonMergePatchApplier`·`JsonPatchApplier`를 만드는 코드에 셋째 인자로 Boot의 `jakarta.validation.Validator` bean을 넘긴다 | 컴파일이 실패한다 | web-advanced patch를 쓰는 서비스 | +| 2 | patch 거부를 읽는 client는 `PATCH_REJECTED`(400) 하나로 본다. 전에는 JSON이 아닌 본문이 `500 INTERNAL_ERROR`, 빈 문서·연산 모양 오류·merge 깊이 초과가 `400 BAD_PARAMETER`, 너무 깊은 pointer가 `403 PATCH_PATH_FORBIDDEN`이었다 | client가 옛 코드로 분기하던 곳이 다른 코드를 받는다 | patch route를 둔 서비스와 그 client | +| 3 | patch 결과가 Bean Validation 제약을 어기면 `400 VALIDATION_FAILED`와 필드별 `details`가 나간다. patch 대상 타입의 제약을 확인한다 | 전에는 제약을 어긴 객체가 그대로 저장 경로로 갔다 | web-advanced patch를 쓰는 서비스 | +| 4 | 스트림 `Failure` 기록의 `code`가 실패의 코드(예: `STREAM_ITEM_TOO_LARGE`) 또는 `INTERNAL_ERROR`다. `DEPENDENCY_FAILURE`로 분기하던 client를 고친다 | 그 분기가 다시는 맞지 않는다 | NDJSON·JSON-seq stream을 읽는 client | +| 5 | virtual thread profile을 켠 배포는 이제 실제로 허가 상한을 건다. `admission-limit`이 부하에 맞는지 본다 | 전에는 상한이 없어 모든 요청이 들어왔다. 이제 넘치면 `503 ADMISSION_REFUSED`와 `Retry-After: 1`이다 | `app.web.advanced.mvc-virtual-threads.enabled=true`인 배포 | diff --git a/docs/web/advanced-capabilities.md b/docs/web/advanced-capabilities.md index 731c048f..719adfc9 100644 --- a/docs/web/advanced-capabilities.md +++ b/docs/web/advanced-capabilities.md @@ -10,7 +10,7 @@ Advanced capability는 따로 된 leaf `adapter:inbound:web-advanced`(`src/adapt | Capability | 켜는 법 | 더하는 것 | 테스트 | | --- | --- | --- | --- | -| MVC virtual thread | `app.web.advanced.mvc-virtual-threads.enabled=true`(+ 허가 상한과 예산) | **모든** 요청에 대한 다른 스케줄링 모델 | `MvcAdvancedConfigurationTest`, `VirtualThreadAdmissionTest` | +| MVC virtual thread | `app.web.advanced.mvc-virtual-threads.enabled=true`(+ 허가 상한과 예산) | **모든** 요청에 대한 다른 스케줄링 모델과 요청마다 거는 허가 상한(`VirtualThreadAdmissionFilter`) | `MvcAdvancedConfigurationTest`, `VirtualThreadAdmissionTest`, `VirtualThreadAdmissionFilterTest` | | NDJSON 스트리밍 | `app.web.advanced.ndjson.enabled=true` | 오래 사는 connection | `MvcStreamingWiringTest`, `WebStreamCoreTest`, `WebStreamDrainTest`, `WebStreamingSoakIT` | | JSON text sequence(RFC 7464) | `app.web.advanced.json-sequence.enabled=true` | 오래 사는 connection | NDJSON과 같다 | | JSON Merge Patch(RFC 7396) | 라이브러리 — `JsonMergePatchApplier` | 부분 문서 | `JsonMergePatchApplierTest` | diff --git a/docs/web/patch-contract.md b/docs/web/patch-contract.md index 5cb64725..c340fe85 100644 --- a/docs/web/patch-contract.md +++ b/docs/web/patch-contract.md @@ -38,6 +38,10 @@ route는 정확히 하나만 받고, 다른 것을 보내면 최선의 짐작 **한도.** 연산은 최대 100개, pointer 깊이는 최대 16, merge patch 중첩 깊이는 최대 32. 앞의 둘은 곱해진다. 연산마다 서버가 먼저 깊이 복사한 문서 위로 pointer를 따라 걷는다. +**거부 코드.** 형식이 틀린 문서(JSON이 아닌 본문, 빈 문서, 한도 초과, 연산 모양 오류)는 모두 `400 PATCH_REJECTED`다. +허용 목록 밖의 경로만 `403 PATCH_PATH_FORBIDDEN`이고, 실패한 `test`는 `409 PATCH_TEST_FAILED`다. 너무 깊은 pointer는 +권한 문제가 아니라 형식 문제라 400이다. + ## 원자성 JSON Patch 문서는 전부 적용되거나 하나도 적용되지 않는다. 모든 연산은 작업 사본에서 돈다. 모든 연산이 성공하고 @@ -63,6 +67,11 @@ patch를 적용한 결과는 필드 하나씩이 아니라 문서 전체로 검 객체를 만들 수 있다. 서로 맞아야 하는 두 필드, 허락되지 않은 상태 전이 같은 것이다. 바뀐 것만 검증하면 그중 아무것도 보지 못한다. +- 두 applier는 서비스의 Bean Validation `Validator`를 생성자로 받고, 결과 객체 전체를 검증한 뒤에 돌려준다. 위반은 + `@Valid` 본문과 같은 `400 VALIDATION_FAILED`와 필드별 `details`다. +- 결과가 자원 타입으로 읽히지 않으면(숫자 자리에 문자열) `400 PATCH_REJECTED`다. +- 상태 전이처럼 업무 규칙인 검증은 여기서 하지 않는다. 유스케이스가 한다. + ## 선행 조건 patch route는 `If-Match`를 요구한다. 그 사이에 바뀐 자원에 대한 부분 갱신은 본 적 없는 버전에 변경을 적용한다. diff --git a/docs/web/streaming-contract.md b/docs/web/streaming-contract.md index b2ccb6a8..01283585 100644 --- a/docs/web/streaming-contract.md +++ b/docs/web/streaming-contract.md @@ -12,8 +12,9 @@ writer는 `adapter:inbound:web-advanced`(골라 쓰는 leaf, `app.web.advanced.n connection은 결과를 알 수 없다. 끝은 셋이다. 1. **`Complete` envelope.** stream이 끝났다. `lastSequence`가 마지막 위치다. -2. **`Failure` 기록.** commit 뒤에 무언가 실패했다. 오류 code와 client에게 보여도 되는 메시지를 담는다. 상태는 여전히 - 200이다. +2. **`Failure` 기록.** commit 뒤에 무언가 실패했다. 상태는 여전히 200이다. `code`는 실패한 예외의 코드다(예: + `STREAM_ITEM_TOO_LARGE`). 코드가 없는 실패는 등록된 `INTERNAL_ERROR`다. `message`는 그 category의 고정 문구다. commit 전에 + 던져졌다면 받았을 코드·문구와 같다. 3. **둘 다 아님.** stream 중간에 connection이 닫혔다. 서버는 이것을 `ABRUPT_CLOSE`로 기록한다. client 쪽에서는 *끝 envelope를 찾지 않는 한* 끝난 stream과 구분할 수 없다. @@ -23,7 +24,7 @@ connection은 결과를 알 수 없다. 끝은 셋이다. ## 위치 모든 `Item`은 1부터 세는 `sequence`를 가진다. 위치는 엄격히 증가하고, 서버가 그것을 강제한다. 반복이나 후퇴는 client가 -견뎌야 할 것이 아니라 서버 쪽 오류다. +견뎌야 할 것이 아니라 서버 쪽 오류다. writer는 그런 항목을 쓰지 않고 stream을 `INTERNAL_ERROR` `Failure` 기록으로 끝낸다. 0은 절대 유효한 위치가 아니다. 첫 항목이 0을 주장한 stream과 sequence를 아예 정하지 않은 stream이 똑같아 보이기 때문이다. @@ -55,21 +56,25 @@ resnapshot은 자원을 보통 endpoint에서 다시 읽고 새 stream을 시작 ## Heartbeat와 시간 초과 -서버는 `heartbeatInterval`마다 keepalive를 쓴다. 그보다 오래 아무것도 보지 못한 client는 connection이 죽었다고 봐야 -한다. socket에서는 조용한 connection과 끊긴 connection이 같고, heartbeat가 둘을 가른다. +writer(`MvcStreamWriter`)는 요청 thread에서 source를 차례로 쓴다. 그래서 heartbeat를 보내지 않고, `idleTimeout`· +`maxStreamAge`로 stream을 닫지도 않는다. 그 값은 `WebStreamPolicy`에 있고, 자기 stream을 `WebStreamRegistry`에 올려 +돌리는 서비스가 쓴다. -stream은 `idleTimeout`(만든 것이 없음)과 `maxStreamAge`(활동과 상관없음)에 닫힌다. 둘 다 보통의 끝이고, connection이 -허락하면 둘 다 끝 envelope를 보낸다. +- client는 heartbeat를 기대하지 않는다. 자기 읽기 시간 초과를 두고, 그 시간에 아무것도 오지 않으면 끝 envelope 없이 + 닫힌 것으로 보고 이어 받기 cursor로 다시 연결한다. +- socket에서는 조용한 connection과 끊긴 connection이 같다. heartbeat가 필요한 route는 서비스가 그것을 더하고 이 문서의 + route 설명에 적는다. ## 느린 소비자 -서버는 뒤처진 소비자를 위해 최대 `maxBufferedItems`까지만 버퍼링한다. 그것을 넘으면 버퍼를 키우지 않고 connection을 -닫는다. 따라가지 못하는 client는 서버가 밀린 것을 쥐고 있기를 기대하지 말고, 이어 받기 cursor로 다시 연결한다. +writer는 버퍼를 두지 않는다. 느린 소비자는 서버의 쓰기를 막고, 그동안 source도 멈춘다. 서버 heap에 밀린 항목이 쌓이지 +않는다. `maxBufferedItems`는 버퍼를 두는 서비스 구현의 한도다. 따라가지 못하는 client는 이어 받기 cursor로 다시 연결한다. ## 종료 -rolling 배포 중에는 노드가 받기를 멈추기 전에 열린 stream이 다시 연결하라는 요청을 받는다. 바로 다시 연결한다. 노드는 -drain 기한에 아직 열린 것을 강제로 닫고, 그것은 갑작스러운 닫힘으로 도착한다. +drain 순서(받기를 멈추고, 다시 연결을 요청하고, 기한에 강제로 닫기)는 `WebStreamDrainCoordinator`에 있다. 서비스가 +자기 stream을 `WebStreamRegistry`에 등록하고 그 조정기를 종료 순서에 넣었을 때만 돈다. 기본 writer만 쓰는 배포에서는 +종료 때 열린 stream이 갑작스러운 닫힘으로 끝난다. 갑작스러운 닫힘에 backoff와 jitter 없이 바로 다시 연결하지 않는다. 노드의 stream이 한꺼번에 끊겼을 때 모든 client가 한꺼번에 다시 연결하면 그것이 교체 노드를 쓰러뜨린다. diff --git a/docs/web/virtual-thread-profile.md b/docs/web/virtual-thread-profile.md index 599927db..610ea717 100644 --- a/docs/web/virtual-thread-profile.md +++ b/docs/web/virtual-thread-profile.md @@ -36,7 +36,11 @@ app: `VirtualThreadAdmissionGuard`는 pool이 아니라 공정한 semaphore다. 스레드를 제한하면 기다림을 되돌려 놓고 virtual thread로 얻은 것을 버리게 된다. virtual thread 만 개가 있어도 백 개만 허가를 쥐고 나머지는 문 앞에서 거부된다. -거부는 **`Retry-After`가 붙은 503**이고, 상한이 만들려는 결과가 바로 그것이다. 1밀리초 만에 거부된 요청이, 받아들여진 뒤 +상한은 `VirtualThreadAdmissionFilter`가 모든 요청에 건다. request-id filter 바로 뒤, 보안 chain보다 앞이라 거부된 요청은 +아무 일도 하지 않는다. async 요청은 async 일이 끝날 때까지 허가를 쥔다. 넘겨준 순간 돌려주면 넘기는 일만 제한하고 정작 +하류 pool을 쓰는 일은 제한하지 못한다. + +거부는 **`Retry-After`가 붙은 503**(`ADMISSION_REFUSED`)이고, 상한이 만들려는 결과가 바로 그것이다. 1밀리초 만에 거부된 요청이, 받아들여진 뒤 가득 찬 pool 뒤에서 30초 뒤에 시간 초과가 난 같은 요청보다 client에게 확실히 낫다. semaphore는 일부러 공정하다. 불공정한 것이 빠르지만, 새로 온 요청이 기다리던 요청을 앞지르게 두고, 앞지름당한 diff --git a/src/adapter/inbound/web-advanced/README.md b/src/adapter/inbound/web-advanced/README.md index 3b854a88..34f7c59c 100644 --- a/src/adapter/inbound/web-advanced/README.md +++ b/src/adapter/inbound/web-advanced/README.md @@ -58,7 +58,7 @@ virtual thread 실행기는 `TaskDecorator` bean 을 요구한다(요청 상관 | --- | --- | --- | --- | --- | --- | --- | | `AdmissionRefusedException` | `ADMISSION_REFUSED` | 503 | `TRANSIENT_DEPENDENCY` | true | `Retry-After: 1` | 잠시 뒤 같은 요청 | | `JsonPatchTestFailedException` | `PATCH_TEST_FAILED` | 409 | `CONFLICT` | false | `details.pointer`(서버 값은 없음) | 다시 읽고 새 patch | -| `JsonPatchRejectedException` | `PATCH_REJECTED` | 400 | `VALIDATION` | false | — | patch 문서를 고친다 | +| `JsonPatchRejectedException` | `PATCH_REJECTED` | 400 | `VALIDATION` | false | — | patch 문서를 고친다. JSON이 아닌 본문, 빈 문서, 한도·깊이 초과, 연산 모양 오류, 결과가 자원 타입으로 읽히지 않는 patch가 모두 이 코드다 | | `PatchAuthorizationException` | `PATCH_PATH_FORBIDDEN` | 403 | `AUTHZ` | false | `details.refusedPaths` | 해당 경로를 빼거나 권한 확보 | | `UnsupportedApiVersionException` | `API_VERSION_UNSUPPORTED` | 404 | `NOT_FOUND` | false | — | 지원 버전 경로로 | | `SunsetViolationException` | `API_DEPRECATION_INVALID` | 500 | `INTERNAL` | false | — | 서버 설정 결함(등록 시점 오류) | diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java index c836c18f..49092b59 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java @@ -6,6 +6,10 @@ import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamTermination; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.NdjsonRecord; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamFraming; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.ClientErrorMessages; +import dev.caskeleton.shared.error.OperationalError; import java.io.IOException; import java.io.OutputStream; import java.time.Clock; @@ -20,6 +24,16 @@ import java.util.Objects; * terminal record before closing, and classify a write failure rather than letting it become a 500 * on a response that is already 200. * + *

Positions are enforced here: an item whose sequence is not above the previous one is a server + * fault, and the stream ends with a terminal failure record instead of handing the client a repeat + * or a rewind it would apply. + * + *

What this writer does not do: it writes synchronously from an iterator on the request thread, + * so it sends no heartbeat while the source is blocked, enforces no idle timeout or maximum age, and + * keeps no buffer (a slow consumer blocks the source instead). Those bounds are in {@code + * WebStreamPolicy} and the drain in {@code WebStreamDrainCoordinator} for a service that runs its + * streams through {@code WebStreamRegistry}; {@code docs/web/streaming-contract.md} says which. + * *

**Flushing after every record is not optional.** Without it the container buffers, and a * streaming response that arrives in one chunk at the end is a slow non-streaming response — which * passes every test that checks the body and fails the only thing the client wanted. @@ -58,6 +72,14 @@ public final class MvcStreamWriter { try { while (records.hasNext()) { NdjsonRecord record = records.next(); + if (record instanceof NdjsonRecord.Item item && item.sequence() <= lastSequence) { + throw new IllegalStateException( + "stream position " + + item.sequence() + + " does not follow " + + lastSequence + + "; positions strictly increase"); + } writeRecord(record, output); if (record instanceof NdjsonRecord.Item item) { evidence.recordDelivered(new StreamSequence(item.sequence())); @@ -91,13 +113,17 @@ public final class MvcStreamWriter { } // Otherwise the source failed after commit. The status is already 200, so the failure goes // into the stream as a terminal record — and if even that cannot be written, it is an abrupt - // close and is recorded as one rather than counted as a completion. + // close and is recorded as one rather than counted as a completion. The record carries the + // failure's own code when it has one (a carrier anywhere in the cause chain, such as + // STREAM_ITEM_TOO_LARGE), else the registered INTERNAL_ERROR, and the category's fixed message: + // the same code and wording a client would have read before commit. + ApiErrorCode code = + ApiErrorCarrier.firstIn(failure) + .map(carrier -> ((ApiErrorCarrier) carrier).errorCode()) + .orElse(OperationalError.INTERNAL_ERROR); try { writeRecord( - new NdjsonRecord.Failure( - lastSequence, - "DEPENDENCY_FAILURE", - "the stream ended early because a dependency failed"), + new NdjsonRecord.Failure(lastSequence, code.code(), ClientErrorMessages.of(code)), output); evidence.recordTermination(WebStreamTermination.TERMINAL_ERROR_RECORD, clock.instant()); return WebStreamTermination.TERMINAL_ERROR_RECORD; diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java new file mode 100644 index 00000000..ee5c9c17 --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java @@ -0,0 +1,111 @@ +package dev.caskeleton.adapter.inbound.web.advanced.mvc; + +import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.AdmissionRefusedException; +import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadAdmissionGuard; +import dev.caskeleton.adapter.inbound.web.error.EnvelopeResponseWriter; +import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; +import dev.caskeleton.adapter.inbound.web.observability.RetryAfterHint; +import jakarta.servlet.AsyncEvent; +import jakarta.servlet.AsyncListener; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Objects; +import org.springframework.core.Ordered; +import org.springframework.web.filter.OncePerRequestFilter; +import tools.jackson.databind.ObjectMapper; + +/** + * Puts every request under the virtual-thread admission limit. + * + *

The guard alone was a bean nothing called: the profile promised a {@code 503} with {@code + * Retry-After} past the limit, and a deployment that switched it on admitted every arrival (review + * 2026-11-12). A filter, not an interceptor, so the limit covers the whole request including the + * security chain, and refuses before any of it runs. + * + *

A request that goes async keeps its permit until the async work ends: releasing when this + * thread returns would bound only the hand-off, and the work the limit protects the downstream pools + * from happens after it. + */ +public final class VirtualThreadAdmissionFilter extends OncePerRequestFilter implements Ordered { + + /** Right after the request-id filter, so a refusal still carries the request id. */ + public static final int ORDER = Ordered.HIGHEST_PRECEDENCE + 11; + + private final VirtualThreadAdmissionGuard guard; + private final ObjectMapper objectMapper; + + public VirtualThreadAdmissionFilter(VirtualThreadAdmissionGuard guard, ObjectMapper objectMapper) { + this.guard = Objects.requireNonNull(guard, "guard"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); + } + + @Override + public int getOrder() { + return ORDER; + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + VirtualThreadAdmissionGuard.Permit permit; + try { + permit = guard.enter(); + } catch (AdmissionRefusedException refused) { + if (refused.errorCode() instanceof RetryAfterHint hint) { + response.setHeader(ApiHeaders.RETRY_AFTER, Integer.toString(hint.retryAfterSeconds())); + } + EnvelopeResponseWriter.write(response, refused.errorCode(), objectMapper); + return; + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new ServletException("interrupted while waiting for admission", interrupted); + } + boolean handedToAsync = false; + try { + chain.doFilter(request, response); + if (request.isAsyncStarted()) { + request.getAsyncContext().addListener(new ReleaseWhenDone(permit)); + handedToAsync = true; + } + } finally { + if (!handedToAsync) { + permit.close(); + } + } + } + + /** Releases the permit when the async request ends, however it ends. */ + private static final class ReleaseWhenDone implements AsyncListener { + + private final VirtualThreadAdmissionGuard.Permit permit; + + ReleaseWhenDone(VirtualThreadAdmissionGuard.Permit permit) { + this.permit = permit; + } + + @Override + public void onComplete(AsyncEvent event) { + permit.close(); + } + + @Override + public void onTimeout(AsyncEvent event) { + permit.close(); + } + + @Override + public void onError(AsyncEvent event) { + permit.close(); + } + + @Override + public void onStartAsync(AsyncEvent event) { + // A restarted async cycle drops the listeners of the previous one. + event.getAsyncContext().addListener(this); + } + } +} diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java index 2273845c..617513f5 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java @@ -13,6 +13,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.core.task.TaskDecorator; import org.springframework.core.task.support.TaskExecutorAdapter; +import tools.jackson.databind.ObjectMapper; /** * Wires the virtual-thread executor and, in the same configuration, the admission limit. @@ -57,6 +58,17 @@ public class VirtualThreadMvcConfiguration { properties.getAdmissionLimit(), properties.getAdmissionWait()); } + /** + * The request path through the guard: without this the guard is a bean nothing calls, and the + * profile admits every arrival while promising a 503 past the limit. + */ + @Bean + @ConditionalOnMissingBean + public VirtualThreadAdmissionFilter virtualThreadAdmissionFilter( + VirtualThreadAdmissionGuard guard, ObjectMapper objectMapper) { + return new VirtualThreadAdmissionFilter(guard, objectMapper); + } + /** * The executor Spring MVC dispatches async request handling onto. * diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java index ce301568..11ddfe0a 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch; +import jakarta.validation.Validator; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -23,14 +24,19 @@ import tools.jackson.databind.node.ObjectNode; public final class JsonMergePatchApplier { private final ObjectMapper mapper; + private final Validator validator; private final PatchFieldAuthorization authorization; /** * @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean) * @param authorization which fields may be modified + * @param validator the service's Bean Validation validator (Boot's {@code Validator} bean); the + * patched document is validated whole before it is returned */ - public JsonMergePatchApplier(ObjectMapper mapper, PatchFieldAuthorization authorization) { + public JsonMergePatchApplier( + ObjectMapper mapper, PatchFieldAuthorization authorization, Validator validator) { this.mapper = Objects.requireNonNull(mapper, "mapper"); + this.validator = Objects.requireNonNull(validator, "validator"); this.authorization = Objects.requireNonNull(authorization, "authorization"); } @@ -52,7 +58,8 @@ public final class JsonMergePatchApplier { authorization.validate(patch.fieldNames()); JsonNode before = mapper.valueToTree(current); if (!before.isObject()) { - throw new IllegalArgumentException("a merge patch target must serialize to a JSON object"); + // The target type is the server's choice, so this is a server fault, not a bad request. + throw new IllegalStateException("a merge patch target must serialize to a JSON object"); } ObjectNode after = merge((ObjectNode) before.deepCopy(), patch.root()); List modified = new ArrayList<>(); @@ -63,7 +70,7 @@ public final class JsonMergePatchApplier { modified.add(field); } } - return new PatchResult<>(mapper.treeToValue(after, type), modified); + return new PatchResult<>(PatchBodies.toTarget(mapper, validator, after, type), modified); } private static ObjectNode merge(ObjectNode target, ObjectNode patch) { diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java index 4aad82e0..87ffb87d 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java @@ -25,7 +25,7 @@ public record JsonMergePatchDocument(ObjectNode root) { Objects.requireNonNull(root, "root"); int depth = depthOf(root, 1); if (depth > MAX_DEPTH) { - throw new IllegalArgumentException( + throw new JsonPatchRejectedException( "a merge patch nested " + depth + " deep exceeds the " @@ -56,17 +56,17 @@ public record JsonMergePatchDocument(ObjectNode root) { * * @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean) * @param body the request body - * @throws IllegalArgumentException if the body is not a JSON object + * @throws JsonPatchRejectedException if the body is not JSON or not a JSON object */ public static JsonMergePatchDocument parse(ObjectMapper mapper, byte[] body) { Objects.requireNonNull(mapper, "mapper"); Objects.requireNonNull(body, "body"); - JsonNode parsed = mapper.readTree(body); + JsonNode parsed = PatchBodies.readTree(mapper, body); if (!parsed.isObject()) { // RFC 7396 permits a scalar or an array as a whole-document replacement. Refused here: a // merge patch that replaces the entire resource is a PUT, and routing it through the patch // path skips the full-document validation a PUT gets. - throw new IllegalArgumentException( + throw new JsonPatchRejectedException( "a merge patch must be a JSON object; a scalar or array patch replaces the whole " + "resource, which is a PUT and belongs on the PUT route with its validation"); } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java index 04a2e8ba..5803aac4 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch; +import jakarta.validation.Validator; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -27,14 +28,19 @@ import tools.jackson.databind.node.ObjectNode; public final class JsonPatchApplier { private final ObjectMapper mapper; + private final Validator validator; private final JsonPointerAuthorization authorization; /** * @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean) * @param authorization which pointers may be modified + * @param validator the service's Bean Validation validator (Boot's {@code Validator} bean); the + * patched document is validated whole before it is returned */ - public JsonPatchApplier(ObjectMapper mapper, JsonPointerAuthorization authorization) { + public JsonPatchApplier( + ObjectMapper mapper, JsonPointerAuthorization authorization, Validator validator) { this.mapper = Objects.requireNonNull(mapper, "mapper"); + this.validator = Objects.requireNonNull(validator, "validator"); this.authorization = Objects.requireNonNull(authorization, "authorization"); } @@ -61,9 +67,9 @@ public final class JsonPatchApplier { } } if (working.equals(before)) { - return new PatchResult<>(mapper.treeToValue(working, type), List.of()); + return new PatchResult<>(PatchBodies.toTarget(mapper, validator, working, type), List.of()); } - return new PatchResult<>(mapper.treeToValue(working, type), touched); + return new PatchResult<>(PatchBodies.toTarget(mapper, validator, working, type), touched); } private JsonNode applyOne(JsonNode root, JsonPatchOperation operation) { diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java index b461b6c0..d560b4fd 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java @@ -24,7 +24,7 @@ public record JsonPatchDocument(List operations) { public JsonPatchDocument { operations = List.copyOf(Objects.requireNonNull(operations, "operations")); if (operations.isEmpty()) { - throw new IllegalArgumentException( + throw new JsonPatchRejectedException( "an empty patch document changes nothing; sending one is a client bug and answering 200 " + "hides it"); } @@ -43,11 +43,12 @@ public record JsonPatchDocument(List operations) { * * @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean) * @param body the request body + * @throws JsonPatchRejectedException if the body is not JSON or not a valid patch document */ public static JsonPatchDocument parse(ObjectMapper mapper, byte[] body) { Objects.requireNonNull(mapper, "mapper"); Objects.requireNonNull(body, "body"); - JsonNode root = mapper.readTree(body); + JsonNode root = PatchBodies.readTree(mapper, body); if (!root.isArray()) { throw new JsonPatchRejectedException( "an RFC 6902 patch is an array of operations; an object here is a merge patch sent to " diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperation.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperation.java index 79d2c290..65c7ab4e 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperation.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperation.java @@ -26,22 +26,22 @@ public record JsonPatchOperation( Objects.requireNonNull(value, "value"); Objects.requireNonNull(from, "from"); if (!path.isEmpty() && !path.startsWith("/")) { - throw new IllegalArgumentException("a JSON Pointer is empty or starts with '/': " + path); + throw new JsonPatchRejectedException("a JSON Pointer is empty or starts with '/': " + path); } if (kind.requiresValue() != value.isPresent()) { - throw new IllegalArgumentException( + throw new JsonPatchRejectedException( kind.wireName() + (kind.requiresValue() ? " requires a value member" : " carries no value member, and one here means the client meant a different op")); } if (kind.requiresFrom() != from.isPresent()) { - throw new IllegalArgumentException( + throw new JsonPatchRejectedException( kind.wireName() + (kind.requiresFrom() ? " requires a from member" : " carries no from member")); } if (from.isPresent() && !from.get().isEmpty() && !from.get().startsWith("/")) { - throw new IllegalArgumentException("a JSON Pointer is empty or starts with '/'"); + throw new JsonPatchRejectedException("a JSON Pointer is empty or starts with '/'"); } if (kind == JsonPatchOperationKind.MOVE && from.isPresent() @@ -49,7 +49,7 @@ public record JsonPatchOperation( // RFC 6902 section 4.4: the target cannot be inside the source. Moving a subtree into itself // is not a thing that has a result, and an implementation that tries produces either an // infinite structure or a silently truncated one. - throw new IllegalArgumentException("a move cannot target a location inside its own source"); + throw new JsonPatchRejectedException("a move cannot target a location inside its own source"); } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPointerAuthorization.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPointerAuthorization.java index bf47c21b..3e6b2273 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPointerAuthorization.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPointerAuthorization.java @@ -66,10 +66,21 @@ public final class JsonPointerAuthorization { /** * Check every pointer a document names, including {@code from} pointers. * - * @throws PatchAuthorizationException naming all of them + * @throws JsonPatchRejectedException if a pointer is deeper than {@link #MAX_POINTER_DEPTH}: a + * malformed document, not a permission question + * @throws PatchAuthorizationException naming every pointer the caller may not modify */ public void validate(List operations) { Objects.requireNonNull(operations, "operations"); + for (JsonPatchOperation operation : operations) { + boolean tooDeep = + depthOf(operation.path()) > MAX_POINTER_DEPTH + || operation.from().filter(from -> depthOf(from) > MAX_POINTER_DEPTH).isPresent(); + if (tooDeep) { + throw new JsonPatchRejectedException( + "a JSON Pointer deeper than " + MAX_POINTER_DEPTH + " segments is over the limit"); + } + } List refused = new ArrayList<>(); for (JsonPatchOperation operation : operations) { if (operation.kind().mutating() && !writable(operation.path())) { diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java new file mode 100644 index 00000000..cca6b7af --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java @@ -0,0 +1,53 @@ +package dev.caskeleton.adapter.inbound.web.advanced.patch; + +import jakarta.validation.ConstraintViolation; +import jakarta.validation.ConstraintViolationException; +import jakarta.validation.Validator; +import java.util.Set; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * The two places a patch meets Jackson, answered as the patch's fault rather than the server's. + * + *

A body that is not JSON, and a patched tree that no longer reads as the target type (a string + * where a number was), are both the client's document. Left to Jackson they reached the web + * adapter's catch-all as {@code 500 INTERNAL_ERROR}; here they are {@code 400 PATCH_REJECTED} like + * every other patch the server will not apply (review 2026-11-12). + */ +final class PatchBodies { + + private PatchBodies() {} + + static JsonNode readTree(ObjectMapper mapper, byte[] body) { + try { + return mapper.readTree(body); + } catch (JacksonException notJson) { + throw new JsonPatchRejectedException("the patch body is not a JSON document"); + } + } + + /** + * The patched tree as the target type, validated as a whole document. + * + *

Whole, not field by field: two fields that must agree, or a state only some transitions + * allow, are invisible to a check of the changed fields alone. A violation is the same {@link + * ConstraintViolationException} a {@code @Valid} body raises, so the client gets {@code 400 + * VALIDATION_FAILED} with the per-field details it already knows. + */ + static T toTarget(ObjectMapper mapper, Validator validator, JsonNode patched, Class type) { + T result; + try { + result = mapper.treeToValue(patched, type); + } catch (JacksonException wrongShape) { + throw new JsonPatchRejectedException( + "the patched document no longer reads as the resource: a value has the wrong type"); + } + Set> violations = validator.validate(result); + if (!violations.isEmpty()) { + throw new ConstraintViolationException(violations); + } + return result; + } +} diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionGuard.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionGuard.java index b66aed53..707391a5 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionGuard.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionGuard.java @@ -4,6 +4,7 @@ import java.time.Duration; import java.util.Objects; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; @@ -57,17 +58,42 @@ public final class VirtualThreadAdmissionGuard { */ public T run(java.util.concurrent.Callable work) throws Exception { Objects.requireNonNull(work, "work"); + try (Permit permit = enter()) { + return work.call(); + } + } + + /** + * Take a permit for work that does not end on this thread, such as an async request. + * + * @return the permit; closing it releases, and closing it twice releases once + * @throws AdmissionRefusedException if no permit became available in time + * @throws InterruptedException if interrupted while waiting + */ + public Permit enter() throws InterruptedException { if (!permits.tryAcquire(acquireTimeout.toMillis(), TimeUnit.MILLISECONDS)) { rejected.incrementAndGet(); throw new AdmissionRefusedException(limit); } int current = active.incrementAndGet(); peakActive.accumulateAndGet(current, Math::max); - try { - return work.call(); - } finally { - active.decrementAndGet(); - permits.release(); + return new Permit(); + } + + /** One admitted unit of work. */ + public final class Permit implements AutoCloseable { + + private final AtomicBoolean released = new AtomicBoolean(); + + private Permit() {} + + /** Release, once. An async request ends through more than one listener callback. */ + @Override + public void close() { + if (released.compareAndSet(false, true)) { + active.decrementAndGet(); + permits.release(); + } } } diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java index ee30ac31..20c76e91 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java @@ -68,6 +68,7 @@ class MvcAdvancedConfigurationTest { .hasNotFailed() .doesNotHaveBean(StreamRecordEncoder.class) .doesNotHaveBean(VirtualThreadAdmissionGuard.class) + .doesNotHaveBean(VirtualThreadAdmissionFilter.class) .doesNotHaveBean(AsyncTaskExecutor.class)); } @@ -125,6 +126,7 @@ class MvcAdvancedConfigurationTest { .hasNotFailed() .hasSingleBean(VirtualThreadProfile.class) .hasSingleBean(VirtualThreadAdmissionGuard.class) + .hasSingleBean(VirtualThreadAdmissionFilter.class) .hasBean("applicationTaskExecutor"); assertThat(context.getBean(VirtualThreadAdmissionGuard.class).limit()).isEqualTo(100); assertThat(context.getBean(VirtualThreadProfile.class).databasePoolSize()) diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java index c738bbbe..f9e25a24 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java @@ -92,7 +92,10 @@ class MvcStreamingWiringTest { writer.write(failingAfter(NdjsonRecord.item(1, "a")), output, evidence); assertThat(how).isEqualTo(WebStreamTermination.TERMINAL_ERROR_RECORD); - assertThat(output.text()).contains("DEPENDENCY_FAILURE"); + assertThat(output.text()) + .as("a failure without a code of its own is the registered INTERNAL_ERROR") + .contains("\"code\":\"INTERNAL_ERROR\"") + .doesNotContain("DEPENDENCY_FAILURE"); assertThat(evidence.termination()).contains(WebStreamTermination.TERMINAL_ERROR_RECORD); } @@ -129,6 +132,58 @@ class MvcStreamingWiringTest { .hasMessageContaining("exceeds the 16 byte ceiling"); } + @Test + @DisplayName("commit 뒤 실패 기록은 실패한 예외의 코드와 고정 문구를 싣는다") + void aTerminalRecordCarriesTheFailuresOwnCode() { + // given + CountingStream output = new CountingStream(); + WebStreamPolicy small = + new WebStreamPolicy( + Duration.ofSeconds(15), Duration.ofSeconds(60), Duration.ofMinutes(30), 8, 200); + MvcStreamWriter writer = + new MvcStreamWriter(encoder(small), StreamFraming.NDJSON, Clock.systemUTC()); + WebStreamEvidence evidence = new WebStreamEvidence(new StreamId("feed"), NOW); + + // when + WebStreamTermination how = + writer.write( + List.>of( + NdjsonRecord.item(1, "a"), NdjsonRecord.item(2, "x".repeat(1_000))) + .iterator(), + output, + evidence); + + // then + assertThat(how).isEqualTo(WebStreamTermination.TERMINAL_ERROR_RECORD); + assertThat(output.text()) + .contains("\"code\":\"STREAM_ITEM_TOO_LARGE\"") + .contains(dev.caskeleton.shared.error.ClientErrorMessages.OPAQUE); + } + + @Test + @DisplayName("위치가 앞 항목보다 크지 않으면 서버 오류로 끝내고 그 항목은 쓰지 않는다") + void aRepeatedPositionEndsTheStreamInsteadOfReachingTheClient() { + // given + CountingStream output = new CountingStream(); + MvcStreamWriter writer = + new MvcStreamWriter( + encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON, Clock.systemUTC()); + WebStreamEvidence evidence = new WebStreamEvidence(new StreamId("feed"), NOW); + + // when + WebStreamTermination how = + writer.write( + List.>of( + NdjsonRecord.item(1, "a"), NdjsonRecord.item(2, "b"), NdjsonRecord.item(2, "c")) + .iterator(), + output, + evidence); + + // then + assertThat(how).isEqualTo(WebStreamTermination.TERMINAL_ERROR_RECORD); + assertThat(output.text()).doesNotContain("\"c\"").contains("\"code\":\"INTERNAL_ERROR\""); + } + /** A stream that counts flushes and can fail on a chosen write. */ private static final class CountingStream extends OutputStream { diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java new file mode 100644 index 00000000..47b1434a --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java @@ -0,0 +1,87 @@ +package dev.caskeleton.adapter.inbound.web.advanced.mvc; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadAdmissionGuard; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import tools.jackson.databind.json.JsonMapper; + +/** The request path through the admission guard. */ +@Tag("web-advanced") +class VirtualThreadAdmissionFilterTest { + + @Test + @DisplayName("한도가 차면 요청은 controller에 닿지 않고 503 ADMISSION_REFUSED와 Retry-After를 받는다") + void aFullLimitRefusesWith503AndRetryAfter() throws Exception { + // given + VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO); + VirtualThreadAdmissionFilter filter = + new VirtualThreadAdmissionFilter(guard, JsonMapper.shared()); + AtomicInteger reached = new AtomicInteger(); + MockHttpServletResponse response = new MockHttpServletResponse(); + + // when + try (VirtualThreadAdmissionGuard.Permit held = guard.enter()) { + filter.doFilter( + new MockHttpServletRequest("GET", "/orders"), + response, + (request, servletResponse) -> reached.incrementAndGet()); + } + + // then + assertThat(reached).as("the guard was a bean nothing called").hasValue(0); + assertThat(response.getStatus()).isEqualTo(503); + assertThat(response.getHeader("Retry-After")).isEqualTo("1"); + assertThat(response.getContentAsString()).contains("ADMISSION_REFUSED"); + assertThat(guard.rejectedCount()).isEqualTo(1); + } + + @Test + @DisplayName("동기 요청은 끝나면 permit을 돌려준다") + void aSynchronousRequestReleasesItsPermit() throws Exception { + // given + VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO); + VirtualThreadAdmissionFilter filter = + new VirtualThreadAdmissionFilter(guard, JsonMapper.shared()); + AtomicInteger activeInside = new AtomicInteger(-1); + + // when + filter.doFilter( + new MockHttpServletRequest("GET", "/orders"), + new MockHttpServletResponse(), + (request, response) -> activeInside.set(guard.active())); + + // then + assertThat(activeInside).hasValue(1); + assertThat(guard.active()).isZero(); + } + + @Test + @DisplayName("async 요청은 async 일이 끝날 때까지 permit을 쥔다") + void anAsyncRequestHoldsItsPermitUntilTheAsyncWorkEnds() throws Exception { + // given + VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO); + VirtualThreadAdmissionFilter filter = + new VirtualThreadAdmissionFilter(guard, JsonMapper.shared()); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/orders"); + request.setAsyncSupported(true); + MockHttpServletResponse response = new MockHttpServletResponse(); + + // when + filter.doFilter(request, response, (req, res) -> request.startAsync(req, res)); + int activeAfterHandOff = guard.active(); + request.getAsyncContext().complete(); + + // then + assertThat(activeAfterHandOff) + .as("releasing on hand-off would bound only the hand-off, not the work") + .isEqualTo(1); + assertThat(guard.active()).isZero(); + } +} diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java index 2795f20c..4e829b76 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java @@ -2,7 +2,12 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch; 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 jakarta.validation.ConstraintViolationException; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.constraints.NotNull; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; @@ -20,12 +25,15 @@ import tools.jackson.databind.json.JsonMapper; class JsonMergePatchApplierTest { private static final ObjectMapper MAPPER = JsonMapper.shared(); + private static final Validator VALIDATOR = + Validation.buildDefaultValidatorFactory().getValidator(); /** A target with a mandatory field and two optional ones. */ record Profile(String displayName, String description, String nickname) {} private static JsonMergePatchApplier applier(String... writableFields) { - return new JsonMergePatchApplier(MAPPER, PatchFieldAuthorization.allow(writableFields)); + return new JsonMergePatchApplier( + MAPPER, PatchFieldAuthorization.allow(writableFields), VALIDATOR); } private static JsonMergePatchDocument patch(String json) { @@ -118,7 +126,7 @@ class JsonMergePatchApplierTest { // A whole-document replacement is a PUT, and routing it through the patch path skips the // full-document validation a PUT gets. assertThatThrownBy(() -> patch("[1,2,3]")) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(JsonPatchRejectedException.class) .hasMessageContaining("belongs on the PUT route"); } @@ -135,7 +143,7 @@ class JsonMergePatchApplierTest { deep.append("}".repeat(40)); assertThatThrownBy(() -> patch(deep.toString())) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(JsonPatchRejectedException.class) .hasMessageContaining("can turn into a 400"); } @@ -153,4 +161,38 @@ class JsonMergePatchApplierTest { assertThat(PatchMediaType.MERGE_PATCH).isEqualTo("application/merge-patch+json"); assertThat(PatchMediaType.JSON_PATCH).isEqualTo("application/json-patch+json"); } + + @Test + @DisplayName("JSON이 아닌 merge patch 본문은 400 PATCH_REJECTED로 거절된다") + void aMergePatchBodyThatIsNotJsonIsRejected() { + // given + String notJson = "displayName=new"; + + // when + Throwable thrown = catchThrowable(() -> patch(notJson)); + + // then + assertThat(thrown).isInstanceOf(JsonPatchRejectedException.class); + } + + /** A target whose field may be patched but not deleted. */ + record Required(@NotNull String displayName, String nickname) {} + + @Test + @DisplayName("merge patch 결과는 문서 전체로 검증되고 위반은 VALIDATION_FAILED가 받는 예외로 나간다") + void theMergedDocumentIsValidatedWhole() { + // given + JsonMergePatchApplier applier = + new JsonMergePatchApplier(MAPPER, PatchFieldAuthorization.allow("displayName"), VALIDATOR); + JsonMergePatchDocument deleting = patch("{\"displayName\":null}"); + + // when + Throwable thrown = + catchThrowable(() -> applier.apply(new Required("old", "n"), deleting, Required.class)); + + // then + assertThat(thrown) + .as("the patch is allowed field by field; only the whole document breaks the constraint") + .isInstanceOf(ConstraintViolationException.class); + } } diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java index 1b1c538f..c50838c0 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java @@ -2,7 +2,12 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch; 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 jakarta.validation.ConstraintViolationException; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.constraints.NotBlank; import java.nio.charset.StandardCharsets; import java.util.List; import org.junit.jupiter.api.DisplayName; @@ -21,6 +26,8 @@ import tools.jackson.databind.json.JsonMapper; class JsonPatchApplierTest { private static final ObjectMapper MAPPER = JsonMapper.shared(); + private static final Validator VALIDATOR = + Validation.buildDefaultValidatorFactory().getValidator(); /** A target with a scalar, a nested object and a list. */ record Profile(String displayName, int version, Address address, List tags) {} @@ -33,7 +40,8 @@ class JsonPatchApplierTest { } private static JsonPatchApplier applier(String... writablePrefixes) { - return new JsonPatchApplier(MAPPER, JsonPointerAuthorization.allow(writablePrefixes)); + return new JsonPatchApplier( + MAPPER, JsonPointerAuthorization.allow(writablePrefixes), VALIDATOR); } private static JsonPatchDocument patch(String json) { @@ -212,10 +220,10 @@ class JsonPatchApplierTest { // Discovered halfway through, it would be a document that has already modified the working // copy. assertThatThrownBy(() -> patch("[{\"op\":\"replace\",\"path\":\"/displayName\"}]")) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(JsonPatchRejectedException.class) .hasMessageContaining("requires a value member"); assertThatThrownBy(() -> patch("[{\"op\":\"move\",\"path\":\"/displayName\"}]")) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(JsonPatchRejectedException.class) .hasMessageContaining("requires a from member"); } @@ -224,7 +232,7 @@ class JsonPatchApplierTest { void moveIntoOwnSourceIsRefused() { assertThatThrownBy( () -> patch("[{\"op\":\"move\",\"from\":\"/address\",\"path\":\"/address/self\"}]")) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(JsonPatchRejectedException.class) .hasMessageContaining("inside its own source"); } @@ -232,7 +240,77 @@ class JsonPatchApplierTest { @DisplayName("an empty patch document is refused") void emptyDocumentIsRefused() { assertThatThrownBy(() -> patch("[]")) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(JsonPatchRejectedException.class) .hasMessageContaining("client bug"); } + + @Test + @DisplayName("JSON이 아닌 본문은 400 PATCH_REJECTED로 거절된다") + void aBodyThatIsNotJsonIsRejectedAsAPatch() { + // given + String notJson = "op=replace&path=/displayName"; + + // when + Throwable thrown = catchThrowable(() -> patch(notJson)); + + // then + assertThat(thrown) + .as("left to Jackson the parse error reached the catch-all as 500 INTERNAL_ERROR") + .isInstanceOf(JsonPatchRejectedException.class); + } + + @Test + @DisplayName("너무 깊은 pointer는 권한 거절(403)이 아니라 문서 거절(400)이다") + void aTooDeepPointerIsAMalformedDocumentNotAPermissionRefusal() { + // given + String deep = "/displayName" + "/x".repeat(JsonPointerAuthorization.MAX_POINTER_DEPTH); + JsonPatchDocument document = + patch("[{\"op\":\"replace\",\"path\":\"" + deep + "\",\"value\":\"v\"}]"); + + // when + Throwable thrown = + catchThrowable( + () -> applier("/displayName").apply(profile(), document, Profile.class)); + + // then + assertThat(thrown).isInstanceOf(JsonPatchRejectedException.class); + } + + @Test + @DisplayName("patch 결과가 대상 타입으로 읽히지 않으면 400 PATCH_REJECTED다") + void aPatchThatBreaksTheTargetTypeIsRejected() { + // given + JsonPatchDocument document = + patch("[{\"op\":\"replace\",\"path\":\"/version\",\"value\":\"not-a-number\"}]"); + + // when + Throwable thrown = + catchThrowable( + () -> applier("/version").apply(profile(), document, Profile.class)); + + // then + assertThat(thrown).isInstanceOf(JsonPatchRejectedException.class); + } + + /** A target with a constraint across the whole document. */ + record Named(@NotBlank String displayName, String nickname) {} + + @Test + @DisplayName("patch 결과는 문서 전체로 검증되고 위반은 VALIDATION_FAILED가 받는 예외로 나간다") + void thePatchedDocumentIsValidatedWhole() { + // given + JsonPatchApplier applier = + new JsonPatchApplier(MAPPER, JsonPointerAuthorization.allow("/displayName"), VALIDATOR); + JsonPatchDocument blanking = + patch("[{\"op\":\"replace\",\"path\":\"/displayName\",\"value\":\" \"}]"); + + // when + Throwable thrown = + catchThrowable(() -> applier.apply(new Named("old", "n"), blanking, Named.class)); + + // then + assertThat(thrown) + .as("each operation is well formed, and only the whole document breaks the constraint") + .isInstanceOf(ConstraintViolationException.class); + } } diff --git a/src/adapter/inbound/web/AGENTS.md b/src/adapter/inbound/web/AGENTS.md index fbc2fd8a..7922037f 100644 --- a/src/adapter/inbound/web/AGENTS.md +++ b/src/adapter/inbound/web/AGENTS.md @@ -62,9 +62,11 @@ bridge, `JsonIdempotentResponseCodec`, route 목록)는 골라 쓰는 leaf `adap **않는다** — ArchUnit 규칙 `REQUEST_DTOS_DO_NOT_SILENCE_UNKNOWN_FIELDS`가 막는다. 요청 record에는 wrapper 타입(`Integer`, `Long`, `Boolean`, `Optional`)을 써서 JSON `null`이 primitive `0`이 되지 못하게 한다. -- **B2 — PATCH 뜻.** RFC 7396 `application/merge-patch+json`(`null = 삭제`)을 쓰지 않는다. PATCH endpoint는 - *없음*(바꾸지 않음), *명시한 null*(필드 비움), *값*(바꿈)을 구별해야 한다. 요청 record에 - `org.openapitools:jackson-databind-nullable`(`JsonNullable`)이나 `Optional` wrapper를 쓴다. +- **B2 — PATCH 뜻.** 이 leaf의 `application/json` PATCH DTO는 *없음*(바꾸지 않음), *명시한 null*(필드 비움), + *값*(바꿈)을 구별해야 한다. 요청 record에 `org.openapitools:jackson-databind-nullable`(`JsonNullable`)이나 + `Optional` wrapper를 쓴다. RFC 7396 merge patch(`application/merge-patch+json`, `null = 삭제`)와 RFC 6902 JSON + Patch는 `adapter:inbound:web-advanced`의 applier로 받는다. 어느 것을 언제 쓰는지와 거부 규칙의 정본은 + `docs/web/patch-contract.md`다. - **B3 — mapper 안의 실패.** record 정규 생성자의 `IllegalArgumentException`, MapStruct가 생성한 NPE, ACL 정규화 실패 등은 `MappingException`을 던져 대응시킨다. 전역 handler가 그것을 `MAPPING_FAILED`(HTTP 400)로 보내고, `BAD_PARAMETER`나 `INTERNAL_ERROR`로 보내지 않는다. mapper가 아닌 호출자의 평범한 -- 2.54.0 From 7b5b4c69837cfb1203172c8c61e03b76afb9cc82 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 04:46:39 +0900 Subject: [PATCH 11/23] =?UTF-8?q?fix(http)!:=20fileserver=C2=B7notificatio?= =?UTF-8?q?n=20HTTP=EC=99=80=20bulk=20envelope=EB=A5=BC=20=EA=B3=B5?= =?UTF-8?q?=EC=9A=A9=20=EA=B3=84=EC=95=BD=EB=8C=80=EB=A1=9C=20=EB=8B=B5?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: fileserver·notification의 HTTP 표면이 공용 계약(web AGENTS B8, http-contract §1, manual 11)과 달랐다. - fileserver batch는 part가 실패해도 success:true였고 결과를 data.results에 넣었다. fullySucceeded()를 아무도 부르지 않았다. 계약끼리도 달랐다(web B8의 BATCH_PARTIAL_FAILURE vs fileserver 계약의 200 + results[].error). - BulkEnvelope.partial의 error.message가 영어 고정 문구였고, BulkItemResult는 호출자 문구를 그대로 실었으며 null 키를 남겼다(mix-in 없음). - Content-Range가 CORS 노출 목록에 없어 브라우저가 다운로드를 이어 받지 못했다. - 알림 제출·template 게시의 모르는 channel·slot·locale이 details 없는 BAD_PARAMETER였고(주석은 validation error), template 경로가 lowerCamel이 아닌 /notification-templates였다. - 전송 넷(raw·multipart·draft-12·tus)이 이름 없는 업로드에 "upload.bin"을 지어 넣었다. 앱 정책 OriginalFilenamePolicy의 기본값은 "file"이라 업무 규칙이 두 곳에 있었다(HARD-STOP 4). - EnvelopeWireShapeTest는 http-contract §1의 증거로 쓰이는데 data null 키 생략, String → Envelope, unsorted page의 sort:null, 부분 실패 문구를 보지 않았다. 고른 방법: - 리뷰 README 6절 ①대로 fileserver batch도 공용 bulk envelope다. 모두 성공 → success:true + results, 하나라도 실패 → success:false + BATCH_PARTIAL_FAILURE + part별 details(index, status, id, code, message). 성공한 part는 되돌리지 않는다. BatchUploadResponse는 쓰는 곳이 없어져 지웠다. - BulkEnvelope.partial과 BulkItemResult.error(index, ApiErrorCode)는 category 고정 문구를 쓴다. BulkItemResult에 null 생략 mix-in을 더했다. - 알림 controller는 NotificationFieldRejection(VALIDATION_FAILED carrier, 필드를 짚는 details 하나, 거절한 값은 싣지 않음)을 던진다. template 경로는 /notificationTemplates다. 읽는 endpoint가 없어 201에 Location을 싣지 않고, manual 11 규칙에 그 경우를 적었다. - 전송은 이름이 없으면 빈 이름을 넘기고 OriginalFilenamePolicy가 정한다. - EnvelopeWireShapeTest에 빠진 넷을 더했다. EnvelopeTest의 when 둘인 시험을 둘로 나눴다. 버린 대안: /notification-templates를 별칭으로 남기기 — 같은 자원의 경로가 둘이 되고 인가·공개 경로 스냅숏이 둘을 따로 봐야 한다. 위험·한계: batch를 읽는 client, 알림 template 경로를 쓰는 client와 배포 스크립트, BulkItemResult.error(index, code, message)를 부르던 코드가 바뀐다 (upgrade 안내 6·7·10·11·12, 14). BREAKING CHANGE: fileserver batch 응답이 공용 bulk envelope가 됐다. 알림 template 경로가 /notificationTemplates다. 알림의 모르는 vocabulary 값은 VALIDATION_FAILED다. BulkItemResult.error는 ApiErrorCode를 받는다. 이름 없는 업로드의 표시 이름이 "file"이다. 할 일은 docs/upgrade/2026-11-round9-contracts.md. Refs: RR9-03-01, RR9-03-02, RR9-03-09, RR9-03-13, RR9-03-21, RR9-05-09 --- docs/fileserver/upgrade-guide.md | 5 +- docs/manual/11-checklist.md | 2 +- .../FileserverHttpSurfaceConfiguration.java | 7 +- .../controller/FileUploadController.java | 52 +++++++++--- .../draft12/Draft12UploadController.java | 3 +- .../fileserver/dto/BatchUploadResponse.java | 21 ----- .../mapper/MultipartUploadRequestMapper.java | 8 +- .../mapper/RawUploadRequestMapper.java | 5 +- .../web/fileserver/tus/TusController.java | 3 +- .../FileserverCorsExposedHeadersTest.java | 5 +- .../controller/FileUploadControllerTest.java | 28 +++++-- .../FileserverProblemHeaderParityTest.java | 19 +++++ .../NotificationFieldRejection.java | 41 +++++++++ .../NotificationSubmissionController.java | 13 +-- .../NotificationTemplateController.java | 29 +++++-- .../NotificationRoutePrefixTest.java | 13 +++ .../NotificationSubmissionControllerTest.java | 35 ++++++++ .../envelope/EnvelopeWireFormatConfig.java | 2 + .../web/envelope/EnvelopeWireShapeTest.java | 84 +++++++++++++++++++ .../upload/CreateUploadRequest.java | 4 +- .../compose-lanes/smoke/notification-smoke.sh | 2 +- src/bootstrap/notification-platform/README.md | 2 +- .../shared/response/BulkEnvelope.java | 3 +- .../shared/response/BulkItemResult.java | 14 +++- .../shared/response/EnvelopeTest.java | 34 +++++++- 25 files changed, 356 insertions(+), 78 deletions(-) delete mode 100644 src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadResponse.java create mode 100644 src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejection.java diff --git a/docs/fileserver/upgrade-guide.md b/docs/fileserver/upgrade-guide.md index af27de87..a8f12e31 100644 --- a/docs/fileserver/upgrade-guide.md +++ b/docs/fileserver/upgrade-guide.md @@ -63,7 +63,10 @@ V1__create_fileserver_metadata.sql → capability_schema_registry: jpa-fileser - **content가 아직 있으면 삭제는 `204`가 아니라 `202`로 답한다.** 파일은 이미 읽을 수 없고, 물리 회수는 미뤘다. `202`를 실패로 다루면 쓸데없이 재시도한다. - **batch 업로드는 part가 실패해도 `200`으로 답한다.** batch는 명시적으로 원자적이지 않고, 상태 코드 하나로는 - 부분 결과를 정직하게 알릴 수 없다. `results[].error`를 읽는다. + 부분 결과를 정직하게 알릴 수 없다. 판별은 `success`다. 모두 성공하면 `success: true`와 `results[]`, 하나라도 + 실패하면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`와 part별 `error.details[]`(`index`, `status`, + 성공한 part의 `id`, 실패한 part의 `code`·`message`)다. 2026-11-12 전에는 실패가 있어도 `success: true`였다 + (`docs/upgrade/2026-11-round9-contracts.md`). - **결과를 모르는 실패는 재시도하면 안 된다.** 실패 Envelope의 `error.details`에서 `"ambiguous": true`를 본다. - **`If-Match`는 version 숫자가 아니라 strong ETag를 받는다.** client는 실제로 받은 표현에 대해서만 주장할 수 있다. diff --git a/docs/manual/11-checklist.md b/docs/manual/11-checklist.md index fff17a68..128f1ccc 100644 --- a/docs/manual/11-checklist.md +++ b/docs/manual/11-checklist.md @@ -34,7 +34,7 @@ ## inbound - [ ] 컨트롤러는 변환만 한다. repository·엔티티를 모른다. -- [ ] 경로는 lowerCamel 복수형(AIP-122). 생성은 201 + `Location`. +- [ ] 경로는 lowerCamel 복수형(AIP-122). 생성은 201 + `Location`. 만든 것을 읽는 endpoint가 없으면 `Location`을 싣지 않고 controller 주석에 그 이유를 적는다. - [ ] 도메인 규칙을 DTO bean validation에 다시 쓰지 않았다. - [ ] 엔드포인트를 더했으면 **요청률 제한**을 어디서 거는지(ingress/app) 배포 설계에 있다. 앱 기본 off·켜는 법은 [docs/security/rate-limiting.md](../security/rate-limiting.md). diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java index 569f66c5..5ba1126c 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java @@ -36,7 +36,9 @@ public class FileserverHttpSurfaceConfiguration { /** * The response headers the upload and download routes write that a cross-origin browser must be - * allowed to read: without {@code Upload-Offset} a tus or draft-12 client cannot resume. + * allowed to read: without {@code Upload-Offset} a tus or draft-12 client cannot resume, and + * without {@code Content-Range} a browser that resumes a download with {@code Range} cannot tell + * which bytes a {@code 206} carries or how long the representation is from a {@code 416}. */ @Bean CorsExposedHeaders fileserverCorsExposedHeaders() { @@ -53,6 +55,7 @@ public class FileserverHttpSurfaceConfiguration { Draft12Headers.UPLOAD_COMPLETE, Draft12Headers.UPLOAD_LIMIT, HttpHeaders.CONTENT_DISPOSITION, - HttpHeaders.ACCEPT_RANGES)); + HttpHeaders.ACCEPT_RANGES, + HttpHeaders.CONTENT_RANGE)); } } diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java index d7ee6fad..9ae7d824 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java @@ -4,12 +4,12 @@ import dev.caskeleton.adapter.inbound.web.core.OwnsAbsoluteWebRoute; import dev.caskeleton.adapter.inbound.web.fileserver.config.BlockingTransferExecutor; import dev.caskeleton.adapter.inbound.web.fileserver.config.FileserverWebProperties; import dev.caskeleton.adapter.inbound.web.fileserver.dto.BatchUploadItemResult; -import dev.caskeleton.adapter.inbound.web.fileserver.dto.BatchUploadResponse; import dev.caskeleton.adapter.inbound.web.fileserver.dto.UploadedFileResponse; import dev.caskeleton.adapter.inbound.web.fileserver.mapper.MultipartUploadRequestMapper; import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapper; import dev.caskeleton.adapter.inbound.web.fileserver.mapper.UploadIntent; import dev.caskeleton.adapter.inbound.web.fileserver.security.FileserverRequestContextFactory; +import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory; import dev.caskeleton.application.fileserver.api.FileState; import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.FileserverException; @@ -21,6 +21,9 @@ import dev.caskeleton.application.fileserver.port.in.UploadFileUseCase; import dev.caskeleton.application.fileserver.upload.CreateUploadRequest; import dev.caskeleton.application.fileserver.upload.FileView; import dev.caskeleton.application.fileserver.upload.FinalizeUploadRequest; +import dev.caskeleton.shared.response.BulkEnvelope; +import dev.caskeleton.shared.response.BulkItemResult; +import dev.caskeleton.shared.response.ResponseMeta; import jakarta.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.InputStream; @@ -117,23 +120,41 @@ public class FileUploadController { /** * Bounded multi-file upload. * - *

The batch is explicitly non-atomic: each part is an independent file, a failure never rolls - * back a sibling that already succeeded, and the response is always {@code 200} carrying the - * ordered per-part outcome. + *

The batch is explicitly non-atomic: each part is an independent file and a failure never + * rolls back a sibling that already succeeded. The response is {@code 200} and the shared bulk + * envelope (web AGENTS B8): every part succeeded → {@code success = true} and {@code results}; + * any part failed → {@code success = false}, {@code BATCH_PARTIAL_FAILURE} and the per-part + * outcome in {@code error.details[]}. It used to answer {@code success = true} with the failures + * inside {@code data}, so a client reading the discriminator saw a batch that worked (review + * 2026-11-12). */ @PostMapping( path = "/v1/files:batch", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity uploadBatch( + public ResponseEntity> uploadBatch( @RequestParam("files") List files) { requirePartCountWithinPolicy(files.size()); RequestContext context = contextFactory.current(); - List results = new ArrayList<>(files.size()); + List outcomes = new ArrayList<>(files.size()); for (int index = 0; index < files.size(); index++) { - results.add(uploadPart(files.get(index), index, context)); + outcomes.add(uploadPart(files.get(index), index, context)); + } + ResponseMeta meta = ResponseMetaFactory.fromMdc(); + if (outcomes.stream().allMatch(PartOutcome::succeeded)) { + return ResponseEntity.ok( + BulkEnvelope.allOk(outcomes.stream().map(PartOutcome::result).toList(), meta)); + } + return ResponseEntity.ok( + BulkEnvelope.partial(outcomes.stream().map(PartOutcome::detail).toList(), meta)); + } + + /** One part's result in both shapes the bulk envelope may need. */ + private record PartOutcome(BatchUploadItemResult result, BulkItemResult detail) { + + boolean succeeded() { + return result.error() == null; } - return ResponseEntity.ok(new BatchUploadResponse(results)); } /** @@ -142,7 +163,7 @@ public class FileUploadController { *

A part failure is converted to a per-part problem instead of aborting the request, which is * what makes the endpoint's non-atomic contract observable rather than merely documented. */ - private BatchUploadItemResult uploadPart(MultipartFile part, int index, RequestContext context) { + private PartOutcome uploadPart(MultipartFile part, int index, RequestContext context) { String clientPartId = partId(part, index); try (InputStream body = part.getInputStream()) { UploadIntent intent = multipartMapper.map(part); @@ -150,14 +171,21 @@ public class FileUploadController { FileView view = transferExecutor.call( () -> upload(intent, content, part.getSize(), context, UploadMode.BATCH)); - return BatchUploadItemResult.accepted(clientPartId, view); + return new PartOutcome( + BatchUploadItemResult.accepted(clientPartId, view), + BulkItemResult.ok(index, view.fileId().canonicalText())); } catch (FileserverException failure) { - return BatchUploadItemResult.rejected(clientPartId, failure.code()); + return rejected(clientPartId, index, failure.code()); } catch (IOException failure) { - return BatchUploadItemResult.rejected(clientPartId, FileserverErrorCode.STORAGE_UNAVAILABLE); + return rejected(clientPartId, index, FileserverErrorCode.STORAGE_UNAVAILABLE); } } + private static PartOutcome rejected(String clientPartId, int index, FileserverErrorCode code) { + return new PartOutcome( + BatchUploadItemResult.rejected(clientPartId, code), BulkItemResult.error(index, code)); + } + /** * Records the application upload mode represented by this HTTP endpoint. * diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java index 74638fc0..ea0c6b5c 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java @@ -239,8 +239,9 @@ public class Draft12UploadController { } } + /** The header's name, or empty: the application's {@code OriginalFilenamePolicy} names it. */ private static String filename(HttpServletRequest request) { String header = request.getHeader("X-Filename"); - return header == null || header.isBlank() ? "upload.bin" : header; + return header == null ? "" : header; } } diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadResponse.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadResponse.java deleted file mode 100644 index a79599a9..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadResponse.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.dto; - -import java.util.List; - -/** - * Ordered per-part outcome of one batch upload. - * - *

The endpoint answers {@code 200} even when some parts failed: the batch has no request-wide - * atomicity, and pretending otherwise with a single status would hide the parts that succeeded. - */ -public record BatchUploadResponse(List results) { - - public BatchUploadResponse { - results = List.copyOf(results); - } - - /** True when every part succeeded, which the envelope layer reports as a plain success. */ - public boolean fullySucceeded() { - return results.stream().allMatch(result -> result.error() == null); - } -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/MultipartUploadRequestMapper.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/MultipartUploadRequestMapper.java index 365dc63f..844ae34d 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/MultipartUploadRequestMapper.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/MultipartUploadRequestMapper.java @@ -13,16 +13,18 @@ import org.springframework.web.multipart.MultipartFile; */ public final class MultipartUploadRequestMapper { - private static final String FALLBACK_FILENAME = "upload.bin"; - public UploadIntent map(MultipartFile part) { return new UploadIntent( filename(part), claimedMediaType(part), OptionalLong.of(part.getSize()), Optional.empty()); } + /** + * The submitted name, or empty when there is none. Naming an unnamed upload is the application's + * {@code OriginalFilenamePolicy}, one place for every transport (review 2026-11-12). + */ private static String filename(MultipartFile part) { String submitted = part.getOriginalFilename(); - return submitted == null || submitted.isBlank() ? FALLBACK_FILENAME : submitted; + return submitted == null ? "" : submitted; } private static Optional claimedMediaType(MultipartFile part) { diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/RawUploadRequestMapper.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/RawUploadRequestMapper.java index c06b5d06..4e6a96ae 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/RawUploadRequestMapper.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/RawUploadRequestMapper.java @@ -20,8 +20,6 @@ public final class RawUploadRequestMapper { public static final String FILENAME_HEADER = "X-Filename"; public static final String DIGEST_HEADER = "X-Content-Sha256"; - private static final String FALLBACK_FILENAME = "upload.bin"; - private final boolean contentLengthRequired; public RawUploadRequestMapper(boolean contentLengthRequired) { @@ -39,9 +37,10 @@ public final class RawUploadRequestMapper { filename(request), claimedMediaType(request), declaredLength, digest(request)); } + /** The header's name, or empty: the application's {@code OriginalFilenamePolicy} names it. */ private static String filename(HttpServletRequest request) { String header = request.getHeader(FILENAME_HEADER); - return header == null || header.isBlank() ? FALLBACK_FILENAME : header; + return header == null ? "" : header; } private static Optional claimedMediaType(HttpServletRequest request) { diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java index ab2f3093..e40a0eba 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java @@ -112,7 +112,8 @@ public class TusController { create.handle( new CreateUploadCommand( new CreateUploadRequest( - parser.filename(request).orElse("upload.bin"), + // Empty when absent: OriginalFilenamePolicy names it, for every transport. + parser.filename(request).orElse(""), Optional.ofNullable(parser.metadata(request).get("filetype")), parser.declaredLength(request), Optional.empty(), diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java index 78d58122..d22b4b54 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test; class FileserverCorsExposedHeadersTest { @Test - @DisplayName("fileserver HTTP 표면은 업로드 재개에 필요한 헤더를 CORS 노출 목록에 기여한다") + @DisplayName("fileserver HTTP 표면은 업로드·다운로드 재개에 필요한 헤더를 CORS 노출 목록에 기여한다") void theSurfaceContributesTheHeadersAResumingClientMustRead() { // when CorsExposedHeaders contributed = @@ -23,6 +23,7 @@ class FileserverCorsExposedHeadersTest { "Upload-Length", "Upload-Expires", "Upload-Complete", - "Content-Disposition"); + "Content-Disposition", + "Content-Range"); } } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java index 70ae0c27..fc876c72 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java @@ -18,6 +18,7 @@ import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; import dev.caskeleton.application.fileserver.upload.CreateUploadRequest; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.mock.web.MockMultipartFile; @@ -89,15 +90,19 @@ class FileUploadControllerTest { } @Test - void aRawUploadWithoutAFilenameHeaderStillGetsASafeDisplayName() throws Exception { + @DisplayName("이름 헤더 없는 raw 업로드는 전송이 이름을 지어 넣지 않고 앱 정책에 빈 이름을 넘긴다") + void aRawUploadWithoutAFilenameHeaderLeavesTheNameToTheApplicationPolicy() throws Exception { + // when mvc.perform( post("/v1/files:raw").contentType(MediaType.APPLICATION_OCTET_STREAM).content("abc")) .andExpect(status().isCreated()); + // then assertThat(uploadService.requests()) .singleElement() .extracting(CreateUploadRequest::originalFilename) - .isEqualTo("upload.bin"); + .as("OriginalFilenamePolicy names an unnamed upload, once for every transport") + .isEqualTo(""); } @Test @@ -127,7 +132,9 @@ class FileUploadControllerTest { } @Test + @DisplayName("모든 part가 성공한 batch는 success=true와 part별 results를 순서대로 준다") void batchReturnsPerPartResultsAndIsExplicitlyNonAtomic() throws Exception { + // when / then mvc.perform( multipart("/v1/files:batch") .file( @@ -137,13 +144,17 @@ class FileUploadControllerTest { new MockMultipartFile( "files", "b.txt", "text/plain", "b".getBytes(StandardCharsets.UTF_8)))) .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) .andExpect(jsonPath("$.results.length()").value(2)) .andExpect(jsonPath("$.results[0].clientPartId").value("a.txt")) .andExpect(jsonPath("$.results[1].clientPartId").value("b.txt")); } @Test + @DisplayName( + "한 part가 실패한 batch는 success=false, BATCH_PARTIAL_FAILURE, part별 details이고 성공한 part는 되돌리지 않는다") void aFailedBatchPartNeverRollsBackTheSiblingThatSucceeded() throws Exception { + // given uploadService.failWith( body -> "b".equals(body) @@ -152,6 +163,7 @@ class FileUploadControllerTest { FileserverFailureContext.of(FileserverErrorCode.FILE_TOO_LARGE, false)) : null); + // when / then mvc.perform( multipart("/v1/files:batch") .file( @@ -161,10 +173,14 @@ class FileUploadControllerTest { new MockMultipartFile( "files", "b.txt", "text/plain", "b".getBytes(StandardCharsets.UTF_8)))) .andExpect(status().isOk()) - .andExpect(jsonPath("$.results[0].status").value("READY")) - .andExpect(jsonPath("$.results[1].status").value("REJECTED")) - .andExpect(jsonPath("$.results[1].error.code").value("FILE_TOO_LARGE")) - .andExpect(jsonPath("$.results[1].error.category").value("VALIDATION")); + .andExpect(jsonPath("$.success").value(false)) + .andExpect(jsonPath("$.results").doesNotExist()) + .andExpect(jsonPath("$.error.code").value("BATCH_PARTIAL_FAILURE")) + .andExpect(jsonPath("$.error.details[0].status").value("ok")) + .andExpect(jsonPath("$.error.details[0].id").isNotEmpty()) + .andExpect(jsonPath("$.error.details[1].index").value(1)) + .andExpect(jsonPath("$.error.details[1].status").value("error")) + .andExpect(jsonPath("$.error.details[1].code").value("FILE_TOO_LARGE")); } @Test diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java index 92b92605..54e9ffca 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java @@ -48,6 +48,25 @@ class FileserverProblemHeaderParityTest { assertThat(headers).doesNotContainKey("Retry-After"); } + @Test + @org.junit.jupiter.api.DisplayName( + "본문이 retryable=false로 좁히는 code는 발생이 retryable이어도 Retry-After를 싣지 않는다") + void aCodeThatIsNeverRetryableAdvertisesNoRetryWhateverTheOccurrenceSaid() { + // given + FileserverException failure = + new FileserverException( + "no atomic publish", + FileserverFailureContext.of(FileserverErrorCode.ATOMIC_PUBLISH_UNSUPPORTED, true)); + + // when + Map headers = FileserverProblemHeaders.of(failure); + + // then + assertThat(headers) + .as("the body says retryable=false for this code; the header must not say otherwise") + .doesNotContainKey("Retry-After"); + } + @Test void anUnsatisfiableRangeDisclosesTheRepresentationLength() { Map headers = diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejection.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejection.java new file mode 100644 index 00000000..6431b9be --- /dev/null +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejection.java @@ -0,0 +1,41 @@ +package dev.caskeleton.adapter.inbound.web.notification.platform.submission; + +import dev.caskeleton.adapter.inbound.web.error.ClientSafeErrorDetails; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.OperationalError; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * A request field whose value is outside the vocabulary this transport parses (a channel, a slot, a + * language tag). + * + *

The same answer a body constraint gets — {@code 400 VALIDATION_FAILED} with one {@code {field, + * code, message}} detail — rather than the {@code BAD_PARAMETER} a bare {@code + * IllegalArgumentException} reaches, which named nothing the client could correct (review + * 2026-11-12). The rejected value is not echoed. + */ +final class NotificationFieldRejection extends RuntimeException + implements ApiErrorCarrier, ClientSafeErrorDetails { + + private static final long serialVersionUID = 1L; + + private final String field; + + NotificationFieldRejection(String field, String reason, Throwable cause) { + super(reason, cause); + this.field = Objects.requireNonNull(field, "field"); + } + + @Override + public ApiErrorCode errorCode() { + return OperationalError.VALIDATION_FAILED; + } + + @Override + public Object clientDetails() { + return List.of(Map.of("field", field, "code", "UNKNOWN_VALUE", "message", "허용된 값이 아닙니다.")); + } +} diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java index 16434929..3f01c215 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java @@ -92,15 +92,18 @@ public final class NotificationSubmissionController { /** * The channel a caller named. * - *

Parsed here rather than bound by Jackson so an unknown name fails as a validation error - * naming the vocabulary, instead of as a deserialization error naming a Java enum. + *

Parsed here rather than bound by Jackson so an unknown name fails as a validation error on + * the {@code channel} field ({@code VALIDATION_FAILED}), instead of as a deserialization error + * naming a Java enum. */ private static Channel channel(String name) { try { return Channel.valueOf(name.trim().toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException unknown) { - throw new IllegalArgumentException( - "channel must be one of " + java.util.Arrays.toString(Channel.values()), unknown); + throw new NotificationFieldRejection( + "channel", + "channel must be one of " + java.util.Arrays.toString(Channel.values()), + unknown); } } @@ -117,7 +120,7 @@ public final class NotificationSubmissionController { } Locale parsed = Locale.forLanguageTag(tag.trim()); if (parsed.equals(Locale.ROOT)) { - throw new IllegalArgumentException("locale must be a BCP 47 language tag"); + throw new NotificationFieldRejection("locale", "locale must be a BCP 47 language tag", null); } return Optional.of(parsed); } diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java index 598dc701..446b4335 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java @@ -32,7 +32,12 @@ import org.springframework.web.bind.annotation.RestController; * publish} and no application or transport ever called it. * *

{@code 201}, unlike a submission's {@code 202}: a published version is an immutable resource - * that exists when the call returns, with nothing deferred to a worker. + * that exists when the call returns, with nothing deferred to a worker. The response carries no + * {@code Location}: there is no endpoint that reads a template version, and a {@code Location} that + * answers 404 is worse than none. The body names the version and its digest. + * + *

The path is lowerCamel plural like every other collection (manual 11, AIP-122); it was {@code + * /notification-templates} until 2026-11-12. * *

Authorized by {@code notification-template:publish}, which is deliberately not {@code * notification:submit}. Publishing a template changes what every future submission renders, and a @@ -45,7 +50,7 @@ import org.springframework.web.bind.annotation.RestController; name = "enabled", havingValue = "true", matchIfMissing = true) -@RequestMapping("/notification-templates") +@RequestMapping("/notificationTemplates") public final class NotificationTemplateController { private final PublishNotificationTemplateUseCase publish; @@ -77,7 +82,7 @@ public final class NotificationTemplateController { locale(request.locale()), Optional.ofNullable(request.fallbackLocale()) .filter(tag -> !tag.isBlank()) - .map(NotificationTemplateController::locale), + .map(tag -> locale("fallbackLocale", tag)), slots(request.slots()), names(request.requiredVariables()), names(request.sensitiveVariables())); @@ -104,8 +109,10 @@ public final class NotificationTemplateController { try { slot = TemplateSlot.valueOf(name.trim().toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException unknown) { - throw new IllegalArgumentException( - "slot must be one of " + java.util.Arrays.toString(TemplateSlot.values()), unknown); + throw new NotificationFieldRejection( + "slots", + "slot must be one of " + java.util.Arrays.toString(TemplateSlot.values()), + unknown); } slots.put(slot, content); }); @@ -120,15 +127,21 @@ public final class NotificationTemplateController { try { return Channel.valueOf(name.trim().toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException unknown) { - throw new IllegalArgumentException( - "channel must be one of " + java.util.Arrays.toString(Channel.values()), unknown); + throw new NotificationFieldRejection( + "channel", + "channel must be one of " + java.util.Arrays.toString(Channel.values()), + unknown); } } private static Locale locale(String tag) { + return locale("locale", tag); + } + + private static Locale locale(String field, String tag) { Locale parsed = Locale.forLanguageTag(tag.trim()); if (parsed.equals(Locale.ROOT)) { - throw new IllegalArgumentException("locale must be a BCP 47 language tag"); + throw new NotificationFieldRejection(field, field + " must be a BCP 47 language tag", null); } return parsed; } diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java index 771c7cd3..2c1d3805 100644 --- a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java @@ -31,6 +31,19 @@ class NotificationRoutePrefixTest { assertThat(prefixed.test(NotificationTemplateController.class)).isTrue(); } + @org.junit.jupiter.api.Test + @org.junit.jupiter.api.DisplayName("template 게시 경로는 다른 collection처럼 lowerCamel 복수형이다") + void theTemplateCollectionPathIsLowerCamelPlural() { + // when + String[] paths = + NotificationTemplateController.class + .getAnnotation(org.springframework.web.bind.annotation.RequestMapping.class) + .value(); + + // then + assertThat(paths).containsExactly("/notificationTemplates"); + } + private static final class InspectablePathMatchConfigurer extends PathMatchConfigurer { Predicate> prefix(String path) { diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java index 2270c921..6cb97c21 100644 --- a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java @@ -2,13 +2,17 @@ package dev.caskeleton.adapter.inbound.web.notification.platform.submission; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationCommand; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -47,4 +51,35 @@ class NotificationSubmissionControllerTest { // then assertThat(List.of(status, accepted.size())).containsExactly(400, 0); } + + @ParameterizedTest(name = "{0}") + @CsvSource({ + "channel, '\"channel\":\"PIGEON\",\"locale\":\"ko-KR\"'", + "locale, '\"channel\":\"EMAIL\",\"locale\":\"%%%\"'" + }) + @DisplayName("모르는 channel·locale은 그 필드를 짚는 400 VALIDATION_FAILED이고 use case에 닿지 않는다") + void anUnknownVocabularyValueIsAValidationFailureNamingTheField(String field, String fields) + throws Exception { + // given + String body = + "{\"recipientRef\":\"r-1\"," + + fields + + ",\"address\":\"a@example.com\",\"template\":\"welcome\",\"category\":\"TRANSACTIONAL\"}"; + + // when + String response = + mvc.perform(post("/notifications").contentType(MediaType.APPLICATION_JSON).content(body)) + .andExpect(status().isBadRequest()) + .andReturn() + .getResponse() + .getContentAsString(); + + // then + assertThat(response) + .contains("\"code\":\"VALIDATION_FAILED\"") + .contains("\"field\":\"" + field + "\"") + .doesNotContain("PIGEON") + .doesNotContain("%%%"); + assertThat(accepted).isEmpty(); + } } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java index f75421a4..0967f597 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java @@ -3,6 +3,7 @@ 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.BulkItemResult; import dev.caskeleton.shared.response.Envelope; import dev.caskeleton.shared.response.ResponseMeta; import org.springframework.context.annotation.Bean; @@ -33,6 +34,7 @@ public class EnvelopeWireFormatConfig { SimpleModule module = new SimpleModule("EnvelopeWireFormatModule"); module.setMixInAnnotation(Envelope.class, OmitNullFields.class); module.setMixInAnnotation(BulkEnvelope.class, OmitNullFields.class); + module.setMixInAnnotation(BulkItemResult.class, OmitNullFields.class); module.setMixInAnnotation(ApiError.class, OmitNullFields.class); module.setMixInAnnotation(ResponseMeta.class, OmitNullFields.class); return module; diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java index 8f7abc31..d2495607 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java @@ -5,6 +5,8 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; import dev.caskeleton.application.idempotency.IdempotencyInFlightException; +import dev.caskeleton.shared.error.ClientErrorMessages; +import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.observability.MdcKeys; import dev.caskeleton.shared.response.BulkEnvelope; import dev.caskeleton.shared.response.BulkItemResult; @@ -26,6 +28,7 @@ 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.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -77,6 +80,33 @@ class EnvelopeWireShapeTest { new ResponseMeta("req-1", "trace-1", "corr-1").withPage(new PageMeta(0, 20, 1, "id"))); } + @GetMapping("/probe/null-data") + public Envelope nullData() { + return Envelope.ok(null, new ResponseMeta("req-1", "trace-1", "corr-1")); + } + + @GetMapping("/probe/text") + public String text() { + ids(true); + return "hello"; + } + + @GetMapping("/probe/page-unsorted") + public Envelope> pageUnsorted() { + return Envelope.ok( + List.of("a"), + new ResponseMeta("req-1", "trace-1", "corr-1").withPage(new PageMeta(0, 20, 1, null))); + } + + @GetMapping("/probe/bulk-partial-items") + public BulkEnvelope bulkPartialItems() { + return BulkEnvelope.partial( + List.of( + BulkItemResult.ok(0, "item-1"), + BulkItemResult.error(1, OperationalError.MAPPING_FAILED)), + new ResponseMeta("req-1", "trace-1", "corr-1")); + } + @GetMapping("/probe/in-flight") public Map inFlight() { ids(false); @@ -178,6 +208,60 @@ class EnvelopeWireShapeTest { assertThat(details.isArray() && details.isEmpty()).isTrue(); } + @Test + @DisplayName("성공인데 data가 null이면 data 키도 없다") + void aNullDataOmitsTheDataKey() throws Exception { + // when + JsonNode body = rawBody("/probe/null-data"); + + // then + assertThat(keys(body)).containsExactlyInAnyOrder("success", "meta"); + } + + @Test + @DisplayName("JSON을 요청하면 String 반환도 같은 Envelope의 data로 나간다") + void aStringBodyIsAnEnvelopeWhenJsonIsAsked() throws Exception { + // when + JsonNode body = + READER.readTree( + mvc.perform(get("/probe/text").accept(MediaType.APPLICATION_JSON)) + .andReturn() + .getResponse() + .getContentAsString()); + + // then + assertThat(keys(body)).containsExactlyInAnyOrder("success", "data", "meta"); + assertThat(body.get("data").asString()).isEqualTo("hello"); + } + + @Test + @DisplayName("정렬 없는 목록의 page는 sort 키를 null로 싣는다") + void anUnsortedPageCarriesSortNull() throws Exception { + // when + JsonNode page = rawBody("/probe/page-unsorted").get("meta").get("page"); + + // then + assertThat(keys(page)).containsExactlyInAnyOrder("number", "size", "total", "sort"); + assertThat(page.get("sort").isNull()).isTrue(); + } + + @Test + @DisplayName("bulk 부분 실패의 message는 고정 문구이고 항목은 자기 상태에 맞는 키만 싣는다") + void aPartialFailureCarriesFixedWordingAndItemsWithoutNullKeys() throws Exception { + // when + JsonNode error = rawBody("/probe/bulk-partial-items").get("error"); + + // then + assertThat(error.get("message").asString()) + .isEqualTo(ClientErrorMessages.of(OperationalError.BATCH_PARTIAL_FAILURE)); + assertThat(keys(error.get("details").get(0))) + .containsExactlyInAnyOrder("index", "status", "id"); + assertThat(keys(error.get("details").get(1))) + .containsExactlyInAnyOrder("index", "status", "code", "message"); + assertThat(error.get("details").get(1).get("message").asString()) + .isEqualTo(ClientErrorMessages.of(OperationalError.MAPPING_FAILED)); + } + private JsonNode rawBody(String path) throws Exception { String text = mvc.perform(get(path)).andReturn().getResponse().getContentAsString(); return READER.readTree(text); diff --git a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadRequest.java b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadRequest.java index 91dcaef5..51c03330 100644 --- a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadRequest.java +++ b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadRequest.java @@ -9,7 +9,9 @@ import java.util.OptionalLong; * Client intent when starting an upload. * *

{@code originalFilename} and {@code claimedMediaType} are untrusted: they are sanitized and - * stored as display metadata, never used to build a physical key or to decide safety. + * stored as display metadata, never used to build a physical key or to decide safety. A transport + * that received no name passes an empty string; the display name of an unnamed upload is {@code + * OriginalFilenamePolicy}'s to choose, not each transport's. * *

The request carries only what the client decides. The namespace and the session lifetime are * {@link UploadPolicy}'s, so no transport can pick its own. diff --git a/src/bootstrap/app/compose-lanes/smoke/notification-smoke.sh b/src/bootstrap/app/compose-lanes/smoke/notification-smoke.sh index f2850e4a..fe37d5bd 100755 --- a/src/bootstrap/app/compose-lanes/smoke/notification-smoke.sh +++ b/src/bootstrap/app/compose-lanes/smoke/notification-smoke.sh @@ -49,7 +49,7 @@ case "${NOTIFICATION_SMOKE_PHASE}" in # reruns against a surviving volume is not a different lane; a 409 here means the platform # holds a version with this id and different content, which is a real failure. PUBLISH_STATUS="$(curl -s -o /tmp/publish.json -w '%{http_code}' \ - -X POST "${APP_BASE_URL}${BASE_PATH}/notification-templates" \ + -X POST "${APP_BASE_URL}${BASE_PATH}/notificationTemplates" \ -H "Authorization: Bearer ${ACCESS_TOKEN}" \ -H 'Content-Type: application/json' \ -d "{\"templateId\":\"${TEMPLATE_ID}\",\"version\":1,\"channel\":\"EMAIL\",\"locale\":\"en\", diff --git a/src/bootstrap/notification-platform/README.md b/src/bootstrap/notification-platform/README.md index 30345276..962b47b1 100644 --- a/src/bootstrap/notification-platform/README.md +++ b/src/bootstrap/notification-platform/README.md @@ -19,7 +19,7 @@ composition:notification-platform ├─ adapter:outbound:notification provider(SMTP·SES), 저장 외 런타임, NotificationPlatformAutoConfiguration ├─ adapter:outbound:persistence-notification (runtimeOnly) 알림 entity·저장소·Flyway stream ├─ adapter:outbound:persistence-jpa (runtimeOnly) DataSource·Flyway core·TransactionPort - └─ adapter:inbound:web-notification POST /notifications, POST /notification-templates, + └─ adapter:inbound:web-notification POST /notifications, POST /notificationTemplates, POST /internal/notification/callbacks/{provider}/{profile} ``` diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkEnvelope.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkEnvelope.java index 511ebdc8..76da7106 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkEnvelope.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkEnvelope.java @@ -1,5 +1,6 @@ package dev.caskeleton.shared.response; +import dev.caskeleton.shared.error.ClientErrorMessages; import dev.caskeleton.shared.error.OperationalError; import java.util.List; @@ -25,7 +26,7 @@ public record BulkEnvelope(boolean success, List results, ApiError error, ApiError.withDetails( OperationalError.BATCH_PARTIAL_FAILURE.code(), OperationalError.BATCH_PARTIAL_FAILURE.category().name(), - "One or more items failed; see details[] for the per-item outcome.", + ClientErrorMessages.of(OperationalError.BATCH_PARTIAL_FAILURE), OperationalError.BATCH_PARTIAL_FAILURE.retryable(), details); return new BulkEnvelope<>(false, null, err, meta); diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkItemResult.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkItemResult.java index 1f802f1d..1e2719c1 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkItemResult.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkItemResult.java @@ -1,14 +1,20 @@ package dev.caskeleton.shared.response; +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.ClientErrorMessages; + /** * Per-item result inside a bulk endpoint's {@code error.details[]} array. * *

    *
  • {@code status = "ok"} + {@code id} when the item succeeded; - *
  • {@code status = "error"} + {@code code} + {@code message} when failed. + *
  • {@code status = "error"} + {@code code} + {@code message} when failed. The message is the + * code's category wording from {@link ClientErrorMessages}, the same text a single-item + * endpoint would send, never the caller's own text (review 2026-11-12). *
* - *

No debug payload — keeps the envelope safe to log/ship. + *

No debug payload — keeps the envelope safe to log/ship. Absent members are omitted on the wire + * like every other envelope field. */ public record BulkItemResult(int index, String status, String id, String code, String message) { @@ -16,7 +22,7 @@ public record BulkItemResult(int index, String status, String id, String code, S return new BulkItemResult(index, "ok", id, null, null); } - public static BulkItemResult error(int index, String code, String message) { - return new BulkItemResult(index, "error", null, code, message); + public static BulkItemResult error(int index, ApiErrorCode code) { + return new BulkItemResult(index, "error", null, code.code(), ClientErrorMessages.of(code)); } } diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/response/EnvelopeTest.java b/src/shared-contract/src/test/java/dev/caskeleton/shared/response/EnvelopeTest.java index 69e1ccd2..d7d75737 100644 --- a/src/shared-contract/src/test/java/dev/caskeleton/shared/response/EnvelopeTest.java +++ b/src/shared-contract/src/test/java/dev/caskeleton/shared/response/EnvelopeTest.java @@ -2,7 +2,10 @@ package dev.caskeleton.shared.response; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.shared.error.ClientErrorMessages; +import dev.caskeleton.shared.error.OperationalError; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class EnvelopeTest { @@ -31,16 +34,39 @@ class EnvelopeTest { } @Test - void bulkAllOkAndPartialCarryMeta() { - BulkEnvelope ok = BulkEnvelope.allOk(List.of("a"), META); + @DisplayName("bulk 전체 성공은 success=true와 meta를 싣는다") + void aFullySucceededBulkCarriesMeta() { + // given + List results = List.of("a"); + + // when + BulkEnvelope ok = BulkEnvelope.allOk(results, META); + + // then assertThat(ok.success()).isTrue(); assertThat(ok.meta().requestId()).isEqualTo("req-1"); + } - BulkEnvelope partial = - BulkEnvelope.partial(List.of(BulkItemResult.error(0, "MAPPING_FAILED", "x")), META); + @Test + @DisplayName("bulk 부분 실패는 BATCH_PARTIAL_FAILURE와 category 고정 문구, 항목 코드의 고정 문구를 싣는다") + void aPartiallyFailedBulkCarriesTheFixedWording() { + // given + List details = + List.of( + BulkItemResult.ok(0, "f-1"), BulkItemResult.error(1, OperationalError.MAPPING_FAILED)); + + // when + BulkEnvelope partial = BulkEnvelope.partial(details, META); + + // then assertThat(partial.success()).isFalse(); assertThat(partial.error().code()).isEqualTo("BATCH_PARTIAL_FAILURE"); assertThat(partial.error().category()).isEqualTo("VALIDATION"); + assertThat(partial.error().message()) + .isEqualTo(ClientErrorMessages.of(OperationalError.BATCH_PARTIAL_FAILURE)); + assertThat(details.get(1).message()) + .as("an item carries its code's wording, never text the caller chose") + .isEqualTo(ClientErrorMessages.of(OperationalError.MAPPING_FAILED)); assertThat(partial.meta().correlationId()).isEqualTo("corr-1"); } } -- 2.54.0 From 697e62e8cb679ef0871d13b92b2c2a613738aeda Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 04:47:03 +0900 Subject: [PATCH 12/23] =?UTF-8?q?fix(errors)!:=20=EC=84=9C=EB=B2=84=20?= =?UTF-8?q?=ED=8F=AC=ED=99=94=EB=8A=94=20=EB=AA=A8=EB=93=A0=20=EC=A0=84?= =?UTF-8?q?=EC=86=A1=EC=9D=B4=20=EA=B3=B5=EC=9A=A9=20SERVER=5FBUSY=20?= =?UTF-8?q?=ED=95=98=EB=82=98=EB=A1=9C=20=EB=8B=B5=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 서버 쪽 상한이 찬 거절이 전송마다 다른 코드였다. web-advanced는 ADMISSION_REFUSED(503), fileserver는 instance·전송 pool 포화까지 TRANSFER_ADMISSION_REJECTED(429 RATE_LIMIT), gRPC는 RATE_LIMIT_EXCEEDED (RESOURCE_EXHAUSTED, "요청이 너무 잦습니다")였다. client는 자기 빈도 탓인지 서버 포화인지 가를 수 없었다. web은 상태만 아는 모든 503을 REQUEST_TIMEOUT으로 답했다 (§4는 비동기 시간 초과만). §4에 OPERATION_NOT_FOUND가 없었고, fileserver 오류 code 27개 중 23개가 계약 문서에 없었으며 예시가 "data": null을 실었다. fileserver는 Retry-After를 발생만 보고 붙여, 본문이 retryable=false로 좁힌 code에도 헤더가 나갔다. gRPC Javadoc과 graphql 스냅숏 머리말이 지운 이름(WORKLOG_NOT_FOUND, spi)을 적었다. 고른 방법(리뷰 README 6절 ②): - 공용 OperationalError.SERVER_BUSY(503, TRANSIENT_DEPENDENCY, retryable, Retry-After 1)를 더했다. registry 행, RetryAfterAdvisor, runbook server-busy.md를 같이 둔다. - web-advanced admission 거절, gRPC call admission(UNAVAILABLE), fileserver의 instance permit·직접 다운로드 permit·전송 pool 포화가 이 코드다. fileserver는 같은 이름의 FileserverErrorCode.SERVER_BUSY를 두고, 이름이 같은 code의 뜻이 같은지 FileserverExceptionTest가 이미 본다. 호출자 자기 scope의 동시 전송 초과만 TRANSFER_ADMISSION_REJECTED 429로 남는다. - 상태만 아는 503은 SERVER_BUSY, AsyncRequestTimeoutException만 REQUEST_TIMEOUT이다(HttpStatusErrorCodes.forException). - fileserver Retry-After는 본문과 같은 규칙(code와 발생이 모두 retryable)으로 붙인다. 재시도 불가 code인 ATOMIC_PUBLISH_UNSUPPORTED를 표에서 뺐다. - docs/fileserver/http-contract.md에 오류 code 표 전체를 두고 예시의 data:null을 지웠다. http-contract §4에 OPERATION_NOT_FOUND와 SERVER_BUSY를 적었다. - decisions 2.3에 결정 ①②③ 행을 더했다. - 포화 시험의 sleep(200)을 첫 거절 신호로 바꾸고, timeout 시험이 code까지 본다(같은 파일이라 RR9-03-20의 그 부분을 여기서 고친다). - web-advanced 파일의 spotless 정리(앞 커밋분)를 함께 싣는다. 버린 대안: JOB_EXECUTOR_REJECTED를 재사용 — 백그라운드 job 이름이라 요청 허가 거절을 읽는 client와 runbook을 잘못 이끈다. 위험·한계: 포화 거절로 분기하던 client와 재시도 정책, WebAdvancedError .ADMISSION_REFUSED를 참조하던 코드, 모든 503을 REQUEST_TIMEOUT으로 보던 client가 바뀐다(upgrade 안내 8·9·13). BREAKING CHANGE: 서버 포화 코드가 SERVER_BUSY 하나다(web-advanced ADMISSION_REFUSED 삭제, fileserver instance·pool 포화 429 → 503, gRPC RESOURCE_EXHAUSTED → UNAVAILABLE). 상태만 아는 503은 SERVER_BUSY다. 할 일은 docs/upgrade/2026-11-round9-contracts.md. Refs: RR9-03-06, RR9-03-07, RR9-03-11, RR9-03-12, RR9-03-15, RR9-03-16, RR9-03-20 --- docs/architecture/graphql-api-surface.txt | 6 +-- docs/fileserver/http-contract.md | 46 +++++++++++++++++-- docs/registries/error-codes.yaml | 15 ++++++ docs/runbooks/server-busy.md | 46 +++++++++++++++++++ docs/upgrade/2026-11-round9-contracts.md | 11 ++++- docs/web/http-contract.md | 9 ++-- docs/web/virtual-thread-profile.md | 2 +- docs/work/reference/decisions.md | 3 ++ src/adapter/inbound/graphql/build.gradle | 12 ++--- src/adapter/inbound/grpc/README.md | 3 +- .../inbound/grpc/GrpcCallAdmission.java | 12 +++-- .../inbound/grpc/GrpcStatusMapper.java | 4 +- .../inbound/grpc/GrpcP1BoundaryWireTest.java | 9 ++-- src/adapter/inbound/web-advanced/README.md | 4 +- .../web/advanced/error/WebAdvancedError.java | 6 +-- .../web/advanced/mvc/MvcStreamWriter.java | 4 +- .../mvc/VirtualThreadAdmissionFilter.java | 15 +++--- .../AdmissionRefusedException.java | 9 ++-- .../error/WebAdvancedErrorMappingTest.java | 2 +- .../mvc/VirtualThreadAdmissionFilterTest.java | 11 +++-- .../advanced/patch/JsonPatchApplierTest.java | 6 +-- .../config/BlockingTransferExecutor.java | 2 +- .../problem/FileserverProblemHeaders.java | 8 ++-- .../MvcUploadExecutorSaturationTest.java | 17 +++++-- .../web/error/GlobalExceptionHandler.java | 2 +- .../web/error/HttpStatusErrorCodes.java | 18 +++++++- .../web/observability/RetryAfterAdvisor.java | 1 + .../error/EnvelopeErrorControllerTest.java | 1 + .../api/error/FileserverErrorCode.java | 12 +++-- .../quota/TransferAdmissionController.java | 12 +++-- .../TransferAdmissionControllerTest.java | 11 ++++- .../shared/error/OperationalError.java | 6 +++ 32 files changed, 244 insertions(+), 81 deletions(-) create mode 100644 docs/runbooks/server-busy.md diff --git a/docs/architecture/graphql-api-surface.txt b/docs/architecture/graphql-api-surface.txt index cd61da7e..5857b247 100644 --- a/docs/architecture/graphql-api-surface.txt +++ b/docs/architecture/graphql-api-surface.txt @@ -1,8 +1,8 @@ # GraphQL leaf public API surface — every public top-level type in src/main/java. # A public type in a single-jar leaf is reachable from every adopter's code, so -# additions are reviewed rather than discovered. `api` and `spi` are the intended -# external surface; the rest are candidates to become internal when this leaf is -# split into capability artifacts. +# additions are reviewed rather than discovered. `api` is the intended external +# surface; the rest are candidates to become internal when this leaf is split into +# capability artifacts. # Update only after review with: # ./gradlew :adapter:inbound:graphql:updateGraphQlApiSurface -PapproveGraphQlApiSurfaceChange # types: 161 diff --git a/docs/fileserver/http-contract.md b/docs/fileserver/http-contract.md index a5fb6aa6..d5518f01 100644 --- a/docs/fileserver/http-contract.md +++ b/docs/fileserver/http-contract.md @@ -9,7 +9,7 @@ |---|---|---|---| | POST | `/v1/files` | `201` READY, `202` VERIFYING | multipart 단일 업로드 | | POST | `/v1/files:raw` | `201`, `202` | 요청 본문 전체가 파일이다 | -| POST | `/v1/files:batch` | `200` | part별 결과를 순서대로 준다. 명시적으로 원자적이지 않다 | +| POST | `/v1/files:batch` | `200` | 공용 bulk envelope(`docs/web/http-contract.md` 1절). 명시적으로 원자적이지 않다 | | GET | `/v1/files/{fileId}` | `200` | 공개 metadata. content key나 경로는 절대 주지 않는다 | | GET | `/v1/files/{fileId}/content` | `200`, `206`, `304` | 다운로드 | | HEAD | `/v1/files/{fileId}/content` | `200`, `304` | 같은 헤더, 본문 없음 | @@ -76,7 +76,6 @@ servlet chain에서 `app.fileserver-platform.security.admin-roles`로 막고, ```json { "success": false, - "data": null, "error": { "code": "UPLOAD_OFFSET_MISMATCH", "category": "CONFLICT", @@ -97,8 +96,10 @@ servlet chain에서 `app.fileserver-platform.security.admin-roles`로 막고, `ambiguous`는 client가 재시도 전에 읽어야 하는 필드다. 결과를 모르는 실패는 이미 효과가 났을 수 있다. `retryable`은 이번 발생에 대한 판단이고, 그 code가 허락하는 범위보다 넓어지지 않는다. -batch 업로드에서 거부된 part는 `results[]` 항목에 같은 `error` 객체(`code`, `category`, `message`, -`retryable`)를 담는다. +batch 업로드는 공용 bulk envelope다. 모든 part가 성공하면 `success: true`와 `results[]`(part마다 `clientPartId`, +`status`, `fileId`)다. 한 part라도 거부되면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`, `error.details[]`다. +`details[]` 항목은 part 순서의 `index`, `status`(`ok`·`error`), 성공한 part의 `id`(fileId), 거부된 part의 `code`와 +category 고정 문구 `message`다. 성공한 part는 되돌리지 않는다. ### Envelope 규칙의 프로토콜 예외 @@ -111,6 +112,43 @@ batch 업로드에서 거부된 part는 `results[]` 항목에 같은 `error` 객 `409 application/problem+json`, `type = https://iana.org/assignments/http-problem-types#mismatching-upload-offset`, `expectedOffset`과 `providedOffset`. Envelope가 아닌 실패 본문은 이것 하나뿐이다. +## 오류 코드 + +`error.code`는 `FileserverErrorCode`(application-fileserver)가 정한다. 아래 표가 그 전부이고, client는 이 값으로 +분기한다. `retryable`은 그 code가 허락하는 최대치다. 실제 응답의 `retryable`은 그 발생에 대한 판단이라 `true`인 +code도 `false`로 올 수 있다(위 「실패 본문」). `Retry-After`는 retryable인 발생에만 붙는다. + +| code | status | category | retryable | `Retry-After` | 언제 | +| --- | --- | --- | --- | --- | --- | +| `BAD_REQUEST` | 400 | `VALIDATION` | false | — | 헤더나 헤더 조합이 잘못됐다 | +| `UNAUTHENTICATED` | 401 | `AUTH` | false | — | 인증하지 않았다 | +| `ACCESS_DENIED` | 403 | `AUTHZ` | false | — | 권한이 없다. 존재를 숨기는 profile에서는 `FILE_NOT_FOUND`로 온다 | +| `FILE_NOT_FOUND` | 404 | `NOT_FOUND` | false | — | 파일이 없거나 숨겼다 | +| `FILE_ALREADY_EXISTS` | 409 | `CONFLICT` | false | — | 대상 이름이 이미 있다(copy·move는 새로 만들기만 한다) | +| `FILE_NOT_READY` | 409 | `CONFLICT` | true | 2 | 검증이 끝나지 않아 아직 읽을 수 없다 | +| `UPLOAD_OFFSET_MISMATCH` | 409 | `CONFLICT` | true | — | 이어 쓰기 offset이 서버 offset과 다르다. `details.currentOffset`부터 다시 보낸다 | +| `CONCURRENT_MODIFICATION` | 409 | `CONFLICT` | true | 1 | 같은 자원을 다른 요청이 바꾸는 중이다 | +| `UPLOAD_EXPIRED` | 410 | `CONFLICT` | false | — | 만료되거나 끝난(취소, 거부, 격리) 업로드다 | +| `CONTENT_LENGTH_REQUIRED` | 411 | `VALIDATION` | false | — | `require-content-length` profile인데 길이가 없다 | +| `PRECONDITION_FAILED` | 412 | `CONFLICT` | false | — | `If-Match`·`If-Unmodified-Since`가 맞지 않는다 | +| `FILE_TOO_LARGE` | 413 | `VALIDATION` | false | — | 파일 크기 정책을 넘었다 | +| `QUOTA_EXCEEDED` | 413 | `CONFLICT` | false | — | 저장 할당량을 넘었다 | +| `UNSUPPORTED_MEDIA_TYPE` | 415 | `VALIDATION` | false | — | 받지 않는 media type이다 | +| `RANGE_NOT_SATISFIABLE` | 416 | `VALIDATION` | false | — | Range를 만족할 수 없다. `Content-Range: bytes */<길이>`를 싣는다 | +| `INTEGRITY_MISMATCH` | 422 | `DATA_INTEGRITY` | false | — | 선언한 digest와 받은 바이트가 다르다 | +| `MALWARE_DETECTED` | 422 | `DATA_INTEGRITY` | false | — | 검사기가 거부했다 | +| `INVALID_PATH` | 422 | `VALIDATION` | false | — | 경로 형식이 틀렸다 | +| `PATH_OUTSIDE_NAMESPACE` | 422 | `VALIDATION` | false | — | 경로가 namespace 밖을 가리킨다 | +| `TRANSFER_ADMISSION_REJECTED` | 429 | `RATE_LIMIT` | true | 1 | 호출자 자신의 동시 전송 permit이 찼다. 자기 전송이 끝나면 풀린다 | +| `CHECKSUM_MISMATCH` | 460 | `DATA_INTEGRITY` | false | — | tus `Upload-Checksum`이 그 요청의 바이트와 다르다. 그 chunk만 버린다 | +| `PARTIAL_WRITE` | 500 | `TRANSIENT_DEPENDENCY` | false | — | 쓰기가 중간에 끊겼다 | +| `AMBIGUOUS_COMPLETION` | 500 | `DATA_INTEGRITY` | false | — | 결과를 모른다. 이미 효과가 났을 수 있어 그대로 재시도하지 않는다 | +| `ATOMIC_PUBLISH_UNSUPPORTED` | 503 | `PERMANENT_DEPENDENCY` | false | — | 저장소가 원자적 게시를 지원하지 않는다(배포 설정 결함) | +| `STORAGE_UNAVAILABLE` | 503 | `TRANSIENT_DEPENDENCY` | true | 30 | 저장소나 검사기를 쓸 수 없다 | +| `SERVER_BUSY` | 503 | `TRANSIENT_DEPENDENCY` | true | 1 | instance 전체의 전송 permit이나 전송 worker pool이 찼다. 공용 서버 포화 코드와 같다 | +| `TRANSFER_TIMEOUT` | 504 | `TRANSIENT_DEPENDENCY` | true | 5 | 전송이 시간 안에 끝나지 않았다 | +| `STORAGE_FULL` | 507 | `TRANSIENT_DEPENDENCY` | false | — | 저장 용량이 없다 | + ## 헤더 계약 | 헤더 | 계약 | diff --git a/docs/registries/error-codes.yaml b/docs/registries/error-codes.yaml index 134ffd8f..d3d531db 100644 --- a/docs/registries/error-codes.yaml +++ b/docs/registries/error-codes.yaml @@ -380,6 +380,21 @@ errors: compatibility_impact: none required_test: contract-verification:rate-limit + # source: 2026-11-12 리뷰 결정 ② — 서버 포화(허가 상한, 꽉 찬 work pool)는 전송마다 다른 코드였다(web-advanced + # ADMISSION_REFUSED 503, fileserver TRANSFER_ADMISSION_REJECTED 429, gRPC RATE_LIMIT_EXCEEDED). 이 코드 하나로 모은다. + # 호출자 자신의 빈도·동시성 초과만 429(RATE_LIMIT_EXCEEDED, fileserver TRANSFER_ADMISSION_REJECTED)다. + - code: SERVER_BUSY + category: TRANSIENT_DEPENDENCY + http_status: 503 + retryable: true + retry_after_seconds: 1 + owner_branch: 2026-11-12-round9-review + owner_layer: presentation + client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." + runbook_link: "runbook://server/busy" + compatibility_impact: behavior-change + required_test: contract-verification:server-saturation + # 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)은 조회 엔드포인트가 없어 폐기. # 값 하나: IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER. processing-lease가 이 값 이하면 기동 실패(재리뷰 RR-02-05). diff --git a/docs/runbooks/server-busy.md b/docs/runbooks/server-busy.md new file mode 100644 index 00000000..cc3e2513 --- /dev/null +++ b/docs/runbooks/server-busy.md @@ -0,0 +1,46 @@ +--- +title: Runbook — 서버 포화(SERVER_BUSY) +category: TRANSIENT_DEPENDENCY +error_codes: [SERVER_BUSY] +severity: P2 +owner: oncall +last_updated: 2026-11-13 +status: 운영 +--- + +# Runbook: 서버 포화 (`runbook://server/busy`) + +이 instance가 요청을 더 받을 자리가 없어 바로 거절했다. 호출자의 빈도 초과(`RATE_LIMIT_EXCEEDED` 429)와 다르다. 이 +코드는 서버 쪽 상한이 찼다는 뜻이다. + +## 증상 + +- HTTP `503`과 `error.code = SERVER_BUSY`, `Retry-After: 1`. gRPC는 `UNAVAILABLE`와 trailer `error-code: SERVER_BUSY`. +- `http_server_requests_seconds_count{status="503"}`이 오르고, 같은 때 p95 지연은 오르지 않는다. 거절은 일을 하기 전에 + 나기 때문이다. +- 이 코드를 내는 곳은 셋이다. + +| 내는 곳 | 찬 상한 | 설정 | +| --- | --- | --- | +| web-advanced `VirtualThreadAdmissionFilter` | 동시에 처리하는 요청 수 | `app.web.advanced.mvc-virtual-threads.admission-limit` | +| fileserver 전송 허가 | instance 전체 업로드·직접 다운로드 permit, 전송 worker pool | `app.fileserver-platform.quota.instance-upload-permits`, `…direct-download-permits` | +| gRPC `GrpcCallAdmission` | feature 호출 worker와 대기열 | `app.grpc.server.executor-max-pool-size`, `executor-queue-capacity` | + +## 진단 + +1. 거절이 한 instance에만 몰리는지 본다. 한 instance만이면 부하 분산이 고르지 않거나 그 instance의 하류가 느리다. +2. 같은 때 하류 지연(DB pool 대기, 외부 HTTP 지연)을 본다. 하류가 느리면 허가를 쥔 요청이 오래 머물러 상한이 찬다. + 이때 상한을 올리면 하류 pool 앞의 줄만 길어진다. +3. 정상 부하에서 상한 자체가 작은지 본다. 거절률이 트래픽에 비례하고 하류가 건강하면 상한이 작다. + +## 조치 + +- 하류가 느린 경우: 하류 runbook(`db-unavailable`, `dependency-timeout`)을 먼저 따른다. 상한은 그대로 둔다. +- 상한이 작은 경우: instance를 늘리거나 위 표의 설정을 올린다. virtual thread `admission-limit`은 DB pool과 외부 + bulkhead를 넘지 않게 둔다(`docs/web/virtual-thread-profile.md`). +- client는 `Retry-After` 뒤에 같은 요청을 다시 보낸다. 고칠 것이 없으면 거절은 1초 안에 풀린다. + +## 에스컬레이션 + +- 5분 넘게 거절률이 전체 요청의 5%를 넘으면 P1으로 올리고 인프라 당번을 부른다. +- 모든 instance가 같이 거절하고 하류가 건강하면 용량 문제다. 배포 소유자에게 scale-out을 요청한다. diff --git a/docs/upgrade/2026-11-round9-contracts.md b/docs/upgrade/2026-11-round9-contracts.md index 8f89e0c3..5731f75c 100644 --- a/docs/upgrade/2026-11-round9-contracts.md +++ b/docs/upgrade/2026-11-round9-contracts.md @@ -16,4 +16,13 @@ | 2 | patch 거부를 읽는 client는 `PATCH_REJECTED`(400) 하나로 본다. 전에는 JSON이 아닌 본문이 `500 INTERNAL_ERROR`, 빈 문서·연산 모양 오류·merge 깊이 초과가 `400 BAD_PARAMETER`, 너무 깊은 pointer가 `403 PATCH_PATH_FORBIDDEN`이었다 | client가 옛 코드로 분기하던 곳이 다른 코드를 받는다 | patch route를 둔 서비스와 그 client | | 3 | patch 결과가 Bean Validation 제약을 어기면 `400 VALIDATION_FAILED`와 필드별 `details`가 나간다. patch 대상 타입의 제약을 확인한다 | 전에는 제약을 어긴 객체가 그대로 저장 경로로 갔다 | web-advanced patch를 쓰는 서비스 | | 4 | 스트림 `Failure` 기록의 `code`가 실패의 코드(예: `STREAM_ITEM_TOO_LARGE`) 또는 `INTERNAL_ERROR`다. `DEPENDENCY_FAILURE`로 분기하던 client를 고친다 | 그 분기가 다시는 맞지 않는다 | NDJSON·JSON-seq stream을 읽는 client | -| 5 | virtual thread profile을 켠 배포는 이제 실제로 허가 상한을 건다. `admission-limit`이 부하에 맞는지 본다 | 전에는 상한이 없어 모든 요청이 들어왔다. 이제 넘치면 `503 ADMISSION_REFUSED`와 `Retry-After: 1`이다 | `app.web.advanced.mvc-virtual-threads.enabled=true`인 배포 | +| 5 | virtual thread profile을 켠 배포는 이제 실제로 허가 상한을 건다. `admission-limit`이 부하에 맞는지 본다 | 전에는 상한이 없어 모든 요청이 들어왔다. 이제 넘치면 `503 SERVER_BUSY`와 `Retry-After: 1`이다 | `app.web.advanced.mvc-virtual-threads.enabled=true`인 배포 | +| 6 | fileserver batch(`POST /v1/files:batch`)를 읽는 client는 `success`로 가른다. 모두 성공하면 `success: true`와 최상위 `results[]`, 하나라도 실패하면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`, part별 `error.details[]`(`index`, `status`, `id`, `code`, `message`)다 | 전에는 실패가 있어도 `success: true`이고 결과가 `data.results[]`에 있었다. 옛 경로로 읽던 client는 결과를 못 찾는다 | fileserver를 쓰는 서비스와 그 client | +| 7 | `BulkItemResult.error(index, code, message)`를 부르던 코드를 `BulkItemResult.error(index, ApiErrorCode)`로 바꾼다. 문구는 code의 category 고정 문구가 된다 | 컴파일이 실패한다 | bulk endpoint를 둔 서비스 | +| 8 | 서버 포화 거절을 읽는 client는 `SERVER_BUSY`(503, retryable, `Retry-After: 1`)로 본다. web-advanced `ADMISSION_REFUSED`, fileserver instance·전송 pool 포화의 `TRANSFER_ADMISSION_REJECTED`(429), gRPC 포화의 `RESOURCE_EXHAUSTED`/`RATE_LIMIT_EXCEEDED`가 이 코드로 바뀌었다(gRPC status는 `UNAVAILABLE`). 호출자 자신의 동시 전송 초과만 `TRANSFER_ADMISSION_REJECTED` 429로 남는다 | 옛 코드로 분기하던 재시도 로직이 맞지 않는다. 자바에서 `WebAdvancedError.ADMISSION_REFUSED`를 참조하던 코드는 컴파일이 실패한다 | 세 전송의 client, web-advanced 코드를 참조하던 서비스 | +| 9 | 컨테이너가 넘긴 503(필터의 `sendError(503)` 등)은 `SERVER_BUSY`다. 비동기 요청 시간 초과만 `REQUEST_TIMEOUT`이다 | 전에는 모든 503이 `REQUEST_TIMEOUT`이었다 | web을 쓰는 모든 서비스의 client | +| 10 | 알림 template 게시 경로를 `/notification-templates`에서 `/notificationTemplates`로 바꾼다(prefix 뒤) | 옛 경로는 404다 | 알림 template을 게시하는 client와 배포 스크립트 | +| 11 | 알림 제출·template 게시의 모르는 `channel`·`slot`·`locale`·`fallbackLocale`은 `400 VALIDATION_FAILED`와 그 필드를 짚는 `details`다(전에는 details 없는 `BAD_PARAMETER`) | `BAD_PARAMETER`로 분기하던 client가 다른 코드를 받는다 | 알림 HTTP client | +| 12 | 이름 없이 올린 파일의 표시 이름이 `upload.bin`에서 `file`이 된다(모든 전송에서 같다) | 표시 이름이 바뀐다. 동작은 같다 | fileserver를 쓰는 서비스 | +| 13 | fileserver `ATOMIC_PUBLISH_UNSUPPORTED`(재시도 불가 code)는 더 이상 `Retry-After`를 싣지 않는다. 본문 `retryable=false`와 맞춘 것이다 | 그 헤더로 재시도하던 client가 재시도하지 않는다(원래 재시도해도 소용없는 실패다) | fileserver client | +| 14 | 브라우저 client는 `Content-Range`를 읽을 수 있다(CORS 노출 목록에 더함) | — 더하기만 한 변경 | fileserver 다운로드를 이어 받는 브라우저 client | diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index 1f66a154..4b324818 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -177,7 +177,7 @@ CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의 `traceparent`, `Location`, `ETag`, `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` - fileserver를 실은 배포: `Tus-Resumable`, `Tus-Version`, `Tus-Extension`, `Tus-Max-Size`, `Upload-Offset`, `Upload-Length`, `Upload-Defer-Length`, `Upload-Expires`, `Upload-Complete`, - `Upload-Limit`, `Content-Disposition`, `Accept-Ranges` + `Upload-Limit`, `Content-Disposition`, `Accept-Ranges`, `Content-Range` 새 응답 헤더를 쓰는 모듈은 `CorsExposedHeaders` bean으로 자기 헤더를 기여한다. @@ -187,15 +187,18 @@ CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의 | 코드 | status | category | `retryable` | `Retry-After` | 언제 | | --- | --- | --- | --- | --- | --- | -| `REQUEST_TIMEOUT` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 없음 | 비동기 요청(`Callable`·`DeferredResult`·스트리밍)이 시간 안에 끝나지 않았다. GraphQL도 같은 이름을 쓰지만 그쪽 `category`는 GraphQL 전용 어휘 `TIMEOUT`이다(`src/adapter/inbound/graphql/README.md`) | +| `REQUEST_TIMEOUT` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 없음 | 비동기 요청(`Callable`·`DeferredResult`·스트리밍)이 시간 안에 끝나지 않았다. 그 밖의 503(필터의 `sendError(503)` 등)은 공용 `SERVER_BUSY`다. GraphQL도 같은 이름을 쓰지만 그쪽 `category`는 GraphQL 전용 어휘 `TIMEOUT`이다(`src/adapter/inbound/graphql/README.md`) | | `IDEMPOTENCY_KEY_INVALID` | 400 | `VALIDATION` | `false` | 없음 | 2절 | | `RATE_LIMIT_UNAVAILABLE` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 있음 | rate-limit 저장소 응답 없음(`docs/web/runbook.md`) | | `RATE_LIMIT_INCOMPATIBLE` | 503 | `INTERNAL` | `false` | 없음 | rate-limit 제공자가 계약과 맞지 않음 | +| `OPERATION_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | durable operation 조회(`DurableOperationController`)에서 그 operation이 없거나 다른 호출자의 것이다. 둘을 가르지 않는다 | - 컨트롤러 파라미터 제약 위반(`@RequestParam @Max(10)`)은 요청 본문 위반과 같은 `400 VALIDATION_FAILED`이고 `details`는 `[{field, code, message}]`다. 거절된 값은 싣지 않는다. -- web-advanced를 실은 서비스의 예외 코드(`ADMISSION_REFUSED` 503 등 10종)는 +- web-advanced를 실은 서비스의 예외 코드(`PATCH_REJECTED` 400 등)는 `src/adapter/inbound/web-advanced/README.md` 「오류 응답」이 정본이다. +- 서버 포화(허가 상한, 꽉 찬 work pool)는 모든 전송이 공용 `SERVER_BUSY`(503, retryable, `Retry-After: 1`) + 하나로 답한다. 호출자 자신의 빈도 초과만 `RATE_LIMIT_EXCEEDED` 429다(`docs/registries/error-codes.yaml`). - 직접 쓰는 거부 응답(401·403·429·503)도 컨트롤러 응답과 같이 `application/json;charset=UTF-8`이다. ## 5. 바꿀 때 diff --git a/docs/web/virtual-thread-profile.md b/docs/web/virtual-thread-profile.md index 610ea717..94522c31 100644 --- a/docs/web/virtual-thread-profile.md +++ b/docs/web/virtual-thread-profile.md @@ -40,7 +40,7 @@ thread로 얻은 것을 버리게 된다. virtual thread 만 개가 있어도 아무 일도 하지 않는다. async 요청은 async 일이 끝날 때까지 허가를 쥔다. 넘겨준 순간 돌려주면 넘기는 일만 제한하고 정작 하류 pool을 쓰는 일은 제한하지 못한다. -거부는 **`Retry-After`가 붙은 503**(`ADMISSION_REFUSED`)이고, 상한이 만들려는 결과가 바로 그것이다. 1밀리초 만에 거부된 요청이, 받아들여진 뒤 +거부는 **`Retry-After`가 붙은 503**(공용 코드 `SERVER_BUSY`)이고, 상한이 만들려는 결과가 바로 그것이다. 1밀리초 만에 거부된 요청이, 받아들여진 뒤 가득 찬 pool 뒤에서 30초 뒤에 시간 초과가 난 같은 요청보다 client에게 확실히 낫다. semaphore는 일부러 공정하다. 불공정한 것이 빠르지만, 새로 온 요청이 기다리던 요청을 앞지르게 두고, 앞지름당한 diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index db1f8aa0..3345f10a 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -116,6 +116,9 @@ | GraphQL 인자 변환 실패 | Spring GraphQL 인자 binder의 `BindException`(`@Argument` 값이 파라미터 타입으로 바뀌지 않음)은 `BAD_PARAMETER`(`REQUEST`)로 답하고, WARN 한 줄(예외 타입만, 입력값 없음)을 남긴다. web이 바뀌지 않는 경로 변수에 답하는 것과 같다 | 소유자 | 2026-11-07 같은 전달, r8-f1 보고 「범위 밖」 2 | | 약속한 응답으로 맞추기 | 레지스트리·`docs/web/http-contract.md`·Javadoc이 이미 약속한 응답으로 코드를 맞추는 것은 결함 수정이다. 고치기 전에 묻지 않고, 응답이 바뀌니 업그레이드 안내 행은 적는다. 약속한 곳끼리 다르면 묻는다 | 소유자(2026-11-07, 기본값 확인) | `docs/work/improve.md` 7절, `docs/work/evidence.md` 11절 | | STOMP 필수 header 누락 | 필수 header·destination 변수가 없을 때 Spring이 던지는 `MessageHandlingException`은 ERROR 그대로 둔다. 메시지에 입력값이 없고, Spring이 같은 타입으로 서버 실패(handler의 `Error` 등)도 감싸서 타입만으로는 클라이언트 탓을 가를 수 없다 | 기본값(2026-11-07) | 2026-11-07 총괄 지시, r8-f1 보고 「범위 밖」 3 | +| 서버 포화 코드 | 서버 쪽 상한(요청 허가, 꽉 찬 work pool)이 찬 거절은 모든 전송이 공용 `SERVER_BUSY`(503, `TRANSIENT_DEPENDENCY`, retryable, `Retry-After: 1`) 하나다. 호출자 자신의 빈도·동시성 초과만 429(`RATE_LIMIT_EXCEEDED`, fileserver `TRANSFER_ADMISSION_REJECTED`)다. 상태만 아는 503도 `SERVER_BUSY`이고, 비동기 요청 시간 초과만 `REQUEST_TIMEOUT`이다 | 기본값(2026-11-12, 소유자가 뒤집을 수 있다) | 2026-11-12 전체 리뷰 기록 README 6절 ② | +| batch 부분 실패 | fileserver batch도 공용 bulk envelope(web AGENTS B8)다. 하나라도 실패하면 `success:false` + `BATCH_PARTIAL_FAILURE` + 항목별 `details` | 기본값(2026-11-12) | 같은 README 6절 ① | +| PATCH 정본 | `docs/web/patch-contract.md`가 merge patch·JSON Patch의 정본이다. web AGENTS B2는 `application/json` PATCH DTO만 다루고 그쪽을 가리킨다 | 기본값(2026-11-12) | 같은 README 6절 ③ | ### 2.4 멱등성 diff --git a/src/adapter/inbound/graphql/build.gradle b/src/adapter/inbound/graphql/build.gradle index 53bbe3a2..1f2b622b 100644 --- a/src/adapter/inbound/graphql/build.gradle +++ b/src/adapter/inbound/graphql/build.gradle @@ -139,17 +139,17 @@ strictTestLanes { // be. // // A snapshot does not shrink the surface. It makes each addition visible in review, which is the -// prerequisite for shrinking it: the `api` and `spi` packages are the surface an adopter is meant -// to use, and everything else in this file is a candidate for becoming internal when the leaf is -// split into capability artifacts. Until then the number cannot grow by accident. +// prerequisite for shrinking it: the `api` package is the surface an adopter is meant to use, and +// everything else in this file is a candidate for becoming internal when the leaf is split into +// capability artifacts. Until then the number cannot grow by accident. apiSurface { label = 'GraphQl' baseline = rootProject.file('docs/architecture/graphql-api-surface.txt') description = 'GraphQL leaf public API surface — every public top-level type in src/main/java.' rationale = [ 'A public type in a single-jar leaf is reachable from every adopter\'s code, so', - 'additions are reviewed rather than discovered. `api` and `spi` are the intended', - 'external surface; the rest are candidates to become internal when this leaf is', - 'split into capability artifacts.', + 'additions are reviewed rather than discovered. `api` is the intended external', + 'surface; the rest are candidates to become internal when this leaf is split into', + 'capability artifacts.', ] } diff --git a/src/adapter/inbound/grpc/README.md b/src/adapter/inbound/grpc/README.md index e713d0cf..19eccf2a 100644 --- a/src/adapter/inbound/grpc/README.md +++ b/src/adapter/inbound/grpc/README.md @@ -94,7 +94,8 @@ executor, 서버 deadline 없음, 연결 수명 무제한이다. 어댑터 서 health/reflection 에는 적용하지 않는다(`Health/Watch` 는 원래 오래 사는 스트림이다). - **포화 시 동작(`GrpcCallAdmission`).** feature 호출은 `executor-max-pool-size + executor-queue-capacity` 개까지만 받고, 넘친 호출은 handler 를 시작하지 않고 즉시 - `RESOURCE_EXHAUSTED`(`RATE_LIMIT_EXCEEDED`, retryable)로 닫는다. 구현: io.grpc + `UNAVAILABLE`(`SERVER_BUSY`, retryable)로 닫는다. 서버 포화는 모든 전송이 이 공용 코드 하나다(2026-11-12 전에는 + `RESOURCE_EXHAUSTED`/`RATE_LIMIT_EXCEEDED`였다). 구현: io.grpc `ServerCallExecutorSupplier`(`@ExperimentalApi`, 1.39부터)가 호출 시작 전에 permit 을 확인해 받은 호출만 고정 크기 work pool 로 옮기고, 못 받은 호출은 가장 바깥 인터셉터가 닫는다. 메서드 조회·context 정리·health·reflection 은 작은 dispatch pool 에서 돈다. 버린 대안: diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCallAdmission.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCallAdmission.java index 1a8c8b77..f86c4012 100644 --- a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCallAdmission.java +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCallAdmission.java @@ -28,9 +28,11 @@ import java.util.concurrent.atomic.AtomicBoolean; * dispatch executor, before the call starts. A feature call that gets a permit is moved to the * bounded work pool; one that does not stays on the dispatch executor and is marked, and this same * object, installed as the outermost feature interceptor, closes the marked call with {@code - * RATE_LIMIT_EXCEEDED} without starting the handler. The permit is returned once, when the admitted - * call completes or is cancelled. Health and reflection are not feature calls: they take no permit - * and run on the dispatch executor, so a saturated pool cannot make health lie. + * SERVER_BUSY} ({@code UNAVAILABLE}) without starting the handler: the shared code every transport + * answers server saturation with, not the caller-rate {@code RATE_LIMIT_EXCEEDED} it used to be. + * The permit is returned once, when the admitted call completes or is cancelled. Health and + * reflection are not feature calls: they take no permit and run on the dispatch executor, so a + * saturated pool cannot make health lie. * *

Each admitted call has at most one task in the work pool at a time (io.grpc serializes a * call's callbacks), so a work queue as deep as the permit count can never reject. @@ -79,8 +81,8 @@ final class GrpcCallAdmission implements ServerCallExecutorSupplier, ServerInter ServerCall call, Metadata headers, ServerCallHandler next) { if (refused.remove(headers)) { call.close( - statusMapper.statusFor(OperationalError.RATE_LIMIT_EXCEEDED), - statusMapper.trailersFor(OperationalError.RATE_LIMIT_EXCEEDED)); + statusMapper.statusFor(OperationalError.SERVER_BUSY), + statusMapper.trailersFor(OperationalError.SERVER_BUSY)); return new ServerCall.Listener<>() {}; } AtomicBoolean released = new AtomicBoolean(); diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcStatusMapper.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcStatusMapper.java index 1fa5c57a..0e7b1b36 100644 --- a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcStatusMapper.java +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcStatusMapper.java @@ -17,9 +17,7 @@ import io.grpc.Status; */ public class GrpcStatusMapper { - /** - * Trailer key carrying the stable {@link ApiErrorCode#code()} (e.g. {@code WORKLOG_NOT_FOUND}). - */ + /** Trailer key carrying the stable {@link ApiErrorCode#code()} (e.g. {@code SERVER_BUSY}). */ static final Metadata.Key CODE_KEY = Metadata.Key.of("error-code", Metadata.ASCII_STRING_MARSHALLER); diff --git a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcP1BoundaryWireTest.java b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcP1BoundaryWireTest.java index 97fd4735..cbd20d75 100644 --- a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcP1BoundaryWireTest.java +++ b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcP1BoundaryWireTest.java @@ -329,8 +329,8 @@ class GrpcP1BoundaryWireTest { } @Test - @DisplayName("스레드와 대기열이 모두 찬 서버는 넘친 호출을 기다리게 두지 않고 즉시 RESOURCE_EXHAUSTED로 거절한다") - void aCallBeyondTheExecutorAndQueueIsRefusedAtOnceAsResourceExhausted() { + @DisplayName("스레드와 대기열이 모두 찬 서버는 넘친 호출을 기다리게 두지 않고 즉시 UNAVAILABLE(SERVER_BUSY)로 거절한다") + void aCallBeyondTheExecutorAndQueueIsRefusedAtOnceAsServerBusy() { withChannel( contextRunner.withPropertyValues( "app.grpc.server.executor-max-pool-size=1", @@ -351,12 +351,11 @@ class GrpcP1BoundaryWireTest { // then assertThat(outcomes) .extracting(Status::getCode) - .containsExactlyInAnyOrder( - Status.Code.OK, Status.Code.OK, Status.Code.RESOURCE_EXHAUSTED); + .containsExactlyInAnyOrder(Status.Code.OK, Status.Code.OK, Status.Code.UNAVAILABLE); assertThat(outcomes) .filteredOn(status -> !status.isOk()) .extracting(Status::getDescription) - .containsExactly(ClientErrorMessages.of(Category.RATE_LIMIT)); + .containsExactly(ClientErrorMessages.of(Category.TRANSIENT_DEPENDENCY)); }); } diff --git a/src/adapter/inbound/web-advanced/README.md b/src/adapter/inbound/web-advanced/README.md index 34f7c59c..9ae11896 100644 --- a/src/adapter/inbound/web-advanced/README.md +++ b/src/adapter/inbound/web-advanced/README.md @@ -51,12 +51,12 @@ virtual thread 실행기는 `TaskDecorator` bean 을 요구한다(요청 상관 이 leaf 의 예외는 모두 `ApiErrorCarrier` 다. 코드는 `error.WebAdvancedError` 한 enum 이 정하고, web 의 `GlobalExceptionHandler.handleCarrier` 한 분기가 Envelope 로 답한다(별도 `@RestControllerAdvice` 없음). -예전에는 10종 모두 `500 INTERNAL_ERROR` 였다(리뷰 2026-11-01 02-07). 아래 표와 enum 은 같은 값을 말하고, +예전에는 10종 모두 `500 INTERNAL_ERROR` 였다(리뷰 2026-11-01 02-07). admission 거절은 2026-11-12부터 공용 `SERVER_BUSY`다. 아래 표와 enum 은 같은 값을 말하고, `WebAdvancedErrorMappingTest` 가 실제 응답으로 확인한다. | 예외 | `error.code` | status | category | retryable | 응답에 더 실리는 것 | 클라이언트 행동 | | --- | --- | --- | --- | --- | --- | --- | -| `AdmissionRefusedException` | `ADMISSION_REFUSED` | 503 | `TRANSIENT_DEPENDENCY` | true | `Retry-After: 1` | 잠시 뒤 같은 요청 | +| `AdmissionRefusedException` | `SERVER_BUSY`(공용 `OperationalError`) | 503 | `TRANSIENT_DEPENDENCY` | true | `Retry-After: 1` | 잠시 뒤 같은 요청. 서버 포화는 모든 전송이 이 코드 하나다 | | `JsonPatchTestFailedException` | `PATCH_TEST_FAILED` | 409 | `CONFLICT` | false | `details.pointer`(서버 값은 없음) | 다시 읽고 새 patch | | `JsonPatchRejectedException` | `PATCH_REJECTED` | 400 | `VALIDATION` | false | — | patch 문서를 고친다. JSON이 아닌 본문, 빈 문서, 한도·깊이 초과, 연산 모양 오류, 결과가 자원 타입으로 읽히지 않는 patch가 모두 이 코드다 | | `PatchAuthorizationException` | `PATCH_PATH_FORBIDDEN` | 403 | `AUTHZ` | false | `details.refusedPaths` | 해당 경로를 빼거나 권한 확보 | diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedError.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedError.java index 7729b0f0..d6ef5439 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedError.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedError.java @@ -11,16 +11,14 @@ import dev.caskeleton.shared.error.Category; * leaf README's "오류 응답" section; it states the same values. * *

Before this existed every one of these reached the client as {@code 500 INTERNAL_ERROR} with - * an ERROR log line, including an admission refusal the profile documents as a 503 (review - * 2026-11-01 02-07). + * an ERROR log line (review 2026-11-01 02-07). The admission refusal it used to name is now the + * shared {@code OperationalError.SERVER_BUSY} (review 2026-11-12). * *

Like {@code RateLimitTransportError}, these are not in {@code * docs/registries/error-codes.yaml}, which is the {@code OperationalError} SSOT. */ public enum WebAdvancedError implements ApiErrorCode, RetryAfterHint { - /** The virtual-thread admission limit was full. A refusal in a millisecond; come back shortly. */ - ADMISSION_REFUSED(Category.TRANSIENT_DEPENDENCY, 503, true, 1), /** A JSON Patch {@code test} did not hold; nothing was applied. Re-read, then retry. */ PATCH_TEST_FAILED(Category.CONFLICT, 409, false, 0), /** The patch document is malformed or over a limit; nothing was applied. */ diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java index 49092b59..d0634a5e 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java @@ -29,8 +29,8 @@ import java.util.Objects; * or a rewind it would apply. * *

What this writer does not do: it writes synchronously from an iterator on the request thread, - * so it sends no heartbeat while the source is blocked, enforces no idle timeout or maximum age, and - * keeps no buffer (a slow consumer blocks the source instead). Those bounds are in {@code + * so it sends no heartbeat while the source is blocked, enforces no idle timeout or maximum age, + * and keeps no buffer (a slow consumer blocks the source instead). Those bounds are in {@code * WebStreamPolicy} and the drain in {@code WebStreamDrainCoordinator} for a service that runs its * streams through {@code WebStreamRegistry}; {@code docs/web/streaming-contract.md} says which. * diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java index ee5c9c17..9a4c6914 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java @@ -4,7 +4,7 @@ import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.AdmissionRefuse import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadAdmissionGuard; import dev.caskeleton.adapter.inbound.web.error.EnvelopeResponseWriter; import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; -import dev.caskeleton.adapter.inbound.web.observability.RetryAfterHint; +import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor; import jakarta.servlet.AsyncEvent; import jakarta.servlet.AsyncListener; import jakarta.servlet.FilterChain; @@ -26,8 +26,8 @@ import tools.jackson.databind.ObjectMapper; * security chain, and refuses before any of it runs. * *

A request that goes async keeps its permit until the async work ends: releasing when this - * thread returns would bound only the hand-off, and the work the limit protects the downstream pools - * from happens after it. + * thread returns would bound only the hand-off, and the work the limit protects the downstream + * pools from happens after it. */ public final class VirtualThreadAdmissionFilter extends OncePerRequestFilter implements Ordered { @@ -37,7 +37,8 @@ public final class VirtualThreadAdmissionFilter extends OncePerRequestFilter imp private final VirtualThreadAdmissionGuard guard; private final ObjectMapper objectMapper; - public VirtualThreadAdmissionFilter(VirtualThreadAdmissionGuard guard, ObjectMapper objectMapper) { + public VirtualThreadAdmissionFilter( + VirtualThreadAdmissionGuard guard, ObjectMapper objectMapper) { this.guard = Objects.requireNonNull(guard, "guard"); this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); } @@ -55,9 +56,9 @@ public final class VirtualThreadAdmissionFilter extends OncePerRequestFilter imp try { permit = guard.enter(); } catch (AdmissionRefusedException refused) { - if (refused.errorCode() instanceof RetryAfterHint hint) { - response.setHeader(ApiHeaders.RETRY_AFTER, Integer.toString(hint.retryAfterSeconds())); - } + RetryAfterAdvisor.retryAfterSeconds(refused.errorCode()) + .ifPresent( + seconds -> response.setHeader(ApiHeaders.RETRY_AFTER, Integer.toString(seconds))); EnvelopeResponseWriter.write(response, refused.errorCode(), objectMapper); return; } catch (InterruptedException interrupted) { diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java index 36912a06..aa75b2d0 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java @@ -1,8 +1,8 @@ package dev.caskeleton.adapter.inbound.web.advanced.virtualthread; -import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError; import dev.caskeleton.shared.error.ApiErrorCarrier; import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.OperationalError; /** * An arrival was refused because the concurrency limit was full. @@ -27,9 +27,12 @@ public final class AdmissionRefusedException extends RuntimeException implements return limit; } - /** {@link WebAdvancedError#ADMISSION_REFUSED}; see the leaf README for the client contract. */ + /** + * {@link OperationalError#SERVER_BUSY}, the one code every transport answers server saturation + * with; see the leaf README for the client contract. + */ @Override public ApiErrorCode errorCode() { - return WebAdvancedError.ADMISSION_REFUSED; + return OperationalError.SERVER_BUSY; } } diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedErrorMappingTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedErrorMappingTest.java index 6e810ebf..f2e85e17 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedErrorMappingTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedErrorMappingTest.java @@ -62,7 +62,7 @@ class WebAdvancedErrorMappingTest { static Stream documentedMappings() { return Stream.of( - Arguments.of("admission", 503, "ADMISSION_REFUSED", "TRANSIENT_DEPENDENCY", true), + Arguments.of("admission", 503, "SERVER_BUSY", "TRANSIENT_DEPENDENCY", true), Arguments.of("patch-test", 409, "PATCH_TEST_FAILED", "CONFLICT", false), Arguments.of("patch-rejected", 400, "PATCH_REJECTED", "VALIDATION", false), Arguments.of("patch-forbidden", 403, "PATCH_PATH_FORBIDDEN", "AUTHZ", false), diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java index 47b1434a..a5c10cd1 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java @@ -12,12 +12,17 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import tools.jackson.databind.json.JsonMapper; -/** The request path through the admission guard. */ +/** + * The request path through the admission guard. + * + *

required_test: {@code contract-verification:server-saturation} — a full limit answers the + * shared {@code SERVER_BUSY} 503 with {@code Retry-After}, before any handler runs. + */ @Tag("web-advanced") class VirtualThreadAdmissionFilterTest { @Test - @DisplayName("한도가 차면 요청은 controller에 닿지 않고 503 ADMISSION_REFUSED와 Retry-After를 받는다") + @DisplayName("한도가 차면 요청은 controller에 닿지 않고 503 SERVER_BUSY와 Retry-After를 받는다") void aFullLimitRefusesWith503AndRetryAfter() throws Exception { // given VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO); @@ -38,7 +43,7 @@ class VirtualThreadAdmissionFilterTest { assertThat(reached).as("the guard was a bean nothing called").hasValue(0); assertThat(response.getStatus()).isEqualTo(503); assertThat(response.getHeader("Retry-After")).isEqualTo("1"); - assertThat(response.getContentAsString()).contains("ADMISSION_REFUSED"); + assertThat(response.getContentAsString()).contains("SERVER_BUSY"); assertThat(guard.rejectedCount()).isEqualTo(1); } diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java index c50838c0..55b02e60 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java @@ -269,8 +269,7 @@ class JsonPatchApplierTest { // when Throwable thrown = - catchThrowable( - () -> applier("/displayName").apply(profile(), document, Profile.class)); + catchThrowable(() -> applier("/displayName").apply(profile(), document, Profile.class)); // then assertThat(thrown).isInstanceOf(JsonPatchRejectedException.class); @@ -285,8 +284,7 @@ class JsonPatchApplierTest { // when Throwable thrown = - catchThrowable( - () -> applier("/version").apply(profile(), document, Profile.class)); + catchThrowable(() -> applier("/version").apply(profile(), document, Profile.class)); // then assertThat(thrown).isInstanceOf(JsonPatchRejectedException.class); diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutor.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutor.java index 8b3516b3..17eb4410 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutor.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutor.java @@ -58,7 +58,7 @@ public final class BlockingTransferExecutor { throw new FileserverException( "transfer pool is saturated", rejected, - FileserverFailureContext.of(FileserverErrorCode.TRANSFER_ADMISSION_REJECTED, true)); + FileserverFailureContext.of(FileserverErrorCode.SERVER_BUSY, true)); } try { return future.get(awaitSeconds, TimeUnit.SECONDS); diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java index bbc0d182..1a6ad304 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java @@ -30,8 +30,8 @@ public final class FileserverProblemHeaders { private static final Map RETRY_AFTER_SECONDS = Map.of( FileserverErrorCode.TRANSFER_ADMISSION_REJECTED, 1, + FileserverErrorCode.SERVER_BUSY, 1, FileserverErrorCode.STORAGE_UNAVAILABLE, 30, - FileserverErrorCode.ATOMIC_PUBLISH_UNSUPPORTED, 30, FileserverErrorCode.TRANSFER_TIMEOUT, 5, FileserverErrorCode.FILE_NOT_READY, 2, FileserverErrorCode.CONCURRENT_MODIFICATION, 1); @@ -47,8 +47,10 @@ public final class FileserverProblemHeaders { Map headers = new LinkedHashMap<>(); Integer retryAfter = RETRY_AFTER_SECONDS.get(failure.code()); // Only a failure the server itself called retryable advertises a retry: telling a client to - // come back after a permanent rejection is worse than saying nothing. - if (retryAfter != null && failure.context().retryable()) { + // come back after a permanent rejection is worse than saying nothing. The same narrowing as the + // body (ErrorResponseFactory): the occurrence can only narrow its code, so a code that is never + // retryable never carries the header, whatever the occurrence said (review 2026-11-12). + if (retryAfter != null && failure.code().retryable() && failure.context().retryable()) { headers.put("Retry-After", String.valueOf(retryAfter)); } if (failure instanceof HttpRangeNotSatisfiableException unsatisfiable) { diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/MvcUploadExecutorSaturationTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/MvcUploadExecutorSaturationTest.java index 0a65bcca..4ded8b41 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/MvcUploadExecutorSaturationTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/MvcUploadExecutorSaturationTest.java @@ -23,6 +23,7 @@ class MvcUploadExecutorSaturationTest { BlockingTransferExecutor executor = new BlockingTransferExecutor(pool, bounds.awaitSeconds()); CountDownLatch release = new CountDownLatch(1); AtomicInteger rejections = new AtomicInteger(); + CountDownLatch firstRejection = new CountDownLatch(1); List callers = new ArrayList<>(); for (int index = 0; index < 8; index++) { @@ -34,21 +35,25 @@ class MvcUploadExecutorSaturationTest { } catch (FileserverException failure) { // A caller that outlived the budget (TRANSFER_TIMEOUT) is not a saturation // signal; only an admission rejection is. - if (failure.code() == FileserverErrorCode.TRANSFER_ADMISSION_REJECTED) { + if (failure.code() == FileserverErrorCode.SERVER_BUSY) { rejections.incrementAndGet(); + firstRejection.countDown(); } } }); callers.add(caller); caller.start(); } - Thread.sleep(200); + // Held until the pool has refused someone, rather than for a guessed 200 ms: under load the + // callers may not have arrived yet, and then the release lets every one of them through. + boolean refused = firstRejection.await(10, TimeUnit.SECONDS); release.countDown(); for (Thread caller : callers) { caller.join(TimeUnit.SECONDS.toMillis(10)); } pool.shutdown(); + assertThat(refused).as("a pool of 1 with a queue of 1 refused within the wait").isTrue(); assertThat(rejections.get()) .as("a pool of 1 with a queue of 1 cannot absorb 8 concurrent transfers") .isPositive(); @@ -102,8 +107,7 @@ class MvcUploadExecutorSaturationTest { .satisfies( failure -> { FileserverException rejected = (FileserverException) failure; - assertThat(rejected.code()) - .isEqualTo(FileserverErrorCode.TRANSFER_ADMISSION_REJECTED); + assertThat(rejected.code()).isEqualTo(FileserverErrorCode.SERVER_BUSY); assertThat(rejected.context().retryable()).isTrue(); }); } @@ -115,7 +119,10 @@ class MvcUploadExecutorSaturationTest { BlockingTransferExecutor executor = new BlockingTransferExecutor(pool, bounds.awaitSeconds()); assertThatThrownBy(() -> executor.call(() -> await(new CountDownLatch(1)))) - .isInstanceOf(FileserverException.class); + .isInstanceOf(FileserverException.class) + .extracting(failure -> ((FileserverException) failure).code()) + .as("the overrun is answered as the timeout it is, not as some other transfer failure") + .isEqualTo(FileserverErrorCode.TRANSFER_TIMEOUT); pool.shutdown(); } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java index 22563880..ee70d0fe 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java @@ -412,7 +412,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { return null; } } - ApiErrorCode code = HttpStatusErrorCodes.forStatus(statusCode); + ApiErrorCode code = HttpStatusErrorCodes.forException(ex, statusCode); if (code.httpStatus() >= 500) { log.error("spring mvc failure classified as {}", code.code(), ex); spanErrorRecorder.recordException(ex, code.code()); diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/HttpStatusErrorCodes.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/HttpStatusErrorCodes.java index e37d6948..47ae06a8 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/HttpStatusErrorCodes.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/HttpStatusErrorCodes.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.error; import dev.caskeleton.shared.error.ApiErrorCode; import dev.caskeleton.shared.error.OperationalError; import org.springframework.http.HttpStatusCode; +import org.springframework.web.context.request.async.AsyncRequestTimeoutException; /** * The operational code a bare HTTP status stands for, when a status is all that is known. @@ -15,6 +16,17 @@ final class HttpStatusErrorCodes { private HttpStatusErrorCodes() {} + /** + * The code for a Spring MVC exception that carries only a status. An async request timeout is + * {@code REQUEST_TIMEOUT}; anything else is classified by its status. + */ + static ApiErrorCode forException(Exception failure, HttpStatusCode status) { + if (failure instanceof AsyncRequestTimeoutException) { + return WebTransportError.REQUEST_TIMEOUT; + } + return forStatus(status); + } + static ApiErrorCode forStatus(HttpStatusCode status) { return switch (status.value()) { case 401 -> OperationalError.UNAUTHENTICATED; @@ -27,8 +39,10 @@ final class HttpStatusErrorCodes { case 414 -> OperationalError.URI_TOO_LONG; case 415 -> OperationalError.UNSUPPORTED_MEDIA_TYPE; case 429 -> OperationalError.RATE_LIMIT_EXCEEDED; - // Spring answers its async request timeout with 503: transient, not an internal fault. - case 503 -> WebTransportError.REQUEST_TIMEOUT; + // A bare 503 is the server saying it cannot serve now (RFC 9110 15.6.4). An async request + // timeout is also a 503, and forException tells it apart; every other one used to be + // labelled REQUEST_TIMEOUT whatever it was (review 2026-11-12). + case 503 -> OperationalError.SERVER_BUSY; default -> status.is4xxClientError() ? OperationalError.BAD_PARAMETER diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java index cdc4aed4..f1a14374 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java @@ -19,6 +19,7 @@ public final class RetryAfterAdvisor { private static final Map RETRY_AFTER_SECONDS = Map.ofEntries( Map.entry("RATE_LIMIT_EXCEEDED", 1), + Map.entry("SERVER_BUSY", 1), // The application's value, which the processing-lease check also reads: the resend // arrives while the first attempt can still finish. docs/web/http-contract.md §2. Map.entry( diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorControllerTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorControllerTest.java index 074f8f8d..436a3bb6 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorControllerTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorControllerTest.java @@ -28,6 +28,7 @@ class EnvelopeErrorControllerTest { "401, 401, UNAUTHENTICATED", "404, 404, ROUTE_NOT_FOUND", "429, 429, RATE_LIMIT_EXCEEDED", + "503, 503, SERVER_BUSY", "409, 400, BAD_PARAMETER", "422, 400, BAD_PARAMETER", "500, 500, INTERNAL_ERROR", diff --git a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java index 24c64ea0..1fe66959 100644 --- a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java +++ b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java @@ -17,10 +17,10 @@ import dev.caskeleton.shared.error.Category; * servlet transport, the reactive transport and the Nginx delegation path cannot answer the same * failure three different ways. * - *

{@code UNAUTHENTICATED}, {@code PRECONDITION_FAILED} and {@code UNSUPPORTED_MEDIA_TYPE} share - * their name with an {@code OperationalError}; they are kept here so the failure context stays one - * enum, and {@code FileserverExceptionTest} pins that each means exactly what the operational code - * means on the wire (category, status, retryability). + *

{@code UNAUTHENTICATED}, {@code PRECONDITION_FAILED}, {@code UNSUPPORTED_MEDIA_TYPE} and + * {@code SERVER_BUSY} share their name with an {@code OperationalError}; they are kept here so the + * failure context stays one enum, and {@code FileserverExceptionTest} pins that each means exactly + * what the operational code means on the wire (category, status, retryability). */ public enum FileserverErrorCode implements ApiErrorCode { BAD_REQUEST(400, Category.VALIDATION, false), @@ -42,6 +42,7 @@ public enum FileserverErrorCode implements ApiErrorCode { MALWARE_DETECTED(422, Category.DATA_INTEGRITY, false), INVALID_PATH(422, Category.VALIDATION, false), PATH_OUTSIDE_NAMESPACE(422, Category.VALIDATION, false), + // The caller's own transfers fill its scope's permits: the caller's rate, so 429. TRANSFER_ADMISSION_REJECTED(429, Category.RATE_LIMIT, true), // tus checksum extension status: one request's bytes did not match the checksum the client sent // for them. The chunk is rolled back before its offset commits, so the upload stays resumable. @@ -52,6 +53,9 @@ public enum FileserverErrorCode implements ApiErrorCode { AMBIGUOUS_COMPLETION(500, Category.DATA_INTEGRITY, false), ATOMIC_PUBLISH_UNSUPPORTED(503, Category.PERMANENT_DEPENDENCY, false), STORAGE_UNAVAILABLE(503, Category.TRANSIENT_DEPENDENCY, true), + // The instance's permits or its transfer pool are full: server saturation, the shared code every + // transport answers it with (decisions 2.3, 2026-11-12). + SERVER_BUSY(503, Category.TRANSIENT_DEPENDENCY, true), TRANSFER_TIMEOUT(504, Category.TRANSIENT_DEPENDENCY, true), STORAGE_FULL(507, Category.TRANSIENT_DEPENDENCY, false); diff --git a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionController.java b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionController.java index d9969dba..b4c28d67 100644 --- a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionController.java +++ b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionController.java @@ -15,9 +15,11 @@ import java.util.concurrent.atomic.AtomicBoolean; * In-process admission control backed by bounded semaphores. * *

The failure vocabulary is deliberately distinct so a client can tell a permanent policy denial - * from a transient one: an exhausted pool is {@code STORAGE_FULL}, and running out of concurrency - * permits — for the caller's scope or for the whole instance — is a retryable admission rejection. - * Stored bytes over a quota ({@code QUOTA_EXCEEDED}) are decided by the quota service, not here. + * from a transient one: an exhausted pool is {@code STORAGE_FULL}; running out of the caller's own + * scope permits is a retryable {@code TRANSFER_ADMISSION_REJECTED} (429, the caller's rate); + * running out of the whole instance's permits is the shared server-saturation {@code SERVER_BUSY} + * (503). Stored bytes over a quota ({@code QUOTA_EXCEEDED}) are decided by the quota service, not + * here. */ public final class TransferAdmissionController { @@ -74,7 +76,7 @@ public final class TransferAdmissionController { scopePermits.release(); throw new FileserverException( "instance upload permits are exhausted", - FileserverFailureContext.of(FileserverErrorCode.TRANSFER_ADMISSION_REJECTED, true)); + FileserverFailureContext.of(FileserverErrorCode.SERVER_BUSY, true)); } return new SemaphorePermit(scopePermits, instanceUploads); } @@ -83,7 +85,7 @@ public final class TransferAdmissionController { if (!directDownloads.tryAcquire()) { throw new FileserverException( "instance direct download permits are exhausted", - FileserverFailureContext.of(FileserverErrorCode.TRANSFER_ADMISSION_REJECTED, true)); + FileserverFailureContext.of(FileserverErrorCode.SERVER_BUSY, true)); } return new SemaphorePermit(directDownloads); } diff --git a/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionControllerTest.java b/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionControllerTest.java index 74a675dc..9c31a867 100644 --- a/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionControllerTest.java +++ b/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionControllerTest.java @@ -119,7 +119,12 @@ class TransferAdmissionControllerTest { assertThatThrownBy(() -> narrow.acquireUpload(scope("tenant-b"), 10)) .isInstanceOf(FileserverException.class) .satisfies( - failure -> assertThat(((FileserverException) failure).context().retryable()).isTrue()); + failure -> { + assertThat(((FileserverException) failure).context().retryable()).isTrue(); + assertThat(((FileserverException) failure).context().code()) + .as("the whole instance is full: server saturation, not the caller's rate") + .isEqualTo(FileserverErrorCode.SERVER_BUSY); + }); held.close(); TransferPermit afterRelease = narrow.acquireUpload(scope("tenant-b"), 10); @@ -197,7 +202,9 @@ class TransferAdmissionControllerTest { TransferPermit download = narrow.acquireDirectDownload(scope("tenant-a")); assertThatThrownBy(() -> narrow.acquireDirectDownload(scope("tenant-a"))) - .isInstanceOf(FileserverException.class); + .isInstanceOf(FileserverException.class) + .extracting(failure -> ((FileserverException) failure).context().code()) + .isEqualTo(FileserverErrorCode.SERVER_BUSY); assertThat(narrow.acquireUpload(scope("tenant-a"), 10).isHeld()).isTrue(); download.close(); diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java index 37d5ed02..70270688 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java @@ -44,6 +44,12 @@ public enum OperationalError implements ApiErrorCode { ROUTE_NOT_FOUND(Category.NOT_FOUND, 404, false), // rate-limit / idempotency RATE_LIMIT_EXCEEDED(Category.RATE_LIMIT, 429, true), + /** + * This instance has no capacity for another request right now: an admission limit, a full work + * pool. Every transport answers server saturation with this one code; {@link + * #RATE_LIMIT_EXCEEDED} is the caller's own rate (decisions 2.3, 2026-11-12). + */ + SERVER_BUSY(Category.TRANSIENT_DEPENDENCY, 503, true), IDEMPOTENT_IN_FLIGHT(Category.CONFLICT, 409, true), IDEMPOTENT_REQUEST_MISMATCH(Category.VALIDATION, 422, false), IDEMPOTENCY_UNAVAILABLE(Category.TRANSIENT_DEPENDENCY, 503, true), -- 2.54.0 From d0bed329fea091a4e64fbb0fcd667851a00bd85f Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 04:48:33 +0900 Subject: [PATCH 13/23] =?UTF-8?q?docs(scripts):=20compose=20=EA=B3=84?= =?UTF-8?q?=EC=95=BD=20=EA=B2=80=EC=82=AC=20=EB=A8=B8=EB=A6=AC=EB=A7=90?= =?UTF-8?q?=EC=97=90=20=EB=B6=80=EB=A5=B4=EB=8A=94=20=EA=B3=B3=EC=9D=84=20?= =?UTF-8?q?=EC=A0=81=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 검사 스크립트 머리말이 누가 부르는지 말하지 않아, 고치는 사람이 그 검사가 어느 단계에서 도는지 build.gradle과 workflow를 뒤져야 했다. prCheck의 verifyComposeProfiles와 runtime smoke 스크립트(실행마다 한 번)를 적는다. Refs: RR9-04-17 --- scripts/verify-compose-profile-contracts.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/verify-compose-profile-contracts.sh b/scripts/verify-compose-profile-contracts.sh index 3e47131d..bda73d01 100755 --- a/scripts/verify-compose-profile-contracts.sh +++ b/scripts/verify-compose-profile-contracts.sh @@ -1,6 +1,9 @@ #!/usr/bin/env bash # The static half of the Compose contract: every lane renders, and renders exactly what it claims. # +# Called by: the pull-request stage `prCheck` (`verifyComposeProfiles`, root build.gradle) and +# scripts/run-compose-runtime-smoke.sh, once per run before the lanes start. +# # Ten things are checked, and each exists because assuming it cost something: # # 1. the Compose version, because `!override` is what stops the dev overlay's tmpfs merging with -- 2.54.0 From 5a68b29c9de45986e9cd67aead999674d5a2354a Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 04:48:42 +0900 Subject: [PATCH 14/23] =?UTF-8?q?docs(scripts):=20compose=20=EA=B3=84?= =?UTF-8?q?=EC=95=BD=20=EA=B2=80=EC=82=AC=EB=A5=BC=20=EB=B6=80=EB=A5=B4?= =?UTF-8?q?=EB=8A=94=20smoke=20=EC=AA=BD=20=EC=84=A4=EB=AA=85=EC=9D=84=20?= =?UTF-8?q?=EC=A7=80=EA=B8=88=20=EB=8F=99=EC=9E=91=EC=97=90=20=EB=A7=9E?= =?UTF-8?q?=EC=B6=98=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 앞 커밋이 「실행마다 한 번」이라고 적었지만 smoke는 아직 lane마다 부른다. 그 변경은 따로 온다. Refs: RR9-04-17 --- scripts/verify-compose-profile-contracts.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/verify-compose-profile-contracts.sh b/scripts/verify-compose-profile-contracts.sh index bda73d01..1c5e4c52 100755 --- a/scripts/verify-compose-profile-contracts.sh +++ b/scripts/verify-compose-profile-contracts.sh @@ -2,7 +2,7 @@ # The static half of the Compose contract: every lane renders, and renders exactly what it claims. # # Called by: the pull-request stage `prCheck` (`verifyComposeProfiles`, root build.gradle) and -# scripts/run-compose-runtime-smoke.sh, once per run before the lanes start. +# scripts/run-compose-runtime-smoke.sh before it starts the lanes. # # Ten things are checked, and each exists because assuming it cost something: # -- 2.54.0 From bae2965f0610e3f87a7a56e8d7dea24fcb05ed80 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 05:03:52 +0900 Subject: [PATCH 15/23] =?UTF-8?q?docs:=20=EB=8B=A8=EA=B3=84=ED=91=9C=C2=B7?= =?UTF-8?q?capability=20=EC=83=81=ED=83=9C=C2=B7=EC=84=A4=EC=A0=95=20?= =?UTF-8?q?=EC=84=A4=EB=AA=85=EC=9D=84=20=EC=A7=80=EA=B8=88=20=EB=B9=8C?= =?UTF-8?q?=EB=93=9C=EC=99=80=20workflow=EC=97=90=20=EB=A7=9E=EC=B6=98?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 살아 있는 문서가 지운 workflow·태스크·job과 옛 동작을 가리켰다. - 단계 구성이 네 곳에 따로 적혔고 둘이 틀렸다. TESTING_STRATEGY의 repository 목록은 releaseCheck를 「ci + ...」라 했고, docs/build.md의 mainCheck· qualificationCheck 행은 testQualityCheck·verifyFeatureScaffold·graphqlStableTest를 빠뜨렸다. - capability-status가 지운 redis-sdk-topology.yml·notification-platform.yml· verifyNotificationEvidence, app-bootstrap의 OutboxConfig(지금 :composition:outbox-relay), 없는 lane 이름을 증거로 들었다. 제거된 코드 표의 재배치 전 경로는 설명 없이 지금 트리에 없었다. - docs/build.md·bootstrap-local.sh가 기본 조립이 Flyway를 돈다고 했다(기본은 web뿐). 알림 키 개수를 복사해 틀렸다. - roadmap messaging-r2가 지운 VerifyMessagingEvidenceTask· MessagingQualificationPlugin을 예시로 들었다. - cache-redis README·build.gradle, httpclient build.gradle이 #13이 합친 integration job을 가리켰다. - renovate.json·취약점 정책이 「두 봇」과 GitHub vulnerability alert를 전제했다. 이 Gitea repo에 Renovate 실행기는 없다. - graphql AGENTS·README가 「모듈별 yml 금지·없음」이라 했지만 leaf는 config/graphql.yml을 직접 읽는다. 지운 execution profile을 적었다. 고친 것: 단계 구성은 gates.md 1절과 루트 build.gradle을 정본으로 가리키고, 남긴 표 행은 지금 태스크대로 고쳤다. capability-status 행 넷을 지금 job·태스크·모듈로 고치고, 제거된 코드 표의 경로가 지운 때의 배치라는 머리말과 지운 ComposeMergeCharacterizationTest 행을 더했다. 기본 조립·Flyway 설명, 알림 키(개수 대신 registry), roadmap(`> 이력`), 세 integration 설명(`main` job이 :integrationCheck :mainCheck를 함께 돈다), renovate·정책(실행기 없음, enforced는 trivy), graphql 설정 파일 설명을 고쳤다. 검증: check-docs.py·check-work-docs.py rc=0, 이 문서들을 읽는 시험은 CapabilityStatusDocumentTest(app-bootstrap document-contract)다. Refs: RR9-04-09, RR9-04-10, RR9-04-20, RR9-04-21, RR9-04-22, RR9-04-25, RR9-04-28, RR9-03-30 --- .github/dependency-vulnerability-policy.md | 9 ++++++--- docs/build.md | 17 ++++++++++------- docs/capability-status.md | 9 ++++++--- docs/roadmap/messaging-r2.md | 6 +++--- docs/testing/TESTING_STRATEGY.md | 15 +++++++-------- renovate.json | 8 +++++--- scripts/bootstrap-local.sh | 7 ++++--- src/adapter/inbound/graphql/AGENTS.md | 4 +++- src/adapter/inbound/graphql/README.md | 9 +++++---- src/adapter/outbound/cache-redis/README.md | 5 ++--- src/adapter/outbound/cache-redis/build.gradle | 10 ++++------ src/adapter/outbound/httpclient/build.gradle | 10 ++++------ 12 files changed, 59 insertions(+), 50 deletions(-) diff --git a/.github/dependency-vulnerability-policy.md b/.github/dependency-vulnerability-policy.md index 80a87906..abc2635d 100644 --- a/.github/dependency-vulnerability-policy.md +++ b/.github/dependency-vulnerability-policy.md @@ -3,8 +3,9 @@ 이 정책을 강제하는 것은 [`scripts/ci/trivy-scan.sh`](../scripts/ci/trivy-scan.sh)(pull request workflow의 `done` job, main·nightly workflow의 `vulnerabilities` job, release workflow의 이미지 job이 부른다), -[`../.trivyignore.yaml`](../.trivyignore.yaml), CODEOWNERS, -[`../renovate.json`](../renovate.json)이다. +[`../.trivyignore.yaml`](../.trivyignore.yaml), CODEOWNERS다. [`../renovate.json`](../renovate.json)은 갱신 PR을 만드는 +설정일 뿐 강제 수단이 아니다. 이 repo를 보는 Renovate 실행기가 지금 Gitea에 없어서, 그 설정은 누가 Renovate를 이 repo에 +붙일 때부터 쓰인다. ## 실행 위치와 플랫폼 경계 @@ -92,7 +93,9 @@ mirror가 살아 있고 최신인지는 운영이 챙길 의존이다. 낡은 mi ## 의존성 갱신 정책 -Renovate가 저장소에 커밋된 보안 갱신 봇 설정이다. 보안 갱신은 갱신 종류와 상관없이 자동 병합하지 않는다 +Renovate가 저장소에 커밋된 보안 갱신 봇 설정이다. 실행기가 붙어 있지 않은 동안 갱신은 trivy 실패를 본 관리자가 +손으로 한다. GitHub vulnerability alert(`vulnerabilityAlerts`)는 GitHub 호스트에서만 있고, 그 밖에서는 +`osvVulnerabilityAlerts`가 근거다. 보안 갱신은 갱신 종류와 상관없이 자동 병합하지 않는다 (`renovate.json`의 `automerge: false`). Renovate는 strict lockfile을 다시 만들지 않는다. 관리자가 `./gradlew resolveAndLockAll --write-locks`로 잠금을 다시 만들고, 잠금 diff를 검토해 함께 커밋한다. 의존성 선언과 모든 `gradle.lockfile`은 같이 움직이고, `verifyDependencyLocks`는 계속 릴리스를 diff --git a/docs/build.md b/docs/build.md index 3c2a19dd..cfc11d79 100644 --- a/docs/build.md +++ b/docs/build.md @@ -20,18 +20,21 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇 (`config/checkstyle/checkstyle.xml`). 줄 길이·들여쓰기·import 순서 모듈이 여기에 없는 것은 누락이 아니라 포매터와 싸우지 않기 위한 선택이다. Error Prone은 컴파일 시점 버그 패턴을 담당한다. +무엇이 어느 단계에서 도는지의 정본은 `docs/work/reference/gates.md` 1절과 루트 `build.gradle`의 단계 태스크다. 아래 표는 +태스크 하나하나가 하는 일이다. + | 게이트 | 하는 일 | | --- | --- | | `architectureCheck` | Clean Architecture 의존 방향, domain-core·shared-contract·application-* 순수성, Git에 실리지 않는 source package, ArchUnit을 검사 | | `qualityCheck` | 모든 leaf의 SpotBugs + FindSecBugs를 실행 | | `configContractCheck` | `:app-bootstrap:verifyEnvKeys`로 환경 설정 계약을 검사 | -| `qualificationCheck` | 전체 기동(system) 레인과 보조 source set Checkstyle을 실행 | +| `qualificationCheck` | 전체 기동(system) 레인(`systemTestCheck`), 보조 source set Checkstyle, 시험 품질 검사(`testQualityCheck`)를 실행 | | `integrationCheck` | 선언된 strict integration lane을 실행. 대부분 container runtime이 필요. 입력이 필요한 lane(Redis topology: `-Predis.topology.mode`, AWS: 보호 자격 증명 env)은 입력이 없으면 빠지고 집계가 그 이유를 출력 | | `performanceCheck` | 선언된 strict performance lane(부하·종료·pool·자원 상한)을 실행. 실서버·container가 필요. 상한은 매번 단언하고 끄는 속성이 없다(`-Pperformance.assertions.enabled`가 `true`가 아니면 실패, skip된 테스트가 있어도 실패). `main.yml` `performance` job이 nightly에 다른 무거운 job 뒤에서 같은 명령으로 돌림 | | `verifyStrictLaneStages` | `--dry-run` 전용. `explicitOnly`가 아닌 strict lane이 `strictLaneStages`에 선언한 단계(`prCheck`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) 중 하나의 계획에 있는지, 단계마다 선언한 workflow job이 `./gradlew <단계>`를 정해진 한 줄로 조건 없이(또는 선언한 조건으로) 돌리는지 검사. 형식은 `build-logic/AGENTS.md` 「단계 job의 모양」. PR 단계가 돌림 | | `prCheck` | PR 단계: `ci` + `verifyDependencyLocks` + compose 렌더링(`verifyComposeProfiles`) + 저장소 배치(`verifyRepositoryLayout`) + 작업 지침 분량·이력 ID(`verifyWorkDocs`) + 문서 검사(`documentCheck`) | | `ci` | 모든 leaf `check`(API surface 검사 포함, 소유자 결정 20) + `architectureCheck` + `qualityCheck` | -| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + `verifyPublicPathSnapshot` + 전송·메시징 qualification 레인 + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) | +| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + `verifyPublicPathSnapshot` + 전송·메시징 qualification(`conditionalTransportQualification`, `verifyMessagingContracts`) + graphql 전송 경계 lane(`graphqlStableTest`) + 생성 명령 왕복(`verifyFeatureScaffold`) + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) | | `releaseCheck` | tag 전용 검사: `verifyReleaseProvenance` + `verifyPublicPathSnapshot`(`ci`를 다시 돌리지 않음) | 따라서 로컬에서 한 모듈만 수정했다면 `./gradlew :domain-core:check`처럼 focused task를 @@ -48,10 +51,10 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇 ### 로컬 첫 실행 `scripts/bootstrap-local.sh`(저장소 루트)은 compile → Docker 확인 → DB 기동 대기 → -app 기동(Flyway 포함) → health smoke를 순서대로 실행한다(예전 `./gradlew bootstrap`, 리뷰 -BUILD-O3-5로 build-logic 플러그인에서 스크립트로 옮김). -DB와 app lifecycle은 저장소 루트의 개발 compose 파일 `compose.yaml`(`db`는 `jpa` profile)이 소유하며, app startup Flyway가 -끝나 public health endpoint가 준비되어야 다음 단계로 넘어간다. `.env.example`은 커밋된 +app 기동 → health smoke를 순서대로 실행한다(예전 `./gradlew bootstrap`, build-logic 플러그인에서 스크립트로 옮김). +DB와 app lifecycle은 저장소 루트의 개발 compose 파일 `compose.yaml`(`db`는 `jpa` profile)이 소유하며, public health +endpoint가 준비되어야 다음 단계로 넘어간다. 기본 조립은 web뿐이라 datasource를 열지 않고 Flyway도 돌지 않는다. +persistence-jpa 줄을 켠 서비스는 그 대기 안에서 startup Flyway가 끝난다. `.env.example`은 커밋된 env 계약이고 `.env`는 로컬 실행 입력이다. `verifyEnvKeys`는 example/registry/shipped YAML을 함께 검사한다. @@ -276,7 +279,7 @@ Kafka 없이 기동한다. 나머지 기능은 `src/bootstrap/app/build.gradle` | WebSocket (STOMP push) | `runtimeOnly project(':adapter:inbound:websocket')` | 없음(기본값으로 동작). origin은 `APP_WEBSOCKET_ALLOWED_ORIGINS` | `APP_WEBSOCKET_ENABLED` | | gRPC 서버 | `runtimeOnly project(':adapter:inbound:grpc')` | `APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL=true` (지금 받는 listener가 loopback plaintext뿐) | `app.grpc.server.enabled` | | 파일 서버 (JPA를 함께 가져옴) | `runtimeOnly project(':composition:fileserver-platform')` | `APP_FILESERVER_PLATFORM_STORAGE_ROOT`, `APP_FILESERVER_PLATFORM_OBSERVABILITY_FINGERPRINT_KEY`, 그리고 `FileAccessPolicyPort` bean 또는 `APP_FILESERVER_PLATFORM_SECURITY_ACCESS_POLICY=role-based` | `APP_FILESERVER_PLATFORM_ENABLED` | -| 알림 (SMTP/SES, JPA 줄도 필요) | `runtimeOnly project(':composition:notification-platform')` | 키 8종과 각 `_ID`(`APP_NOTIFICATION_PLATFORM_*_KEY`, `*_KEY_ID`), 쓰는 provider 설정(`APP_NOTIFICATION_PLATFORM_SMTP_*` 또는 `_SES_*`) | `APP_NOTIFICATION_PLATFORM_ENABLED` | +| 알림 (SMTP/SES, JPA 줄도 필요) | `runtimeOnly project(':composition:notification-platform')` | 키와 각 `_ID`(`APP_NOTIFICATION_PLATFORM_*_KEY`, `*_KEY_ID`, 목록은 registry), 쓰는 provider 설정(`APP_NOTIFICATION_PLATFORM_SMTP_*` 또는 `_SES_*`) | `APP_NOTIFICATION_PLATFORM_ENABLED` | 전체 목록과 타입·기본값은 `docs/registries/env-keys.yaml`, 각 모듈이 제공하는 것은 그 모듈 README의 "제공하는 것 · 추가할 한 줄 · env 키" 절에 있다. 기능 사이의 의존(알림·파일 서버 → JPA, outbox relay diff --git a/docs/capability-status.md b/docs/capability-status.md index 3fcaf608..2a1272fa 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -30,10 +30,10 @@ lanes and CI; it is not a deployment artifact. | 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 `main.yml` → `main` (`:integrationCheck`), qualify it against PostgreSQL. `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 `main.yml` → `main` (`: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 and the messaging library `dev.cakit.messaging` (messaging-library repo, catalog `messagingLibrary`) with its Kafka transport) | Kafka only | On when present (`KafkaCapabilityActivationTest`). The application's own publish and consume paths run against a live Kafka in `messagingKafkaRelayIntegrationTest` and `messagingInboxRedeliveryIntegrationTest`. The library's broker certification (`verifyMessagingCertificationEvidence`) runs in the messaging-library repo's main stage since 2026-11-08. 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:redisContainerContractTest` (Testcontainers Redis, `integrationCheck`); `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. | +| 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:redisContainerContractTest` (Testcontainers Redis, `integrationCheck`); `cache-redis:redisTopologyTest`, run by `main.yml` job `redis-topology` (`scripts/ci/redis-topology.sh`). 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 and PostgreSQL | One generation: the application `IdempotencyExecutor`, built once by `composition:idempotency` (`IdempotencyAutoConfiguration`) over the one store the selected provider contributes (`cache-redis` or `persistence-jpa`); startup is refused unless exactly one store exists. `app-bootstrap`이 그 모듈을 `runtimeOnly` 한 줄로 받고, 다른 조립은 없다. Redis is covered by the row above. PostgreSQL has `persistence-jpa:postgresqlIdempotencyIntegrationTest`, run by `main.yml` → `main` (`:integrationCheck`). The `postgresql` provider refuses a non-PostgreSQL data source, so `bootRunH2` uses `disabled` or `redis`. 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. | +| 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 (`OutboxRelayAutoConfiguration`) is the composition module `:composition:outbox-relay` 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. `persistence-jpa:postgresqlOutboxConcurrentRelayIntegrationTest` 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`. `NotificationEvidenceVerifierTest` refuses a grade in `docs/notification/support-matrix.md` that no proven claim backs; it runs in the leaf's main-stage lane `notificationDocumentContractTest`, run by `main.yml` → `main` (`:mainCheck`). 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 `main.yml` → `main` (`: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 `main.yml` → `main` (`: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. | @@ -71,6 +71,8 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap 복구가 필요하면 표의 커밋에서 경로를 꺼낸다(`git show <커밋>:<경로>`). +표의 경로는 지운 때의 배치다. 2026-11 재배치(Gradle 루트를 저장소 루트로) 전에 지운 행은 `src/app-bootstrap/`·`src/adapters/` 같은 옛 경로를 적고, 그 경로는 지금 트리에 없다. 지금 위치로 고치지 않는다. 그 커밋에서 꺼낼 때 쓰는 경로가 그것이기 때문이다. 옛 배치와 새 배치의 대응은 `docs/upgrade/2026-11-relayout.md`다. + 리뷰 후속 작업(2026-09-25~28, `docs/history/plans/2026-09-25-review-followup.md`)에서 지운 것은 마지막으로 존재한 커밋이 `6d27356e`인 행으로 표 끝에 이어 붙였다. | 대상 | 경로 | 마지막으로 존재한 커밋 | 이유 | @@ -526,3 +528,4 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap | `SecretSourceValidator`의 `RELATIONAL_PERSISTENCE_PROPERTY`·`isRelationalPersistenceOn()`(모듈 스위치 해석) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java` | `0ebb77b5` | P22-new-1: persistence-jpa가 기여 | | 설정 키 `app.notification.platform.smtp.max-concurrency`(이름 변경 → `dispatch-concurrency`, env `APP_NOTIFICATION_PLATFORM_SMTP_DISPATCH_CONCURRENCY` 그대로) | `NotificationSmtpSettings.java`, `notification.yml` | `0ebb77b5` | P20-new-1 | | Redis ACL `+@pubsub`·`&prod:*`(application 계정 2개) | `infra/redis-sdk/acl/*.acl` | `0ebb77b5` | P22-new-2 | +| 시험 `ComposeMergeCharacterizationTest` | `src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/compose/ComposeMergeCharacterizationTest.java` | `fe0f8141` | 어느 lane도 고르지 않아 한 번도 돌지 않았다(`integrationTest` lane은 `requires`로 적은 클래스만 고른다). 보던 것(기본·dev 조합 렌더링, 계약 스크립트)은 PR 단계 `verifyComposeProfiles`가 모든 lane으로 본다(2026-11-12 리뷰) | diff --git a/docs/roadmap/messaging-r2.md b/docs/roadmap/messaging-r2.md index c463d1b7..20886a03 100644 --- a/docs/roadmap/messaging-r2.md +++ b/docs/roadmap/messaging-r2.md @@ -42,8 +42,8 @@ verifyMessagingTargetBindingPreflight 1. 각 시나리오를 실제로 실행하는 Test 태스크. 2. 그 실행 결과(JUnit XML)에서 payload-free manifest를 만드는 producer. 3. `src/adapter/outbound/messaging/release/evidence/build-evidence-manifest-v1.schema.json`으로 그 manifest 바이트를 - 검증하는 단계(build-tools `VerifyMessagingEvidenceTask`가 쓰고 바로 검증한다). + 검증하는 단계. manifest를 쓰는 태스크가 쓰자마자 검증한다. 4. 위 셋이 모두 생긴 다음에 `verifyMessagingR2` 태스크 등록. -build-tools `MessagingQualificationPlugin`의 `verifyMessagingContracts`가 그 네 단계를 모두 갖춘 -예시다. +> 이력: 네 단계를 모두 갖춘 예시였던 build-tools `MessagingQualificationPlugin`(`verifyMessagingContracts`)과 +> `VerifyMessagingEvidenceTask`는 메시징 플랫폼을 messaging-library repo로 옮기며(2026-11-08) 이 repo에서 지웠다. diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index b8a0b20f..25b5741d 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -141,15 +141,14 @@ fixture는 **지원 코드**다. TEST/INTEGRATION/SYSTEM/ARCHITECTURE/PERFORMANC ### repository -- `integrationCheck`: production leaf들의 INTEGRATION lanes. -- `systemTestCheck`: production leaf들의 SYSTEM lanes. -- `architectureCheck`: repository architecture rules + ARCHITECTURE lanes. -- `qualificationCheck`: SYSTEM composition + auxiliary-source style gate. -- `ci`: leaf checks + architecture/quality/config contract + qualification. -- `releaseCheck`: `ci` + release-only provenance/archive/public-path checks. +category별 묶음 태스크는 셋이다. `integrationCheck`(모든 leaf의 INTEGRATION lane), `systemTestCheck`(SYSTEM lane), +`architectureCheck`(저장소 아키텍처 규칙과 ARCHITECTURE lane). 이것들을 어느 단계(`prCheck`·`mainCheck`· +`integrationCheck`·`performanceCheck`·`releaseCheck`)가 부르는지와 단계마다 무엇이 더 붙는지의 정본은 +`docs/work/reference/gates.md` 1절과 루트 `build.gradle`의 단계 태스크다. 여기에 복사하지 않는다. -`integrationCheck`는 현재 `ci`에 암묵적으로 포함되지 않는다. -여러 integration lane이 container runtime을 요구하므로 별도 workflow/main/nightly에서 실행할 수 있다. +- `integrationCheck`는 `ci`에 들지 않는다. container runtime이 드는 lane이 많아 main 단계(`main.yml` `main` job)가 + 따로 부른다. +- `systemTestCheck`는 `qualificationCheck`를 거쳐 main 단계에서 돈다. PERFORMANCE는 기본 로컬 `check`에 붙이지 않는다. 명시적 benchmark/performance task나 scheduled workflow가 실행한다. diff --git a/renovate.json b/renovate.json index 9312ff94..5d6b2136 100644 --- a/renovate.json +++ b/renovate.json @@ -6,15 +6,17 @@ "This repository uses strict per-leaf Gradle lockfiles; Renovate does not regenerate those locks here.", "A maintainer must run `./gradlew resolveAndLockAll --write-locks`, review the lock diff,", "and commit the refreshed lockfiles before a dependency PR can pass `verifyDependencyLocks`.", - "Transitive vulnerabilities are NOT covered by either bot (direct deps only) — pin them with a Gradle", - "dependency constraint / resolutionStrategy.force (§4) and regenerate locks (supply-chain D8)." + "Transitive vulnerabilities are NOT covered by Renovate (direct deps only) — pin them with a Gradle", + "dependency constraint / resolutionStrategy.force (§4) and regenerate locks (supply-chain D8).", + "This file takes effect only where a Renovate instance is pointed at the repository; none is wired", + "for the Gitea host today. The enforced gate is scripts/ci/trivy-scan.sh in the pipelines." ], "extends": [ "config:recommended", "security:only-security-updates" ], "vulnerabilityAlerts": { - "description": "Stable GitHub vulnerability alerts → immediate security PR, ignoring schedule.", + "description": "GitHub-hosted only: Renovate reads GitHub's Dependabot alerts, which a Gitea host does not have. osvVulnerabilityAlerts below is the source elsewhere.", "enabled": true, "labels": [ "security", diff --git a/scripts/bootstrap-local.sh b/scripts/bootstrap-local.sh index 0cf723cb..31c3aca7 100755 --- a/scripts/bootstrap-local.sh +++ b/scripts/bootstrap-local.sh @@ -10,8 +10,9 @@ # This was the build-logic `ca.developer-bootstrap` plugin (`./gradlew bootstrap`). Starting # containers and probing an HTTP endpoint is not a build rule, so it is a script now (review # 2026-09-24 BUILD-O3-5). The four stages and their order are unchanged: the next stage starts only -# when the previous one succeeded, and the app stage waits for startup Flyway through the compose -# healthcheck before the smoke probe runs. +# when the previous one succeeded, and the app stage waits for the compose healthcheck before the +# smoke probe runs. The default composition is web only: it opens no datasource and runs no +# Flyway. A service that adds the persistence-jpa line gets startup Flyway inside the same wait. # # Until 2026-11-07 it merged docker-compose.yml with docker-compose.local.yml and asked for a `db` # service neither file had defined since the database moved to a third file, so the documented @@ -40,7 +41,7 @@ fi echo "bootstrap 2/4: starting the PostgreSQL dependency and waiting for readiness" "${compose[@]}" up -d --wait db -echo "bootstrap 3/4: building and starting the app; startup Flyway finishes before health is ready" +echo "bootstrap 3/4: building and starting the app and waiting for its health" "${compose[@]}" up -d --build --wait app echo "bootstrap 4/4: requiring HTTP 200 and status=UP from ${health_endpoint}" diff --git a/src/adapter/inbound/graphql/AGENTS.md b/src/adapter/inbound/graphql/AGENTS.md index 608c3e39..59b7a259 100644 --- a/src/adapter/inbound/graphql/AGENTS.md +++ b/src/adapter/inbound/graphql/AGENTS.md @@ -113,7 +113,9 @@ required-class 검사가 이 테스트가 조용히 사라지는 것을 막는 모듈을 자동 커버 — per-module 규칙 추가 불필요). - 프로덕션 feature 쿼리/뮤테이션을 스켈레톤에 두는 것 — health 표면만 (web 의 `HealthcheckController` 와 동일 원칙). feature 스키마/컨트롤러/매퍼는 그 기능을 가진 서비스가 소유한다. -- 모듈별 `yml` — 설정은 프레임워크 `spring.graphql.*` 로 composition-root `application.yml` 에 산다. +- `config/graphql.yml` 밖의 설정 파일 — 이 leaf의 설정 기본값은 그 파일 하나다. 의존성에 support가 없어 공용 + `ModuleDefaultsEnvironmentPostProcessor` 대신 `GraphQlActivationEnvironmentPostProcessor`가 읽는다(manual 10 기준 7 뒤 예외). + 전송 설정 `spring.graphql.*`은 composition-root `application.yml`에 둔다. ## 오류 대응 (`Category → ErrorType`) diff --git a/src/adapter/inbound/graphql/README.md b/src/adapter/inbound/graphql/README.md index c7db8089..f1691604 100644 --- a/src/adapter/inbound/graphql/README.md +++ b/src/adapter/inbound/graphql/README.md @@ -123,7 +123,8 @@ gRPC 와 달리 spring-graphql / graphql-java 는 Spring Boot BOM 이 관리한 ## 설정 — 프레임워크 `spring.graphql.*` + 플랫폼 `app.graphql.*` 전송 계층 설정(path, graphiql, introspection, schema location)은 프레임워크 `spring.graphql.*` -가 소유한다. composition-root `application.yml` 에서 설정하며 모듈별 `yml` 은 없다. +가 소유한다. composition-root `application.yml` 에서 설정한다. 이 leaf의 `app.graphql.*` 기본값과 env 연결은 +모듈의 `config/graphql.yml` 하나에 있고, `GraphQlActivationEnvironmentPostProcessor`가 가장 낮은 우선순위로 읽는다. 플랫폼 정책은 `spring.graphql.*` 로 표현할 수 없다 — cost/page 한계, preparsed 캐시 경계, 관측 label 로 허용할 operation 이름은 전부 이 leaf 의 결정이다. 그래서 @@ -148,9 +149,9 @@ app: observed-operation-names: [] # 비우면 모든 operation 이름이 `other` 로 접힌다 ``` -이 모듈의 `config/graphql.yml`이 위 wired 설정을 `APP_GRAPHQL_*`로 노출한다. `APP_GRAPHQL_ENABLED`와 -`APP_GRAPHQL_DEPLOYMENT_MODE` 외에도 execution profile, console, page/complexity, preparsed-cache -한계와 관측 operation allowlist가 같은 property tree로 들어간다. +이 모듈의 `config/graphql.yml`이 위 설정을 `APP_GRAPHQL_*`로 노출한다. `APP_GRAPHQL_ENABLED`와 +`APP_GRAPHQL_DEPLOYMENT_MODE` 외에도 console(`APP_GRAPHQL_GRAPHIQL_ENABLED`, `APP_GRAPHQL_INTROSPECTION_ENABLED`), +page/complexity, preparsed-cache 한계, N+1 경고 임계와 관측 operation allowlist가 같은 property tree로 들어간다. production mode는 env만으로 완성되지 않는다. 애플리케이션 좌표를 스켈레톤이 알 수 없으므로 **명시적인 `GraphQlAuthorizationPolicy` bean이 반드시 필요**하며, 이것은 의도된 fail-closed diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index 51cb4fab..a36c9291 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -329,9 +329,8 @@ rate-limit 어댑터가 있다고 SDK 명령 정책이 강제된다고 짐작하 `redisContainerContractTest`는 cache-region, lease, 멱등성 store 포트 계약(메모리 fake가 통과하는 것. 멱등성 계약의 시간 있는 경우는 여기서 서버 자신의 시계로 돌고, `test`에서는 명령 fake의 시계로 돈다 — 후자는 program 자체가 아니라 fixture가 가진 program 사본을 증명한다)과 살아 있는 semantic 포트 시험을, standalone topology의 ACL 파일 아래에서 스스로 -띄운 Redis에 대고 돌린다. `integrationCheck`(`main.yml`의 `integration` job)에 있고 거기에만 있다: -`mainCheck`에도 적었을 때는 main push마다 두 번 돌았다. image는 `gradle/container-images.properties`의 -`redis`다. +띄운 Redis에 대고 돌린다. `integrationCheck`에 있고 거기에만 있다. `main.yml`의 `main` job이 +`./gradlew :integrationCheck :mainCheck`로 둘을 함께 돌린다. image는 `gradle/container-images.properties`의 `redis`다. 살아 있는 Redis·topology 검증은 빠른 단위 시험과 따로다. 특정 Redis topology나 ACL 배치에 대한 릴리스 주장에는 그에 맞는 살아 있는 검증 lane이 필요하다. 메모리 gateway는 결정적인 계약 시험을 위한 것이지, 외부 Redis 배포가 같은 diff --git a/src/adapter/outbound/cache-redis/build.gradle b/src/adapter/outbound/cache-redis/build.gradle index 73a6fbac..5f7d47a8 100644 --- a/src/adapter/outbound/cache-redis/build.gradle +++ b/src/adapter/outbound/cache-redis/build.gradle @@ -71,12 +71,10 @@ redisTopologyLane { // the same defect (05-02, 05-03). The image is gradle/container-images.properties' `redis`, // and the ACL file is the one the development stack and the redis-sdk topologies share // (compose/redis/acl), so the accounts and their rights are the standalone -// topology's. Integration category, so integrationCheck runs it — main.yml's `integration` job, on -// every push to main and nightly. It is deliberately not in this leaf's mainCheck as well: `main` and -// `integration` are two jobs of the same workflow run, so a -// lane in both started a second Redis container and ran every live contract twice per push without -// covering anything the first run did not (found while fixing review 2026-11-03). Sentinel, cluster -// and TLS remain the topology lane's. +// topology's. Integration category, so integrationCheck runs it — main.yml's `main` job runs +// `./gradlew :integrationCheck :mainCheck` on every push to main and nightly. It is not in this leaf's +// mainCheck as well: one stage is where a lane is owned, and verifyStrictLaneStages names that stage. +// Sentinel, cluster and TLS remain the topology lane's. def redisAclDirectory = rootProject.projectDir.toPath().resolve('compose/redis/acl').toFile() strictTestLanes { lane('redisContainerContractTest') { diff --git a/src/adapter/outbound/httpclient/build.gradle b/src/adapter/outbound/httpclient/build.gradle index cf16d057..a2a22066 100644 --- a/src/adapter/outbound/httpclient/build.gradle +++ b/src/adapter/outbound/httpclient/build.gradle @@ -230,12 +230,10 @@ strictTestLanes { // the deadline and evidence contracts against real TCP faults — a slow drip, a cut stream, a refused // connect — and review 2026-11-01 05-06/05-16 put it in the main stage because it was reachable only // through integrationCheck, which then ran on no main-branch build. That premise no longer holds: -// main.yml's `integration` job runs integrationCheck (an integration lane, so this one) on every push -// to main and nightly, in the same workflow run as the `main` job. In both -// stages, every main push started a second Toxiproxy and httpbin and ran every fault twice without -// covering anything the first run did not (review 2026-11-03 README §8, closed in round 9; the -// cache-redis container lane left mainCheck for the same reason). verifyStrictLaneStages still fails -// if no executed stage reaches it. It stays out of `check` for the reason above. +// main.yml's `main` job runs `./gradlew :integrationCheck :mainCheck` (an integration lane, so this +// one) on every push to main and nightly. One stage owns the lane, so it is in integrationCheck only +// (the cache-redis container lane likewise). verifyStrictLaneStages still fails if no executed stage +// reaches it. It stays out of `check` for the reason above. tasks.named('mainCheck') { dependsOn 'spring70CompatibilityTest' } -- 2.54.0 From bb28dae5c9b1ed779244322594237be8d7f6b8e1 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 05:03:52 +0900 Subject: [PATCH 16/23] =?UTF-8?q?docs:=20=EC=95=88=EB=82=B4=EA=B0=80=20?= =?UTF-8?q?=EC=97=86=EB=8D=98=20leaf=20=EC=97=AC=EC=84=AF=EC=97=90=20AGENT?= =?UTF-8?q?S=C2=B7README=EB=A5=BC=20=EC=93=B0=EA=B3=A0=20web=20=EB=AC=B8?= =?UTF-8?q?=EC=84=9C=20=EB=91=98=EC=9D=84=20=EC=A7=80=EA=B8=88=20=EB=8F=99?= =?UTF-8?q?=EC=9E=91=EC=97=90=20=EB=A7=9E=EC=B6=98=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: - application-notification·-fileserver·-objectstorage는 가장 가까운 AGENTS가 루트뿐이고 README가 없었다. web-notification·web-fileserver·redis-runtime도 자기 AGENTS·README가 없었다. 그 leaf를 고치는 세션은 지역 규칙(전송이 이름을 짓지 않음, 포화 코드의 갈림, callback 경로가 절대 경로인 이유 등)을 볼 곳이 없었다. - docs/README.md 지도의 security/ 행이 rate-limiting.md를 덮지 않았다. - shared-contract AGENTS 책임 목록이 PageMeta·ResponseMeta·Category·공용 carrier 예외 셋·ServerFailureLog·ActiveTrace를 빠뜨렸다. - docs/web/repository-adaptation.md가 「애플리케이션 칸은 강제하지 않는다」고 했지만 web은 JSON 본문 1 MiB(app.web.mvc.max-json-body-size, 413)를 강제한다. - openapi-32-compatibility.md가 아무도 만들지 않는 3.1.2 릴리스 산출물과 3.1 snapshot 불변식을 이 repo의 것처럼 적었다(샘플 삭제 뒤). 고친 것: leaf 여섯에 AGENTS.md(등록 정보, 책임, 규칙, 시험)·CLAUDE.md(@AGENTS.md)· README.md(책임과 소유하지 않는 것, 공개 표면, 조립, 시험 명령, 더 읽을 곳)를 쓰고, 규칙의 정본은 가리키기만 했다. 지도 행, shared-contract 책임 목록, 본문 한도 표와 머리말, OpenAPI 문서를 고쳤다. 순서: 새 leaf 문서가 계약 PR(batch bulk envelope, 알림 VALIDATION_FAILED, SERVER_BUSY, 전송이 이름을 짓지 않음)의 동작을 적는다. 그 PR 뒤에 병합한다. 검증: check-docs.py·check-work-docs.py rc=0. Refs: RR9-04-35, RR9-04-36, RR9-04-42 --- docs/README.md | 2 +- docs/web/openapi-32-compatibility.md | 12 ++++--- docs/web/repository-adaptation.md | 9 +++--- src/adapter/inbound/web-fileserver/AGENTS.md | 30 ++++++++++++++++++ src/adapter/inbound/web-fileserver/CLAUDE.md | 1 + src/adapter/inbound/web-fileserver/README.md | 31 +++++++++++++++++++ .../inbound/web-notification/AGENTS.md | 29 +++++++++++++++++ .../inbound/web-notification/CLAUDE.md | 1 + .../inbound/web-notification/README.md | 31 +++++++++++++++++++ src/adapter/outbound/redis-runtime/AGENTS.md | 29 +++++++++++++++++ src/adapter/outbound/redis-runtime/CLAUDE.md | 1 + src/adapter/outbound/redis-runtime/README.md | 31 +++++++++++++++++++ src/application/fileserver/AGENTS.md | 29 +++++++++++++++++ src/application/fileserver/CLAUDE.md | 1 + src/application/fileserver/README.md | 31 +++++++++++++++++++ src/application/notification/AGENTS.md | 29 +++++++++++++++++ src/application/notification/CLAUDE.md | 1 + src/application/notification/README.md | 31 +++++++++++++++++++ src/application/objectstorage/AGENTS.md | 27 ++++++++++++++++ src/application/objectstorage/CLAUDE.md | 1 + src/application/objectstorage/README.md | 30 ++++++++++++++++++ src/shared-contract/AGENTS.md | 11 +++++-- 22 files changed, 385 insertions(+), 13 deletions(-) create mode 100644 src/adapter/inbound/web-fileserver/AGENTS.md create mode 100644 src/adapter/inbound/web-fileserver/CLAUDE.md create mode 100644 src/adapter/inbound/web-fileserver/README.md create mode 100644 src/adapter/inbound/web-notification/AGENTS.md create mode 100644 src/adapter/inbound/web-notification/CLAUDE.md create mode 100644 src/adapter/inbound/web-notification/README.md create mode 100644 src/adapter/outbound/redis-runtime/AGENTS.md create mode 100644 src/adapter/outbound/redis-runtime/CLAUDE.md create mode 100644 src/adapter/outbound/redis-runtime/README.md create mode 100644 src/application/fileserver/AGENTS.md create mode 100644 src/application/fileserver/CLAUDE.md create mode 100644 src/application/fileserver/README.md create mode 100644 src/application/notification/AGENTS.md create mode 100644 src/application/notification/CLAUDE.md create mode 100644 src/application/notification/README.md create mode 100644 src/application/objectstorage/AGENTS.md create mode 100644 src/application/objectstorage/CLAUDE.md create mode 100644 src/application/objectstorage/README.md diff --git a/docs/README.md b/docs/README.md index 730ce894..77d6a10b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -33,7 +33,7 @@ | `registries/` | 레지스트리: env 키, 오류 코드, 메트릭, HTTP 헤더, 로그(MDC) 키, 비밀 분류, use case capability, 객체 저장소 준비도. 테스트가 코드와 대조한다 | | `web/` | HTTP wire 계약(`web/http-contract.md`), PATCH·스트리밍 계약, 선택형 web 기능(`web-advanced`), web 장애 대응 | | `architecture/` | 공개 API 표면 스냅숏(`*-api-surface.txt`). API surface 검사가 대조한다 | -| `security/` | 기본 공개 경로 스냅숏. `verifyPublicPathSnapshot`이 대조한다 | +| `security/` | 공개 경로 스냅숏(`verifyPublicPathSnapshot`이 대조한다)과 요청률 제한을 어디서 거는지(`rate-limiting.md`) | | `observability/` | 구조화 로그 필드 사전 | ### 영역 운영 문서 diff --git a/docs/web/openapi-32-compatibility.md b/docs/web/openapi-32-compatibility.md index a6a477d6..7357d8d6 100644 --- a/docs/web/openapi-32-compatibility.md +++ b/docs/web/openapi-32-compatibility.md @@ -7,12 +7,14 @@ API 설명의 가치는 전부 그것을 소비하는 쪽에 있다. client generator가 다 이해하지 못하는 버전의 문서는 실패하지 않는다. 컴파일되는데 틀린 client를 만든다. 문서가 아예 없는 것보다 나쁘다. -그래서 3.1.2가 릴리스 산출물로 남고, 3.2는 그 옆에서 만든다. +그래서 3.2는 3.1 문서를 바꾸지 않고 그 옆에서 만든다. 이 템플릿 자체는 OpenAPI 문서를 릴리스 산출물로 내지 +않는다(만들던 샘플을 2026-09-25에 지웠다). 아래는 3.1 문서를 내는 서비스가 3.2를 함께 만들 때의 규칙이다. ## 불변식 -**3.2를 만드는 것이 3.1 snapshot을 바꾸면 안 된다.** 둘은 같은 모델에서 나온다. 그래서 3.2로 가는 길에 모델을 -바꾸는 기여자는 실제로 내보내는 산출물을 바꾼다. 조용히, 그리고 3.2를 만들 때만. +**3.2를 만드는 것이 그 서비스의 3.1 문서를 바꾸면 안 된다.** 둘은 같은 모델에서 나온다. 그래서 3.2로 가는 길에 +모델을 바꾸는 기여자는 실제로 내보내는 산출물을 바꾼다. 조용히, 그리고 3.2를 만들 때만. 서비스는 자기 3.1 문서를 +snapshot으로 두고 3.2를 만들 때 그것이 그대로인지 본다. 이 저장소에는 그것을 검사하는 것이 더는 없다. snapshot을 hash하고 어떤 parser, linter, generator, client 컴파일이 3.2 출력을 읽었는지 기록하던 승격 보고서 `OpenApi32CompatibilityReport`와 `OpenApiToolchainMatrix`는 2026-09-25에 @@ -23,5 +25,5 @@ API 설명의 가치는 전부 그것을 소비하는 쪽에 있다. client gene ## 돌리기 -이 저장소의 어떤 workflow도 3.2를 만들지 않는다. `OpenApiVersionLane.STABLE_3_1`이 릴리스 산출물이고, -`WebOpenApi32GeneratorTest`가 generator를 다룬다. +이 저장소의 어떤 workflow도 OpenAPI 문서를 만들지 않는다. `OpenApiVersionLane.STABLE_3_1`은 서비스가 내보낼 안정 +lane의 이름이고, `WebOpenApi32GeneratorTest`가 3.2 generator를 다룬다. diff --git a/docs/web/repository-adaptation.md b/docs/web/repository-adaptation.md index b8e7e765..1725f8f9 100644 --- a/docs/web/repository-adaptation.md +++ b/docs/web/repository-adaptation.md @@ -144,9 +144,10 @@ worker는 바뀐 행 수로 그것을 안다. ## 8. 예산 강제: edge가 막는 것과 애플리케이션이 막는 것 > **2026-09-25에 지움.** servlet 예산 filter(`WebMvcBudgetFilter`)와 그 problem 대응은 2세대 플랫폼과 함께 지웠다. -> 내보내는 애플리케이션은 더는 아래 애플리케이션 칸을 강제하지 않는다. `budget` 목록(`WebRequestBudget`, -> `WebBudgetCatalog`)은 `adapter:inbound:web-advanced`에 라이브러리 코드로 남고, 쓰이지 않던 meter(`WebBudgetMeter`와 -> 그 결과/위반 타입)는 지웠다. edge 칸은 여전히 맞다. +> 내보내는 애플리케이션은 아래 애플리케이션 칸 중 JSON 요청 본문 한도 하나만 강제한다(`app.web.mvc.max-json-body-size`, +> 기본 1 MiB, web `JsonBodyLimitFilter`, 넘으면 413 `PAYLOAD_TOO_LARGE` Envelope). 나머지 칸의 이름(`maxUriBytes` 등)은 +> `budget` 목록(`WebRequestBudget`, `WebBudgetCatalog`)의 값이고, 그 목록은 `adapter:inbound:web-advanced`에 라이브러리 +> 코드로만 남았다. 쓰이지 않던 meter(`WebBudgetMeter`와 그 결과/위반 타입)는 지웠다. edge 칸은 여전히 맞다. 설계(Task 49)는 edge proxy의 한도와 애플리케이션 자체 한도의 차이를 장애 중에 발견하지 말고 적어 두라고 요구한다. 같은 차원에 한도는 늘 둘 있고, 둘은 결코 같지 않으며, 어느 쪽이 걸리는지가 호출자가 보는 것을 정한다. @@ -155,7 +156,7 @@ worker는 바뀐 행 수로 그것을 안다. | --- | --- | --- | --- | | 요청 줄 / URI | `large_client_header_buffers`(기본 8k) | `maxUriBytes` | edge가 먼저 — nginx가 자기 HTML로 414 | | 요청 헤더 | `large_client_header_buffers` | `maxHeaderBytes` | edge가 먼저 — nginx 400, problem document 없음 | -| 요청 본문 | `client_max_body_size`(기본 1m) | `maxBodyBytes`(플랫폼 상한 8 MiB) | 더 작은 쪽. nginx는 HTML로 413 | +| 요청 본문 | `client_max_body_size`(기본 1m) | JSON 본문: `app.web.mvc.max-json-body-size`(기본 1 MiB, 강제함). JSON 아닌 본문: 전역 한도 없음, endpoint가 둔다 | 더 작은 쪽. nginx는 HTML로 413, 애플리케이션은 Envelope로 413 | | query parameter 수 | 강제하지 않음 | `maxQueryParameters` | 늘 애플리케이션 | | JSON 깊이 / 배열 크기 | 강제하지 않음 | `maxJsonDepth`, `maxArrayElements` | 늘 애플리케이션 | | 실행 시간 | `proxy_read_timeout`(기본 60s) | `maxExecutionTime`(상한 2분) | 플랫폼 쪽이 더 크면 edge가 먼저 | diff --git a/src/adapter/inbound/web-fileserver/AGENTS.md b/src/adapter/inbound/web-fileserver/AGENTS.md new file mode 100644 index 00000000..5bb5f6f3 --- /dev/null +++ b/src/adapter/inbound/web-fileserver/AGENTS.md @@ -0,0 +1,30 @@ +# adapter:inbound:web-fileserver — 파일 서버의 HTTP 표면 + +## 등록 정보 + +- 모듈 ID: `adapter-inbound-web-fileserver` +- Gradle 경로: `:adapter:inbound:web-fileserver` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:inbound:web-fileserver:test --console=plain` +- registry 정본: `gradle/modules.json`. + +패키지 루트: `dev.caskeleton.adapter.inbound.web.fileserver`. 무엇을 주는지와 조립은 [README.md](README.md)에 있다. + +## 책임 + +- 업로드(`controller`, tus `tus`, IETF draft-12 `draft12`)·다운로드·관리(`admin`) HTTP endpoint와 그 요청 해석(`mapper`). +- 실패를 Envelope로 바꾸는 `problem`(`FileserverExceptionHandler`, `FileserverProblemHeaders`), 전송 worker pool(`config.BlockingTransferExecutor`), nginx `X-Accel-Redirect`(`nginx`). +- CORS 노출 헤더 기여(`config.FileserverHttpSurfaceConfiguration`). + +## 규칙 + +- 전송은 업로드 이름을 지어 넣지 않는다. 받은 이름이 없으면 빈 이름을 넘기고 `application-fileserver`의 `OriginalFilenamePolicy`가 정한다. +- `Retry-After`는 본문 `retryable`과 같은 규칙으로 붙인다: code가 재시도를 허락하고 그 발생도 재시도 가능할 때만. +- batch 업로드는 공용 bulk envelope(web AGENTS B8)다. 부분 실패는 `success: false` + `BATCH_PARTIAL_FAILURE`다. +- 새 응답 헤더를 쓰면 `FileserverHttpSurfaceConfiguration`의 CORS 노출 목록에 같은 변경에서 더한다. +- `adapter:inbound:web`의 inbound 규칙이 그대로 적용된다: repository 접근 없음, 업무 규칙 없음. + +## 테스트 + +```bash +./gradlew :adapter:inbound:web-fileserver:test --console=plain +``` diff --git a/src/adapter/inbound/web-fileserver/CLAUDE.md b/src/adapter/inbound/web-fileserver/CLAUDE.md new file mode 100644 index 00000000..43c994c2 --- /dev/null +++ b/src/adapter/inbound/web-fileserver/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/adapter/inbound/web-fileserver/README.md b/src/adapter/inbound/web-fileserver/README.md new file mode 100644 index 00000000..ec9a3460 --- /dev/null +++ b/src/adapter/inbound/web-fileserver/README.md @@ -0,0 +1,31 @@ +# adapter:inbound:web-fileserver + +파일 서버의 HTTP 표면을 담는 leaf다. 업로드·다운로드 protocol을 유스케이스 호출로 바꾼다. + +## 책임과 소유하지 않는 것 + +- 업로드(`controller`, tus `tus`, IETF draft-12 `draft12`)·다운로드·관리(`admin`) HTTP endpoint와 그 요청 해석(`mapper`). +- 실패를 Envelope로 바꾸는 `problem`(`FileserverExceptionHandler`, `FileserverProblemHeaders`), 전송 worker pool(`config.BlockingTransferExecutor`), nginx `X-Accel-Redirect`(`nginx`). +- CORS 노출 헤더 기여(`config.FileserverHttpSurfaceConfiguration`). +- 소유하지 않는 것: 할당량·표시 이름 같은 정책(`application-fileserver`), 바이트 저장(`adapter:outbound:fileserver`), 공용 Envelope 처리(`adapter:inbound:web`). + +## 공개 표면 + +HTTP endpoint(`docs/fileserver/http-contract.md` 「공개 endpoint」·「관리 endpoint」), 오류 code 표(같은 문서 「오류 코드」). 설정 prefix는 없다(`app.fileserver-platform.*`는 `adapter:outbound:fileserver`의 것). + +## 조립 + +직접 더하지 않는다. `runtimeOnly project(':composition:fileserver-platform')` 한 줄이 이 leaf를 함께 싣고, 조립 모듈이 이 leaf의 설정 class를 import한다. 끄는 키는 `APP_FILESERVER_PLATFORM_ENABLED`다. + +## 테스트 명령 + +```bash +./gradlew :adapter:inbound:web-fileserver:test --console=plain +``` + +## 더 읽을 곳 + +- [AGENTS.md](AGENTS.md)(이 leaf의 규칙) +- `docs/fileserver/http-contract.md`(HTTP 계약 정본) +- `src/adapter/inbound/web/AGENTS.md`(요청 경계, bulk envelope) +- `src/bootstrap/fileserver-platform/README.md`(조립) diff --git a/src/adapter/inbound/web-notification/AGENTS.md b/src/adapter/inbound/web-notification/AGENTS.md new file mode 100644 index 00000000..89040bdf --- /dev/null +++ b/src/adapter/inbound/web-notification/AGENTS.md @@ -0,0 +1,29 @@ +# adapter:inbound:web-notification — 알림 플랫폼의 HTTP 표면 + +## 등록 정보 + +- 모듈 ID: `adapter-inbound-web-notification` +- Gradle 경로: `:adapter:inbound:web-notification` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:inbound:web-notification:test --console=plain` +- registry 정본: `gradle/modules.json`. + +패키지 루트: `dev.caskeleton.adapter.inbound.web.notification`. 무엇을 주는지와 조립은 [README.md](README.md)에 있다. + +## 책임 + +- 알림 제출(`NotificationSubmissionController`)과 template 게시(`NotificationTemplateController`) HTTP endpoint. +- provider callback 수신(`NotificationCallbackMvcController`)과 그 경로만 덮는 보안 chain(`CallbackMvcSecurityConfiguration`). +- 요청 DTO를 `application-notification`의 command로 바꾼다. 업무 판정은 하지 않는다. + +## 규칙 + +- controller는 변환만 한다. 모르는 channel·slot·locale은 그 필드를 짚는 `400 VALIDATION_FAILED`로 거절하고, 발송 판정은 유스케이스에 넘긴다. +- callback 경로는 presentation prefix를 받지 않는 절대 경로다. provider에 한 번 등록한 URL이 prefix 변경으로 움직이면 안 된다(`NotificationRoutePrefixTest`). +- callback chain은 인증 없이 열고 서명 검증을 유스케이스가 한다. 그 `permitAll`은 공개 경로 스냅숏에 들어 있다(`docs/security/public-paths-snapshot.txt`). +- `adapter:inbound:web`의 inbound 규칙이 그대로 적용된다: repository 접근 없음, DTO를 application으로 넘기지 않음. + +## 테스트 + +```bash +./gradlew :adapter:inbound:web-notification:test --console=plain +``` diff --git a/src/adapter/inbound/web-notification/CLAUDE.md b/src/adapter/inbound/web-notification/CLAUDE.md new file mode 100644 index 00000000..43c994c2 --- /dev/null +++ b/src/adapter/inbound/web-notification/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/adapter/inbound/web-notification/README.md b/src/adapter/inbound/web-notification/README.md new file mode 100644 index 00000000..3d1e2d36 --- /dev/null +++ b/src/adapter/inbound/web-notification/README.md @@ -0,0 +1,31 @@ +# adapter:inbound:web-notification + +알림 플랫폼의 HTTP 표면을 담는 leaf다. 요청을 유스케이스 command로 바꾸고 응답을 Envelope로 돌려준다. + +## 책임과 소유하지 않는 것 + +- 알림 제출(`NotificationSubmissionController`)과 template 게시(`NotificationTemplateController`) HTTP endpoint. +- provider callback 수신(`NotificationCallbackMvcController`)과 그 경로만 덮는 보안 chain(`CallbackMvcSecurityConfiguration`). +- 요청 DTO를 `application-notification`의 command로 바꾼다. 업무 판정은 하지 않는다. +- 소유하지 않는 것: 발송 판정·서명 검증(`application-notification`), provider 호출(`adapter:outbound:notification`), 공용 오류 처리(`adapter:inbound:web`). + +## 공개 표면 + +HTTP endpoint 셋(경로는 `docs/notification/`과 각 controller 주석), 권한 `notification:submit`·`notification-template:publish`. 설정 prefix는 없다. + +## 조립 + +직접 더하지 않는다. `runtimeOnly project(':composition:notification-platform')` 한 줄이 이 leaf를 함께 싣고, 이 leaf의 `NotificationWebAutoConfiguration`이 켜진다. 끄는 키는 `APP_NOTIFICATION_PLATFORM_ENABLED`다. + +## 테스트 명령 + +```bash +./gradlew :adapter:inbound:web-notification:test --console=plain +``` + +## 더 읽을 곳 + +- [AGENTS.md](AGENTS.md)(이 leaf의 규칙) +- `src/adapter/inbound/web/AGENTS.md`(요청 경계 B1~B8, 직렬화 S1~S4) +- `docs/notification/`(callback 대조, provider runbook) +- `src/bootstrap/notification-platform/README.md`(조립) diff --git a/src/adapter/outbound/redis-runtime/AGENTS.md b/src/adapter/outbound/redis-runtime/AGENTS.md new file mode 100644 index 00000000..83e192d5 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/AGENTS.md @@ -0,0 +1,29 @@ +# adapter:outbound:redis-runtime — Redis 연결과 명령 실행의 공용 runtime + +## 등록 정보 + +- 모듈 ID: `adapter-outbound-redis-runtime` +- Gradle 경로: `:adapter:outbound:redis-runtime` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:redis-runtime:test --console=plain` +- registry 정본: `gradle/modules.json`. + +패키지 루트: `dev.caskeleton.adapter.outbound.cache.redis.runtime`. 무엇을 주는지와 조립은 [README.md](README.md)에 있다. + +## 책임 + +- Redis 연결(standalone·sentinel·cluster·TLS)과 그 수명(`connection`의 `RedisRuntimeClient`, lane·account), 의미 단위 명령(`command.SemanticRedisCommands`), key 규칙(`key`), 설정(`config`의 `app.redis.*`, `RedisRuntimeSettings`)과 health. +- `cache-redis`와 `redis-sdk`가 같은 연결 하나를 쓰게 하는 바닥이다. 업무 포트를 구현하지 않는다. +- testFixtures: 메모리 명령(`InMemorySemanticRedisCommands`), stub client, 실 topology endpoint(`RedisTopologyEndpoint`). 두 위 leaf의 시험이 쓴다. + +## 규칙 + +- 어떤 프로젝트 leaf에도 의존하지 않는다(registry 허용 의존이 비어 있다). application 포트를 모른다. +- 설정 트리는 `app.redis.*`다(manual 10 기준 4의 Redis 예외: setter + `validate()`). 새 트리를 만들지 않는다. +- 연결은 `RedisRuntimeClient` 하나를 함께 쓴다. 위 leaf가 Lettuce 연결을 따로 열지 않는다. +- 실 topology 검증은 `ca.redis-topology-lane`의 topology lane이다. 좌표를 받아야 도는 lane이라 명시적으로만 돈다. + +## 테스트 + +```bash +./gradlew :adapter:outbound:redis-runtime:test --console=plain +``` diff --git a/src/adapter/outbound/redis-runtime/CLAUDE.md b/src/adapter/outbound/redis-runtime/CLAUDE.md new file mode 100644 index 00000000..43c994c2 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/adapter/outbound/redis-runtime/README.md b/src/adapter/outbound/redis-runtime/README.md new file mode 100644 index 00000000..3e12619f --- /dev/null +++ b/src/adapter/outbound/redis-runtime/README.md @@ -0,0 +1,31 @@ +# adapter:outbound:redis-runtime + +Redis 연결과 명령 실행의 공용 runtime을 담는 leaf다. 업무 포트는 위 leaf(`cache-redis`, `redis-sdk`)가 구현한다. + +## 책임과 소유하지 않는 것 + +- Redis 연결(standalone·sentinel·cluster·TLS)과 그 수명(`connection`의 `RedisRuntimeClient`, lane·account), 의미 단위 명령(`command.SemanticRedisCommands`), key 규칙(`key`), 설정(`config`의 `app.redis.*`, `RedisRuntimeSettings`)과 health. +- `cache-redis`와 `redis-sdk`가 같은 연결 하나를 쓰게 하는 바닥이다. 업무 포트를 구현하지 않는다. +- testFixtures: 메모리 명령(`InMemorySemanticRedisCommands`), stub client, 실 topology endpoint(`RedisTopologyEndpoint`). 두 위 leaf의 시험이 쓴다. +- 소유하지 않는 것: cache·rate-limit·lease·멱등성 포트 구현(`adapter:outbound:cache-redis`), Redis SDK 표면(`adapter:outbound:redis-sdk`). + +## 공개 표면 + +`connection.RedisRuntimeClient`, `command.SemanticRedisCommands`, key 타입, 설정 `app.redis.*`(env `APP_REDIS_*`, `docs/registries/env-keys.yaml`, 기본값 `config/module-defaults/redis-runtime.yml`). + +## 조립 + +직접 더하지 않는다. `runtimeOnly project(':adapter:outbound:cache-redis')`가 이 leaf를 함께 싣고, 이 leaf의 `RedisRuntimeAutoConfiguration`이 켜진다. 끄는 키는 `APP_REDIS_ENABLED`다. + +## 테스트 명령 + +```bash +./gradlew :adapter:outbound:redis-runtime:test --console=plain +``` + +## 더 읽을 곳 + +- [AGENTS.md](AGENTS.md)(이 leaf의 규칙) +- `src/adapter/outbound/cache-redis/AGENTS.md`(Redis 설정 트리의 이유, capability) +- `docs/redis/`(명령 정책, 운영, 지원 표) +- `src/adapter/outbound/redis-sdk/compose/README.md`(topology lane 좌표) diff --git a/src/application/fileserver/AGENTS.md b/src/application/fileserver/AGENTS.md new file mode 100644 index 00000000..2f1f7427 --- /dev/null +++ b/src/application/fileserver/AGENTS.md @@ -0,0 +1,29 @@ +# application-fileserver — 파일 서버의 유스케이스와 정책 + +## 등록 정보 + +- 모듈 ID: `application-fileserver` +- Gradle 경로: `:application-fileserver` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :application-fileserver:test --console=plain` +- registry 정본: `gradle/modules.json`. + +패키지 루트: `dev.caskeleton.application.fileserver`. 무엇을 주는지와 조립은 [README.md](README.md)에 있다. + +## 책임 + +- 업로드(단일·raw·batch·이어 쓰기)·다운로드·복사·이동·삭제·정리의 유스케이스와 그 정책(할당량, 전송 허가, 표시 이름). +- 들어오는 포트(`port.in`), 나가는 포트, 오류 어휘 `api.error.FileserverErrorCode`(HTTP 표는 `docs/fileserver/http-contract.md` 「오류 코드」). +- testFixtures `testkit`: 포트마다 fake와 공유 계약. + +## 규칙 + +- framework 의존이 없다(`ca.java-library`). 허용 의존은 registry의 `application-core`·`shared-contract`뿐이다. +- 업로드 이름의 표시 규칙은 `api.security.OriginalFilenamePolicy` 한 곳이다. 이름 없는 업로드의 이름도 여기서 정한다. 전송이 기본 이름을 지어 넣지 않는다. +- 전송 허가(`quota.TransferAdmissionController`)는 호출자 자신의 동시 전송 초과를 `TRANSFER_ADMISSION_REJECTED`(429), instance 전체 포화를 `SERVER_BUSY`(503)로 가른다. +- `FileserverErrorCode`에 code를 더하면 `docs/fileserver/http-contract.md` 「오류 코드」 표에 같은 변경에서 행을 더한다. + +## 테스트 + +```bash +./gradlew :application-fileserver:test --console=plain +``` diff --git a/src/application/fileserver/CLAUDE.md b/src/application/fileserver/CLAUDE.md new file mode 100644 index 00000000..43c994c2 --- /dev/null +++ b/src/application/fileserver/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/application/fileserver/README.md b/src/application/fileserver/README.md new file mode 100644 index 00000000..c2a59f31 --- /dev/null +++ b/src/application/fileserver/README.md @@ -0,0 +1,31 @@ +# application-fileserver + +파일 서버의 유스케이스와 정책을 담는 leaf다. HTTP·저장소·조립은 각각 다른 leaf가 한다. + +## 책임과 소유하지 않는 것 + +- 업로드(단일·raw·batch·이어 쓰기)·다운로드·복사·이동·삭제·정리의 유스케이스와 그 정책(할당량, 전송 허가, 표시 이름). +- 들어오는 포트(`port.in`), 나가는 포트, 오류 어휘 `api.error.FileserverErrorCode`(HTTP 표는 `docs/fileserver/http-contract.md` 「오류 코드」). +- testFixtures `testkit`: 포트마다 fake와 공유 계약. +- 소유하지 않는 것: HTTP 모양(`adapter:inbound:web-fileserver`), 바이트 저장(`adapter:outbound:fileserver`), metadata 저장(`adapter:outbound:persistence-fileserver`), 조립(`composition:fileserver-platform`). + +## 공개 표면 + +들어오는 포트 `port.in`(예: `CreateUploadUseCase`, `AppendUploadUseCase`, `DescribeFileUseCase`, `ForceDeleteFileUseCase`), 오류 `api.error`, 정책 `api.security`·`quota`. 설정 prefix는 없다(설정은 `adapter:outbound:fileserver`의 `app.fileserver-platform.*`). + +## 조립 + +직접 더하지 않는다. `runtimeOnly project(':composition:fileserver-platform')` 한 줄이 유스케이스와 HTTP 표면을 함께 싣는다. 끄는 키는 `APP_FILESERVER_PLATFORM_ENABLED`다. + +## 테스트 명령 + +```bash +./gradlew :application-fileserver:test --console=plain +``` + +## 더 읽을 곳 + +- [AGENTS.md](AGENTS.md)(이 leaf의 규칙) +- `docs/fileserver/`(HTTP 계약, 설정, 운영, 보안) +- `src/adapter/outbound/fileserver/README.md`(저장소 adapter) +- `src/bootstrap/fileserver-platform/README.md`(조립) diff --git a/src/application/notification/AGENTS.md b/src/application/notification/AGENTS.md new file mode 100644 index 00000000..8fe73991 --- /dev/null +++ b/src/application/notification/AGENTS.md @@ -0,0 +1,29 @@ +# application-notification — 알림 플랫폼의 유스케이스와 포트 + +## 등록 정보 + +- 모듈 ID: `application-notification` +- Gradle 경로: `:application-notification` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :application-notification:test --console=plain` +- registry 정본: `gradle/modules.json`. + +패키지 루트: `dev.caskeleton.application.notification`. 무엇을 주는지와 조립은 [README.md](README.md)에 있다. + +## 책임 + +- 알림 플랫폼의 업무 흐름: 제출·예약·취소·조회, template 게시, provider callback 수집, 발송 판정과 재시도 정책. +- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`)와 나가는 포트(`platform.port.out`), 오류 어휘(`platform.api.error`). +- testFixtures: 포트마다 fake 하나와 공유 계약. adapter의 시험이 같은 계약을 상속한다. + +## 규칙 + +- framework 의존이 없다(`ca.java-library`). Spring·JPA·HTTP 타입을 쓰지 않는다. 허용 의존은 registry의 `application-core`·`shared-contract`뿐이다. +- 전송 DTO(HTTP 요청·응답 record)를 여기에 두지 않는다. 전송 모양은 `adapter:inbound:web-notification`의 것이다. +- 발송 판정(마케팅 억제, category 필수)은 여기서 한다. 전송이나 설정에서 기본값을 골라 넣지 않는다. +- 공개 타입이 늘면 `docs/notification/api-surface-snapshot.txt`가 바뀐다(`adapter:outbound:notification`의 `verifyNotificationApiSurface`가 이 leaf까지 본다). + +## 테스트 + +```bash +./gradlew :application-notification:test --console=plain +``` diff --git a/src/application/notification/CLAUDE.md b/src/application/notification/CLAUDE.md new file mode 100644 index 00000000..43c994c2 --- /dev/null +++ b/src/application/notification/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/application/notification/README.md b/src/application/notification/README.md new file mode 100644 index 00000000..8c7c169b --- /dev/null +++ b/src/application/notification/README.md @@ -0,0 +1,31 @@ +# application-notification + +알림 플랫폼의 유스케이스와 포트를 담는 leaf다. 알림을 제출하는 HTTP·발송 provider·저장은 각각 다른 leaf가 한다. + +## 책임과 소유하지 않는 것 + +- 알림 플랫폼의 업무 흐름: 제출·예약·취소·조회, template 게시, provider callback 수집, 발송 판정과 재시도 정책. +- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`)와 나가는 포트(`platform.port.out`), 오류 어휘(`platform.api.error`). +- testFixtures: 포트마다 fake 하나와 공유 계약. adapter의 시험이 같은 계약을 상속한다. +- 소유하지 않는 것: HTTP 모양(`adapter:inbound:web-notification`), provider 호출·설정(`adapter:outbound:notification`), 저장(`adapter:outbound:persistence-notification`), 조립(`composition:notification-platform`). + +## 공개 표면 + +들어오는 포트 `platform.port.in`(예: `SubmitNotificationUseCase`, `PublishNotificationTemplateUseCase`, `IngestProviderCallbackUseCase`), 나가는 포트 `platform.port.out`, 오류 `platform.api.error`. 설정 prefix는 없다(설정은 `adapter:outbound:notification`의 `app.notification.platform.*`). + +## 조립 + +직접 더하지 않는다. `runtimeOnly project(':composition:notification-platform')` 한 줄이 유스케이스를 조립하고 이 leaf를 함께 싣는다. 끄는 키는 `APP_NOTIFICATION_PLATFORM_ENABLED`다. + +## 테스트 명령 + +```bash +./gradlew :application-notification:test --console=plain +``` + +## 더 읽을 곳 + +- [AGENTS.md](AGENTS.md)(이 leaf의 규칙) +- `src/adapter/outbound/notification/README.md`(플랫폼 전체, 설정) +- `docs/notification/`(지원 표, 운영, callback 대조) +- `src/bootstrap/notification-platform/README.md`(조립) diff --git a/src/application/objectstorage/AGENTS.md b/src/application/objectstorage/AGENTS.md new file mode 100644 index 00000000..da3cdece --- /dev/null +++ b/src/application/objectstorage/AGENTS.md @@ -0,0 +1,27 @@ +# application-objectstorage — 객체 저장소 포트 + +## 등록 정보 + +- 모듈 ID: `application-objectstorage` +- Gradle 경로: `:application-objectstorage` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :application-objectstorage:test --console=plain` +- registry 정본: `gradle/modules.json`. + +패키지 루트: `dev.caskeleton.application.objectstorage`. 무엇을 주는지와 조립은 [README.md](README.md)에 있다. + +## 책임 + +- 객체 저장소를 쓰는 쪽이 보는 포트와 그 값 타입: 전송(`ObjectTransferPort`), 검사, 게시(staged·managed), 회수, 결과 확인. +- `model`·`request`·`identity`·`content`의 값 타입. 구현은 `adapter:outbound:objectstorage` 하나다. + +## 규칙 + +- framework·AWS SDK 의존이 없다(`ca.java-library`). 허용 의존은 registry의 `application-core`·`shared-contract`뿐이다. +- S3·MinIO 개념(bucket 정책, presign 구현)은 adapter의 것이다. 포트는 저장소에 상관없는 말로 쓴다. +- 포트를 바꾸면 adapter의 계약 시험(`adapter:outbound:objectstorage` testFixtures)을 같은 변경에서 고친다. + +## 테스트 + +```bash +./gradlew :application-objectstorage:test --console=plain +``` diff --git a/src/application/objectstorage/CLAUDE.md b/src/application/objectstorage/CLAUDE.md new file mode 100644 index 00000000..43c994c2 --- /dev/null +++ b/src/application/objectstorage/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/application/objectstorage/README.md b/src/application/objectstorage/README.md new file mode 100644 index 00000000..2cf93658 --- /dev/null +++ b/src/application/objectstorage/README.md @@ -0,0 +1,30 @@ +# application-objectstorage + +객체 저장소 포트와 그 값 타입을 담는 leaf다. 구현은 `adapter:outbound:objectstorage` 하나다. + +## 책임과 소유하지 않는 것 + +- 객체 저장소를 쓰는 쪽이 보는 포트와 그 값 타입: 전송(`ObjectTransferPort`), 검사, 게시(staged·managed), 회수, 결과 확인. +- `model`·`request`·`identity`·`content`의 값 타입. 구현은 `adapter:outbound:objectstorage` 하나다. +- 소유하지 않는 것: S3·MinIO 호출과 설정(`adapter:outbound:objectstorage`), 파일 서버의 업로드 흐름(`application-fileserver`). + +## 공개 표면 + +`port`의 여덟 포트(`ObjectTransferPort`, `ObjectInspectionPort`, `StagedObjectPublicationPort`, `ManagedObjectPublicationPort`, `ObjectRetirementPort` 등)와 값 타입. 설정 prefix는 없다(`app.object-storage.*`는 adapter의 것). + +## 조립 + +직접 더하지 않는다. `runtimeOnly project(':adapter:outbound:objectstorage')` 한 줄이 이 leaf를 함께 싣는다. 끄는 키는 `APP_OBJECTSTORAGE_ENABLED`다. + +## 테스트 명령 + +```bash +./gradlew :application-objectstorage:test --console=plain +``` + +## 더 읽을 곳 + +- [AGENTS.md](AGENTS.md)(이 leaf의 규칙) +- `src/adapter/outbound/objectstorage/README.md`(adapter, 설정, MinIO lane) +- `docs/objectstorage/env-fields.yaml`(env 칸) +- `docs/storage-capability-boundary.md`(파일 서버와의 경계) diff --git a/src/shared-contract/AGENTS.md b/src/shared-contract/AGENTS.md index 8c140d9a..04e75caa 100644 --- a/src/shared-contract/AGENTS.md +++ b/src/shared-contract/AGENTS.md @@ -15,13 +15,18 @@ tracing 이음매, domain-context 전파)은 [README.md](README.md)에 있다. 남는다. ## 책임 (Responsibility) -- 응답 envelope(`response/Envelope`, `response/ApiError`, `response/BulkEnvelope`, `response/BulkItemResult`). -- 오류 코드 계약(`error/ApiErrorCode` 인터페이스, `error/OperationalError` enum, +- 응답 envelope(`response/Envelope`, `response/ApiError`, `response/BulkEnvelope`, `response/BulkItemResult`)와 그 meta + (`response/ResponseMeta`, 목록의 `response/PageMeta`). +- 오류 코드 계약(`error/ApiErrorCode` 인터페이스, `error/Category`, `error/OperationalError` enum, `error/ApiErrorCarrier`)과 클라이언트에 보여 줄 문구 표 하나(`error/ClientErrorMessages`. 한국어이고 `Category`마다 문구 하나이며 모든 전송 계층이 쓴다). +- 전송이 같은 규칙으로 읽는 공용 carrier 예외(`error/DependencyFailureException`, + `error/PersistenceFailureException`, `error/AdapterDisabledException`)와 서버 실패 로그 한 줄의 모양 + (`error/ServerFailureLog`. 모든 전송이 같은 레벨·키로 남긴다). - 계층을 가로지르는 mapper 표지 예외(`error/MappingException`). - 요청 값 계약(`request/Patch`). -- tracing 계약 타입(`tracing/TraceParent`, `tracing/SpanErrorRecorder`) — W3C `traceparent` 값 타입과 +- tracing 계약 타입(`tracing/TraceParent`, `tracing/SpanErrorRecorder`, `tracing/ActiveTrace`) — W3C `traceparent` 값 타입, + 지금 trace를 읽는 이음매와 span 오류 기록 이음매(feature-distributed-tracing-contract. OTel tracer 런타임은 fork가 켜는 이음매라서 이 타입들은 Java 표준 라이브러리만 쓴다). - 모든 leaf가 복사해 쓰던 표준 라이브러리 도우미(2026-09-25 리뷰 후속으로 여기로 옮겼다): -- 2.54.0 From 377cf176531bfb6ac55b6a54e503ee1f5a4154af Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 05:09:45 +0900 Subject: [PATCH 17/23] =?UTF-8?q?fix(http):=20=EC=83=88=20=EB=88=88=20?= =?UTF-8?q?=EB=A6=AC=EB=B7=B0=EA=B0=80=20=EC=B0=BE=EC=9D=80=20=EA=B3=84?= =?UTF-8?q?=EC=95=BD=20=EB=B9=88=ED=8B=88=EC=9D=84=20=EB=8B=AB=EB=8A=94?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR 전 리뷰(계약·시험 렌즈, 구조 리뷰) 발견을 고친다. - 상태만 아는 503·429(Spring이 던진 ResponseStatusException 등)가 SERVER_BUSY· RATE_LIMIT_EXCEEDED로 나가면서 Retry-After를 싣지 않았다. error dispatch는 싣는데 handleExceptionInternal은 안 실었다. registry 값을 같은 advisor로 단다. - virtual thread admission filter가 보안 chain 앞이라 cross-origin 거절 503에 CORS 헤더가 없어 브라우저가 본문도 Retry-After도 못 읽었고, 인증 없는 요청도 permit을 썼다. chain 바로 뒤(-99)로 옮겼다. - permit을 한 번만 돌려주는 가드, onTimeout 뒤 onComplete, onStartAsync 재등록을 지키는 시험이 없었다. 둘을 더했다. - stream 위치 규칙이 writer와 WebStreamEvidence 두 곳에 있었다. 증거에 requireNext를 두고 writer가 쓰기 전에 부른다. - fileserver Retry-After가 좁히기 식을 복사했고 SERVER_BUSY 값을 두 번 적었다. ErrorResponseFactory.effectiveRetryable 하나를 같이 쓰고, 공용 이름의 code는 RetryAfterAdvisor 값을 읽는다. 재시도 불가 code 전부가 헤더를 싣지 않는지 본다. - batch 전체 성공의 results[]에 "error": null이 나갔다. 항목 record가 null을 생략한다. batch 시험은 envelope wire 규칙을 실은 mapper로 키 집합을 본다. - 알림 channel·locale 파싱이 두 controller에 있었다. NotificationVocabulary 하나로 모으고, detail은 web 검증 어휘(INVALID)를 쓴다. 예외 이름을 NotificationFieldRejectedException으로 바꿨다(THROWABLES_ARE_NAMED_EXCEPTION). template 게시의 거절 시험을 더했다. - patch 전체 검증 설명에서 상태 전이 예를 뺐다. 검증 대상은 web 표현 DTO이고 업무 규칙은 유스케이스의 것이다. - web README의 RetryAfterHint 예시, upgrade 안내 행 넷(bulk 문구·null 키, stream 역행 항목, 상태만 아는 503·429의 Retry-After, admission filter 순서)과 부분 실패의 part 짚기(index)를 적었다. Refs: RR9-03-01, RR9-03-02, RR9-03-06, RR9-03-13, RR9-03-15, RR9-03-23, RR9-03-24, RR9-03-25, RR9-03-27 --- docs/fileserver/http-contract.md | 2 +- docs/upgrade/2026-11-round9-contracts.md | 6 +- docs/web/patch-contract.md | 6 +- docs/web/virtual-thread-profile.md | 5 +- .../web/advanced/mvc/MvcStreamWriter.java | 16 ++--- .../mvc/VirtualThreadAdmissionFilter.java | 15 +++-- .../web/advanced/patch/PatchBodies.java | 6 +- .../advanced/stream/WebStreamEvidence.java | 49 ++++++++++---- .../mvc/VirtualThreadAdmissionFilterTest.java | 58 ++++++++++++++++ .../fileserver/dto/BatchUploadItemResult.java | 5 ++ .../problem/FileserverProblemHeaders.java | 20 ++++-- .../controller/FileUploadControllerTest.java | 35 +++++++++- .../FileserverProblemHeaderParityTest.java | 34 ++++++++++ ...> NotificationFieldRejectedException.java} | 9 +-- .../NotificationSubmissionController.java | 34 +--------- .../NotificationTemplateController.java | 61 ++--------------- .../submission/NotificationVocabulary.java | 65 ++++++++++++++++++ .../NotificationTemplateControllerTest.java | 67 +++++++++++++++++++ src/adapter/inbound/web/README.md | 2 +- .../web/error/ErrorResponseFactory.java | 10 ++- .../web/error/GlobalExceptionHandler.java | 15 ++++- .../web/error/TransportErrorHandlingTest.java | 38 +++++++++++ 22 files changed, 416 insertions(+), 142 deletions(-) rename src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/{NotificationFieldRejection.java => NotificationFieldRejectedException.java} (73%) create mode 100644 src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationVocabulary.java create mode 100644 src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateControllerTest.java diff --git a/docs/fileserver/http-contract.md b/docs/fileserver/http-contract.md index d5518f01..3178e907 100644 --- a/docs/fileserver/http-contract.md +++ b/docs/fileserver/http-contract.md @@ -99,7 +99,7 @@ servlet chain에서 `app.fileserver-platform.security.admin-roles`로 막고, batch 업로드는 공용 bulk envelope다. 모든 part가 성공하면 `success: true`와 `results[]`(part마다 `clientPartId`, `status`, `fileId`)다. 한 part라도 거부되면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`, `error.details[]`다. `details[]` 항목은 part 순서의 `index`, `status`(`ok`·`error`), 성공한 part의 `id`(fileId), 거부된 part의 `code`와 -category 고정 문구 `message`다. 성공한 part는 되돌리지 않는다. +category 고정 문구 `message`다. 부분 실패에서 part는 요청에 보낸 순서의 `index`로 짚는다(`clientPartId`는 전부 성공한 `results[]`에만 있다). 성공한 part는 되돌리지 않는다. ### Envelope 규칙의 프로토콜 예외 diff --git a/docs/upgrade/2026-11-round9-contracts.md b/docs/upgrade/2026-11-round9-contracts.md index 5731f75c..650bcc8c 100644 --- a/docs/upgrade/2026-11-round9-contracts.md +++ b/docs/upgrade/2026-11-round9-contracts.md @@ -17,7 +17,7 @@ | 3 | patch 결과가 Bean Validation 제약을 어기면 `400 VALIDATION_FAILED`와 필드별 `details`가 나간다. patch 대상 타입의 제약을 확인한다 | 전에는 제약을 어긴 객체가 그대로 저장 경로로 갔다 | web-advanced patch를 쓰는 서비스 | | 4 | 스트림 `Failure` 기록의 `code`가 실패의 코드(예: `STREAM_ITEM_TOO_LARGE`) 또는 `INTERNAL_ERROR`다. `DEPENDENCY_FAILURE`로 분기하던 client를 고친다 | 그 분기가 다시는 맞지 않는다 | NDJSON·JSON-seq stream을 읽는 client | | 5 | virtual thread profile을 켠 배포는 이제 실제로 허가 상한을 건다. `admission-limit`이 부하에 맞는지 본다 | 전에는 상한이 없어 모든 요청이 들어왔다. 이제 넘치면 `503 SERVER_BUSY`와 `Retry-After: 1`이다 | `app.web.advanced.mvc-virtual-threads.enabled=true`인 배포 | -| 6 | fileserver batch(`POST /v1/files:batch`)를 읽는 client는 `success`로 가른다. 모두 성공하면 `success: true`와 최상위 `results[]`, 하나라도 실패하면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`, part별 `error.details[]`(`index`, `status`, `id`, `code`, `message`)다 | 전에는 실패가 있어도 `success: true`이고 결과가 `data.results[]`에 있었다. 옛 경로로 읽던 client는 결과를 못 찾는다 | fileserver를 쓰는 서비스와 그 client | +| 6 | fileserver batch(`POST /v1/files:batch`)를 읽는 client는 `success`로 가른다. 모두 성공하면 `success: true`와 최상위 `results[]`, 하나라도 실패하면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`, part별 `error.details[]`(`index`, `status`, `id`, `code`, `message`)다. 부분 실패에서는 part를 요청 순서 `index`로 짚는다(`clientPartId`는 전부 성공한 `results[]`에만 있다) | 전에는 실패가 있어도 `success: true`이고 결과가 `data.results[]`에 있었다. 옛 경로로 읽던 client는 결과를 못 찾는다 | fileserver를 쓰는 서비스와 그 client | | 7 | `BulkItemResult.error(index, code, message)`를 부르던 코드를 `BulkItemResult.error(index, ApiErrorCode)`로 바꾼다. 문구는 code의 category 고정 문구가 된다 | 컴파일이 실패한다 | bulk endpoint를 둔 서비스 | | 8 | 서버 포화 거절을 읽는 client는 `SERVER_BUSY`(503, retryable, `Retry-After: 1`)로 본다. web-advanced `ADMISSION_REFUSED`, fileserver instance·전송 pool 포화의 `TRANSFER_ADMISSION_REJECTED`(429), gRPC 포화의 `RESOURCE_EXHAUSTED`/`RATE_LIMIT_EXCEEDED`가 이 코드로 바뀌었다(gRPC status는 `UNAVAILABLE`). 호출자 자신의 동시 전송 초과만 `TRANSFER_ADMISSION_REJECTED` 429로 남는다 | 옛 코드로 분기하던 재시도 로직이 맞지 않는다. 자바에서 `WebAdvancedError.ADMISSION_REFUSED`를 참조하던 코드는 컴파일이 실패한다 | 세 전송의 client, web-advanced 코드를 참조하던 서비스 | | 9 | 컨테이너가 넘긴 503(필터의 `sendError(503)` 등)은 `SERVER_BUSY`다. 비동기 요청 시간 초과만 `REQUEST_TIMEOUT`이다 | 전에는 모든 503이 `REQUEST_TIMEOUT`이었다 | web을 쓰는 모든 서비스의 client | @@ -26,3 +26,7 @@ | 12 | 이름 없이 올린 파일의 표시 이름이 `upload.bin`에서 `file`이 된다(모든 전송에서 같다) | 표시 이름이 바뀐다. 동작은 같다 | fileserver를 쓰는 서비스 | | 13 | fileserver `ATOMIC_PUBLISH_UNSUPPORTED`(재시도 불가 code)는 더 이상 `Retry-After`를 싣지 않는다. 본문 `retryable=false`와 맞춘 것이다 | 그 헤더로 재시도하던 client가 재시도하지 않는다(원래 재시도해도 소용없는 실패다) | fileserver client | | 14 | 브라우저 client는 `Content-Range`를 읽을 수 있다(CORS 노출 목록에 더함) | — 더하기만 한 변경 | fileserver 다운로드를 이어 받는 브라우저 client | +| 15 | bulk 부분 실패의 `error.message`가 영어 문구에서 category 고정 문구(`ClientErrorMessages`)로 바뀌었다. 항목(`details[]`)은 자기 상태에 맞는 키만 싣는다(성공 항목에 `code`·`message` 키 없음, 실패 항목에 `id` 키 없음) | 문구로 분기하던 client(원래 하면 안 된다)나 null 키를 기대하던 strict client가 다르게 본다 | bulk endpoint를 둔 서비스의 client | +| 16 | 스트림에서 위치가 앞 항목보다 크지 않은 항목은 이제 나가지 않고, 스트림이 `INTERNAL_ERROR` `Failure` 기록으로 끝난다(전에는 그 항목을 쓴 뒤 끝났다) | 서버 결함이 있는 source의 client가 마지막 항목을 받지 않는다 | NDJSON·JSON-seq stream을 읽는 client | +| 17 | 상태만 아는 503·429(Spring이 던진 `ResponseStatusException` 등)도 registry의 `Retry-After`를 싣는다 | — 헤더를 더하기만 한 변경 | web을 쓰는 서비스의 client | +| 18 | virtual thread admission filter가 Spring Security chain 뒤에서 돈다. 인증·권한에서 거절된 요청은 허가를 쓰지 않고, 거절 503에 CORS 헤더가 붙는다 | — | virtual thread profile을 켠 배포 | diff --git a/docs/web/patch-contract.md b/docs/web/patch-contract.md index c340fe85..5ab4cdb2 100644 --- a/docs/web/patch-contract.md +++ b/docs/web/patch-contract.md @@ -64,13 +64,13 @@ JSON Patch 문서는 전부 적용되거나 하나도 적용되지 않는다. ## 검증 patch를 적용한 결과는 필드 하나씩이 아니라 문서 전체로 검증한다. 필드 하나하나는 모두 유효한 patch가 유효하지 않은 -객체를 만들 수 있다. 서로 맞아야 하는 두 필드, 허락되지 않은 상태 전이 같은 것이다. 바뀐 것만 검증하면 그중 아무것도 -보지 못한다. +객체를 만들 수 있다. 서로 맞아야 하는 두 필드가 그런 예다. 바뀐 것만 검증하면 그것을 보지 못한다. - 두 applier는 서비스의 Bean Validation `Validator`를 생성자로 받고, 결과 객체 전체를 검증한 뒤에 돌려준다. 위반은 `@Valid` 본문과 같은 `400 VALIDATION_FAILED`와 필드별 `details`다. - 결과가 자원 타입으로 읽히지 않으면(숫자 자리에 문자열) `400 PATCH_REJECTED`다. -- 상태 전이처럼 업무 규칙인 검증은 여기서 하지 않는다. 유스케이스가 한다. +- 검증하는 대상은 web 표현 DTO이고, 제약은 요청 문법이다(web AGENTS B4·C1). 상태 전이처럼 업무 규칙인 검증은 여기서 + 하지 않는다. 결과를 command로 바꿔 받은 유스케이스가 한다. ## 선행 조건 diff --git a/docs/web/virtual-thread-profile.md b/docs/web/virtual-thread-profile.md index 94522c31..aac36da7 100644 --- a/docs/web/virtual-thread-profile.md +++ b/docs/web/virtual-thread-profile.md @@ -36,8 +36,9 @@ app: `VirtualThreadAdmissionGuard`는 pool이 아니라 공정한 semaphore다. 스레드를 제한하면 기다림을 되돌려 놓고 virtual thread로 얻은 것을 버리게 된다. virtual thread 만 개가 있어도 백 개만 허가를 쥐고 나머지는 문 앞에서 거부된다. -상한은 `VirtualThreadAdmissionFilter`가 모든 요청에 건다. request-id filter 바로 뒤, 보안 chain보다 앞이라 거부된 요청은 -아무 일도 하지 않는다. async 요청은 async 일이 끝날 때까지 허가를 쥔다. 넘겨준 순간 돌려주면 넘기는 일만 제한하고 정작 +상한은 `VirtualThreadAdmissionFilter`가 모든 요청에 건다. Spring Security chain 바로 뒤라, 거절 응답에도 CORS 헤더가 +붙어 브라우저가 503과 `Retry-After`를 읽고, 보안 chain이 거절한 요청(인증 없음, 권한 없음)은 허가를 쓰지 않는다. 거절된 +요청은 handler에 닿지 않는다. async 요청은 async 일이 끝날 때까지 허가를 쥔다. 넘겨준 순간 돌려주면 넘기는 일만 제한하고 정작 하류 pool을 쓰는 일은 제한하지 못한다. 거부는 **`Retry-After`가 붙은 503**(공용 코드 `SERVER_BUSY`)이고, 상한이 만들려는 결과가 바로 그것이다. 1밀리초 만에 거부된 요청이, 받아들여진 뒤 diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java index d0634a5e..aee74a29 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java @@ -24,9 +24,9 @@ import java.util.Objects; * terminal record before closing, and classify a write failure rather than letting it become a 500 * on a response that is already 200. * - *

Positions are enforced here: an item whose sequence is not above the previous one is a server - * fault, and the stream ends with a terminal failure record instead of handing the client a repeat - * or a rewind it would apply. + *

Positions are enforced before each write, by {@code WebStreamEvidence#requireNext}: an item + * whose sequence is not above the previous one is a server fault, and the stream ends with a + * terminal failure record instead of handing the client a repeat or a rewind it would apply. * *

What this writer does not do: it writes synchronously from an iterator on the request thread, * so it sends no heartbeat while the source is blocked, enforces no idle timeout or maximum age, @@ -72,13 +72,9 @@ public final class MvcStreamWriter { try { while (records.hasNext()) { NdjsonRecord record = records.next(); - if (record instanceof NdjsonRecord.Item item && item.sequence() <= lastSequence) { - throw new IllegalStateException( - "stream position " - + item.sequence() - + " does not follow " - + lastSequence - + "; positions strictly increase"); + if (record instanceof NdjsonRecord.Item item) { + // WebStreamEvidence owns the rule; asked before the write so the item never leaves. + evidence.requireNext(new StreamSequence(item.sequence())); } writeRecord(record, output); if (record instanceof NdjsonRecord.Item item) { diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java index 9a4c6914..87f4344c 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilter.java @@ -22,8 +22,8 @@ import tools.jackson.databind.ObjectMapper; * *

The guard alone was a bean nothing called: the profile promised a {@code 503} with {@code * Retry-After} past the limit, and a deployment that switched it on admitted every arrival (review - * 2026-11-12). A filter, not an interceptor, so the limit covers the whole request including the - * security chain, and refuses before any of it runs. + * 2026-11-12). A filter, not an interceptor, so the limit covers the handler and its async work; + * ordered after the security chain (see {@link #ORDER}). * *

A request that goes async keeps its permit until the async work ends: releasing when this * thread returns would bound only the hand-off, and the work the limit protects the downstream @@ -31,8 +31,15 @@ import tools.jackson.databind.ObjectMapper; */ public final class VirtualThreadAdmissionFilter extends OncePerRequestFilter implements Ordered { - /** Right after the request-id filter, so a refusal still carries the request id. */ - public static final int ORDER = Ordered.HIGHEST_PRECEDENCE + 11; + /** + * Right after the Spring Security filter chain (Boot's {@code SecurityProperties + * .DEFAULT_FILTER_ORDER}, -100). Two reasons. The chain applies CORS, so a cross-origin refusal + * carries {@code Access-Control-Allow-Origin} and the browser can read its 503 and {@code + * Retry-After}; in front of the chain it reached the page as a network error. And a request the + * chain refuses (unauthenticated, forbidden) never takes a permit from the admitted ones (review + * 2026-11-12). + */ + public static final int ORDER = -99; private final VirtualThreadAdmissionGuard guard; private final ObjectMapper objectMapper; diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java index cca6b7af..63853ad5 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java @@ -31,8 +31,10 @@ final class PatchBodies { /** * The patched tree as the target type, validated as a whole document. * - *

Whole, not field by field: two fields that must agree, or a state only some transitions - * allow, are invisible to a check of the changed fields alone. A violation is the same {@link + *

Whole, not field by field: two fields whose values must agree are invisible to a check of + * the changed fields alone. {@code T} is the web representation DTO, whose constraints are + * request syntax (web AGENTS B4·C1); business rules such as allowed state transitions belong to + * the use case the caller hands the result to as a command. A violation is the same {@link * ConstraintViolationException} a {@code @Valid} body raises, so the client gets {@code 400 * VALIDATION_FAILED} with the per-field details it already knows. */ diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java index f02a2b1f..10927ca7 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java @@ -38,6 +38,22 @@ public final class WebStreamEvidence { return streamId; } + /** + * Refuse a position before it is written: the same check {@link #recordDelivered} makes after the + * write, so a writer can keep a repeat or a rewind off the wire instead of only recording it. + * + * @throws IllegalStateException if the position does not advance, or the stream already ended + */ + public void requireNext(StreamSequence sequence) { + Objects.requireNonNull(sequence, "sequence"); + lock.lock(); + try { + requireAdvances(sequence); + } finally { + lock.unlock(); + } + } + /** * Record that an item reached the transport. * @@ -47,20 +63,7 @@ public final class WebStreamEvidence { Objects.requireNonNull(sequence, "sequence"); lock.lock(); try { - if (termination != null) { - throw new IllegalStateException( - "an item was delivered after the stream ended as " - + termination - + "; the terminal envelope has already told the client there is nothing more"); - } - if (lastDelivered != null && sequence.compareTo(lastDelivered) <= 0) { - throw new IllegalStateException( - "stream position went from " - + lastDelivered.value() - + " to " - + sequence.value() - + "; a client deduplicating on position would silently drop this item"); - } + requireAdvances(sequence); lastDelivered = sequence; deliveredCount++; } finally { @@ -68,6 +71,24 @@ public final class WebStreamEvidence { } } + /** Callers hold the lock. */ + private void requireAdvances(StreamSequence sequence) { + if (termination != null) { + throw new IllegalStateException( + "an item was delivered after the stream ended as " + + termination + + "; the terminal envelope has already told the client there is nothing more"); + } + if (lastDelivered != null && sequence.compareTo(lastDelivered) <= 0) { + throw new IllegalStateException( + "stream position went from " + + lastDelivered.value() + + " to " + + sequence.value() + + "; a client deduplicating on position would silently drop this item"); + } + } + /** Record how the stream ended. The first call wins; the end happens once. */ public void recordTermination(WebStreamTermination how, Instant at) { Objects.requireNonNull(how, "how"); diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java index a5c10cd1..18dbb94d 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java @@ -1,13 +1,18 @@ package dev.caskeleton.adapter.inbound.web.advanced.mvc; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.AdmissionRefusedException; import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadAdmissionGuard; +import jakarta.servlet.AsyncEvent; +import jakarta.servlet.AsyncListener; import java.time.Duration; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockAsyncContext; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import tools.jackson.databind.json.JsonMapper; @@ -89,4 +94,57 @@ class VirtualThreadAdmissionFilterTest { .isEqualTo(1); assertThat(guard.active()).isZero(); } + + @Test + @DisplayName("async 시간 초과 뒤 완료가 또 와도 permit은 한 번만 돌아가 상한이 늘지 않는다") + void aTimeoutFollowedByCompletionReleasesThePermitOnce() throws Exception { + // given + VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO); + VirtualThreadAdmissionFilter filter = + new VirtualThreadAdmissionFilter(guard, JsonMapper.shared()); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/orders"); + request.setAsyncSupported(true); + filter.doFilter( + request, new MockHttpServletResponse(), (req, res) -> request.startAsync(req, res)); + MockAsyncContext async = (MockAsyncContext) request.getAsyncContext(); + AsyncEvent event = new AsyncEvent(async); + + // when — a container calls onTimeout, then onComplete, for one timed-out request + for (AsyncListener listener : async.getListeners()) { + listener.onTimeout(event); + listener.onComplete(event); + } + + // then + assertThat(guard.active()).isZero(); + try (VirtualThreadAdmissionGuard.Permit only = guard.enter()) { + assertThat(catchThrowable(guard::enter)) + .as("a permit released twice would let a second request past a limit of one") + .isInstanceOf(AdmissionRefusedException.class); + } + } + + @Test + @DisplayName("async가 다시 시작되면 새 cycle에도 permit을 돌려주는 listener가 붙는다") + void aRestartedAsyncCycleKeepsTheReleaseListener() throws Exception { + // given + VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO); + VirtualThreadAdmissionFilter filter = + new VirtualThreadAdmissionFilter(guard, JsonMapper.shared()); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/orders"); + request.setAsyncSupported(true); + MockHttpServletResponse response = new MockHttpServletResponse(); + filter.doFilter(request, response, (req, res) -> request.startAsync(req, res)); + MockAsyncContext first = (MockAsyncContext) request.getAsyncContext(); + MockAsyncContext restarted = new MockAsyncContext(request, response); + + // when + for (AsyncListener listener : first.getListeners()) { + listener.onStartAsync(new AsyncEvent(restarted)); + } + restarted.complete(); + + // then + assertThat(guard.active()).isZero(); + } } diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadItemResult.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadItemResult.java index b2131c4c..72bbf272 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadItemResult.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadItemResult.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.inbound.web.fileserver.dto; +import com.fasterxml.jackson.annotation.JsonInclude; import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.upload.FileView; import dev.caskeleton.shared.error.ClientErrorMessages; @@ -12,7 +13,11 @@ import dev.caskeleton.shared.response.ApiError; * rolls back a sibling that already succeeded. A rejected part carries the same {@link ApiError} * the single-file endpoints put in their Envelope: stable code, category, the shared client message * and {@code retryable}. The server-side message never crosses this boundary. + * + *

Absent members are omitted on the wire, like every envelope field (http-contract §1): an + * accepted part has no {@code error} key rather than {@code "error": null}. */ +@JsonInclude(JsonInclude.Include.NON_NULL) public record BatchUploadItemResult( String clientPartId, String status, String fileId, ApiError error) { diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java index 1a6ad304..6d68a418 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java @@ -1,10 +1,13 @@ package dev.caskeleton.adapter.inbound.web.fileserver.problem; +import dev.caskeleton.adapter.inbound.web.error.ErrorResponseFactory; import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpRangeNotSatisfiableException; +import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor; import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.FileserverException; import java.util.LinkedHashMap; import java.util.Map; +import java.util.OptionalInt; /** * The headers a Fileserver failure carries, owned once for every transport. @@ -30,7 +33,6 @@ public final class FileserverProblemHeaders { private static final Map RETRY_AFTER_SECONDS = Map.of( FileserverErrorCode.TRANSFER_ADMISSION_REJECTED, 1, - FileserverErrorCode.SERVER_BUSY, 1, FileserverErrorCode.STORAGE_UNAVAILABLE, 30, FileserverErrorCode.TRANSFER_TIMEOUT, 5, FileserverErrorCode.FILE_NOT_READY, 2, @@ -45,13 +47,17 @@ public final class FileserverProblemHeaders { */ public static Map of(FileserverException failure) { Map headers = new LinkedHashMap<>(); - Integer retryAfter = RETRY_AFTER_SECONDS.get(failure.code()); // Only a failure the server itself called retryable advertises a retry: telling a client to - // come back after a permanent rejection is worse than saying nothing. The same narrowing as the - // body (ErrorResponseFactory): the occurrence can only narrow its code, so a code that is never - // retryable never carries the header, whatever the occurrence said (review 2026-11-12). - if (retryAfter != null && failure.code().retryable() && failure.context().retryable()) { - headers.put("Retry-After", String.valueOf(retryAfter)); + // come back after a permanent rejection is worse than saying nothing. The body's own rule + // (ErrorResponseFactory.effectiveRetryable): the occurrence can only narrow its code, so a code + // that is never retryable never carries the header, whatever the occurrence said. A code that + // shares its name with an operational one (SERVER_BUSY) takes the registry's value from + // RetryAfterAdvisor rather than a second copy here. + if (ErrorResponseFactory.effectiveRetryable(failure.code(), failure.context().retryable())) { + Integer own = RETRY_AFTER_SECONDS.get(failure.code()); + OptionalInt seconds = + own != null ? OptionalInt.of(own) : RetryAfterAdvisor.retryAfterSeconds(failure.code()); + seconds.ifPresent(value -> headers.put("Retry-After", String.valueOf(value))); } if (failure instanceof HttpRangeNotSatisfiableException unsatisfiable) { headers.put("Content-Range", "bytes */" + unsatisfiable.representationLength()); diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java index fc876c72..fde11716 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java @@ -7,6 +7,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeWireFormatConfig; import dev.caskeleton.adapter.inbound.web.fileserver.mapper.MultipartUploadRequestMapper; import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapper; import dev.caskeleton.adapter.inbound.web.fileserver.testkit.FileserverWebFixtures; @@ -17,13 +18,19 @@ import dev.caskeleton.application.fileserver.api.error.FileserverException; import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; import dev.caskeleton.application.fileserver.upload.CreateUploadRequest; import java.nio.charset.StandardCharsets; +import java.util.Set; +import java.util.TreeSet; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; +import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; class FileUploadControllerTest { @@ -42,6 +49,11 @@ class FileUploadControllerTest { FileserverWebFixtures.contextFactory(), FileserverWebFixtures.transferExecutor(), FileserverWebFixtures.properties())) + // The envelope wire rules a deployment's mapper carries, so a key the wire omits is + // asserted absent rather than merely null. + .setMessageConverters( + new JacksonJsonHttpMessageConverter( + JsonMapper.builder().addModule(EnvelopeWireFormatConfig.module()).build())) .build(); } @@ -147,7 +159,12 @@ class FileUploadControllerTest { .andExpect(jsonPath("$.success").value(true)) .andExpect(jsonPath("$.results.length()").value(2)) .andExpect(jsonPath("$.results[0].clientPartId").value("a.txt")) - .andExpect(jsonPath("$.results[1].clientPartId").value("b.txt")); + .andExpect(jsonPath("$.results[1].clientPartId").value("b.txt")) + .andExpect( + result -> + assertThat(keys(json(result).get("results").get(0))) + .as("an accepted part carries no error key, not \"error\": null") + .containsExactlyInAnyOrder("clientPartId", "status", "fileId")); } @Test @@ -174,7 +191,11 @@ class FileUploadControllerTest { "files", "b.txt", "text/plain", "b".getBytes(StandardCharsets.UTF_8)))) .andExpect(status().isOk()) .andExpect(jsonPath("$.success").value(false)) - .andExpect(jsonPath("$.results").doesNotExist()) + .andExpect( + result -> + assertThat(keys(json(result))) + .as("a partial failure has no results key at all") + .containsExactlyInAnyOrder("success", "error", "meta")) .andExpect(jsonPath("$.error.code").value("BATCH_PARTIAL_FAILURE")) .andExpect(jsonPath("$.error.details[0].status").value("ok")) .andExpect(jsonPath("$.error.details[0].id").isNotEmpty()) @@ -197,4 +218,14 @@ class FileUploadControllerTest { assertThat(body).doesNotContain("/tmp").doesNotContain("multipart").doesNotContain("staging"); } + + private static JsonNode json(MvcResult result) throws Exception { + return JsonMapper.shared().readTree(result.getResponse().getContentAsString()); + } + + private static Set keys(JsonNode node) { + Set keys = new TreeSet<>(); + node.properties().forEach(entry -> keys.add(entry.getKey())); + return keys; + } } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java index 54e9ffca..caf1be7c 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java @@ -67,6 +67,40 @@ class FileserverProblemHeaderParityTest { .doesNotContainKey("Retry-After"); } + @Test + @org.junit.jupiter.api.DisplayName( + "공용 이름의 SERVER_BUSY는 registry 값(RetryAfterAdvisor)으로 Retry-After를 싣는다") + void aSharedSaturationCodeTakesTheRegistrysRetryAfter() { + // given + FileserverException failure = + new FileserverException( + "pool full", FileserverFailureContext.of(FileserverErrorCode.SERVER_BUSY, true)); + + // when + Map headers = FileserverProblemHeaders.of(failure); + + // then + assertThat(headers).containsEntry("Retry-After", "1"); + } + + @org.junit.jupiter.params.ParameterizedTest(name = "{0}") + @org.junit.jupiter.params.provider.EnumSource(FileserverErrorCode.class) + @org.junit.jupiter.api.DisplayName("재시도 불가 code는 발생이 재시도 가능이라고 해도 Retry-After를 싣지 않는다") + void aNonRetryableCodeNeverAdvertisesARetry(FileserverErrorCode code) { + // given + org.junit.jupiter.api.Assumptions.assumeFalse(code.retryable(), "a retryable code may"); + FileserverException failure = + new FileserverException("refused", FileserverFailureContext.of(code, true)); + + // when + Map headers = FileserverProblemHeaders.of(failure); + + // then + assertThat(headers) + .as("the body narrows retryable to false for %s; the header must agree", code) + .doesNotContainKey("Retry-After"); + } + @Test void anUnsatisfiableRangeDisclosesTheRepresentationLength() { Map headers = diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejection.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejectedException.java similarity index 73% rename from src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejection.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejectedException.java index 6431b9be..b3a2d2c9 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejection.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejectedException.java @@ -15,16 +15,17 @@ import java.util.Objects; *

The same answer a body constraint gets — {@code 400 VALIDATION_FAILED} with one {@code {field, * code, message}} detail — rather than the {@code BAD_PARAMETER} a bare {@code * IllegalArgumentException} reaches, which named nothing the client could correct (review - * 2026-11-12). The rejected value is not echoed. + * 2026-11-12). The detail uses web's validation vocabulary for a value no rule names ({@code + * INVALID}, its fixed wording). The rejected value is not echoed. */ -final class NotificationFieldRejection extends RuntimeException +final class NotificationFieldRejectedException extends RuntimeException implements ApiErrorCarrier, ClientSafeErrorDetails { private static final long serialVersionUID = 1L; private final String field; - NotificationFieldRejection(String field, String reason, Throwable cause) { + NotificationFieldRejectedException(String field, String reason, Throwable cause) { super(reason, cause); this.field = Objects.requireNonNull(field, "field"); } @@ -36,6 +37,6 @@ final class NotificationFieldRejection extends RuntimeException @Override public Object clientDetails() { - return List.of(Map.of("field", field, "code", "UNKNOWN_VALUE", "message", "허용된 값이 아닙니다.")); + return List.of(Map.of("field", field, "code", "INVALID", "message", "값이 올바르지 않습니다.")); } } diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java index 3f01c215..9bc663d0 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java @@ -1,7 +1,6 @@ package dev.caskeleton.adapter.inbound.web.notification.platform.submission; import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory; -import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationCommand; import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationUseCase; import dev.caskeleton.shared.response.Envelope; @@ -70,7 +69,7 @@ public final class NotificationSubmissionController { new AcceptNotificationCommand( Optional.empty(), request.recipientRef(), - channel(request.channel()), + NotificationVocabulary.channel(request.channel()), request.address(), request.template(), // An omitted version or locale stays omitted: the use case owns both defaults. @@ -89,39 +88,10 @@ public final class NotificationSubmissionController { ResponseMetaFactory.fromMdc())); } - /** - * The channel a caller named. - * - *

Parsed here rather than bound by Jackson so an unknown name fails as a validation error on - * the {@code channel} field ({@code VALIDATION_FAILED}), instead of as a deserialization error - * naming a Java enum. - */ - private static Channel channel(String name) { - try { - return Channel.valueOf(name.trim().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException unknown) { - throw new NotificationFieldRejection( - "channel", - "channel must be one of " + java.util.Arrays.toString(Channel.values()), - unknown); - } - } - - /** - * The locale a caller named, or none. - * - *

{@link Locale#forLanguageTag} answers {@code Locale.ROOT} for anything it cannot parse - * rather than failing, so an unparseable tag is refused explicitly — silently rendering a Korean - * notification in the root locale is the kind of wrong that reaches a recipient. - */ private static Optional locale(String tag) { if (tag == null || tag.isBlank()) { return Optional.empty(); } - Locale parsed = Locale.forLanguageTag(tag.trim()); - if (parsed.equals(Locale.ROOT)) { - throw new NotificationFieldRejection("locale", "locale must be a BCP 47 language tag", null); - } - return Optional.of(parsed); + return Optional.of(NotificationVocabulary.locale("locale", tag)); } } diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java index 446b4335..5b61ddc7 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java @@ -1,16 +1,11 @@ package dev.caskeleton.adapter.inbound.web.notification.platform.submission; import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory; -import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.port.in.PublishNotificationTemplateCommand; import dev.caskeleton.application.notification.platform.port.in.PublishNotificationTemplateUseCase; -import dev.caskeleton.application.notification.platform.template.TemplateSlot; import dev.caskeleton.shared.response.Envelope; import jakarta.validation.Valid; -import java.util.EnumMap; import java.util.List; -import java.util.Locale; -import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -78,12 +73,12 @@ public final class NotificationTemplateController { new PublishNotificationTemplateCommand( request.templateId(), Optional.ofNullable(request.version()), - channel(request.channel()), - locale(request.locale()), + NotificationVocabulary.channel(request.channel()), + NotificationVocabulary.locale("locale", request.locale()), Optional.ofNullable(request.fallbackLocale()) .filter(tag -> !tag.isBlank()) - .map(tag -> locale("fallbackLocale", tag)), - slots(request.slots()), + .map(tag -> NotificationVocabulary.locale("fallbackLocale", tag)), + NotificationVocabulary.slots(request.slots()), names(request.requiredVariables()), names(request.sensitiveVariables())); @@ -94,55 +89,7 @@ public final class NotificationTemplateController { ResponseMetaFactory.fromMdc())); } - /** - * The slots a caller named. - * - *

An unknown slot name is refused rather than dropped. Silently ignoring it publishes a - * template missing the content the caller wrote, and the failure then arrives at render time as a - * missing required slot for a template that looks published and complete. - */ - private static Map slots(Map source) { - Map slots = new EnumMap<>(TemplateSlot.class); - source.forEach( - (name, content) -> { - TemplateSlot slot; - try { - slot = TemplateSlot.valueOf(name.trim().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException unknown) { - throw new NotificationFieldRejection( - "slots", - "slot must be one of " + java.util.Arrays.toString(TemplateSlot.values()), - unknown); - } - slots.put(slot, content); - }); - return slots; - } - private static Set names(List source) { return source == null ? Set.of() : Set.copyOf(source); } - - private static Channel channel(String name) { - try { - return Channel.valueOf(name.trim().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException unknown) { - throw new NotificationFieldRejection( - "channel", - "channel must be one of " + java.util.Arrays.toString(Channel.values()), - unknown); - } - } - - private static Locale locale(String tag) { - return locale("locale", tag); - } - - private static Locale locale(String field, String tag) { - Locale parsed = Locale.forLanguageTag(tag.trim()); - if (parsed.equals(Locale.ROOT)) { - throw new NotificationFieldRejection(field, field + " must be a BCP 47 language tag", null); - } - return parsed; - } } diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationVocabulary.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationVocabulary.java new file mode 100644 index 00000000..6dd9784d --- /dev/null +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationVocabulary.java @@ -0,0 +1,65 @@ +package dev.caskeleton.adapter.inbound.web.notification.platform.submission; + +import dev.caskeleton.application.notification.platform.api.routing.Channel; +import dev.caskeleton.application.notification.platform.template.TemplateSlot; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; + +/** + * The names a notification request may use for a channel, a template slot and a locale, parsed once + * for both controllers. + * + *

Parsed here rather than bound by Jackson so an unknown name fails as a validation error on its + * field ({@link NotificationFieldRejectedException}, {@code VALIDATION_FAILED}) instead of as a + * deserialization error naming a Java enum. + */ +final class NotificationVocabulary { + + private NotificationVocabulary() {} + + static Channel channel(String name) { + try { + return Channel.valueOf(name.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException unknown) { + throw new NotificationFieldRejectedException( + "channel", "channel must be one of " + Arrays.toString(Channel.values()), unknown); + } + } + + /** + * A BCP 47 tag. {@link Locale#forLanguageTag} answers {@code Locale.ROOT} for anything it cannot + * parse rather than failing, so an unparseable tag is refused explicitly: silently rendering in + * the root locale is the kind of wrong that reaches a recipient. + */ + static Locale locale(String field, String tag) { + Locale parsed = Locale.forLanguageTag(tag.trim()); + if (parsed.equals(Locale.ROOT)) { + throw new NotificationFieldRejectedException( + field, field + " must be a BCP 47 language tag", null); + } + return parsed; + } + + /** + * The slots a caller named. An unknown slot is refused rather than dropped: ignoring it publishes + * a template missing the content the caller wrote, which then fails at render time as a missing + * required slot of a template that looks published and complete. + */ + static Map slots(Map source) { + Map slots = new EnumMap<>(TemplateSlot.class); + source.forEach( + (name, content) -> { + TemplateSlot slot; + try { + slot = TemplateSlot.valueOf(name.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException unknown) { + throw new NotificationFieldRejectedException( + "slots", "slot must be one of " + Arrays.toString(TemplateSlot.values()), unknown); + } + slots.put(slot, content); + }); + return slots; + } +} diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateControllerTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateControllerTest.java new file mode 100644 index 00000000..f3ae6828 --- /dev/null +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateControllerTest.java @@ -0,0 +1,67 @@ +package dev.caskeleton.adapter.inbound.web.notification.platform.submission; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; +import dev.caskeleton.application.notification.platform.port.in.PublishNotificationTemplateCommand; +import dev.caskeleton.shared.tracing.SpanErrorRecorder; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +class NotificationTemplateControllerTest { + + private final List published = new ArrayList<>(); + + private final MockMvc mvc = + MockMvcBuilders.standaloneSetup( + new NotificationTemplateController( + command -> { + published.add(command); + throw new IllegalStateException("the probe stops after recording"); + })) + .setControllerAdvice(new GlobalExceptionHandler(SpanErrorRecorder.NOOP)) + .build(); + + @ParameterizedTest(name = "{0}") + @CsvSource( + delimiter = '|', + value = { + "channel|\"channel\":\"PIGEON\",\"locale\":\"ko-KR\",\"slots\":{\"SUBJECT\":\"s\"}", + "locale|\"channel\":\"EMAIL\",\"locale\":\"%%%\",\"slots\":{\"SUBJECT\":\"s\"}", + "fallbackLocale|\"channel\":\"EMAIL\",\"locale\":\"ko-KR\",\"fallbackLocale\":\"%%%\",\"slots\":{\"SUBJECT\":\"s\"}", + "slots|\"channel\":\"EMAIL\",\"locale\":\"ko-KR\",\"slots\":{\"FOOTNOTE\":\"s\"}" + }) + @DisplayName("template 게시의 모르는 값은 그 필드를 짚는 400 VALIDATION_FAILED이고 use case에 닿지 않는다") + void anUnknownVocabularyValueIsAValidationFailureNamingTheField(String field, String fields) + throws Exception { + // given + String body = "{\"templateId\":\"welcome\"," + fields + "}"; + + // when + String response = + mvc.perform( + post("/notificationTemplates") + .contentType(MediaType.APPLICATION_JSON) + .content(body)) + .andExpect(status().isBadRequest()) + .andReturn() + .getResponse() + .getContentAsString(); + + // then + assertThat(response) + .contains("\"code\":\"VALIDATION_FAILED\"") + .contains("\"field\":\"" + field + "\"") + .doesNotContain("PIGEON") + .doesNotContain("FOOTNOTE"); + assertThat(published).isEmpty(); + } +} diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 9173bad1..90c6b3ae 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -532,7 +532,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML 이 advisor 가 유일한 Retry-After 노출 지점이라 여기 중앙화한다. `DEPENDENCY_4XX_CLIENT` 는 비재시도(retryable=false)라 `shouldAdvise` 가드로 empty 반환. - 다른 leaf 가 소유한 코드는 이 표에 이름으로 넣지 않고 `RetryAfterHint` 를 구현해 값을 스스로 말한다 - (web-advanced `ADMISSION_REFUSED` = 1초). + (web-advanced `WebAdvancedError`). 서버 포화는 공용 `SERVER_BUSY`(1초)이고 이 표에 있다. - `IDEMPOTENT_IN_FLIGHT` 는 2초: 기본 processing lease(30s)보다 짧아 첫 시도가 끝날 수 있는 동안 같은 키로 다시 묻게 한다. 근거와 클라이언트 행동은 `docs/web/http-contract.md` §2. - 표는 레지스트리의 `retry_after_seconds` 가 있는 행마다 한 줄이다(`LOCK_ACQUISITION_TIMEOUT` 1초, DB·outbox·job diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ErrorResponseFactory.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ErrorResponseFactory.java index 8864d64e..62f5821e 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ErrorResponseFactory.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ErrorResponseFactory.java @@ -31,6 +31,14 @@ public final class ErrorResponseFactory { return body(code, code.retryable(), details); } + /** + * Whether this occurrence may be retried: the occurrence can only narrow its code. The one rule + * for the body's {@code retryable} and for any {@code Retry-After} a transport adds beside it. + */ + public static boolean effectiveRetryable(ApiErrorCode code, boolean occurrenceRetryable) { + return code.retryable() && occurrenceRetryable; + } + /** * Body whose {@code retryable} is decided for this occurrence. * @@ -39,7 +47,7 @@ public final class ErrorResponseFactory { */ public static Envelope body(ApiErrorCode code, boolean retryable, Object details) { String message = ClientErrorMessages.of(code); - boolean effectiveRetryable = code.retryable() && retryable; + boolean effectiveRetryable = effectiveRetryable(code, retryable); ApiError err = details == null ? ApiError.of(code.code(), code.category().name(), message, effectiveRetryable) diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java index ee70d0fe..617b1500 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java @@ -417,7 +417,20 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { log.error("spring mvc failure classified as {}", code.code(), ex); spanErrorRecorder.recordException(ex, code.code()); } + // The code's registry Retry-After, as the error dispatch (EnvelopeErrorController) adds it: a + // 503 classified SERVER_BUSY or a 429 RATE_LIMIT_EXCEEDED left without it here (review + // 2026-11-12). A header Spring already prepared wins. + // Copied: the headers Spring hands over may be read-only. + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.putAll(headers); + if (!responseHeaders.containsHeader(ApiHeaders.RETRY_AFTER)) { + RetryAfterAdvisor.retryAfterSeconds(code) + .ifPresent( + seconds -> responseHeaders.set(ApiHeaders.RETRY_AFTER, String.valueOf(seconds))); + } return new ResponseEntity<>( - ErrorResponseFactory.body(code, null), headers, HttpStatusCode.valueOf(code.httpStatus())); + ErrorResponseFactory.body(code, null), + responseHeaders, + HttpStatusCode.valueOf(code.httpStatus())); } } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java index 85e9c0b7..f6eb8918 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java @@ -124,6 +124,32 @@ class TransportErrorHandlingTest { .andExpect(jsonPath("$.error.code").value("BAD_PARAMETER")); } + @Test + @DisplayName("상태만 아는 503은 SERVER_BUSY이고 registry의 Retry-After를 싣는다") + void aBare503IsServerBusyWithItsRetryAfter() throws Exception { + // when + var result = mvc.perform(get("/t/status-503")); + + // then + result + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.error.code").value("SERVER_BUSY")) + .andExpect(header().string("Retry-After", "1")); + } + + @Test + @DisplayName("상태만 아는 429도 RATE_LIMIT_EXCEEDED의 Retry-After를 싣는다") + void aBare429CarriesItsRetryAfter() throws Exception { + // when + var result = mvc.perform(get("/t/status-429")); + + // then + result + .andExpect(status().isTooManyRequests()) + .andExpect(jsonPath("$.error.code").value("RATE_LIMIT_EXCEEDED")) + .andExpect(header().string("Retry-After", "1")); + } + @Test @DisplayName("비동기 요청 시간 초과는 500이 아니라 재시도 가능한 503 REQUEST_TIMEOUT이다") void anAsyncTimeoutIsARetryable503NotAnInternalError() throws Exception { @@ -199,6 +225,18 @@ class TransportErrorHandlingTest { throw new AsyncRequestTimeoutException(); } + @GetMapping("/t/status-503") + Map status503() { + throw new org.springframework.web.server.ResponseStatusException( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE); + } + + @GetMapping("/t/status-429") + Map status429() { + throw new org.springframework.web.server.ResponseStatusException( + org.springframework.http.HttpStatus.TOO_MANY_REQUESTS); + } + @GetMapping("/t/bounded") Map bounded(@RequestParam("limit") @Max(10) int limit) { return Map.of("limit", limit); -- 2.54.0 From 7fdbbcaa878aa0b29b1898872ea8bccac4c1836b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 05:20:40 +0900 Subject: [PATCH 18/23] =?UTF-8?q?docs:=20leaf=20=EC=95=88=EB=82=B4?= =?UTF-8?q?=EC=99=80=20web=20=ED=95=9C=EB=8F=84=20=ED=91=9C=EC=9D=98=20?= =?UTF-8?q?=ED=8B=80=EB=A6=B0=20=EC=9C=84=EC=B9=98=C2=B7=EC=A3=BC=EC=B2=B4?= =?UTF-8?q?=EB=A5=BC=20=EC=BD=94=EB=93=9C=EC=97=90=20=EB=A7=9E=EC=B6=98?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제(새 눈 리뷰): - web-notification 안내가 callback 서명 검증을 유스케이스가 한다고 적었다. 실제로는 composition의 ProviderCallbackIngressBridge가 outbound provider adapter(SES는 SnsSignatureVerifier)로 검증하고 검증된 event만 넘긴다. - application-notification 안내가 없는 패키지 platform.port.out을 나가는 포트 위치로 적었고, testFixtures를 「포트마다 fake 하나」라고 실제보다 크게 적었다. - web-fileserver 책임 목록에 lifecycle(삭제·복사·이동)과 http(Range·조건부 다운로드 계획) 패키지가 없었다. - redis-runtime README가 app.redis.* 기본값 위치를 잘못 적었다. objectstorage README가 포트 개수를 복사했다. - web 한도 표가 multipart 한도를 「전역 한도 없음」이라 했고, 아무도 막지 않는 칸을 「늘 애플리케이션」이라 했다. - TESTING_STRATEGY가 묶음 태스크를 셋이라 세며 performanceCheck를 빠뜨렸다. - roadmap messaging-r2 이력 블록의 날짜·이유가 틀렸다(6d27356e, 2026-09-25). - 지운 ComposeMergeCharacterizationTest 행의 커밋이 지운 쪽 기준이 아니었다. 고친 것: 위 문장을 지금 코드대로 고쳤다. 공개 경로 스냅숏 문장과 fileserver 「오류 코드」 절 안내는 공개 표면 PR·계약 PR이 만드는 것이라 병합 순서로 맞춘다. 검증: check-docs.py·check-work-docs.py rc=0. Refs: RR9-04-09, RR9-04-21, RR9-04-35, RR9-04-42, RR9-03-30 --- docs/capability-status.md | 2 +- docs/roadmap/messaging-r2.md | 5 +++-- docs/testing/TESTING_STRATEGY.md | 6 +++--- docs/web/repository-adaptation.md | 18 +++++++++--------- src/adapter/inbound/web-fileserver/AGENTS.md | 3 ++- src/adapter/inbound/web-fileserver/README.md | 3 ++- src/adapter/inbound/web-notification/AGENTS.md | 3 ++- src/adapter/inbound/web-notification/README.md | 2 +- src/adapter/outbound/redis-runtime/README.md | 2 +- src/application/notification/AGENTS.md | 4 ++-- src/application/notification/README.md | 6 +++--- src/application/objectstorage/README.md | 2 +- 12 files changed, 30 insertions(+), 26 deletions(-) diff --git a/docs/capability-status.md b/docs/capability-status.md index 2a1272fa..2302c0a3 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -528,4 +528,4 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap | `SecretSourceValidator`의 `RELATIONAL_PERSISTENCE_PROPERTY`·`isRelationalPersistenceOn()`(모듈 스위치 해석) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java` | `0ebb77b5` | P22-new-1: persistence-jpa가 기여 | | 설정 키 `app.notification.platform.smtp.max-concurrency`(이름 변경 → `dispatch-concurrency`, env `APP_NOTIFICATION_PLATFORM_SMTP_DISPATCH_CONCURRENCY` 그대로) | `NotificationSmtpSettings.java`, `notification.yml` | `0ebb77b5` | P20-new-1 | | Redis ACL `+@pubsub`·`&prod:*`(application 계정 2개) | `infra/redis-sdk/acl/*.acl` | `0ebb77b5` | P22-new-2 | -| 시험 `ComposeMergeCharacterizationTest` | `src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/compose/ComposeMergeCharacterizationTest.java` | `fe0f8141` | 어느 lane도 고르지 않아 한 번도 돌지 않았다(`integrationTest` lane은 `requires`로 적은 클래스만 고른다). 보던 것(기본·dev 조합 렌더링, 계약 스크립트)은 PR 단계 `verifyComposeProfiles`가 모든 lane으로 본다(2026-11-12 리뷰) | +| 시험 `ComposeMergeCharacterizationTest` | `src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/compose/ComposeMergeCharacterizationTest.java` | `ca1fbfde`(지운 커밋 `23139722`의 부모) | 어느 lane도 고르지 않아 한 번도 돌지 않았다(`integrationTest` lane은 `requires`로 적은 클래스만 고른다). 보던 것(기본·dev 조합 렌더링, 계약 스크립트)은 PR 단계 `verifyComposeProfiles`가 모든 lane으로 본다(2026-11-12 리뷰) | diff --git a/docs/roadmap/messaging-r2.md b/docs/roadmap/messaging-r2.md index 20886a03..047faaca 100644 --- a/docs/roadmap/messaging-r2.md +++ b/docs/roadmap/messaging-r2.md @@ -45,5 +45,6 @@ verifyMessagingTargetBindingPreflight 검증하는 단계. manifest를 쓰는 태스크가 쓰자마자 검증한다. 4. 위 셋이 모두 생긴 다음에 `verifyMessagingR2` 태스크 등록. -> 이력: 네 단계를 모두 갖춘 예시였던 build-tools `MessagingQualificationPlugin`(`verifyMessagingContracts`)과 -> `VerifyMessagingEvidenceTask`는 메시징 플랫폼을 messaging-library repo로 옮기며(2026-11-08) 이 repo에서 지웠다. +> 이력: 네 단계를 모두 갖춘 예시였던 build-tools `MessagingQualificationPlugin`과 `VerifyMessagingEvidenceTask`는 +> 2026-09-25 capability 포장(`6d27356e`)에서 지웠다. 루트 `verifyMessagingContracts`는 남아 있고, 지금은 +> application·shared 계약 lane 둘을 묶기만 한다(루트 `build.gradle`). diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index 25b5741d..8a976d3c 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -141,9 +141,9 @@ fixture는 **지원 코드**다. TEST/INTEGRATION/SYSTEM/ARCHITECTURE/PERFORMANC ### repository -category별 묶음 태스크는 셋이다. `integrationCheck`(모든 leaf의 INTEGRATION lane), `systemTestCheck`(SYSTEM lane), -`architectureCheck`(저장소 아키텍처 규칙과 ARCHITECTURE lane). 이것들을 어느 단계(`prCheck`·`mainCheck`· -`integrationCheck`·`performanceCheck`·`releaseCheck`)가 부르는지와 단계마다 무엇이 더 붙는지의 정본은 +category별 묶음 태스크: `integrationCheck`(모든 leaf의 INTEGRATION lane), `performanceCheck`(PERFORMANCE lane), +`systemTestCheck`(SYSTEM lane. app-bootstrap은 `check`가 이미 돌려 뺀다), `architectureCheck`(저장소 아키텍처 규칙과 +ARCHITECTURE lane). 이것들을 어느 단계(`prCheck`·`mainCheck`·`releaseCheck` 등)가 부르는지와 단계마다 무엇이 더 붙는지의 정본은 `docs/work/reference/gates.md` 1절과 루트 `build.gradle`의 단계 태스크다. 여기에 복사하지 않는다. - `integrationCheck`는 `ci`에 들지 않는다. container runtime이 드는 lane이 많아 main 단계(`main.yml` `main` job)가 diff --git a/docs/web/repository-adaptation.md b/docs/web/repository-adaptation.md index 1725f8f9..4fd0d807 100644 --- a/docs/web/repository-adaptation.md +++ b/docs/web/repository-adaptation.md @@ -144,8 +144,8 @@ worker는 바뀐 행 수로 그것을 안다. ## 8. 예산 강제: edge가 막는 것과 애플리케이션이 막는 것 > **2026-09-25에 지움.** servlet 예산 filter(`WebMvcBudgetFilter`)와 그 problem 대응은 2세대 플랫폼과 함께 지웠다. -> 내보내는 애플리케이션은 아래 애플리케이션 칸 중 JSON 요청 본문 한도 하나만 강제한다(`app.web.mvc.max-json-body-size`, -> 기본 1 MiB, web `JsonBodyLimitFilter`, 넘으면 413 `PAYLOAD_TOO_LARGE` Envelope). 나머지 칸의 이름(`maxUriBytes` 등)은 +> 내보내는 애플리케이션이 직접 강제하는 칸은 요청 본문 한도뿐이다. JSON 본문은 web 한도(`app.web.mvc.max-json-body-size`, +> 기본 1 MiB, web `JsonBodyLimitFilter`, 넘으면 413 `PAYLOAD_TOO_LARGE` Envelope), multipart는 Spring 기본 한도다. 나머지 칸의 이름(`maxUriBytes` 등)은 > `budget` 목록(`WebRequestBudget`, `WebBudgetCatalog`)의 값이고, 그 목록은 `adapter:inbound:web-advanced`에 라이브러리 > 코드로만 남았다. 쓰이지 않던 meter(`WebBudgetMeter`와 그 결과/위반 타입)는 지웠다. edge 칸은 여전히 맞다. @@ -156,11 +156,11 @@ worker는 바뀐 행 수로 그것을 안다. | --- | --- | --- | --- | | 요청 줄 / URI | `large_client_header_buffers`(기본 8k) | `maxUriBytes` | edge가 먼저 — nginx가 자기 HTML로 414 | | 요청 헤더 | `large_client_header_buffers` | `maxHeaderBytes` | edge가 먼저 — nginx 400, problem document 없음 | -| 요청 본문 | `client_max_body_size`(기본 1m) | JSON 본문: `app.web.mvc.max-json-body-size`(기본 1 MiB, 강제함). JSON 아닌 본문: 전역 한도 없음, endpoint가 둔다 | 더 작은 쪽. nginx는 HTML로 413, 애플리케이션은 Envelope로 413 | -| query parameter 수 | 강제하지 않음 | `maxQueryParameters` | 늘 애플리케이션 | -| JSON 깊이 / 배열 크기 | 강제하지 않음 | `maxJsonDepth`, `maxArrayElements` | 늘 애플리케이션 | -| 실행 시간 | `proxy_read_timeout`(기본 60s) | `maxExecutionTime`(상한 2분) | 플랫폼 쪽이 더 크면 edge가 먼저 | -| 응답 크기 | 강제하지 않음 | `maxResponseBytes`(상한 32 MiB) | 늘 애플리케이션 | +| 요청 본문 | `client_max_body_size`(기본 1m) | JSON 본문: `app.web.mvc.max-json-body-size`(기본 1 MiB, 강제함). multipart 본문: Spring 기본 한도(`spring.servlet.multipart.*`, 넘으면 Envelope 413). 그 밖의 raw 본문: 전역 한도 없음, endpoint가 둔다 | 더 작은 쪽. nginx는 HTML로 413, 애플리케이션은 Envelope로 413 | +| query parameter 수 | 강제하지 않음 | `maxQueryParameters` | 아무도 막지 않는다(애플리케이션 칸은 목록 값뿐) | +| JSON 깊이 / 배열 크기 | 강제하지 않음 | `maxJsonDepth`, `maxArrayElements` | 깊이는 Jackson 기본 `StreamReadConstraints`만 걸린다. 배열 크기는 아무도 막지 않는다 | +| 실행 시간 | `proxy_read_timeout`(기본 60s) | `maxExecutionTime`(상한 2분) | edge. 애플리케이션 칸은 목록 값뿐이다 | +| 응답 크기 | 강제하지 않음 | `maxResponseBytes`(상한 32 MiB) | 아무도 막지 않는다(애플리케이션 칸은 목록 값뿐) | 둘 다 직관과 반대라서 적어 둘 만한 결과가 둘 있다. @@ -168,8 +168,8 @@ worker는 바뀐 행 수로 그것을 안다. HTML 오류 쪽을 답하므로, `error.code`로 분기하는 client는 파싱할 수 없는 본문을 받는다. client에게 중요한 차원이면 edge 한도를 애플리케이션보다 *높게* 두어 애플리케이션이 거부하게 한다. -**edge 한도가 애플리케이션보다 높아도 쓸데없지 않다.** 애플리케이션의 meter가 세기 전에 문제가 될 만큼 큰 본문과 -프로세스 사이에 서 있는 것은 그것뿐이다. 둘 다 있어야 하고, 정할 것은 순서뿐이다. +**edge 한도가 애플리케이션보다 높아도 쓸데없지 않다.** 애플리케이션이 막지 않는 차원(위 표의 「아무도 막지 않는다」)에서 +큰 요청과 프로세스 사이에 서 있는 것은 그것뿐이다. 둘 다 있어야 하고, 정할 것은 순서뿐이다. ## 9. Nginx lane (2026-09-25에 지움) diff --git a/src/adapter/inbound/web-fileserver/AGENTS.md b/src/adapter/inbound/web-fileserver/AGENTS.md index 5bb5f6f3..99f9b4a3 100644 --- a/src/adapter/inbound/web-fileserver/AGENTS.md +++ b/src/adapter/inbound/web-fileserver/AGENTS.md @@ -11,7 +11,8 @@ ## 책임 -- 업로드(`controller`, tus `tus`, IETF draft-12 `draft12`)·다운로드·관리(`admin`) HTTP endpoint와 그 요청 해석(`mapper`). +- 업로드(`controller`, tus `tus`, IETF draft-12 `draft12`)·다운로드·파일 삭제와 복사·이동(`lifecycle`)·관리(`admin`) HTTP endpoint와 그 요청 해석(`mapper`). +- 다운로드의 Range·조건부 요청 해석과 응답 계획(`http`의 `HttpDownloadPlanner`, `HttpRangeResolver`). - 실패를 Envelope로 바꾸는 `problem`(`FileserverExceptionHandler`, `FileserverProblemHeaders`), 전송 worker pool(`config.BlockingTransferExecutor`), nginx `X-Accel-Redirect`(`nginx`). - CORS 노출 헤더 기여(`config.FileserverHttpSurfaceConfiguration`). diff --git a/src/adapter/inbound/web-fileserver/README.md b/src/adapter/inbound/web-fileserver/README.md index ec9a3460..35efe20b 100644 --- a/src/adapter/inbound/web-fileserver/README.md +++ b/src/adapter/inbound/web-fileserver/README.md @@ -4,7 +4,8 @@ ## 책임과 소유하지 않는 것 -- 업로드(`controller`, tus `tus`, IETF draft-12 `draft12`)·다운로드·관리(`admin`) HTTP endpoint와 그 요청 해석(`mapper`). +- 업로드(`controller`, tus `tus`, IETF draft-12 `draft12`)·다운로드·파일 삭제와 복사·이동(`lifecycle`)·관리(`admin`) HTTP endpoint와 그 요청 해석(`mapper`). +- 다운로드의 Range·조건부 요청 해석과 응답 계획(`http`의 `HttpDownloadPlanner`, `HttpRangeResolver`). - 실패를 Envelope로 바꾸는 `problem`(`FileserverExceptionHandler`, `FileserverProblemHeaders`), 전송 worker pool(`config.BlockingTransferExecutor`), nginx `X-Accel-Redirect`(`nginx`). - CORS 노출 헤더 기여(`config.FileserverHttpSurfaceConfiguration`). - 소유하지 않는 것: 할당량·표시 이름 같은 정책(`application-fileserver`), 바이트 저장(`adapter:outbound:fileserver`), 공용 Envelope 처리(`adapter:inbound:web`). diff --git a/src/adapter/inbound/web-notification/AGENTS.md b/src/adapter/inbound/web-notification/AGENTS.md index 89040bdf..a9d030b5 100644 --- a/src/adapter/inbound/web-notification/AGENTS.md +++ b/src/adapter/inbound/web-notification/AGENTS.md @@ -19,7 +19,8 @@ - controller는 변환만 한다. 모르는 channel·slot·locale은 그 필드를 짚는 `400 VALIDATION_FAILED`로 거절하고, 발송 판정은 유스케이스에 넘긴다. - callback 경로는 presentation prefix를 받지 않는 절대 경로다. provider에 한 번 등록한 URL이 prefix 변경으로 움직이면 안 된다(`NotificationRoutePrefixTest`). -- callback chain은 인증 없이 열고 서명 검증을 유스케이스가 한다. 그 `permitAll`은 공개 경로 스냅숏에 들어 있다(`docs/security/public-paths-snapshot.txt`). +- callback chain은 인증 없이 연다. 서명 검증은 이 leaf의 `ProviderCallbackIngress`에 맡긴다. 구현은 `composition:notification-platform`의 `ProviderCallbackIngressBridge`이고, `adapter:outbound:notification`의 provider adapter(`ProviderCallbackAdapterRegistry`, SES는 `SnsSignatureVerifier`)로 검증한 뒤 검증된 event만 유스케이스에 넘긴다. 유스케이스는 서명을 보지 않는다. +- 그 `permitAll`은 공개 경로 스냅숏(`docs/security/public-paths-snapshot.txt`)에 들어 있다. callback 경로를 바꾸면 스냅숏도 바뀐다. - `adapter:inbound:web`의 inbound 규칙이 그대로 적용된다: repository 접근 없음, DTO를 application으로 넘기지 않음. ## 테스트 diff --git a/src/adapter/inbound/web-notification/README.md b/src/adapter/inbound/web-notification/README.md index 3d1e2d36..83516d8b 100644 --- a/src/adapter/inbound/web-notification/README.md +++ b/src/adapter/inbound/web-notification/README.md @@ -7,7 +7,7 @@ - 알림 제출(`NotificationSubmissionController`)과 template 게시(`NotificationTemplateController`) HTTP endpoint. - provider callback 수신(`NotificationCallbackMvcController`)과 그 경로만 덮는 보안 chain(`CallbackMvcSecurityConfiguration`). - 요청 DTO를 `application-notification`의 command로 바꾼다. 업무 판정은 하지 않는다. -- 소유하지 않는 것: 발송 판정·서명 검증(`application-notification`), provider 호출(`adapter:outbound:notification`), 공용 오류 처리(`adapter:inbound:web`). +- 소유하지 않는 것: 발송 판정(`application-notification`), callback 서명 검증과 provider 호출(`adapter:outbound:notification`, `composition:notification-platform`이 `ProviderCallbackIngress`로 이어 준다), 공용 오류 처리(`adapter:inbound:web`). ## 공개 표면 diff --git a/src/adapter/outbound/redis-runtime/README.md b/src/adapter/outbound/redis-runtime/README.md index 3e12619f..06723fea 100644 --- a/src/adapter/outbound/redis-runtime/README.md +++ b/src/adapter/outbound/redis-runtime/README.md @@ -11,7 +11,7 @@ Redis 연결과 명령 실행의 공용 runtime을 담는 leaf다. 업무 포트 ## 공개 표면 -`connection.RedisRuntimeClient`, `command.SemanticRedisCommands`, key 타입, 설정 `app.redis.*`(env `APP_REDIS_*`, `docs/registries/env-keys.yaml`, 기본값 `config/module-defaults/redis-runtime.yml`). +`connection.RedisRuntimeClient`, `command.SemanticRedisCommands`, key 타입, 설정 `app.redis.*`(env `APP_REDIS_*`, `docs/registries/env-keys.yaml`). 기본값은 `RedisRuntimeSettings`의 Java 기본값이고, `app.redis.enabled`만 cache-redis의 `config/module-defaults/cache-redis.yml`이 정한다. 이 leaf의 `config/module-defaults/redis-runtime.yml`은 health 상태 순서만 싣는다. ## 조립 diff --git a/src/application/notification/AGENTS.md b/src/application/notification/AGENTS.md index 8fe73991..e230f2de 100644 --- a/src/application/notification/AGENTS.md +++ b/src/application/notification/AGENTS.md @@ -12,8 +12,8 @@ ## 책임 - 알림 플랫폼의 업무 흐름: 제출·예약·취소·조회, template 게시, provider callback 수집, 발송 판정과 재시도 정책. -- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`)와 나가는 포트(`platform.port.out`), 오류 어휘(`platform.api.error`). -- testFixtures: 포트마다 fake 하나와 공유 계약. adapter의 시험이 같은 계약을 상속한다. +- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`), 나가는 포트(`*Port`, 쓰는 흐름의 패키지에 있다: `platform.dispatch`·`platform.callback`·`platform.policy`·`platform.observation`·`platform.admin`·`platform.inbox`·`platform.template`), 오류 어휘(`platform.api.error`). `port.out` 패키지는 따로 없다. +- testFixtures: 흐름 패키지마다 `testkit`에 저장 포트의 in-memory fake와 공유 계약(`*Contract`), provider adapter 계약(`ProviderAdapterContract`). adapter의 시험이 같은 계약을 상속한다. ## 규칙 diff --git a/src/application/notification/README.md b/src/application/notification/README.md index 8c7c169b..fa031656 100644 --- a/src/application/notification/README.md +++ b/src/application/notification/README.md @@ -5,13 +5,13 @@ ## 책임과 소유하지 않는 것 - 알림 플랫폼의 업무 흐름: 제출·예약·취소·조회, template 게시, provider callback 수집, 발송 판정과 재시도 정책. -- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`)와 나가는 포트(`platform.port.out`), 오류 어휘(`platform.api.error`). -- testFixtures: 포트마다 fake 하나와 공유 계약. adapter의 시험이 같은 계약을 상속한다. +- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`), 나가는 포트(`*Port`, 쓰는 흐름의 패키지에 있다: `platform.dispatch`·`platform.callback`·`platform.policy`·`platform.observation`·`platform.admin`·`platform.inbox`·`platform.template`), 오류 어휘(`platform.api.error`). `port.out` 패키지는 따로 없다. +- testFixtures: 흐름 패키지마다 `testkit`에 저장 포트의 in-memory fake와 공유 계약(`*Contract`), provider adapter 계약(`ProviderAdapterContract`). adapter의 시험이 같은 계약을 상속한다. - 소유하지 않는 것: HTTP 모양(`adapter:inbound:web-notification`), provider 호출·설정(`adapter:outbound:notification`), 저장(`adapter:outbound:persistence-notification`), 조립(`composition:notification-platform`). ## 공개 표면 -들어오는 포트 `platform.port.in`(예: `SubmitNotificationUseCase`, `PublishNotificationTemplateUseCase`, `IngestProviderCallbackUseCase`), 나가는 포트 `platform.port.out`, 오류 `platform.api.error`. 설정 prefix는 없다(설정은 `adapter:outbound:notification`의 `app.notification.platform.*`). +들어오는 포트 `platform.port.in`(예: `SubmitNotificationUseCase`, `PublishNotificationTemplateUseCase`, `IngestProviderCallbackUseCase`), 흐름 패키지의 나가는 포트(`*Port`), 오류 `platform.api.error`. 설정 prefix는 없다(설정은 `adapter:outbound:notification`의 `app.notification.platform.*`). ## 조립 diff --git a/src/application/objectstorage/README.md b/src/application/objectstorage/README.md index 2cf93658..7e784726 100644 --- a/src/application/objectstorage/README.md +++ b/src/application/objectstorage/README.md @@ -10,7 +10,7 @@ ## 공개 표면 -`port`의 여덟 포트(`ObjectTransferPort`, `ObjectInspectionPort`, `StagedObjectPublicationPort`, `ManagedObjectPublicationPort`, `ObjectRetirementPort` 등)와 값 타입. 설정 prefix는 없다(`app.object-storage.*`는 adapter의 것). +`port`의 포트(`ObjectTransferPort`, `ObjectInspectionPort`, `StagedObjectPublicationPort`, `ManagedObjectPublicationPort`, `ObjectRetirementPort` 등)와 값 타입. 설정 prefix는 없다(`app.object-storage.*`는 adapter의 것). ## 조립 -- 2.54.0 From 4ca61cd9bc1eec29e54a03f9291b3a98b53b7d0b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 05:35:51 +0900 Subject: [PATCH 19/23] =?UTF-8?q?docs:=20=EC=95=8C=EB=A6=BC=C2=B7=ED=8C=8C?= =?UTF-8?q?=EC=9D=BC=C2=B7=EA=B0=9D=EC=B2=B4=20=EC=A0=80=EC=9E=A5=EC=86=8C?= =?UTF-8?q?=C2=B7Redis=20leaf=20=EC=95=88=EB=82=B4=EC=9D=98=20=EB=B2=94?= =?UTF-8?q?=EC=9C=84=EB=A5=BC=20=EC=BD=94=EB=93=9C=EB=8C=80=EB=A1=9C=20?= =?UTF-8?q?=EC=A2=81=ED=9E=88=EA=B3=A0=20callback=20=EC=98=88=EC=99=B8?= =?UTF-8?q?=EB=A5=BC=20=EC=A0=81=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제(구조 리뷰): - application-notification 안내가 나가는 포트를 `*Port`로만 적어 provider·security 패키지와 이름이 다른 포트 일곱(NotificationProviderAdapter, TemplateRegistry 등)을 빠뜨렸다. provider를 더하는 세션이 같은 계약을 두 번 만들 수 있다. - notification·fileserver testFixtures를 모든 포트에 있는 것처럼 적었다. - application-objectstorage 안내가 adapter의 provider SPI 계약을 이 leaf 포트의 계약처럼 적었다. 이 leaf에는 포트 계약 시험이 없다. - redis-runtime 안내가 redis-sdk를 포트 구현 leaf로 적었고, redis-sdk로 싣는 길에서는 APP_REDIS_ENABLED를 직접 줘야 한다는 것을 적지 않았다. - provider callback은 본문 없이 status만 답하는데, Envelope가 아닌 응답이 fileserver 프로토콜 예외뿐인 것처럼 적혀 있었다. objectstorage README는 registry에 있는 APP_OBJECTSTORAGE_ENABLED를 「전용 키 없음」이라 했다. 고친 것: 위 문장을 코드대로 고치고, callback 응답(204·400·413·503, 본문 없음)을 HTTP 계약 §1·callback 문서·leaf 안내에 예외로 적었다. callback 동작은 그대로 둔다(인증 전 경로라 거절 이유를 싣지 않고, provider는 status로 재전송을 정한다). 검증: check-docs.py·check-work-docs.py rc=0. 이 문서들을 읽는 시험은 존재 확인뿐이다 (NotificationReleaseGateTest). Refs: RR9-04-42 --- docs/notification/callback-reconciliation.md | 3 +++ docs/web/http-contract.md | 4 ++++ src/adapter/inbound/web-notification/AGENTS.md | 1 + src/adapter/inbound/web-notification/README.md | 2 +- src/adapter/outbound/objectstorage/README.md | 2 +- src/adapter/outbound/redis-runtime/README.md | 7 +++++-- src/application/fileserver/AGENTS.md | 2 +- src/application/fileserver/README.md | 2 +- src/application/notification/AGENTS.md | 4 ++-- src/application/notification/README.md | 6 +++--- src/application/objectstorage/AGENTS.md | 2 +- 11 files changed, 23 insertions(+), 12 deletions(-) diff --git a/docs/notification/callback-reconciliation.md b/docs/notification/callback-reconciliation.md index 7e2d833a..9a3af5ed 100644 --- a/docs/notification/callback-reconciliation.md +++ b/docs/notification/callback-reconciliation.md @@ -16,6 +16,9 @@ body size limit → 2xx ``` +응답은 본문 없는 status다: 받으면(중복도) 204, 서명·형식 거절은 400, 본문 한도 초과는 413, 검증을 돌리지 못하면 +503과 `Retry-After`. provider는 4xx면 멈추고 5xx면 다시 보낸다. 인증 전 경로라 거절 이유를 싣지 않는다. + projection보다 ledger 추가를 먼저 하기 때문에 빠른 2xx가 정직하다. provider에게는 이벤트가 기록됐다고 알리고, projector 결함은 이벤트 유실이 아니라 replay 문제가 된다. diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index 1f66a154..78d154f6 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -70,6 +70,10 @@ status는 코드 표(`HttpStatusErrorCodes`)에 있는 것만 그대로 나간 4xx·5xx status로 나가는 본문은 `success:true`로 감싸지 않는다. 실패 Envelope가 아닌 본문을 오류 status로 돌려주는 핸들러는 그 본문이 그대로 나간다. +Envelope가 아닌 응답은 두 곳뿐이다. fileserver의 프로토콜 예외(`docs/fileserver/http-contract.md` 「Envelope 규칙의 +프로토콜 예외」)와 알림 provider callback이다. callback은 provider가 status만 읽는 webhook 응답이라 본문 없이 +204·400·413·503만 답한다(`src/adapter/inbound/web-notification/AGENTS.md`). + ### 왜 이렇게 나가는가 `Envelope`·`BulkEnvelope`·`ApiError`·`ResponseMeta`는 `shared-contract`에 있고, 이 leaf는 Java diff --git a/src/adapter/inbound/web-notification/AGENTS.md b/src/adapter/inbound/web-notification/AGENTS.md index a9d030b5..41fac979 100644 --- a/src/adapter/inbound/web-notification/AGENTS.md +++ b/src/adapter/inbound/web-notification/AGENTS.md @@ -21,6 +21,7 @@ - callback 경로는 presentation prefix를 받지 않는 절대 경로다. provider에 한 번 등록한 URL이 prefix 변경으로 움직이면 안 된다(`NotificationRoutePrefixTest`). - callback chain은 인증 없이 연다. 서명 검증은 이 leaf의 `ProviderCallbackIngress`에 맡긴다. 구현은 `composition:notification-platform`의 `ProviderCallbackIngressBridge`이고, `adapter:outbound:notification`의 provider adapter(`ProviderCallbackAdapterRegistry`, SES는 `SnsSignatureVerifier`)로 검증한 뒤 검증된 event만 유스케이스에 넘긴다. 유스케이스는 서명을 보지 않는다. - 그 `permitAll`은 공개 경로 스냅숏(`docs/security/public-paths-snapshot.txt`)에 들어 있다. callback 경로를 바꾸면 스냅숏도 바뀐다. +- callback 응답은 Envelope 규칙의 예외다. 본문 없이 204(받음, 중복도 같다)·400(서명·형식 거절)·413(본문 한도)·503(검증을 못 돌림, `Retry-After`)만 답한다. 인증 전 경로라 거절 이유를 싣지 않고, provider는 status만 본다(4xx면 멈추고 5xx면 다시 보낸다). 본문을 더하거나 status를 바꾸면 provider의 재전송 동작이 바뀐다(`NotificationCallbackMvcController` Javadoc). - `adapter:inbound:web`의 inbound 규칙이 그대로 적용된다: repository 접근 없음, DTO를 application으로 넘기지 않음. ## 테스트 diff --git a/src/adapter/inbound/web-notification/README.md b/src/adapter/inbound/web-notification/README.md index 83516d8b..55fc45f5 100644 --- a/src/adapter/inbound/web-notification/README.md +++ b/src/adapter/inbound/web-notification/README.md @@ -1,6 +1,6 @@ # adapter:inbound:web-notification -알림 플랫폼의 HTTP 표면을 담는 leaf다. 요청을 유스케이스 command로 바꾸고 응답을 Envelope로 돌려준다. +알림 플랫폼의 HTTP 표면을 담는 leaf다. 요청을 유스케이스 command로 바꾼다. 제출·template 게시는 Envelope로 답하고, provider callback은 본문 없이 status만 답한다. ## 책임과 소유하지 않는 것 diff --git a/src/adapter/outbound/objectstorage/README.md b/src/adapter/outbound/objectstorage/README.md index 6d57c05a..c8b38502 100644 --- a/src/adapter/outbound/objectstorage/README.md +++ b/src/adapter/outbound/objectstorage/README.md @@ -44,7 +44,7 @@ transfer와 multipart는 코드가 없다: 조립되지 않은 구현을 지웠 이 줄을 지우면 port 구현, provider, 설정 바인딩이 모두 함께 빠진다. - 켜기와 끄기: 모듈이 있으면 켜진다. `app.object-storage.enabled=false`로만 끄고, 그때 모듈은 아무 bean도 두지 않는다. -- env 키: 전용 `APP_*` 키는 없다. provider·destination이 map 구조라 배포의 `application-*.yml`에 +- env 키: `APP_OBJECTSTORAGE_ENABLED`(끄기) 하나뿐이다. provider·destination은 map 구조라 배포의 `application-*.yml`에 `app.object-storage.{default-destination, providers..*, destinations..*}`를 적는다(아래 「켜기와 라우팅」). 빠지면 기동 시 binding compile이 실패한다. diff --git a/src/adapter/outbound/redis-runtime/README.md b/src/adapter/outbound/redis-runtime/README.md index 06723fea..99d74e16 100644 --- a/src/adapter/outbound/redis-runtime/README.md +++ b/src/adapter/outbound/redis-runtime/README.md @@ -1,6 +1,6 @@ # adapter:outbound:redis-runtime -Redis 연결과 명령 실행의 공용 runtime을 담는 leaf다. 업무 포트는 위 leaf(`cache-redis`, `redis-sdk`)가 구현한다. +Redis 연결과 명령 실행의 공용 runtime을 담는 leaf다. 업무 포트는 `cache-redis`가 구현하고, `redis-sdk`는 서비스 코드가 직접 부르는 SDK 표면을 준다(bean도 포트 구현도 없다). ## 책임과 소유하지 않는 것 @@ -15,7 +15,10 @@ Redis 연결과 명령 실행의 공용 runtime을 담는 leaf다. 업무 포트 ## 조립 -직접 더하지 않는다. `runtimeOnly project(':adapter:outbound:cache-redis')`가 이 leaf를 함께 싣고, 이 leaf의 `RedisRuntimeAutoConfiguration`이 켜진다. 끄는 키는 `APP_REDIS_ENABLED`다. +직접 더하지 않는다. 이 leaf를 싣는 길은 둘이다. + +- `runtimeOnly project(':adapter:outbound:cache-redis')`: cache-redis의 기본값(`app.redis.enabled: ${APP_REDIS_ENABLED:true}`)이 함께 와서 `RedisRuntimeAutoConfiguration`이 켜진다. 끄는 키는 `APP_REDIS_ENABLED`다. +- `implementation project(':adapter:outbound:redis-sdk')`: SDK가 이 leaf를 `api`로 싣는다. 이 길에는 cache-redis 기본값이 없고 `RedisRuntimeAutoConfiguration`은 `app.redis.enabled=true`일 때만 켜지므로, `APP_REDIS_ENABLED=true`를 직접 준다(`src/adapter/outbound/redis-sdk/README.md` 「env 키」). ## 테스트 명령 diff --git a/src/application/fileserver/AGENTS.md b/src/application/fileserver/AGENTS.md index 2f1f7427..8c39a929 100644 --- a/src/application/fileserver/AGENTS.md +++ b/src/application/fileserver/AGENTS.md @@ -13,7 +13,7 @@ - 업로드(단일·raw·batch·이어 쓰기)·다운로드·복사·이동·삭제·정리의 유스케이스와 그 정책(할당량, 전송 허가, 표시 이름). - 들어오는 포트(`port.in`), 나가는 포트, 오류 어휘 `api.error.FileserverErrorCode`(HTTP 표는 `docs/fileserver/http-contract.md` 「오류 코드」). -- testFixtures `testkit`: 포트마다 fake와 공유 계약. +- testFixtures `testkit`: 저장·대기열 포트의 공유 계약(`*PortContract`)과 in-memory 구현, 내용 gateway·정책의 fake. 모든 포트에 계약이 있지는 않다(다운로드·zero-copy·사용량·지표 포트는 없다). ## 규칙 diff --git a/src/application/fileserver/README.md b/src/application/fileserver/README.md index c2a59f31..4f2f1f9c 100644 --- a/src/application/fileserver/README.md +++ b/src/application/fileserver/README.md @@ -6,7 +6,7 @@ - 업로드(단일·raw·batch·이어 쓰기)·다운로드·복사·이동·삭제·정리의 유스케이스와 그 정책(할당량, 전송 허가, 표시 이름). - 들어오는 포트(`port.in`), 나가는 포트, 오류 어휘 `api.error.FileserverErrorCode`(HTTP 표는 `docs/fileserver/http-contract.md` 「오류 코드」). -- testFixtures `testkit`: 포트마다 fake와 공유 계약. +- testFixtures `testkit`: 저장·대기열 포트의 공유 계약(`*PortContract`)과 in-memory 구현, 내용 gateway·정책의 fake. 모든 포트에 계약이 있지는 않다(다운로드·zero-copy·사용량·지표 포트는 없다). - 소유하지 않는 것: HTTP 모양(`adapter:inbound:web-fileserver`), 바이트 저장(`adapter:outbound:fileserver`), metadata 저장(`adapter:outbound:persistence-fileserver`), 조립(`composition:fileserver-platform`). ## 공개 표면 diff --git a/src/application/notification/AGENTS.md b/src/application/notification/AGENTS.md index e230f2de..9c163f4d 100644 --- a/src/application/notification/AGENTS.md +++ b/src/application/notification/AGENTS.md @@ -12,8 +12,8 @@ ## 책임 - 알림 플랫폼의 업무 흐름: 제출·예약·취소·조회, template 게시, provider callback 수집, 발송 판정과 재시도 정책. -- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`), 나가는 포트(`*Port`, 쓰는 흐름의 패키지에 있다: `platform.dispatch`·`platform.callback`·`platform.policy`·`platform.observation`·`platform.admin`·`platform.inbox`·`platform.template`), 오류 어휘(`platform.api.error`). `port.out` 패키지는 따로 없다. -- testFixtures: 흐름 패키지마다 `testkit`에 저장 포트의 in-memory fake와 공유 계약(`*Contract`), provider adapter 계약(`ProviderAdapterContract`). adapter의 시험이 같은 계약을 상속한다. +- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`), 나가는 포트(쓰는 흐름의 패키지에 있다: `platform.dispatch`·`platform.callback`·`platform.policy`·`platform.observation`·`platform.admin`·`platform.inbox`·`platform.template`·`platform.provider`·`platform.security`), 오류 어휘(`platform.api.error`). `port.out` 패키지는 따로 없다. 나가는 포트 이름은 대개 `*Port`지만 아닌 것도 있다: `provider.NotificationProviderAdapter`·`BatchNotificationProviderAdapter`·`AttachmentResolver`, `security.SecretMaterialProvider`·`ContactPointProtector`, `template.TemplateRegistry`, `callback.ProviderEventLedger`. 새 포트를 만들기 전에 이 이름들도 찾는다. +- testFixtures(흐름 패키지의 `testkit`): 저장 포트의 in-memory fake와 공유 계약(`*Contract`), provider adapter 계약(`ProviderAdapterContract`). 모든 포트에 있지는 않다. adapter의 시험이 같은 계약을 상속한다. ## 규칙 diff --git a/src/application/notification/README.md b/src/application/notification/README.md index fa031656..682a0357 100644 --- a/src/application/notification/README.md +++ b/src/application/notification/README.md @@ -5,13 +5,13 @@ ## 책임과 소유하지 않는 것 - 알림 플랫폼의 업무 흐름: 제출·예약·취소·조회, template 게시, provider callback 수집, 발송 판정과 재시도 정책. -- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`), 나가는 포트(`*Port`, 쓰는 흐름의 패키지에 있다: `platform.dispatch`·`platform.callback`·`platform.policy`·`platform.observation`·`platform.admin`·`platform.inbox`·`platform.template`), 오류 어휘(`platform.api.error`). `port.out` 패키지는 따로 없다. -- testFixtures: 흐름 패키지마다 `testkit`에 저장 포트의 in-memory fake와 공유 계약(`*Contract`), provider adapter 계약(`ProviderAdapterContract`). adapter의 시험이 같은 계약을 상속한다. +- 들어오는 포트(`platform.port.in`의 `*UseCase`·`*Command`·`*Query`), 나가는 포트(쓰는 흐름의 패키지에 있다: `platform.dispatch`·`platform.callback`·`platform.policy`·`platform.observation`·`platform.admin`·`platform.inbox`·`platform.template`·`platform.provider`·`platform.security`), 오류 어휘(`platform.api.error`). `port.out` 패키지는 따로 없다. 나가는 포트 이름은 대개 `*Port`지만 아닌 것도 있다: `provider.NotificationProviderAdapter`·`BatchNotificationProviderAdapter`·`AttachmentResolver`, `security.SecretMaterialProvider`·`ContactPointProtector`, `template.TemplateRegistry`, `callback.ProviderEventLedger`. 새 포트를 만들기 전에 이 이름들도 찾는다. +- testFixtures(흐름 패키지의 `testkit`): 저장 포트의 in-memory fake와 공유 계약(`*Contract`), provider adapter 계약(`ProviderAdapterContract`). 모든 포트에 있지는 않다. adapter의 시험이 같은 계약을 상속한다. - 소유하지 않는 것: HTTP 모양(`adapter:inbound:web-notification`), provider 호출·설정(`adapter:outbound:notification`), 저장(`adapter:outbound:persistence-notification`), 조립(`composition:notification-platform`). ## 공개 표면 -들어오는 포트 `platform.port.in`(예: `SubmitNotificationUseCase`, `PublishNotificationTemplateUseCase`, `IngestProviderCallbackUseCase`), 흐름 패키지의 나가는 포트(`*Port`), 오류 `platform.api.error`. 설정 prefix는 없다(설정은 `adapter:outbound:notification`의 `app.notification.platform.*`). +들어오는 포트 `platform.port.in`(예: `SubmitNotificationUseCase`, `PublishNotificationTemplateUseCase`, `IngestProviderCallbackUseCase`), 흐름 패키지의 나가는 포트(`*Port`와 위의 이름들), 오류 `platform.api.error`. 설정 prefix는 없다(설정은 `adapter:outbound:notification`의 `app.notification.platform.*`). ## 조립 diff --git a/src/application/objectstorage/AGENTS.md b/src/application/objectstorage/AGENTS.md index da3cdece..1543a289 100644 --- a/src/application/objectstorage/AGENTS.md +++ b/src/application/objectstorage/AGENTS.md @@ -18,7 +18,7 @@ - framework·AWS SDK 의존이 없다(`ca.java-library`). 허용 의존은 registry의 `application-core`·`shared-contract`뿐이다. - S3·MinIO 개념(bucket 정책, presign 구현)은 adapter의 것이다. 포트는 저장소에 상관없는 말로 쓴다. -- 포트를 바꾸면 adapter의 계약 시험(`adapter:outbound:objectstorage` testFixtures)을 같은 변경에서 고친다. +- 이 leaf에는 포트 계약 시험이 아직 없다. adapter testFixtures의 `ObjectStorageProviderContract`는 adapter 안의 provider SPI를 시험하고, 이 leaf의 포트는 시험하지 않는다. 값 타입(`model`·`request`·`identity`·`content`)을 바꾸면 그 provider 계약을 같은 변경에서 고친다. ## 테스트 -- 2.54.0 From 1185b36a6da0616b7de79a6607e4c5f9eeb4504a Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 06:34:32 +0900 Subject: [PATCH 20/23] =?UTF-8?q?test:=20=EA=B1=B0=EC=A7=93=20=ED=86=B5?= =?UTF-8?q?=EA=B3=BC=C2=B7=ED=9D=94=EB=93=A4=EB=A6=BC=C2=B7=EC=A0=80?= =?UTF-8?q?=EC=9E=A5=EC=86=8C=20=EC=9D=BD=EA=B8=B0=20=EA=B2=BD=EB=A1=9C?= =?UTF-8?q?=EB=A5=BC=20=EB=A7=89=EB=8F=84=EB=A1=9D=20=EC=8B=9C=ED=97=98?= =?UTF-8?q?=EC=9D=84=20=EA=B3=A0=EC=B9=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: - GraphQlDeploymentModeRegistryParityTest가 태그 없이 test에서 docs/registries/env-keys.yaml을 읽었다. 입력을 선언하지 않아 test 캐시가 registry 변경을 놓쳤고, modules.json을 거슬러 올라가 저장소 루트 가드를 우회했다(build-logic/AGENTS.md 「저장소 파일을 읽는 테스트」). - 「값을 싣지 않는다」 단언 넷(WebSecurityContextBridgeTest, scalar 둘)이 예외 타입을 보지 않아, 메시지 null인 NPE로 바꿔도 통과했다. - FileserverAdminControllerRequestBodyValidationTest는 @RequestBody가 하나도 없는 controller에도 통과했다. - GraphQlRequestDeadlineTest가 sleep(500) 뒤에 하위 필드 부재를 단언했다. 부하에 따라 기다림이 짧으면 거짓 통과다. - 두 동작을 한 시험에서 보던 셋(표 입력 반복문, when 둘). 고친 것: - registry 대조 시험에 document-contract 태그를 달고 graphql leaf에 mainStage lane graphqlDocumentContractTest를 둔다(lane은 다음 커밋의 build.gradle에 있다. 그 파일의 다른 변경과 같이 간다). - 부재 단언에 예외 타입(CoercingParseValueException, UntrustedTenantInputException)을 먼저 둔다. - admin 시험은 @RequestBody 매개변수 목록을 고정한 뒤 @Valid를 본다. - deadline 시험은 slowNode 실행이 끝났다는 신호(Instrumentation beginExecution 완료, 세대 번호로 이전 시험의 늦은 완료를 거른다)를 기다린 뒤 부재를 본다. - 표 입력(scalar 넷의 부재 단언 포함)은 @ParameterizedTest로, 두 동작은 시험 둘로 나눴다. 고친 시험은 GWT와 catchThrowable로 when을 하나로 둔다. - decisions 2.1에 「시험 형식 일괄 전환 안 함」(리뷰 README 6절 ④) 행을 더했다. Refs: RR9-03-17, RR9-03-18, RR9-03-19, RR9-03-20, RR9-03-22 --- docs/work/reference/decisions.md | 1 + .../runtime/GraphQlRequestDeadlineTest.java | 10 +++- .../runtime/RuntimeLimitsTestSupport.java | 38 +++++++++++++ ...aphQlDeploymentModeRegistryParityTest.java | 15 ++++- .../GraphQlMutationResultMapperTest.java | 13 ++++- .../HmacGraphQlCursorCodecTest.java | 4 ++ .../scalar/GraphQlScalarContractTest.java | 35 ++++++++++-- .../scalar/GraphQlScalarSymmetryTest.java | 1 + .../WebSecurityContextBridgeTest.java | 55 +++++++++++++++---- ...inControllerRequestBodyValidationTest.java | 29 ++++++++-- 10 files changed, 172 insertions(+), 29 deletions(-) diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index db1f8aa0..a1429d19 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -58,6 +58,7 @@ | 개선 매뉴얼을 먼저(지난 것) | 다음 개선 작업 전에 repo마다 개선 매뉴얼을 만든다 → 2026-11-06 「매뉴얼 체계」로 바뀜 | 소유자 | 2026-11-05 | 2026-11-05 총괄 세션 brief | | 스킬 | 리뷰·수정에 알맞은 스킬을 쓴다 | 소유자 | 2026-11-05 | `1103` 2절 | | `@DisplayName` 언어 | 한국어(기본값 영어를 거부) | 소유자 | 2026-09-25 | 결정 5, `.claude/rules/java-tests.md` 규칙 2 | +| 시험 형식 일괄 전환 | 영어 `@DisplayName`과 `// when` 없는 시험을 한꺼번에 바꾸지 않는다. 규칙(`.claude/rules/java-tests.md`)은 그대로이고, 고치는 시험에 적용한다. 한꺼번에 바꾸면 수천 줄의 diff가 결함 수정을 가린다 | 기본값(소유자가 뒤집을 수 있다) | 2026-11-12 | 2026-11-12 전체 리뷰 기록 README 6절 ④ | | 학습 문서(지난 것) | 삭제된 코드를 설명하는 학습 문서(지금 `docs/history/study/*.ko.md`, `docs/history/packages/*-superpowers-package/`)는 현재 코드에 맞게 갱신 → 2026-11-07 갱신하지 않고 기록으로 보관(머리 블록만 단다)으로 바뀜 | 소유자 | 2026-09-25 | 결정 6, design-docs `repo-structure/README.md` 3.2절 | | 문서 체계 | 문서를 수명으로 나눈다. 살아 있는 문서는 제자리에 두고 한국어로 옮긴다. 기록은 `docs/history/`, 설계서는 `docs/design/`, 결정 기록은 `docs/adr/`에 둔다. 폴더 이름은 짝 프론트와 같이 쓴다 | 소유자 | 2026-11-07 | design-docs `repo-structure/README.md` 3.2절, 적용은 `docs/README.md` | | 한국어의 범위 | 살아 있는 문서는 본문까지 한국어로 쓴다. 기록 문서는 맨 위에 한국어 머리 블록(상태·작성일·요약·현재 정본)을 달고 본문은 원문 그대로 둔다. 상태는 한국어 고정 어휘다 | 소유자 | 2026-11-07 | design-docs `repo-structure/README.md` 3.2절 | diff --git a/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestDeadlineTest.java b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestDeadlineTest.java index 6bf15a36..dc59e246 100644 --- a/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestDeadlineTest.java +++ b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestDeadlineTest.java @@ -98,8 +98,9 @@ class GraphQlRequestDeadlineTest { assertThat(finished) .as("the running resolver is not interrupted; it finishes on its own thread") .isTrue(); - // Room for graphql-java to have dispatched the child, had the cancellation not stopped it. - Thread.sleep(500); + assertThat(SlowWork.slowExecutionEnded.await(5, TimeUnit.SECONDS)) + .as("the execution ends after its last field, so a child that was going to start has") + .isTrue(); assertThat(SlowWork.DETAIL_INVOCATIONS) .as("a cancelled execution must not start new fields once the client has been answered") .hasValue(0); @@ -114,5 +115,10 @@ class GraphQlRequestDeadlineTest { GraphQlClientPolicy shortBudgetClientPolicy() { return RuntimeLimitsTestSupport.policyWithExecutionBudget(BUDGET); } + + @Bean + graphql.execution.instrumentation.Instrumentation slowExecutionEndSignal() { + return SlowWork.executionEndSignal(); + } } } diff --git a/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/RuntimeLimitsTestSupport.java b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/RuntimeLimitsTestSupport.java index cc8529d2..9f79efd6 100644 --- a/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/RuntimeLimitsTestSupport.java +++ b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/RuntimeLimitsTestSupport.java @@ -2,6 +2,13 @@ package dev.caskeleton.adapter.inbound.graphql.runtime; import dev.caskeleton.adapter.inbound.graphql.HealthGraphqlController; import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; +import graphql.ExecutionResult; +import graphql.execution.instrumentation.Instrumentation; +import graphql.execution.instrumentation.InstrumentationContext; +import graphql.execution.instrumentation.InstrumentationState; +import graphql.execution.instrumentation.SimpleInstrumentationContext; +import graphql.execution.instrumentation.SimplePerformantInstrumentation; +import graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters; import java.net.URI; import java.time.Duration; import java.util.concurrent.CountDownLatch; @@ -85,12 +92,43 @@ final class RuntimeLimitsTestSupport { static final AtomicInteger DETAIL_INVOCATIONS = new AtomicInteger(); static volatile CountDownLatch slowFinished = new CountDownLatch(1); + /** + * Counted down when a {@code slowNode} execution begun after the last {@link #reset()} has + * ended. The point after which a child field can no longer start, so an absence asserted after + * it is an absence and not a guess at how long the engine needs. + */ + static volatile CountDownLatch slowExecutionEnded = new CountDownLatch(1); + + private static final AtomicInteger GENERATION = new AtomicInteger(); + private SlowWork() {} static void reset() { SLOW_STARTED.set(0); DETAIL_INVOCATIONS.set(0); slowFinished = new CountDownLatch(1); + slowExecutionEnded = new CountDownLatch(1); + GENERATION.incrementAndGet(); + } + + /** Signals the end of each {@code slowNode} execution begun in the current generation. */ + static Instrumentation executionEndSignal() { + return new SimplePerformantInstrumentation() { + @Override + public InstrumentationContext beginExecution( + InstrumentationExecutionParameters parameters, InstrumentationState state) { + int generation = GENERATION.get(); + CountDownLatch ended = slowExecutionEnded; + boolean slow = + parameters.getQuery() != null && parameters.getQuery().contains("slowNode"); + return SimpleInstrumentationContext.whenCompleted( + (result, failure) -> { + if (slow && generation == GENERATION.get()) { + ended.countDown(); + } + }); + } + }; } } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentModeRegistryParityTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentModeRegistryParityTest.java index f255abc9..d752acc4 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentModeRegistryParityTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentModeRegistryParityTest.java @@ -8,6 +8,8 @@ import java.nio.file.Path; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -16,7 +18,11 @@ import org.junit.jupiter.api.Test; *

A mode the registry documents but the enum cannot bind fails at startup with a type-conversion * error; a mode the enum has but the registry omits is one no operator is told about. Which runtime * accepts each mode is held by {@code GraphQlDeploymentModeContractTest}. + * + *

Tagged {@code document-contract}: it reads a repository document, so it runs in the leaf's + * main-stage lane {@code graphqlDocumentContractTest}, never in the cached {@code test}. */ +@Tag("document-contract") class GraphQlDeploymentModeRegistryParityTest { private static final Pattern ALLOWED_VALUES = @@ -24,11 +30,16 @@ class GraphQlDeploymentModeRegistryParityTest { "name: APP_GRAPHQL_DEPLOYMENT_MODE.*?allowed_values: \\[([^\\]]*)\\]", Pattern.DOTALL); @Test + @DisplayName("registry의 APP_GRAPHQL_DEPLOYMENT_MODE 허용 값은 enum이 받는 값과 정확히 같다") void theRegistryListsExactlyTheModesTheEnumHas() throws IOException { + // given String registry = Files.readString(repositoryRoot().resolve("docs/registries/env-keys.yaml")); - Matcher matcher = ALLOWED_VALUES.matcher(registry); - assertThat(matcher.find()).isTrue(); + // when + Matcher matcher = ALLOWED_VALUES.matcher(registry); + + // then + assertThat(matcher.find()).as("the registry row and its allowed_values").isTrue(); assertThat(Arrays.stream(matcher.group(1).split(",")).map(String::trim)) .as("the registry is what an operator sets APP_GRAPHQL_DEPLOYMENT_MODE from") .containsExactlyInAnyOrderElementsOf( diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationResultMapperTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationResultMapperTest.java index ded2370e..5a5f6921 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationResultMapperTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationResultMapperTest.java @@ -41,9 +41,13 @@ class GraphQlMutationResultMapperTest { } @Test - void oneRootFieldCallsOneUseCase() { + void oneRootFieldThatCallsOneUseCaseIsAccepted() { assertThatCode(() -> GraphQlMutationContractValidator.requireSingleUseCase(CREATE_ORDER, 1)) .doesNotThrowAnyException(); + } + + @Test + void oneRootFieldThatCallsTwoUseCasesIsRefused() { assertThatThrownBy(() -> GraphQlMutationContractValidator.requireSingleUseCase(CREATE_ORDER, 2)) .isInstanceOf(GraphQlMutationContractException.class) .hasMessageContaining("one use case"); @@ -58,6 +62,13 @@ class GraphQlMutationResultMapperTest { () -> GraphQlMutationContractValidator.rejectRequestWideTransaction(roots, true)) .isInstanceOf(GraphQlMutationContractException.class) .hasMessageContaining("not a shared transaction"); + } + + @Test + void severalRootMutationsWithoutARequestWideTransactionAreAccepted() { + List roots = + List.of(CREATE_ORDER, new GraphQlMutationCoordinate("Mutation.createInvoice")); + assertThatCode( () -> GraphQlMutationContractValidator.rejectRequestWideTransaction(roots, false)) .doesNotThrowAnyException(); diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/pagination/HmacGraphQlCursorCodecTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/pagination/HmacGraphQlCursorCodecTest.java index bad9cd32..f3b9d3d3 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/pagination/HmacGraphQlCursorCodecTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/pagination/HmacGraphQlCursorCodecTest.java @@ -232,6 +232,10 @@ class HmacGraphQlCursorCodecTest { void framingRejectsADeclaredLengthLongerThanTheBody() { assertThatThrownBy(() -> GraphQlCursorFraming.readAll("99:short")) .isInstanceOf(GraphQlCursorException.class); + } + + @Test + void framingAcceptsADeclaredLengthThatMatchesTheBody() { assertThatCode(() -> GraphQlCursorFraming.readAll("5:hello")).doesNotThrowAnyException(); } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/scalar/GraphQlScalarContractTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/scalar/GraphQlScalarContractTest.java index eb56b126..136180fc 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/scalar/GraphQlScalarContractTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/scalar/GraphQlScalarContractTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.graphql.scalar; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlScalarDefinition; import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlScalarManifest; @@ -13,7 +14,13 @@ import java.time.Instant; import java.time.LocalDate; import java.util.Map; import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** Stable custom scalar serialization and coercion contract (Stable plan Task 13). */ class GraphQlScalarContractTest { @@ -79,14 +86,30 @@ class GraphQlScalarContractTest { assertThat(LongScalar.serialize(42L)).isEqualTo("42"); } - @Test - void coercionErrorsDoNotEchoTheOffendingValue() { + static Stream parsers() { + return Stream.of( + Arguments.of("UUID", (Function) UuidScalar::parse), + Arguments.of("Date", (Function) DateScalar::parse), + Arguments.of("BigDecimal", (Function) BigDecimalScalar::parse), + Arguments.of("Long", (Function) LongScalar::parse)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("parsers") + @DisplayName("scalar 변환 오류는 거절한 값을 메시지에 싣지 않는다") + void coercionErrorsDoNotEchoTheOffendingValue(String scalar, Function parse) { + // given String secret = "4111-1111-1111-1111"; - assertThatThrownBy(() -> UuidScalar.parse(secret)).hasMessageNotContaining(secret); - assertThatThrownBy(() -> DateScalar.parse(secret)).hasMessageNotContaining(secret); - assertThatThrownBy(() -> BigDecimalScalar.parse(secret)).hasMessageNotContaining(secret); - assertThatThrownBy(() -> LongScalar.parse(secret)).hasMessageNotContaining(secret); + // when + Throwable refused = catchThrowable(() -> parse.apply(secret)); + + // then + // The type first: a message that merely lacks the value also passes for an NPE thrown before + // the scalar ever looked at it, which is not the refusal this test is about. + assertThat(refused) + .isInstanceOf(CoercingParseValueException.class) + .hasMessageNotContaining(secret); } @Test diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/scalar/GraphQlScalarSymmetryTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/scalar/GraphQlScalarSymmetryTest.java index 62a05f39..89a49592 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/scalar/GraphQlScalarSymmetryTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/scalar/GraphQlScalarSymmetryTest.java @@ -81,6 +81,7 @@ class GraphQlScalarSymmetryTest { String secret = "9".repeat(500); assertThatThrownBy(() -> BigDecimalScalar.parse(secret)) + .isInstanceOf(graphql.schema.CoercingParseValueException.class) .hasMessageNotContaining(secret) .hasMessageNotContaining("999"); } diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebSecurityContextBridgeTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebSecurityContextBridgeTest.java index 8f5540bf..e10dc5b8 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebSecurityContextBridgeTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebSecurityContextBridgeTest.java @@ -1,13 +1,15 @@ package dev.caskeleton.adapter.inbound.web.advanced.security; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * A tenant a caller chose is a cross-tenant read waiting to happen. @@ -40,22 +42,51 @@ class WebSecurityContextBridgeTest { assertThatThrownBy( () -> bridge.resolve(AuthenticationView.anonymous(), Map.of("tenant", "tenant-attacker"))) + .isInstanceOf(UntrustedTenantInputException.class) .hasMessageNotContaining("tenant-attacker"); } - @Test - @DisplayName("every spelling of a tenant input is refused") - void everySpellingOfATenantInputIsRefused() { + @ParameterizedTest(name = "{0}") + @ValueSource(strings = {"X-Tenant-Id", "tenant-id", "TenantId", "TENANT"}) + @DisplayName("tenant 입력은 어떤 철자로 와도 거절된다") + void everySpellingOfATenantInputIsRefused(String name) { + // given WebTenantContextResolver resolver = new WebTenantContextResolver(); - for (String name : new String[] {"X-Tenant-Id", "tenant-id", "TenantId", "TENANT"}) { - assertThatThrownBy(() -> resolver.rejectTenantInput(Map.of(name, "t"))) - .as("a case or hyphen variant is the same header to a proxy") - .isInstanceOf(UntrustedTenantInputException.class); - } - assertThatCode(() -> resolver.rejectTenantInput(Map.of("Accept", "application/json"))) - .doesNotThrowAnyException(); - assertThatCode(() -> resolver.rejectTenantInput(null)).doesNotThrowAnyException(); + // when + Throwable refused = catchThrowable(() -> resolver.rejectTenantInput(Map.of(name, "t"))); + + // then + assertThat(refused) + .as("a case or hyphen variant is the same header to a proxy") + .isInstanceOf(UntrustedTenantInputException.class); + } + + @Test + @DisplayName("tenant가 아닌 입력은 거절되지 않는다") + void anInputThatNamesNoTenantIsNotRefused() { + // given + WebTenantContextResolver resolver = new WebTenantContextResolver(); + + // when + Throwable refused = + catchThrowable(() -> resolver.rejectTenantInput(Map.of("Accept", "application/json"))); + + // then + assertThat(refused).isNull(); + } + + @Test + @DisplayName("입력이 없으면 거절되지 않는다") + void noInputIsNotRefused() { + // given + WebTenantContextResolver resolver = new WebTenantContextResolver(); + + // when + Throwable refused = catchThrowable(() -> resolver.rejectTenantInput(null)); + + // then + assertThat(refused).isNull(); } @Test diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/admin/FileserverAdminControllerRequestBodyValidationTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/admin/FileserverAdminControllerRequestBodyValidationTest.java index 55382dd8..60649b09 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/admin/FileserverAdminControllerRequestBodyValidationTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/admin/FileserverAdminControllerRequestBodyValidationTest.java @@ -7,12 +7,12 @@ import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.web.bind.annotation.RequestBody; /** - * W4 red team BE-INPUT-002 — every {@code @RequestBody} on the admin controller must also carry - * {@code @Valid}. + * Every {@code @RequestBody} on the admin controller must also carry {@code @Valid}. * *

{@code reconcileOrphans} shipped a {@code @RequestBody} without {@code @Valid}, unlike every * sibling handler (relocate/force-delete/…). Harmless today because {@code @@ -24,20 +24,37 @@ import org.springframework.web.bind.annotation.RequestBody; class FileserverAdminControllerRequestBodyValidationTest { @Test + @DisplayName("admin controller의 @RequestBody 매개변수는 모두 @Valid를 함께 단다") void everyRequestBodyParameterAlsoCarriesValid() { + // given + List bodies = new ArrayList<>(); List offenders = new ArrayList<>(); + + // when for (Method method : FileserverAdminController.class.getDeclaredMethods()) { for (Parameter parameter : method.getParameters()) { - if (parameter.isAnnotationPresent(RequestBody.class) - && !parameter.isAnnotationPresent(Valid.class)) { - offenders.add(method.getName() + "(" + parameter.getType().getSimpleName() + ")"); + if (!parameter.isAnnotationPresent(RequestBody.class)) { + continue; + } + String handler = method.getName() + "(" + parameter.getType().getSimpleName() + ")"; + bodies.add(handler); + if (!parameter.isAnnotationPresent(Valid.class)) { + offenders.add(handler); } } } + + // then + assertThat(bodies) + .as( + "the handlers this test is about; an empty list would pass the check below for a" + + " controller that lost its bodies or a scan that found nothing") + .containsExactlyInAnyOrder( + "reconcileOrphans(OrphanReconcileHttpRequest)", "forceDelete(ForceDeleteHttpRequest)"); assertThat(offenders) .as( "admin @RequestBody handlers without @Valid would silently drop any Bean Validation " - + "constraint added to their DTO later (BE-INPUT-002)") + + "constraint added to their DTO later") .isEmpty(); } } -- 2.54.0 From cbfa776270a7b51ea5cc66a247998be0df1134cb Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 06:34:32 +0900 Subject: [PATCH 21/23] =?UTF-8?q?build!:=20=EC=8B=9C=ED=97=98=20classpath?= =?UTF-8?q?=C2=B7=EC=9D=B4=EB=AF=B8=EC=A7=80=20=EA=B3=A0=EC=A0=95=C2=B7?= =?UTF-8?q?=EC=B9=B4=ED=83=88=EB=A1=9C=EA=B7=B8=C2=B7API=20surface=20?= =?UTF-8?q?=EC=9E=85=EB=A0=A5=EC=9D=84=20=EC=A0=95=EB=B3=B8=EB=8C=80?= =?UTF-8?q?=EB=A1=9C=20=EB=A7=9E=EC=B6=98=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: - ca.spring-library가 모든 spring leaf(30)의 testImplementation에 spring-boot-starter-webmvc-test를 넣어, MockMvc를 쓰지 않는 23 leaf가 Tomcat을 시험 classpath에 resolve하고 lock했다. - container-images.properties 머리말은 「digest로 고정」이라는데 postgres-17·18이 tag만이었다. 머리말은 「쓰는 lane만 다시 돈다」고 했지만 파일 전체가 모든 Test task의 입력이라 이미지 하나만 바꿔도 모든 lane이 다시 돈다. postgres-16-4는 아무도 읽지 않았다. - libs.versions.toml에 아무도 읽지 않는 칸이 있었다(라이브러리 9, 버전 4, 루트에 적용하지 않는 플러그인 4). - config/spotbugs/exclude.xml에 없는 클래스의 항목이 있었다(exclude-test.xml에 이미 있다). - notification의 API surface가 상대 경로로 application-notification 소스를 가리켰고, ApiSurface 플러그인은 없는 추가 root를 말없이 건너뛰어 승인 update가 줄어든 표면을 기록할 수 있었다. - verify-mongodb-platform.sh가 고르는 클래스가 없는 :app-bootstrap:test --tests '*CleanArchitectureTest'를 불러 늘 실패했고, 이미지 기록이 카탈로그와 다른 tag였다. 고친 것: - 규약은 spring-boot-starter-test만 준다. 시험이 실제로 쓰는 것을 leaf가 직접 선언한다. MockMvc를 쓰는 web·web-advanced·web-fileserver·web-notification· app-bootstrap은 webmvc-test starter, graphql은 TestRestTemplate의 spring-boot-resttestclient, durable-operation은 WebApplicationContextRunner의 spring-web, 시험이 JSON을 읽는 objectstorage·persistence-jpa·persistence-mongo· notification-platform은 jackson-databind, redis-runtime은 jackson-annotations (compileOnly, 본 코드와 같은 이유)다. 모든 Java source set을 한 빌드에서 컴파일해 빠진 곳이 없음을 확인하고 lockfile을 다시 만들었다(Tomcat·webmvc 시험 자동설정이 빠짐). graphql·persistence-mongo AGENTS의 허용·시험 목록을 같이 고쳤다. - postgres 17·18을 desktop runner에서 받은 digest로 고정했다(17.11, 18.6). 목록을 읽을 때 digest 없는 값을 GradleException으로 거절한다(ContainerImageCatalogTest). 머리말을 실제 캐시 동작으로 고쳤고 postgres-16-4를 지웠다. persistence-jpa release registry의 PostgreSQL tag는 아무도 읽지 않아 지우고, 이미지는 카탈로그가 정한다고 적었다. - 카탈로그의 미사용 칸을 지우고 머리말을 지금 쓰임에 맞췄다. - 죽은 spotbugs 항목을 지웠다. - notification은 project(':application-notification')로 root를 잡고, 없는 추가 root는 설정 단계에서 실패한다(ApiSurfaceConventionTest). - mongo 스크립트는 :app-bootstrap:architectureTest를 부르고, 이미지 기록은 카탈로그 mongo-8 값을 읽는다. - graphql build.gradle에 앞 커밋의 document-contract lane을 함께 둔다. 저장소 루트 (ca.repository.root)와 읽는 registry 파일은 그 lane만 받고, 시험은 그 속성으로만 루트를 읽는다(cwd에서 거슬러 찾지 않는다). 버린 대안: 이미지마다 쓰는 lane을 선언해 입력을 나누기 — lane 수십 개에 키 목록을 다시 적어야 하고 빠뜨리면 캐시가 거짓 통과한다. 검증: 아래 PR 본문(desktop resolveAndLockAll·build-logic test·모든 source set 컴파일· leaf check). BREAKING CHANGE: ca.spring-library가 시험 classpath에 spring-boot-starter-webmvc-test를 넣지 않는다. MockMvc·TestRestTemplate·Jackson을 그 starter로 받던 파생 leaf는 의존을 직접 선언해야 시험이 컴파일된다. 카탈로그의 digest 없는 이미지와 없는 API surface 추가 root는 설정 단계에서 실패한다. version catalog의 미사용 칸을 지웠다. 할 일은 docs/upgrade/2026-11-round9-build.md다. Refs: RR9-04-06, RR9-04-11, RR9-04-12, RR9-04-13, RR9-04-14, RR9-04-15, RR9-04-16 --- .../apisurface/ApiSurfacePlugin.java | 20 +++++-- .../SpringLibraryConventionPlugin.java | 11 ++-- .../java/JavaConventionsPlugin.java | 21 +++++++- .../apisurface/ApiSurfaceConventionTest.java | 21 ++++++++ .../java/ContainerImageCatalogTest.java | 50 +++++++++++++++++ config/spotbugs/exclude.xml | 10 ---- docs/upgrade/2026-11-round9-build.md | 25 +++++++++ gradle/container-images.properties | 18 +++---- gradle/libs.versions.toml | 54 +++++-------------- src/adapter/inbound/graphql/AGENTS.md | 9 +++- src/adapter/inbound/graphql/build.gradle | 21 ++++++++ src/adapter/inbound/graphql/gradle.lockfile | 3 -- ...aphQlDeploymentModeRegistryParityTest.java | 16 +++--- src/adapter/inbound/grpc/gradle.lockfile | 22 -------- src/adapter/inbound/messaging/gradle.lockfile | 27 ++-------- src/adapter/inbound/web-advanced/build.gradle | 3 ++ .../inbound/web-fileserver/build.gradle | 3 ++ .../inbound/web-notification/build.gradle | 3 ++ src/adapter/inbound/web/build.gradle | 3 ++ src/adapter/inbound/websocket/gradle.lockfile | 4 -- .../outbound/cache-redis/gradle.lockfile | 22 -------- .../outbound/fileserver/gradle.lockfile | 23 -------- .../outbound/httpclient/gradle.lockfile | 18 ------- .../outbound/identifier/gradle.lockfile | 23 -------- .../outbound/messaging-kafka/gradle.lockfile | 28 ++-------- .../outbound/messaging/gradle.lockfile | 18 ------- .../outbound/notification/build.gradle | 4 +- .../outbound/notification/gradle.lockfile | 18 ------- .../outbound/objectstorage/build.gradle | 2 + .../outbound/objectstorage/gradle.lockfile | 19 ------- .../persistence-fileserver/gradle.lockfile | 24 +-------- .../outbound/persistence-jpa/build.gradle | 2 + .../outbound/persistence-jpa/gradle.lockfile | 19 ------- .../release/release-registry.json | 12 +++-- .../outbound/persistence-mongo/AGENTS.md | 2 +- .../outbound/persistence-mongo/build.gradle | 2 + .../persistence-mongo/gradle.lockfile | 19 ------- .../persistence-notification/gradle.lockfile | 22 -------- .../outbound/redis-runtime/build.gradle | 3 ++ .../outbound/redis-runtime/gradle.lockfile | 24 +-------- .../outbound/redis-sdk/gradle.lockfile | 23 -------- src/adapter/outbound/support/gradle.lockfile | 22 -------- src/bootstrap/app/build.gradle | 3 ++ src/bootstrap/durable-operation/build.gradle | 3 ++ .../durable-operation/gradle.lockfile | 39 ++++++-------- .../fileserver-platform/gradle.lockfile | 39 ++++++-------- src/bootstrap/idempotency/gradle.lockfile | 24 +-------- .../notification-platform/build.gradle | 2 + .../notification-platform/gradle.lockfile | 33 +++++------- src/bootstrap/outbox-relay/gradle.lockfile | 22 -------- src/bootstrap/service-runtime/gradle.lockfile | 21 -------- 51 files changed, 298 insertions(+), 581 deletions(-) create mode 100644 build-logic/src/test/java/dev/caskeleton/buildlogic/java/ContainerImageCatalogTest.java create mode 100644 docs/upgrade/2026-11-round9-build.md diff --git a/build-logic/src/main/java/dev/caskeleton/buildlogic/apisurface/ApiSurfacePlugin.java b/build-logic/src/main/java/dev/caskeleton/buildlogic/apisurface/ApiSurfacePlugin.java index a022deaa..9f261c36 100644 --- a/build-logic/src/main/java/dev/caskeleton/buildlogic/apisurface/ApiSurfacePlugin.java +++ b/build-logic/src/main/java/dev/caskeleton/buildlogic/apisurface/ApiSurfacePlugin.java @@ -34,10 +34,22 @@ public final class ApiSurfacePlugin implements Plugin { if (extension.getSourceRoot() != null && !extension.getSourceRoot().isBlank()) { sourcePaths.add(extension.getSourceRoot()); } - extension.getAdditionalSourceRoots().stream() - .filter(path -> path != null && !path.isBlank()) - .forEach(sourcePaths::add); - List roots = sourcePaths.stream().map(project::file).toList(); + List additional = + extension.getAdditionalSourceRoots().stream() + .filter(path -> path != null && !path.isBlank()) + .map(project::file) + .toList(); + // A missing additional root used to be skipped without a word, so an approved update + // recorded a surface with a whole module's types gone (2026-11-12 review). + List missing = additional.stream().filter(root -> !root.isDirectory()).toList(); + if (!missing.isEmpty()) { + throw new GradleException( + project.getPath() + + " apiSurface.additionalSourceRoots names a folder that does not exist: " + + missing); + } + List roots = new ArrayList<>(sourcePaths.stream().map(project::file).toList()); + roots.addAll(additional); String verifyTaskName = "verify" + label + "ApiSurface"; String updateTaskName = "update" + label + "ApiSurface"; String approvalProperty = "approve" + label + "ApiSurfaceChange"; diff --git a/build-logic/src/main/java/dev/caskeleton/buildlogic/convention/SpringLibraryConventionPlugin.java b/build-logic/src/main/java/dev/caskeleton/buildlogic/convention/SpringLibraryConventionPlugin.java index f4757d60..46905c75 100644 --- a/build-logic/src/main/java/dev/caskeleton/buildlogic/convention/SpringLibraryConventionPlugin.java +++ b/build-logic/src/main/java/dev/caskeleton/buildlogic/convention/SpringLibraryConventionPlugin.java @@ -3,6 +3,14 @@ package dev.caskeleton.buildlogic.convention; import org.gradle.api.Plugin; import org.gradle.api.Project; +/** + * Quality conventions plus the Spring Boot test starter for a Spring library leaf. + * + *

Only {@code spring-boot-starter-test}. The web MVC test starter (MockMvc, {@code @WebMvcTest}, + * and an embedded Tomcat with them) used to be added to every leaf here, so thirty leaves resolved + * and locked a servlet container for tests that never start one. A leaf whose tests use MockMvc + * declares {@code spring-boot-starter-webmvc-test} in its own build script (2026-11-12 review). + */ public final class SpringLibraryConventionPlugin implements Plugin { @Override public void apply(Project project) { @@ -10,8 +18,5 @@ public final class SpringLibraryConventionPlugin implements Plugin { project .getDependencies() .add("testImplementation", "org.springframework.boot:spring-boot-starter-test"); - project - .getDependencies() - .add("testImplementation", "org.springframework.boot:spring-boot-starter-webmvc-test"); } } diff --git a/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java b/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java index e3cf9012..7b75200e 100644 --- a/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java +++ b/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java @@ -310,7 +310,14 @@ public final class JavaConventionsPlugin implements Plugin { return catalog; } - private static Map containerImages(File catalog) { + /** + * The catalog, refused when an image is not pinned by digest. + * + *

The catalog's header promises digests: a red lane should mean this repository changed, not + * that a registry moved a tag. Two images were tag-only for weeks with a note to pin them later + * (2026-11-12 review), and nothing noticed, so the promise is checked where the file is read. + */ + static Map containerImages(File catalog) { Properties properties = new Properties(); try (var in = Files.newInputStream(catalog.toPath())) { properties.load(in); @@ -319,6 +326,18 @@ public final class JavaConventionsPlugin implements Plugin { } Map images = new TreeMap<>(); properties.stringPropertyNames().forEach(key -> images.put(key, properties.getProperty(key))); + List unpinned = + images.entrySet().stream() + .filter(entry -> !entry.getValue().contains("@sha256:")) + .map(Map.Entry::getKey) + .toList(); + if (!unpinned.isEmpty()) { + throw new GradleException( + catalog.getName() + + ": pin every image by digest (repository@sha256:...), with its tag in a comment;" + + " not pinned: " + + unpinned); + } return Map.copyOf(images); } } diff --git a/build-logic/src/test/java/dev/caskeleton/buildlogic/apisurface/ApiSurfaceConventionTest.java b/build-logic/src/test/java/dev/caskeleton/buildlogic/apisurface/ApiSurfaceConventionTest.java index 06869bc6..ab4550d8 100644 --- a/build-logic/src/test/java/dev/caskeleton/buildlogic/apisurface/ApiSurfaceConventionTest.java +++ b/build-logic/src/test/java/dev/caskeleton/buildlogic/apisurface/ApiSurfaceConventionTest.java @@ -173,6 +173,27 @@ class ApiSurfaceConventionTest { """); } + @Test + @org.junit.jupiter.api.DisplayName("없는 추가 source root는 건너뛰지 않고 그 경로를 짚어 실패한다") + void aMissingAdditionalSourceRootFailsInsteadOfShrinkingTheSurface() throws Exception { + // given + Files.writeString( + projectDir.resolve("build.gradle"), + Files.readString(projectDir.resolve("build.gradle")) + .replace( + "baseline = file('surface.txt')", + "baseline = file('surface.txt')\n additionalSourceRoots = ['../moved/src/main/java']")); + + // when + BuildResult result = + runner("updateFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").buildAndFail(); + + // then + assertTrue( + result.getOutput().contains("additionalSourceRoots names a folder that does not exist"), + result.getOutput()); + } + private void writeConfiguredBuild(String sourceRoot) throws Exception { Files.writeString( projectDir.resolve("build.gradle"), diff --git a/build-logic/src/test/java/dev/caskeleton/buildlogic/java/ContainerImageCatalogTest.java b/build-logic/src/test/java/dev/caskeleton/buildlogic/java/ContainerImageCatalogTest.java new file mode 100644 index 00000000..2c5035c7 --- /dev/null +++ b/build-logic/src/test/java/dev/caskeleton/buildlogic/java/ContainerImageCatalogTest.java @@ -0,0 +1,50 @@ +package dev.caskeleton.buildlogic.java; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import org.gradle.api.GradleException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class ContainerImageCatalogTest { + + @Test + @DisplayName("digest 없이 tag만 적은 이미지는 목록을 읽는 단계에서 그 키를 짚어 실패한다") + void aTagOnlyImageFailsNamingItsKey(@TempDir Path directory) throws IOException { + // given + Path catalog = directory.resolve("container-images.properties"); + Files.writeString( + catalog, + "pinned=postgres@sha256:" + + "0".repeat(64) + + "\nfloating=postgres:17-alpine\n"); + + // when + Throwable failure = catchThrowable(() -> JavaConventionsPlugin.containerImages(catalog.toFile())); + + // then + assertThat(failure) + .isInstanceOf(GradleException.class) + .hasMessageEndingWith("not pinned: [floating]"); + } + + @Test + @DisplayName("모든 이미지가 digest로 고정된 목록은 키와 값을 그대로 돌려준다") + void aDigestPinnedCatalogIsReadAsIs(@TempDir Path directory) throws IOException { + // given + Path catalog = directory.resolve("container-images.properties"); + String image = "postgres@sha256:" + "a".repeat(64); + Files.writeString(catalog, "# postgres:17-alpine\npostgres-17=" + image + "\n"); + + // when + var images = JavaConventionsPlugin.containerImages(catalog.toFile()); + + // then + assertThat(images).containsExactly(java.util.Map.entry("postgres-17", image)); + } +} diff --git a/config/spotbugs/exclude.xml b/config/spotbugs/exclude.xml index 99a0419c..2ee07473 100644 --- a/config/spotbugs/exclude.xml +++ b/config/spotbugs/exclude.xml @@ -59,16 +59,6 @@ - - - - - - -