feat!: 남은 리뷰 발견을 고치고 개발 매뉴얼과 기능 생성 명령을 더한다

문제: High·P1을 고친 뒤에도 P2·P3 약 90건이 남았다. 연결·구독·메시지
크기 상한이 없는 전송(WebSocket·gRPC·GraphQL deadline), 낙관적 충돌의
500, upsert 경쟁, Mongo 무제한 timeout, 샘플 목록 N+1, 갈라진 복사본
(TenantId 3벌, 이벤트 ID 문법 5곳, SQLState 표 2벌), 문서를 읽는 PR
테스트와 캐시를 막는 lane 설정 등이다. 새 기능을 어디에 어떤 순서로
만드는지 알려 주는 문서와 도구가 없었다. MinIO 공식 이미지가 사라져
객체 저장소 lane이 돌지 않았다.

방법: 영역별 묶음으로 실패 테스트를 먼저 쓰고 고쳤다. 고치는 중에 찾은
결함도 함께 고쳤다(durable operation id가 UUIDv4라 이벤트가 전부 DEAD,
S3 어댑터 생성·작은 chunk 읽기 실패, Redis 조건부 기록의 EVALSHA 권한).
MinIO는 pgsty/minio를 digest로 고정했다(Chainguard는 태그·실행 사용자·
mc 이미지 문제로 버림). docs/manual/에 작업 순서와 판단 지점을 쓰고,
scripts/new-feature.sh가 5개 leaf에 뼈대를 만든다. 생성→빌드→통과
왕복을 verifyFeatureScaffold가 mainCheck에서 본다. 묶음별 결과와
결정은 리뷰 README 14절에 있다.

위험·한계: 파생 서비스 동작이 바뀐다. JDBC batch 50 기본, 운영 jar에서
H2 제거, 트랜잭션 30초 제한, 격리 수준을 Hikari에서 고정, gRPC·
WebSocket·GraphQL 새 한도, correlation ID 규칙 밖이면 서버가 교체,
샘플 키 오류 코드 IDEMPOTENCY_KEY_INVALID. 새 leaf 두 개
(composition:durable-operation, adapter:inbound:messaging)와 새
마이그레이션(postgresql V20·V21, notification V11·V12, sample V8_1,
grpc-ledger V002)이 생긴다. V21 유일 인덱스는 기존 중복이 있으면
실패한다(runbook에 확인 쿼리).

검증: ci, mainCheck(생성 명령 왕복 포함), integrationCheck(MinIO 포함
전 컨테이너 lane), -p optional-platforms ci integrationCheck 통과.

Refs: docs/reviews/2026-11-01-maturity-review/README.md 14절
BREAKING CHANGE: JDBC batch 기본 켜짐, H2 운영 의존 제거, 트랜잭션
기본 제한 30초, gRPC·WebSocket·GraphQL 서버 한도 기본값 추가,
샘플 Idempotency-Key 오류 코드 변경.
This commit is contained in:
DongHyeonka
2026-11-03 19:52:06 +09:00
parent 34565130e0
commit 1400dc1506
768 changed files with 26982 additions and 3348 deletions
+10 -3
View File
@@ -257,9 +257,9 @@ APP_ASYNC_EXECUTOR_CORE_SIZE=10
APP_ASYNC_EXECUTOR_MAX_SIZE=50
APP_ASYNC_EXECUTOR_QUEUE_CAPACITY=200
APP_PERSISTENCE_JPA_ENABLED=true
APP_JPA_HIBERNATE_BATCH_SIZE=0
APP_JPA_HIBERNATE_ORDER_INSERTS=false
APP_JPA_HIBERNATE_ORDER_UPDATES=false
APP_JPA_HIBERNATE_BATCH_SIZE=50
APP_JPA_HIBERNATE_ORDER_INSERTS=true
APP_JPA_HIBERNATE_ORDER_UPDATES=true
APP_JPA_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE=0
APP_JPA_HIBERNATE_GENERATE_STATISTICS=false
APP_PERSISTENCE_MONGO_ENABLED=true
@@ -279,6 +279,8 @@ APP_GRAPHQL_MAXIMUM_COMPLEXITY=10000
APP_GRAPHQL_PREPARSED_CACHE_ENTRIES=1000
APP_GRAPHQL_PREPARSED_CACHE_WEIGHT=10000000
APP_GRAPHQL_PREPARSED_CACHE_EXPIRE_AFTER_ACCESS=30m
# 한 요청에서 같은 필드가 DataLoader 없이 이 횟수보다 많이 resolve 되면 WARN + metric (N+1 신호)
APP_GRAPHQL_PER_PARENT_FETCH_WARNING_THRESHOLD=10
# Optional build-composition: these bind only when :adapter:inbound:websocket is present.
# The default bootJar does not contain that leaf.
@@ -287,6 +289,11 @@ APP_WEBSOCKET_ENDPOINT=/ws
APP_WEBSOCKET_ALLOWED_ORIGINS=http://localhost:3000
APP_WEBSOCKET_BROADCAST_DESTINATION=/topic/events
APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY=10000
APP_WEBSOCKET_MESSAGE_SIZE_LIMIT=64KB
APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT=512KB
APP_WEBSOCKET_SEND_TIME_LIMIT=10s
APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE=60s
APP_WEBSOCKET_MAX_CONNECTIONS=1000
APP_OUTBOX_ENABLED=false
APP_OUTBOX_RELAY_ENABLED=false
APP_NOTIFICATION_PLATFORM_ENABLED=true
+4 -2
View File
@@ -198,8 +198,10 @@ EXPOSE 8080 9001
# the actuator work lived on an unmerged branch. It has been merged for some time, and a stale
# warning about a healthcheck is the kind of comment that gets a real red container ignored.)
#
# A readiness failure here is a correct UNHEALTHY, not a broken probe: the readiness group includes
# the datasource, so a container started with no reachable PostgreSQL is genuinely not ready.
# A readiness failure here is a correct UNHEALTHY, not a broken probe. In the default composition
# the readiness group is readinessState alone (config/observability.yml); a capability that owns a
# connection adds its own indicator when it is selected — the JPA module adds the datasource — so a
# container started without that dependency reachable is genuinely not ready.
# Kubernetes ignores HEALTHCHECK and uses its own probes against the same path; this exists for
# docker and Compose.
#
+12 -2
View File
@@ -18,8 +18,12 @@
#
# The multi-stage build, --parents descriptor glob, STRICT lock verification,
# non-root user, read-only-root-fs writable mounts, and JVM container ergonomics
# are all identical to src/Dockerfile — only the bootJar target differs. Keep the
# two files' builder stages in sync.
# are all identical to src/Dockerfile — only the bootJar target differs.
#
# Two files rather than one with a COMPOSITION=sample argument: the release image refuses to build
# without version and source metadata, and folding a zero-argument demo into it would make that
# refusal conditional. The part that must not drift — the dependency stage's COPY lines — is held
# equal by DeveloperExperienceContractTest.
# =============================================================================
# Demo defaults so the image builds with zero build-args. Two format constraints from the root
@@ -49,8 +53,14 @@ WORKDIR /build/src
# (Requires the labs Dockerfile frontend — see the `# syntax` directive at the top of this file.)
COPY gradlew ./
COPY gradle/ gradle/
COPY gradle.properties ./
COPY config/ ./config/
COPY --parents settings.gradle build.gradle **/build.gradle **/gradle.lockfile ./
# The convention plugins, whole — see src/Dockerfile. Without them settings.gradle's
# includeBuild('build-logic') has no version catalog and no plugins, and this stage failed before
# resolving anything (07-04). DeveloperExperienceContractTest holds these COPY lines equal to the
# release image's.
COPY build-logic/ ./build-logic/
# Resolve every module configuration in STRICT mode (no --write-locks in a demo build either).
RUN test -n "${RELEASE_VERSION}" \
+2
View File
@@ -162,6 +162,8 @@ health 스키마만 소유한다.
| 관측 tag cardinality (`observation/`) | `wired` | `runtime/GraphQlRequestObservationConventionAdapter` 가 Spring 의 `ExecutionRequestObservationConvention` 을 구현해 Boot 의 `GraphQlObservationAutoConfiguration` 이 이 컨벤션을 가져간다. `autoconfigure/GraphQlObservationWiringTest`(프레임워크가 실제로 해석), `runtime/GraphQlRequestObservationConventionAdapterTest`(실제 `MeterRegistry` 에 임의 이름 10,000개 → series 1개) |
| object 인가 (`security/`) | `modelled` | 답하는 계약은 중립 `dev.caskeleton.application.security.ObjectAccessPolicy` 가 소유하고 이 leaf 는 `ApplicationObjectAuthorization` 매핑만 가진다. 실행 경로에 연결하는 configuration 은 없다 |
| DataLoader/batching (`dataloader/`) | `wired` | `runtime/GraphQlBatchLoaderRegistrationTest` (실제 graphql-java 실행 + Spring `BatchLoaderRegistry`, 50 parent → 3 downstream 호출), `dataloader/GraphQlBatchContractTest` |
| 요청 deadline (`maxExecutionTime`) | `wired` | `systemTest/runtime/GraphQlRequestDeadlineTest`(virtual thread: deadline 근처 `REQUEST_TIMEOUT`, 하위 필드 미실행), `GraphQlRequestDeadlineOnRequestThreadTest`(요청 스레드: 느린 resolver 가 끝난 뒤 응답 — 한계). 이미 도는 resolver 는 끊지 않는다(README 「요청 deadline」) |
| per-parent fetch(N+1) 신호 | `wired` | `systemTest/runtime/GraphQlPerParentFetchTest`(일반 `@SchemaMapping` 자식 → WARN 1줄 + `graphql.per.parent.fetch`, registrar 자식 → 조용함). 거부하지 않는다 |
| cursor 서명·connection (`pagination/`), fetch profile (`fetch/`) | 라이브러리 | 요청 경로에 없다. 서비스가 직접 호출한다 — README "라이브러리 API". `autoconfigure/GraphQlPolicyRequestPathTest` 가 auto-configuration 이 codec·key ring 을 만들지 않음을 고정 |
| 실부하·장애 | 미달성 | 증거 없음 |
+77 -3
View File
@@ -126,6 +126,7 @@ app:
preparsed-cache-entries: 1000
preparsed-cache-weight: 10000000
preparsed-cache-expire-after-access: 30m
per-parent-fetch-warning-threshold: 10 # 아래 「N+1」 절
observed-operation-names: [] # 비우면 모든 operation 이름이 `other` 로 접힌다
```
@@ -238,9 +239,82 @@ tenant/정렬 축으로 넘어가는 것을 막기 위함이며, 키 회전은 `
## DataLoader 는 요청 스코프, 캐시 키는 actor·tenant 지문으로 격리
`dataloader/GraphQlDataLoaderRequestRegistry` 는 요청마다 새 인스턴스를 만든다. 전역 캐시는
tenant 간 데이터 누출 경로가 된다. `security/GraphQlBatchContext.cacheScope()` 는 raw tenant id 가
아니라 **sha256 지문**을 캐시 스코프에 쓴다(로그·메트릭에 tenant 원문이 새지 않도록).
요청 스코프는 Spring 이 준다. `runtime/GraphQlBatchLoaderRegistrar.register` 는 loader 를 Spring 의
`BatchLoaderRegistry` 에 등록하고, Spring 은 실행마다 새 `DataLoaderRegistry` 를 만든다. 그래서
loader 캐시는 그 요청이 끝나면 함께 사라지고, 한 호출자가 받은 행이 다음 호출자에게 가지 않는다
(`GraphQlBatchLoaderRegistrationTest.oneRequestsCacheIsNotHandedToTheNext`). 전역 캐시는 tenant 간
데이터 누출 경로가 된다. 각 chunk 는 `dataloader/GraphQlBatchContext` 를 받고, 그
`cacheScope()` 는 raw tenant id 가 아니라 actor·tenant 의 **sha256 지문**이다(로그·메트릭에 tenant
원문이 새지 않도록).
요청마다 새로 만든다고 설명하던 `GraphQlDataLoaderRequestRegistry` 와
`GraphQlDataLoaderFactory.newRequestRegistry()` 는 어느 요청 경로에도 연결되지 않아 2026-11-02 에
삭제했다(리뷰 03-04).
플랫폼 context 없이 batch 가 불리면(transport interceptor 미배선) `GraphQlPlatformContextMissingException`
으로 거부한다. wire 는 `INTERNAL_ERROR` + `constraint: PLATFORM_CONTEXT`, 로그는 WARN 한 줄이다.
instrumentation 이 context 없는 요청을 거부할 때와 같은 constraint 다. 예전에는 `REQUEST_TIMEOUT` 으로
나가서 조립 오류가 "느리다"로 보였고 클라이언트가 재시도했다(리뷰 03-05).
## N+1 — list 부모 아래 자식 필드는 `GraphQlBatchLoaderRegistrar.register` 로
플랫폼의 batch 보호(chunk 크기, 요청 deadline 으로 줄인 batch 예산, actor·tenant scope)는
`GraphQlBatchLoaderRegistrar.register` 로 등록한 loader 에만 붙는다. 조립 예시는 복사본을 두지 않고
컴파일·실행되는 테스트 소스를 가리킨다:
[`src/systemTest/java/.../example/OrderCustomerBatchLoading.java`](src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/example/OrderCustomerBatchLoading.java).
세 부분이다 — loader 이름의 `GraphQlBatchPolicy` 를 담은 `GraphQlBatchPolicyRegistry` bean, 생성자에서
`registrar.register(batchLoaders, CUSTOMER_BY_ID, (ids, batch) -> customers.findByIds(ids))` 한 번,
자식 필드 `@SchemaMapping` 은 `environment.getDataLoader(...).load(key)` 만 한다.
`GraphQlPerParentFetchTest` 가 이 예시로 부모 8개 → downstream 1번을 확인한다.
같은 일을 하는 다른 길과의 차이:
| 방법 | 부모 N개일 때 downstream 호출 | chunk·deadline·tenant scope |
| --- | --- | --- |
| `GraphQlBatchLoaderRegistrar.register` | batch 당 1번(policy 의 `maxBatchSize` 로 chunk) | 적용 |
| Spring `@BatchMapping` | 1번 | 미적용 — 크기 상한·deadline·tenant 지문이 없다 |
| 부모마다 부르는 일반 `@SchemaMapping` | N번 | 미적용 |
adopter 가 잊었을 때를 위해 `runtime/GraphQlPerParentFetchInstrumentation` 이 실행을 센다. 한
요청에서 같은 필드 좌표가 **DataLoader 를 거치지 않고**(환경에서 DataLoader·registry 를 꺼내지 않고)
resolver 를 `app.graphql.limits.per-parent-fetch-warning-threshold`(기본 10)번보다 많이 부르면 그
좌표로 WARN 한 줄과 `graphql.per.parent.fetch` observation(태그 `graphql.schema.coordinate`) 하나를
남긴다. 거부하지는 않는다 — 부모마다 부르는 resolver 가 싼지는 adopter 만 안다. property 읽기 같은
trivial fetcher 는 세지 않는다. 기본 10 은 기본 page 크기 20 보다 작아서 기본 page 아래의 N+1 은
잡히고, 보통 문서가 alias 로 root 를 몇 번 부르는 정도로는 울리지 않는 값이다. metric 은 애플리케이션의
`ObservationRegistry` 로 나가며(Actuator 가 있으면 timer 로 집계), 없으면 WARN 만 남는다.
버린 대안: 카탈로그에 등록되지 않은 list 자식 필드를 기동 때 경고 — 모든 list 필드를 adopter 가
카탈로그에 등록해야 의미가 생겨 비용에 비해 효과가 작다. 재검토 조건: sample 에 GraphQL feature 가
들어오면 그 코드가 위 예시를 대신한다.
## 요청 deadline — 무엇이 끊기고 무엇이 안 끊기나
`GraphQlClientPolicy.maxExecutionTime`(기본 10초)으로 만든 `GraphQlDeadline` 하나를 다음이 읽는다.
- `runtime/GraphQlPlatformWebInterceptor`: deadline 까지 남은 시간으로 응답에 timer 를 건다. 시간이
지나면 클라이언트는 `REQUEST_TIMEOUT`(category `TIMEOUT`)을 받고, Spring 이 실행을 cancel 해서
graphql-java 가 다음 필드를 더 dispatch 하지 않는다.
- `runtime/GraphQlDeadlineInstrumentation`: deadline 이 지난 뒤에는 non-trivial resolver 를 부르지 않고
그 필드를 `REQUEST_TIMEOUT` 으로 실패시킨다.
- `GraphQlCostBudgetHandler`: deadline 이 이미 지났으면 실행을 시작하지 않는다.
- `GraphQlBatchExecutor`: registrar 로 등록한 batch 예산을 남은 시간으로 줄이고, chunk 사이에서 멈춘다.
**한계(테스트로 고정).** 이미 돌고 있는 resolver 는 끊지 않는다. 그 스레드는 resolver 가 끝날 때까지
돌고, 그 안의 DB·HTTP 호출은 각 client 의 timeout 이 끊는다 — JPA/Mongo/HTTP client 에 deadline 을
넘겨주는 장치는 없다. 응답이 deadline 에 바로 나가는지는 resolver 가 어느 스레드에서 도는지에 달렸다.
| 실행 스레드 | 클라이언트가 응답을 받는 때 | 테스트 |
| --- | --- | --- |
| virtual thread 켬(템플릿 기본 `SPRING_THREADS_VIRTUAL_ENABLED=true`): Spring 이 blocking controller 를 executor 에서 부른다 | deadline 근처 | `GraphQlRequestDeadlineTest` |
| virtual thread 끔: blocking controller 가 요청 스레드에서 돈다 | 느린 resolver 가 끝난 뒤. 그 아래 필드는 실행되지 않는다 | `GraphQlRequestDeadlineOnRequestThreadTest` |
고른 방법과 버린 대안: deadline 은 플랫폼 interceptor 안에서 요청 context 의 `GraphQlDeadline` 값
그대로 건다. Spring 의 `TimeoutWebGraphQlInterceptor` 는 GraphQL 본문 없는 HTTP 408 로 끝나 플랫폼
`REQUEST_TIMEOUT` 코드를 잃고, 자기 duration 을 따로 받아 deadline 과 갈라질 수 있어 쓰지 않았다.
resolver 마다 deadline 을 검사하게 하는 방법은 adopter 가 기억해야 하는 숨은 규칙이 되어 버렸다.
예산을 좁히기만 하던 `execution/GraphQlTimeoutPolicy` 는 main 호출자가 없었고 같은 계산이
`GraphQlBatchExecutor.effectiveBudget` 에 있어 삭제했다(리뷰 03-02).
## 관측은 저-카디널리티 강제
-2
View File
@@ -119,7 +119,6 @@ strictTestLanes {
description = 'Runs exact no-skip GraphQL conditional transport wire evidence.'
requires 'dev.caskeleton.adapter.inbound.graphql.GraphqlHttpBoundaryQualificationTest'
rejectSkipped = true
jvmArgs '-Duser.timezone=UTC'
}
// The transport-boundary ArchUnit suite runs in `test` too; this lane is the guard that it is
// still discovered and not skipped — a missing class leaves `test` green.
@@ -127,7 +126,6 @@ strictTestLanes {
description = 'Runs the GraphQL transport-boundary architecture suite and fails if it is gone or skipped.'
requires 'dev.caskeleton.adapter.inbound.graphql.GraphQlTransportBoundaryArchitectureTest'
rejectSkipped = true
jvmArgs '-Duser.timezone=UTC'
}
}
@@ -9,15 +9,19 @@ import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionPipeline;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlCostBudgetHandler;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDeadlineInstrumentation;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDocumentAuthorizationHandler;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionChain;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlOperationSelectionHandler;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPerParentFetchInstrumentation;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformInstrumentation;
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationInterceptor;
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationPolicy;
import graphql.execution.instrumentation.Instrumentation;
import io.micrometer.observation.ObservationRegistry;
import java.time.Clock;
import java.util.List;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -130,4 +134,31 @@ class GraphQlExecutionChainConfiguration {
GraphQlExecutionChain chain, GraphQlWireErrorMapper errors) {
return new GraphQlPlatformInstrumentation(chain, errors);
}
/**
* Refuses to start a resolver after the request deadline (review 03-02).
*
* <p>The transport interceptor's timer answers the client at the deadline; this is the part that
* still holds when the execution runs on the request thread and the timer cannot fire in time.
*/
@Bean
@ConditionalOnMissingBean(GraphQlDeadlineInstrumentation.class)
Instrumentation graphQlDeadlineInstrumentation(Clock graphQlPlatformClock) {
return new GraphQlDeadlineInstrumentation(graphQlPlatformClock);
}
/**
* Logs and records a field that resolves per parent without a DataLoader (review 03-03).
*
* <p>Records through the application's {@link ObservationRegistry} when there is one, the same
* registry Spring for GraphQL's own observations use; without one only the WARN line remains.
*/
@Bean
@ConditionalOnMissingBean(GraphQlPerParentFetchInstrumentation.class)
Instrumentation graphQlPerParentFetchInstrumentation(
GraphQlPlatformSettings properties, ObjectProvider<ObservationRegistry> observations) {
return new GraphQlPerParentFetchInstrumentation(
properties.limits().perParentFetchWarningThreshold(),
observations.getIfAvailable(() -> ObservationRegistry.NOOP));
}
}
@@ -82,17 +82,23 @@ public record GraphQlPlatformSettings(
* @param preparsedCacheEntries largest number of cached parsed documents
* @param preparsedCacheWeight largest total cached document weight, in characters
* @param preparsedCacheExpireAfterAccess how long an unused cached document is kept
* @param perParentFetchWarningThreshold how many times one field coordinate may run a resolver
* without a DataLoader in one request before it is logged and recorded as a likely N+1
* ({@code GraphQlPerParentFetchInstrumentation}). 10 sits below the default page size of 20,
* so a default page whose child resolves per parent is reported, and above the handful of
* aliased root calls an ordinary document makes
*/
public record Limits(
@DefaultValue("100") int maximumPageSize,
@DefaultValue("10000") long maximumComplexity,
@DefaultValue("1000") long preparsedCacheEntries,
@DefaultValue("10000000") long preparsedCacheWeight,
@DefaultValue("30m") Duration preparsedCacheExpireAfterAccess) {
@DefaultValue("30m") Duration preparsedCacheExpireAfterAccess,
@DefaultValue("10") int perParentFetchWarningThreshold) {
/** The declared defaults, for programmatic construction. */
public static Limits defaults() {
return new Limits(100, 10_000, 1_000, 10_000_000, Duration.ofMinutes(30));
return new Limits(100, 10_000, 1_000, 10_000_000, Duration.ofMinutes(30), 10);
}
}
@@ -52,6 +52,9 @@ public final class GraphQlPlatformStartupValidator {
if (properties.limits().maximumComplexity() < 1) {
problems.add("maximum complexity must be positive");
}
if (properties.limits().perParentFetchWarningThreshold() < 1) {
problems.add("per-parent fetch warning threshold must be positive");
}
return List.copyOf(problems);
}
@@ -7,10 +7,24 @@ import java.time.Instant;
/**
* The absolute instant a GraphQL request must be finished by.
*
* <p>A deadline rather than a duration, because the same budget has to be handed down to resolvers,
* DataLoader batches and the JPA/Mongo/HTTP client deadlines without each layer restarting the
* clock. Remaining time is always computed from an injected {@link Clock} so the value stays
* testable and the record itself holds no mutable state.
* <p>A deadline rather than a duration, so every reader measures against the same instant instead
* of restarting the clock. Who reads it today, and nothing more:
*
* <ul>
* <li>{@code GraphQlPlatformWebInterceptor} ends the request with {@code REQUEST_TIMEOUT} when it
* passes, and Spring cancels the execution so no further field is dispatched. A resolver
* already running is not interrupted.
* <li>{@code GraphQlCostBudgetHandler} refuses to start an execution whose deadline has passed.
* <li>{@code GraphQlBatchExecutor} clamps each platform-registered DataLoader batch to what is
* left, and stops between chunks once it is spent.
* </ul>
*
* <p>It is <em>not</em> handed to JPA, Mongo or HTTP client calls. A resolver that calls one is
* bounded by that client's own timeout; a resolver that wants the request's remainder reads it from
* {@link GraphQlRequestContext#deadline()} and passes it on itself.
*
* <p>Remaining time is always computed from an injected {@link Clock} so the value stays testable
* and the record itself holds no mutable state.
*
* @param value the instant at which the request budget is exhausted
*/
@@ -5,10 +5,11 @@ import java.time.Clock;
import java.util.Objects;
/**
* Creates the loaders for one execution.
* Supplies the per-loader batch executor and the per-execution batch context.
*
* <p>A factory rather than a bean per loader: instances must be created per execution, and a
* factory is what makes that structurally true instead of a convention someone has to remember.
* <p>It does not hold loader instances. The request scope is Spring's: {@code
* GraphQlBatchLoaderRegistrar} registers with Spring's {@code BatchLoaderRegistry}, and Spring
* builds a fresh {@code DataLoaderRegistry} — and so a fresh loader cache — for every execution.
*/
public final class GraphQlDataLoaderFactory {
@@ -33,11 +34,6 @@ public final class GraphQlDataLoaderFactory {
this.clock = Objects.requireNonNull(clock);
}
/** A registry holding this execution's loader instances. */
public GraphQlDataLoaderRequestRegistry newRequestRegistry() {
return new GraphQlDataLoaderRequestRegistry();
}
/** The batch context for this execution. */
public GraphQlBatchContext batchContext(GraphQlRequestContext context) {
return GraphQlBatchContext.from(context);
@@ -1,64 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.dataloader;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* The DataLoader instances belonging to one GraphQL execution (design §13).
*
* <p>A new registry per execution, never a shared singleton. The request-scoped cache is the
* reason: it is keyed by entity id and holds whatever the loader returned for <em>this</em> caller,
* so sharing it across requests means one user's cached order is served to the next user who asks
* for the same id.
*
* <p>Cross-request caching is a separate concern with a different key model, and belongs to the
* cache capability rather than here.
*/
public final class GraphQlDataLoaderRequestRegistry {
private final Map<GraphQlDataLoaderName, Object> loaders = new LinkedHashMap<>();
/** Whether any loader has been created for this execution. */
public boolean isEmpty() {
return loaders.isEmpty();
}
/**
* Registers a loader instance for this execution.
*
* @throws IllegalArgumentException when the loader is already registered for this execution
*/
public GraphQlDataLoaderRequestRegistry register(GraphQlDataLoaderName name, Object loader) {
if (name == null || loader == null) {
throw new IllegalArgumentException("loader name and instance are required");
}
if (loaders.putIfAbsent(name, loader) != null) {
throw new IllegalArgumentException("loader " + name.value() + " is already registered");
}
return this;
}
/**
* The loader instance registered for this execution.
*
* @throws IllegalArgumentException when it was not registered
*/
public Object require(GraphQlDataLoaderName name) {
Object loader = loaders.get(name);
if (loader == null) {
throw new IllegalArgumentException("loader " + name.value() + " is not registered");
}
return loader;
}
/** Loader names registered for this execution. */
public Set<GraphQlDataLoaderName> loaderNames() {
return Set.copyOf(loaders.keySet());
}
/** Releases every loader when the execution finishes, so nothing outlives the request. */
public void clear() {
loaders.clear();
}
}
@@ -6,7 +6,10 @@ import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
/**
* Raised when work continues after the request was cancelled or its budget expired.
* Raised when the request budget ({@code GraphQlClientPolicy.maxExecutionTime}) has run out.
*
* <p>Two places raise it: the cost stage, when the deadline passed before execution started, and
* the transport interceptor, when it passes while the execution is running.
*
* <p>Carries the stable timeout error code and no request content.
*/
@@ -17,12 +20,12 @@ public class GraphQlRequestCancelledException extends RuntimeException
/** Creates the failure. */
public GraphQlRequestCancelledException() {
super("GraphQL request was cancelled: " + GraphQlTimeoutPolicy.TIMEOUT_ERROR_CODE);
super("GraphQL request was cancelled: " + GraphQlErrorCode.REQUEST_TIMEOUT);
}
/** The stable error code clients see. */
public String code() {
return GraphQlTimeoutPolicy.TIMEOUT_ERROR_CODE;
return GraphQlErrorCode.REQUEST_TIMEOUT;
}
@Override
@@ -1,38 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.execution;
import java.time.Duration;
/**
* A remaining time budget that only ever narrows (design §10).
*
* <p>Every layer below GraphQL — resolver, DataLoader batch, database statement, HTTP call — asks
* this for its own budget, and gets the smaller of what it asked for and what is actually left.
* Without that clamp a five-second database timeout under a two-second request budget keeps the
* connection busy for three seconds after the client has already been answered.
*
* @param remaining time left in the parent budget
*/
public record GraphQlTimeoutPolicy(Duration remaining) {
/** Stable error code emitted when the request budget is exhausted. */
public static final String TIMEOUT_ERROR_CODE = "REQUEST_TIMEOUT";
public GraphQlTimeoutPolicy {
if (remaining == null || remaining.isZero() || remaining.isNegative()) {
throw new IllegalArgumentException("remaining time must be positive");
}
}
/** The budget a child operation may use: never more than what remains. */
public Duration child(Duration requested) {
if (requested == null || requested.isZero() || requested.isNegative()) {
throw new IllegalArgumentException("requested budget must be positive");
}
return requested.compareTo(remaining) < 0 ? requested : remaining;
}
/** A policy for the child budget, for chaining further down. */
public GraphQlTimeoutPolicy childPolicy(Duration requested) {
return new GraphQlTimeoutPolicy(child(requested));
}
}
@@ -18,5 +18,12 @@ public final class GraphQlObservationNames {
/** One DataLoader batch. */
public static final String DATA_LOADER = "graphql.dataloader";
/**
* The platform's own: one request in which a field coordinate crossed the per-parent fetch
* threshold ({@code GraphQlPerParentFetchInstrumentation}). Not emitted by Spring; tagged only
* with the schema coordinate.
*/
public static final String PER_PARENT_FETCH = "graphql.per.parent.fetch";
private GraphQlObservationNames() {}
}
@@ -3,13 +3,14 @@ package dev.caskeleton.adapter.inbound.graphql.runtime;
import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchContext;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchExecutor;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderFactory;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.graphql.execution.BatchLoaderRegistry;
import reactor.core.publisher.Mono;
@@ -31,6 +32,8 @@ import reactor.core.publisher.Mono;
*/
public final class GraphQlBatchLoaderRegistrar {
private static final Logger LOG = LoggerFactory.getLogger(GraphQlBatchLoaderRegistrar.class);
private final GraphQlDataLoaderFactory factory;
/**
@@ -73,7 +76,14 @@ public final class GraphQlBatchLoaderRegistrar {
if (context == null) {
// Fail closed. A loader running without the platform context has no deadline, no
// tenant and no actor, and would happily batch across whatever the caller was.
return Mono.error(new GraphQlBatchTimeoutException(loaderName.value()));
// Reported as the assembly fault it is, the same way the instrumentation reports a
// request without the context: INTERNAL_ERROR on the wire, the cause in the log.
LOG.warn(
"graphql batch rejected: no platform context (loader={});"
+ " the platform transport interceptor is not wired",
loaderName.value());
return Mono.error(
new GraphQlPlatformContextMissingException("loader " + loaderName.value()));
}
GraphQlBatchContext batchContext = factory.batchContext(context);
return Mono.fromCallable(
@@ -0,0 +1,61 @@
package dev.caskeleton.adapter.inbound.graphql.runtime;
import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException;
import graphql.execution.instrumentation.InstrumentationState;
import graphql.execution.instrumentation.SimplePerformantInstrumentation;
import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters;
import graphql.schema.DataFetcher;
import java.time.Clock;
import java.util.Objects;
/**
* Refuses to start a resolver once the request deadline has passed (review 03-02).
*
* <p>The transport interceptor ends the request at its deadline with a timer, and that is enough
* whenever the execution runs off the request thread. It is not enough when it runs on it: on a
* servlet stack without virtual threads Spring for GraphQL invokes a blocking controller method on
* the request thread, the whole execution happens inside the subscription, and the timer only
* starts after it has finished. This check is what still holds there: every non-trivial fetch after
* the deadline fails with {@code REQUEST_TIMEOUT} instead of calling the resolver, so a slow parent
* does not drag its children's downstream calls behind it.
*
* <p>Trivial fetchers (property reads) are left alone: they do no downstream work, and checking the
* clock on every one of them would cost more than it saves. A resolver already running is not
* interrupted — nothing here can stop a blocking call it did not start.
*
* <p>Chosen over cancelling the {@code ExecutionInput}: graphql-java answers a cancelled execution
* with its own {@code AbortExecutionException} message, which would replace the platform's {@code
* REQUEST_TIMEOUT} code with an unmapped one.
*/
public final class GraphQlDeadlineInstrumentation extends SimplePerformantInstrumentation {
private final Clock clock;
/**
* Creates the instrumentation.
*
* @param clock the clock the request deadline is measured against
*/
public GraphQlDeadlineInstrumentation(Clock clock) {
this.clock = Objects.requireNonNull(clock, "clock is required");
}
@Override
public DataFetcher<?> instrumentDataFetcher(
DataFetcher<?> dataFetcher,
InstrumentationFieldFetchParameters parameters,
InstrumentationState state) {
if (parameters.isTrivialDataFetcher()) {
return dataFetcher;
}
return environment -> {
GraphQlRequestContext context =
environment.getGraphQlContext().get(GraphQlRequestContext.CONTEXT_KEY);
if (context != null && context.deadline().expired(clock)) {
throw new GraphQlRequestCancelledException();
}
return dataFetcher.get(environment);
};
}
}
@@ -0,0 +1,150 @@
package dev.caskeleton.adapter.inbound.graphql.runtime;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationNames;
import graphql.execution.ExecutionStepInfo;
import graphql.execution.instrumentation.InstrumentationState;
import graphql.execution.instrumentation.SimplePerformantInstrumentation;
import graphql.execution.instrumentation.parameters.InstrumentationCreateStateParameters;
import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import graphql.schema.DelegatingDataFetchingEnvironment;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationRegistry;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.dataloader.DataLoader;
import org.dataloader.DataLoaderRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Makes an N+1 resolver visible: counts, per request, how often one field coordinate runs a
* resolver that did not go through a DataLoader (review 03-03).
*
* <p>The platform's batch protection — chunking, the request deadline, the tenant-scoped cache —
* reaches only loaders registered through {@link GraphQlBatchLoaderRegistrar}. A child field under
* a list parent written as a plain {@code @SchemaMapping} calls its downstream once per parent, and
* nothing in the platform can see that from the schema. What it can see is the execution: the same
* coordinate fetched again and again in one request, each time without touching a DataLoader.
*
* <p>"Through a DataLoader" means the resolver asked its {@code DataFetchingEnvironment} for one or
* for the registry. Spring resolves a {@code DataLoader} method argument that way,
* {@code @BatchMapping} does too, and so does a hand-written fetcher; none of those are counted.
* Trivial property reads are not counted either. Counting is by invocation, not by thread, so a
* resolver Spring runs on the executor (virtual threads) is counted the same as one on the request
* thread.
*
* <p>When a coordinate crosses the threshold in one request this logs one WARN for it and records
* one {@value GraphQlObservationNames#PER_PARENT_FETCH} observation tagged with the schema
* coordinate, which is bounded by the schema. It never rejects: a per-parent resolver may be
* perfectly cheap, and only the adopter knows. The signal exists so an expensive one is found in
* the log or a dashboard rather than in a database incident.
*
* <p>Chosen over a startup check of unregistered list children (review 03-03 option c): that needs
* every list field registered in the cost catalog before it can say anything, while this needs
* nothing from the adopter.
*/
public final class GraphQlPerParentFetchInstrumentation extends SimplePerformantInstrumentation {
private static final Logger LOG =
LoggerFactory.getLogger(GraphQlPerParentFetchInstrumentation.class);
/** The metric tag carrying the field coordinate; allowlisted by the cardinality policy. */
public static final String COORDINATE_TAG = "graphql.schema.coordinate";
private final int warningThreshold;
private final ObservationRegistry observations;
/**
* Creates the instrumentation.
*
* @param warningThreshold per-parent fetches of one coordinate in one request that are still
* quiet; one more logs and records
* @param observations where the crossing is recorded; {@link ObservationRegistry#NOOP} records
* nothing
*/
public GraphQlPerParentFetchInstrumentation(
int warningThreshold, ObservationRegistry observations) {
if (warningThreshold < 1) {
throw new IllegalArgumentException("per-parent fetch warning threshold must be positive");
}
this.warningThreshold = warningThreshold;
this.observations = Objects.requireNonNull(observations, "observation registry is required");
}
@Override
public InstrumentationState createState(InstrumentationCreateStateParameters parameters) {
return new Counts();
}
@Override
public DataFetcher<?> instrumentDataFetcher(
DataFetcher<?> dataFetcher,
InstrumentationFieldFetchParameters parameters,
InstrumentationState state) {
if (parameters.isTrivialDataFetcher() || !(state instanceof Counts counts)) {
return dataFetcher;
}
return environment -> {
LoaderTracking tracking = new LoaderTracking(environment);
Object value = dataFetcher.get(tracking);
if (!tracking.usedDataLoader) {
record(counts, coordinate(environment.getExecutionStepInfo()));
}
return value;
};
}
private void record(Counts counts, String coordinate) {
int fetches =
counts
.byCoordinate
.computeIfAbsent(coordinate, key -> new AtomicInteger())
.incrementAndGet();
if (fetches != warningThreshold + 1) {
return;
}
LOG.warn(
"graphql field {} resolved per parent more than {} times in one request without a"
+ " DataLoader; register it with GraphQlBatchLoaderRegistrar",
coordinate,
warningThreshold);
Observation.createNotStarted(GraphQlObservationNames.PER_PARENT_FETCH, observations)
.lowCardinalityKeyValue(COORDINATE_TAG, coordinate)
.observe(() -> {});
}
private static String coordinate(ExecutionStepInfo step) {
return step.getObjectType().getName() + "." + step.getFieldDefinition().getName();
}
/** Per-execution counts, one per coordinate. */
private static final class Counts implements InstrumentationState {
private final Map<String, AtomicInteger> byCoordinate = new ConcurrentHashMap<>();
}
/** Notes whether the resolver reached for a DataLoader; changes nothing it sees. */
private static final class LoaderTracking extends DelegatingDataFetchingEnvironment {
private volatile boolean usedDataLoader;
LoaderTracking(DataFetchingEnvironment delegate) {
super(delegate);
}
@Override
public <K, V> DataLoader<K, V> getDataLoader(String dataLoaderName) {
usedDataLoader = true;
return super.getDataLoader(dataLoaderName);
}
@Override
public DataLoaderRegistry getDataLoaderRegistry() {
usedDataLoader = true;
return super.getDataLoaderRegistry();
}
}
}
@@ -0,0 +1,52 @@
package dev.caskeleton.adapter.inbound.graphql.runtime;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
import java.util.Optional;
/**
* Raised when platform machinery runs without the request context the transport interceptor puts in
* place.
*
* <p>That is an assembly fault — the interceptor is not wired — not anything the client did, so the
* client sees an opaque {@code INTERNAL_ERROR} carrying the {@value #CONSTRAINT} constraint and the
* operator gets the WARN line naming the cause. It replaced the batch registrar's {@code
* GraphQlBatchTimeoutException}, which reported the same fault as a retryable {@code
* REQUEST_TIMEOUT}: a mis-assembled deployment looked slow, and clients retried it (review 03-05).
*
* <p>Package-private: only the runtime machinery raises it, and the wire mapper reads it through
* {@link GraphQlPlatformRejection}, so no adopter code needs the type.
*/
final class GraphQlPlatformContextMissingException extends RuntimeException
implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L;
/** The constraint identity every missing-context rejection carries on the wire. */
static final String CONSTRAINT = "PLATFORM_CONTEXT";
/**
* Creates the failure.
*
* @param where bounded name of the machinery that found the context missing
*/
GraphQlPlatformContextMissingException(String where) {
super("no GraphQL platform context in " + where);
}
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.platform(GraphQlErrorCode.INTERNAL_ERROR);
}
@Override
public Category failureCategory() {
return Category.INTERNAL;
}
@Override
public Optional<String> constraint() {
return Optional.of(CONSTRAINT);
}
}
@@ -36,7 +36,8 @@ public final class GraphQlPlatformInstrumentation extends SimplePerformantInstru
private static final Logger LOG = LoggerFactory.getLogger(GraphQlPlatformInstrumentation.class);
/** Constraint reported when the request arrived without a platform context. */
public static final String MISSING_CONTEXT_CONSTRAINT = "PLATFORM_CONTEXT";
public static final String MISSING_CONTEXT_CONSTRAINT =
GraphQlPlatformContextMissingException.CONSTRAINT;
private final GraphQlExecutionChain chain;
private final GraphQlWireErrorMapper errors;
@@ -6,6 +6,7 @@ import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext;
import dev.caskeleton.adapter.inbound.graphql.context.TenantContext;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlExtensionsPolicy;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlJsonStructurePolicy;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestSize;
@@ -18,6 +19,7 @@ import graphql.ExecutionInput;
import graphql.ExecutionResult;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
@@ -38,6 +40,10 @@ import reactor.core.publisher.Mono;
* the context this interceptor puts into the GraphQL context, so a deployment that omits it gets a
* rejected request rather than an unpoliced one.
*
* <p>It also ends the request at its deadline: the execution is answered with {@code
* REQUEST_TIMEOUT} when {@code GraphQlClientPolicy.maxExecutionTime} runs out, whatever is still
* running (see {@link #intercept} for what that does and does not stop).
*
* <p>The document size check is here rather than in a policy object for the same reason: the
* transport is where the size is known, and refusing a large document before parsing is the only
* place the refusal is cheap.
@@ -111,7 +117,25 @@ public final class GraphQlPlatformWebInterceptor implements WebGraphQlIntercepto
// Also on the Reactor context, so a reactive resolver reads the same value rather than a
// second one assembled from whatever it can reach.
return chain.next(request).contextWrite(view -> view.put(GraphQlRequestContext.class, context));
//
// The timeout is the request deadline itself, read from the context just built, so the budget
// the pipeline and the DataLoader batches check and the one that ends the request are one value
// (review 03-02). On expiry the client gets REQUEST_TIMEOUT and Spring cancels the execution,
// which stops graphql-java from dispatching further fields. A resolver already running is not
// interrupted: it finishes on its own thread, and its downstream timeouts are what bound it. On
// a servlet stack without virtual threads that resolver is running on the request thread, so
// the answer can only leave when it returns (GraphQlRequestDeadlineOnRequestThreadTest).
//
// Chosen over Spring's TimeoutWebGraphQlInterceptor: that one answers with an HTTP 408 and no
// GraphQL body, so the client would lose the platform's REQUEST_TIMEOUT code, and it needs its
// own duration — a second copy of the budget that could drift from this deadline.
Duration budget = context.deadline().remaining(clock);
return chain
.next(request)
.contextWrite(view -> view.put(GraphQlRequestContext.class, context))
.timeout(
budget,
Mono.fromSupplier(() -> reject(request, new GraphQlRequestCancelledException())));
}
/**
@@ -22,6 +22,9 @@ app:
preparsed-cache-entries: ${APP_GRAPHQL_PREPARSED_CACHE_ENTRIES:1000}
preparsed-cache-weight: ${APP_GRAPHQL_PREPARSED_CACHE_WEIGHT:10000000}
preparsed-cache-expire-after-access: ${APP_GRAPHQL_PREPARSED_CACHE_EXPIRE_AFTER_ACCESS:30m}
# 한 요청에서 같은 필드 좌표가 DataLoader 없이 resolver 를 이 횟수보다 많이 부르면 WARN 한 줄과
# graphql.per.parent.fetch metric 을 남긴다(N+1 신호, 거부하지 않는다). 기본 10 = 기본 page 크기 20 보다 작다.
per-parent-fetch-warning-threshold: ${APP_GRAPHQL_PER_PARENT_FETCH_WARNING_THRESHOLD:10}
# /actuator/info 에 싣는 이 모듈의 상태(management.info.env). compose smoke 가 lane 이 실제로 켠
# capability 를 이 값으로 확인한다. 위 스위치를 해석한 값이고, 기본값은 GraphQlRootAutoConfiguration 의
@@ -0,0 +1,79 @@
package dev.caskeleton.adapter.inbound.graphql.example;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchPolicy;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchPolicyRegistry;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBatchLoaderRegistrar;
import graphql.schema.DataFetchingEnvironment;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.graphql.data.method.annotation.SchemaMapping;
import org.springframework.graphql.execution.BatchLoaderRegistry;
import org.springframework.stereotype.Controller;
/**
* The README example "a child field under a list parent" — compiled and executed here.
*
* <p>{@code src/adapter/inbound/graphql/README.md} points at this file instead of carrying a copy,
* so the example cannot drift from code that compiles. {@code GraphQlPerParentFetchTest} runs it
* over the real endpoint and counts the downstream calls.
*
* <p>Three parts, all on the adopter's side:
*
* <ol>
* <li>a policy for the loader name (batch size and batch timeout), as a {@link
* GraphQlBatchPolicyRegistry} bean;
* <li>the downstream call, registered once through {@link GraphQlBatchLoaderRegistrar} — the
* platform wraps it in chunking, the request deadline and the request's actor/tenant scope;
* <li>the child field, which only asks the DataLoader for its key.
* </ol>
*/
@Controller
public class OrderCustomerBatchLoading {
/** The loader's platform name; the policy and the registration meet on it. */
public static final GraphQlDataLoaderName CUSTOMER_BY_ID =
new GraphQlDataLoaderName("customer-by-id");
/** The adopter's downstream port: one call for many ids. */
public interface CustomerDirectory {
Map<String, Customer> findByIds(List<String> ids);
}
public record Order(String id, String customerId) {}
public record Customer(String id, String name) {}
public OrderCustomerBatchLoading(
BatchLoaderRegistry batchLoaders,
GraphQlBatchLoaderRegistrar registrar,
CustomerDirectory customers) {
// The batch context carries the request's actor, tenant, deadline and cache scope; a downstream
// that filters by tenant reads it from there rather than from a thread-local.
registrar.<String, Customer>register(
batchLoaders, CUSTOMER_BY_ID, (ids, batch) -> customers.findByIds(ids));
}
/** The child field: one {@code load} per parent, one downstream call per batch. */
@SchemaMapping(typeName = "Order", field = "customer")
public CompletableFuture<Customer> customer(Order order, DataFetchingEnvironment environment) {
return environment
.<String, Customer>getDataLoader(CUSTOMER_BY_ID.value())
.load(order.customerId());
}
/** The loader's policy: at most 100 keys per downstream call, two seconds per batch. */
@Configuration(proxyBeanMethods = false)
public static class Policies {
@Bean
GraphQlBatchPolicyRegistry graphQlBatchPolicyRegistry() {
return new GraphQlBatchPolicyRegistry()
.register(new GraphQlBatchPolicy(CUSTOMER_BY_ID, 100, Duration.ofSeconds(2), true));
}
}
}
@@ -0,0 +1,191 @@
package dev.caskeleton.adapter.inbound.graphql.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import dev.caskeleton.adapter.inbound.graphql.example.OrderCustomerBatchLoading;
import dev.caskeleton.adapter.inbound.graphql.example.OrderCustomerBatchLoading.Customer;
import dev.caskeleton.adapter.inbound.graphql.example.OrderCustomerBatchLoading.CustomerDirectory;
import dev.caskeleton.adapter.inbound.graphql.example.OrderCustomerBatchLoading.Order;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationNames;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.observation.DefaultMeterObservationHandler;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import io.micrometer.observation.ObservationRegistry;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.resttestclient.TestRestTemplate;
import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.data.method.annotation.SchemaMapping;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
/**
* A child field resolved once per parent is reported; the same field through the registrar is not
* (review 03-03).
*
* <p>Both children of {@code Order} return the same customer. {@code customerPerParent} is the
* plain {@code @SchemaMapping} an adopter writes first; {@code customer} is the README example
* ({@link OrderCustomerBatchLoading}). The downstream counter is what tells them apart; the WARN
* line and the metric are what an operator would see.
*/
@SpringBootTest(
classes = GraphQlPerParentFetchTest.TestApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {
"app.graphql.enabled=true",
"app.graphql.deployment-mode=LOCAL",
"spring.graphql.graphiql.enabled=false",
"app.graphql.limits.per-parent-fetch-warning-threshold=5",
RuntimeLimitsTestSupport.SCHEMA_LOCATIONS,
RuntimeLimitsTestSupport.SCHEMA_FILES
})
@AutoConfigureTestRestTemplate
class GraphQlPerParentFetchTest {
private static final AtomicInteger DOWNSTREAM_CALLS = new AtomicInteger();
@LocalServerPort int port;
@Autowired TestRestTemplate http;
@Autowired MeterRegistry meters;
private final ListAppender<ILoggingEvent> warnings = new ListAppender<>();
private final Logger logger =
(Logger) LoggerFactory.getLogger(GraphQlPerParentFetchInstrumentation.class);
@BeforeEach
void captureWarningsAndReset() {
meters.clear();
DOWNSTREAM_CALLS.set(0);
warnings.start();
logger.addAppender(warnings);
}
@AfterEach
void releaseCapture() {
logger.detachAppender(warnings);
warnings.stop();
}
@Test
@DisplayName("list 부모 아래 일반 @SchemaMapping 자식이 임계값을 넘으면 WARN 한 줄과 좌표 metric 이 남는다")
void aChildResolvedPerParentPastTheThresholdIsLoggedOnceAndCounted() {
// when
ResponseEntity<String> response =
RuntimeLimitsTestSupport.post(
http, port, "{ orders(count: 8) { id customerPerParent { name } } }");
// then
assertThat(response.getBody()).contains("\"name\":\"customer c-7\"");
assertThat(DOWNSTREAM_CALLS).as("eight parents, eight downstream calls").hasValue(8);
assertThat(warnings.list)
.singleElement()
.extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage)
.containsExactly(
Level.WARN,
"graphql field Order.customerPerParent resolved per parent more than 5 times in one"
+ " request without a DataLoader; register it with GraphQlBatchLoaderRegistrar");
assertThat(
meters
.get(GraphQlObservationNames.PER_PARENT_FETCH)
.tag(GraphQlPerParentFetchInstrumentation.COORDINATE_TAG, "Order.customerPerParent")
.timer()
.count())
.isEqualTo(1);
}
@Test
@DisplayName("registrar 로 조립한 자식은 한 번의 downstream 호출로 끝나고 경고하지 않는다")
void theSameChildThroughTheRegistrarIsOneCallAndStaysQuiet() {
// when
ResponseEntity<String> response =
RuntimeLimitsTestSupport.post(http, port, "{ orders(count: 8) { id customer { name } } }");
// then
assertThat(response.getBody()).contains("\"name\":\"customer c-7\"");
assertThat(DOWNSTREAM_CALLS).as("eight parents, one batch").hasValue(1);
assertThat(warnings.list).isEmpty();
assertThat(meters.find(GraphQlObservationNames.PER_PARENT_FETCH).timer()).isNull();
}
/** The list parent and the per-parent child an adopter writes before knowing better. */
@Controller
static class OrderController {
private final CustomerDirectory customers;
OrderController(CustomerDirectory customers) {
this.customers = customers;
}
@QueryMapping
List<Order> orders(@Argument int count) {
return IntStream.range(0, count)
.mapToObj(index -> new Order("o-" + index, "c-" + index))
.toList();
}
@SchemaMapping(typeName = "Order", field = "customerPerParent")
Customer customerPerParent(Order order) {
return customers.findByIds(List.of(order.customerId())).get(order.customerId());
}
}
@SpringBootConfiguration
@EnableAutoConfiguration
@Import({
RuntimeLimitsTestSupport.Transport.class,
OrderController.class,
OrderCustomerBatchLoading.class,
OrderCustomerBatchLoading.Policies.class
})
static class TestApplication {
/** A downstream that counts its calls. */
@Bean
CustomerDirectory customerDirectory() {
return ids -> {
DOWNSTREAM_CALLS.incrementAndGet();
Map<String, Customer> rows = new LinkedHashMap<>();
ids.forEach(id -> rows.put(id, new Customer(id, "customer " + id)));
return rows;
};
}
@Bean
SimpleMeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}
/** Observations become meters, as they do in a deployment with Actuator. */
@Bean
ObservationRegistry observationRegistry(SimpleMeterRegistry meters) {
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(new DefaultMeterObservationHandler(meters));
return registry;
}
}
}
@@ -0,0 +1,93 @@
package dev.caskeleton.adapter.inbound.graphql.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import dev.caskeleton.adapter.inbound.graphql.runtime.RuntimeLimitsTestSupport.SlowWork;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.resttestclient.TestRestTemplate;
import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.ResponseEntity;
/**
* The limit of the request deadline, pinned so nobody reads more into it (review 03-02).
*
* <p>With virtual threads off, Spring for GraphQL runs a blocking controller method on the servlet
* thread that is executing the request. The deadline still fires on time and cancels the execution,
* but the thread that would write the answer is the one stuck in the resolver: the client receives
* {@code REQUEST_TIMEOUT} only when that resolver returns. Nothing in the JVM can stop a blocking
* call it did not start; the resolver's own downstream timeouts are what bound it.
*/
@SpringBootTest(
classes = GraphQlRequestDeadlineOnRequestThreadTest.TestApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {
"app.graphql.enabled=true",
"app.graphql.deployment-mode=LOCAL",
"spring.graphql.graphiql.enabled=false",
"spring.threads.virtual.enabled=false",
RuntimeLimitsTestSupport.SCHEMA_LOCATIONS,
RuntimeLimitsTestSupport.SCHEMA_FILES
})
@AutoConfigureTestRestTemplate
class GraphQlRequestDeadlineOnRequestThreadTest {
private static final Duration BUDGET = Duration.ofMillis(500);
private static final int SLOW_RESOLVER_MILLIS = 2_000;
@LocalServerPort int port;
@Autowired TestRestTemplate http;
@BeforeEach
void warmUpAndReset() {
RuntimeLimitsTestSupport.post(http, port, "{ _health }");
SlowWork.reset();
}
@Test
@DisplayName("요청 스레드에서 도는 blocking resolver 는 끝난 뒤에 REQUEST_TIMEOUT 이 나가고 하위 필드는 실행되지 않는다")
void aBlockingResolverOnTheRequestThreadDelaysTheTimeoutAnswerUntilItReturns() {
// given
long started = System.nanoTime();
// when
ResponseEntity<String> response =
RuntimeLimitsTestSupport.post(
http, port, "{ slowNode(millis: " + SLOW_RESOLVER_MILLIS + ") { id detail } }");
// then
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started);
assertThat(response.getBody())
.contains("\"code\":\"REQUEST_TIMEOUT\"")
.doesNotContain("detail-of-");
assertThat(SlowWork.DETAIL_INVOCATIONS)
.as("the cancelled execution stops before the child field")
.hasValue(0);
assertThat(elapsedMillis)
.as("the servlet thread was inside the resolver; the answer could not leave earlier")
.isGreaterThanOrEqualTo(SLOW_RESOLVER_MILLIS);
}
@SpringBootConfiguration
@EnableAutoConfiguration
@Import({RuntimeLimitsTestSupport.Transport.class, RuntimeLimitsTestSupport.SlowController.class})
static class TestApplication {
@Bean
GraphQlClientPolicy shortBudgetClientPolicy() {
return RuntimeLimitsTestSupport.policyWithExecutionBudget(BUDGET);
}
}
}
@@ -0,0 +1,118 @@
package dev.caskeleton.adapter.inbound.graphql.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import dev.caskeleton.adapter.inbound.graphql.runtime.RuntimeLimitsTestSupport.SlowWork;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.resttestclient.TestRestTemplate;
import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.ResponseEntity;
/**
* The request budget ({@code GraphQlClientPolicy.maxExecutionTime}) is enforced while the request
* runs, not only checked before it starts (review 03-02).
*
* <p>Runs with virtual threads on, which is the template's default ({@code
* SPRING_THREADS_VIRTUAL_ENABLED:true}): Spring for GraphQL then invokes a blocking controller
* method on the application executor, the servlet thread is free, and the answer can leave at the
* deadline. {@link GraphQlRequestDeadlineOnRequestThreadTest} pins what happens when it cannot.
*/
@SpringBootTest(
classes = GraphQlRequestDeadlineTest.TestApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {
"app.graphql.enabled=true",
"app.graphql.deployment-mode=LOCAL",
"spring.graphql.graphiql.enabled=false",
"spring.threads.virtual.enabled=true",
RuntimeLimitsTestSupport.SCHEMA_LOCATIONS,
RuntimeLimitsTestSupport.SCHEMA_FILES
})
@AutoConfigureTestRestTemplate
class GraphQlRequestDeadlineTest {
private static final Duration BUDGET = Duration.ofSeconds(1);
private static final int SLOW_RESOLVER_MILLIS = 4_000;
@LocalServerPort int port;
@Autowired TestRestTemplate http;
@BeforeEach
void warmUpAndReset() {
// The first request pays for class loading and parsing; it must not eat the budget under test.
RuntimeLimitsTestSupport.post(http, port, "{ _health }");
SlowWork.reset();
}
@Test
@DisplayName("deadline 이 지나도 resolver 가 끝나지 않으면 deadline 근처에서 REQUEST_TIMEOUT 으로 응답한다")
void aResolverStillRunningAtTheDeadlineIsAnsweredWithRequestTimeoutNearTheDeadline() {
// given
long started = System.nanoTime();
// when
ResponseEntity<String> response =
RuntimeLimitsTestSupport.post(
http, port, "{ slowNode(millis: " + SLOW_RESOLVER_MILLIS + ") { id detail } }");
// then
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started);
assertThat(response.getBody())
.contains("\"code\":\"REQUEST_TIMEOUT\"")
.contains("\"category\":\"TIMEOUT\"")
.doesNotContain("detail-of-");
assertThat(SlowWork.SLOW_STARTED)
.as("the budget must have run out during execution, not before it")
.hasValue(1);
assertThat(elapsedMillis)
.as("answered at the deadline, not when the %d ms resolver returned", SLOW_RESOLVER_MILLIS)
.isGreaterThanOrEqualTo(BUDGET.toMillis())
.isLessThan(SLOW_RESOLVER_MILLIS - 1_000L);
}
@Test
@DisplayName("deadline 응답 뒤에는 느린 resolver 가 끝나도 그 아래 필드를 더 실행하지 않는다")
void noChildFieldStartsAfterTheDeadlineAnswerHasGone() throws InterruptedException {
// given
RuntimeLimitsTestSupport.post(
http, port, "{ slowNode(millis: " + SLOW_RESOLVER_MILLIS + ") { id detail } }");
// when
boolean finished =
SlowWork.slowFinished.await(SLOW_RESOLVER_MILLIS * 2L, TimeUnit.MILLISECONDS);
// then
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.DETAIL_INVOCATIONS)
.as("a cancelled execution must not start new fields once the client has been answered")
.hasValue(0);
}
@SpringBootConfiguration
@EnableAutoConfiguration
@Import({RuntimeLimitsTestSupport.Transport.class, RuntimeLimitsTestSupport.SlowController.class})
static class TestApplication {
@Bean
GraphQlClientPolicy shortBudgetClientPolicy() {
return RuntimeLimitsTestSupport.policyWithExecutionBudget(BUDGET);
}
}
}
@@ -0,0 +1,146 @@
package dev.caskeleton.adapter.inbound.graphql.runtime;
import dev.caskeleton.adapter.inbound.graphql.HealthGraphqlController;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import java.net.URI;
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.boot.graphql.autoconfigure.GraphQlSourceBuilderCustomizer;
import org.springframework.boot.resttestclient.TestRestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.data.method.annotation.SchemaMapping;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
import org.springframework.stereotype.Controller;
/**
* What the runtime-limit evidence tests share: the transport fixture and the slow resolver.
*
* <p>The request deadline (review 03-02) and the per-parent fetch signal (review 03-03) are both
* properties of a running request, so both are measured over the real {@code /graphql} endpoint
* rather than against a policy object.
*/
final class RuntimeLimitsTestSupport {
/** Schema properties every runtime-limit test boots with. */
static final String SCHEMA_LOCATIONS =
"spring.graphql.schema.locations=classpath:graphql-runtime-limits-no-discovery/";
static final String SCHEMA_FILES =
"spring.graphql.schema.additional-files="
+ "classpath:graphql/skeleton.graphqls,"
+ "classpath:graphql-runtime-limits/runtime-limits.graphqls";
private RuntimeLimitsTestSupport() {}
/**
* A client policy whose only difference from the platform default is the execution budget.
*
* <p>A short budget instead of an injected clock: what is under test is a timer firing while a
* resolver is still running, and only real time can be in the middle of that.
*/
static GraphQlClientPolicy policyWithExecutionBudget(Duration maxExecutionTime) {
GraphQlClientPolicy defaults = GraphQlClientPolicy.defaults(100, 10_000, false);
return new GraphQlClientPolicy(
defaults.maxDocumentBytes(),
defaults.maxVariablesBytes(),
defaults.maxDepth(),
defaults.maxFields(),
defaults.maxAliases(),
defaults.maxFragments(),
defaults.maxInputListElements(),
defaults.defaultPageSize(),
defaults.maxPageSize(),
defaults.maxComplexity(),
maxExecutionTime,
defaults.introspectionAllowed(),
defaults.namedOperationRequired());
}
static ResponseEntity<String> post(TestRestTemplate http, int port, String document) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String body = "{\"query\":\"" + document.replace("\"", "\\\"") + "\"}";
return http.exchange(
new RequestEntity<>(
body, headers, HttpMethod.POST, URI.create("http://localhost:" + port + "/graphql")),
String.class);
}
/** Counts the slow resolver and the child that must not start after the answer has gone. */
static final class SlowWork {
static final AtomicInteger SLOW_STARTED = new AtomicInteger();
static final AtomicInteger DETAIL_INVOCATIONS = new AtomicInteger();
static volatile CountDownLatch slowFinished = new CountDownLatch(1);
private SlowWork() {}
static void reset() {
SLOW_STARTED.set(0);
DETAIL_INVOCATIONS.set(0);
slowFinished = new CountDownLatch(1);
}
}
record SlowNode(String id) {}
/** A resolver that is still working when the request budget runs out. */
@Controller
static class SlowController {
@QueryMapping
SlowNode slowNode(@Argument int millis) throws InterruptedException {
SlowWork.SLOW_STARTED.incrementAndGet();
try {
Thread.sleep(millis);
} finally {
SlowWork.slowFinished.countDown();
}
return new SlowNode("slow-1");
}
@SchemaMapping(typeName = "SlowNode", field = "detail")
String detail(SlowNode node) {
SlowWork.DETAIL_INVOCATIONS.incrementAndGet();
return "detail-of-" + node.id();
}
}
/** The transport fixture: the schema source switched on and every request let through. */
@Configuration(proxyBeanMethods = false)
@Import(HealthGraphqlController.class)
static class Transport {
/** Boot's schema condition does not inspect additional-files; this activates the source. */
@Bean
GraphQlSourceBuilderCustomizer runtimeLimitsSchemaActivation() {
return builder -> {};
}
/**
* Lets every request through to the GraphQL endpoint, exempting only that endpoint from CSRF
* (see {@code GraphQlPlatformExecutionPathTest} for why this is not a deployment-wide disable).
*/
@Bean
SecurityFilterChain runtimeLimitsSecurityFilterChain(HttpSecurity http) throws Exception {
return http.csrf(
csrf ->
csrf.ignoringRequestMatchers(
PathPatternRequestMatcher.withDefaults().matcher("/graphql")))
.authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll())
.build();
}
}
}
@@ -0,0 +1,28 @@
# Schema for the runtime-limit evidence tests: the request deadline (review 03-02) and the
# per-parent fetch signal (review 03-03).
#
# `slowNode` sleeps on purpose so the deadline has something to cut, and its `detail` child is the
# work that must not start once the request has been answered. `orders` is a list parent with two
# children that resolve the same data two ways: `customerPerParent` with a plain @SchemaMapping —
# one downstream call per order — and `customer` through GraphQlBatchLoaderRegistrar.
extend type Query {
slowNode(millis: Int!): SlowNode
orders(count: Int!): [Order!]!
}
type SlowNode {
id: ID!
detail: String
}
type Order {
id: ID!
customer: Customer
customerPerParent: Customer
}
type Customer {
id: ID!
name: String!
}
@@ -33,7 +33,8 @@ class GraphQlPlatformStartupValidatorTest {
GraphQlPlatformSettings.productionDefaults()
.withGraphiqlEnabled(true)
.withLimits(
new GraphQlPlatformSettings.Limits(0, 0, 1, 1, java.time.Duration.ofMinutes(1)));
new GraphQlPlatformSettings.Limits(
0, 0, 1, 1, java.time.Duration.ofMinutes(1), 10));
assertThat(new GraphQlPlatformStartupValidator().problems(properties)).hasSize(3);
}
@@ -6,18 +6,15 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.adapter.inbound.graphql.testkit.GraphQlRequestContexts;
import java.time.Clock;
import java.time.Duration;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
/** Request-scoped DataLoader policy and registry (Stable plan Task 36). */
class GraphQlDataLoaderRequestRegistryTest {
@Test
void createsDifferentRegistryForEachExecution() {
Supplier<GraphQlDataLoaderRequestRegistry> factory = GraphQlDataLoaderRequestRegistry::new;
assertThat(factory.get()).isNotSameAs(factory.get());
}
/**
* DataLoader policy registry and factory (Stable plan Task 36).
*
* <p>The per-execution request scope is Spring's {@code DataLoaderRegistry}, exercised end to end
* by {@code GraphQlBatchLoaderRegistrationTest.oneRequestsCacheIsNotHandedToTheNext}.
*/
class GraphQlDataLoaderFactoryTest {
@Test
void loaderNamesMustBeRegisteredInTheBoundedCatalog() {
@@ -59,16 +56,6 @@ class GraphQlDataLoaderRequestRegistryTest {
.hasMessageContaining("downstream limit");
}
@Test
void loadersAndTheirCachesDoNotOutliveTheExecution() {
var registry = new GraphQlDataLoaderRequestRegistry();
registry.register(new GraphQlDataLoaderName("order.customer"), new Object());
assertThat(registry.isEmpty()).isFalse();
registry.clear();
assertThat(registry.isEmpty()).isTrue();
}
@Test
void keysAreNeverSharedBetweenExecutionsWithDifferentActorsOrTenants() {
var factory =
@@ -81,7 +68,6 @@ class GraphQlDataLoaderRequestRegistryTest {
var tenantB = factory.batchContext(GraphQlRequestContexts.testContext("tenant-b"));
assertThat(tenantA.cacheScope()).isNotEqualTo(tenantB.cacheScope());
assertThat(factory.newRequestRegistry()).isNotSameAs(factory.newRequestRegistry());
}
@Test
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
@@ -16,12 +17,13 @@ class GraphQlWireErrorMapperTest {
return Stream.of(
Arguments.of(
new GraphQlBatchTimeoutException("customer-by-id"), "REQUEST_TIMEOUT", "TIMEOUT"),
Arguments.of(new GraphQlRequestCancelledException(), "REQUEST_TIMEOUT", "TIMEOUT"),
Arguments.of(new GraphQlMissingKeyException(), "GRAPHQL_BATCH_KEY_MISSING", "BUSINESS"));
}
@ParameterizedTest
@MethodSource("dataLoaderFailures")
@DisplayName("DataLoader 의 timeout·missing key 는 INTERNAL_ERROR 로 가려지지 않고 플랫폼 code 로 나간다")
@DisplayName("요청·DataLoader 의 timeout·missing key 는 INTERNAL_ERROR 로 가려지지 않고 플랫폼 code 로 나간다")
void dataLoaderFailuresKeepAPlatformCode(
RuntimeException failure, String expectedCode, String expectedCategory) {
// given
@@ -1,43 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.execution;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Duration;
import org.junit.jupiter.api.Test;
/** Layered timeout, resolver budget and cancellation contract (Stable plan Task 22). */
class GraphQlTimeoutPolicyTest {
@Test
void childBudgetCannotExceedParent() {
GraphQlTimeoutPolicy policy = new GraphQlTimeoutPolicy(Duration.ofSeconds(2));
assertThat(policy.child(Duration.ofSeconds(5))).isEqualTo(Duration.ofSeconds(2));
assertThat(policy.child(Duration.ofSeconds(1))).isEqualTo(Duration.ofSeconds(1));
}
@Test
void budgetsNarrowMonotonicallyDownTheChain() {
GraphQlTimeoutPolicy request = new GraphQlTimeoutPolicy(Duration.ofSeconds(5));
GraphQlTimeoutPolicy resolver = request.childPolicy(Duration.ofSeconds(3));
GraphQlTimeoutPolicy database = resolver.childPolicy(Duration.ofSeconds(10));
assertThat(resolver.remaining()).isEqualTo(Duration.ofSeconds(3));
assertThat(database.remaining()).isEqualTo(Duration.ofSeconds(3));
}
@Test
void anExhaustedBudgetCannotBecomeAPolicy() {
assertThatThrownBy(() -> new GraphQlTimeoutPolicy(Duration.ZERO))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new GraphQlTimeoutPolicy(Duration.ofSeconds(-1)))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void executionTimeoutMapsToAStableErrorCode() {
assertThat(GraphQlTimeoutPolicy.TIMEOUT_ERROR_CODE).isEqualTo("REQUEST_TIMEOUT");
assertThat(new GraphQlRequestCancelledException().code()).isEqualTo("REQUEST_TIMEOUT");
}
}
@@ -2,6 +2,10 @@ package dev.caskeleton.adapter.inbound.graphql.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import dev.caskeleton.adapter.inbound.graphql.context.GraphQlDeadline;
import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchContext;
@@ -11,6 +15,7 @@ import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchPolicyRegis
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderFactory;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyPolicy;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
import dev.caskeleton.adapter.inbound.graphql.testkit.GraphQlRequestContexts;
import graphql.ExecutionInput;
import graphql.ExecutionResult;
@@ -33,7 +38,10 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.dataloader.DataLoaderRegistry;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.graphql.execution.DataFetcherExceptionResolver;
import org.springframework.graphql.execution.DefaultBatchLoaderRegistry;
/**
@@ -134,6 +142,44 @@ class GraphQlBatchLoaderRegistrationTest {
assertThat(downstream.calls).hasValue(0);
}
@Test
@DisplayName("플랫폼 context 없이 불린 batch 는 시간 초과가 아니라 INTERNAL_ERROR 조립 오류로 나가고 WARN 한 줄을 남긴다")
void aLoaderWithoutThePlatformContextIsReportedAsAWiringFaultNotATimeout() {
// given
RecordingLoader downstream = new RecordingLoader();
Fixture fixture = fixture(chunkSize(20), Clock.systemUTC());
Logger logger = (Logger) LoggerFactory.getLogger(GraphQlBatchLoaderRegistrar.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
// when
ExecutionResult result;
try {
result = fixture.executeWithoutRequestContext(orders(5, 5), downstream);
} finally {
logger.detachAppender(appender);
appender.stop();
}
// then
assertThat(result.getErrors())
.isNotEmpty()
.allSatisfy(
error ->
assertThat(error.getExtensions())
.containsEntry("code", "INTERNAL_ERROR")
.containsEntry("category", "INTERNAL")
.containsEntry("constraint", "PLATFORM_CONTEXT"));
assertThat(appender.list)
.singleElement()
.extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage)
.containsExactly(
Level.WARN,
"graphql batch rejected: no platform context (loader=customer-by-id);"
+ " the platform transport interceptor is not wired");
}
@Test
void aBatchThatOverrunsTheRequestBudgetStopsAtTheChunkThatSpentIt() {
MutableClock clock = new MutableClock(Instant.parse("2026-08-14T00:00:00Z"));
@@ -328,7 +374,14 @@ class GraphQlBatchLoaderRegistrationTest {
DataLoaderRegistry dataLoaders = new DataLoaderRegistry();
batchLoaders.registerDataLoaders(dataLoaders, input.getGraphQLContext());
// Spring's exception handling over the platform mapper, so a failure reaches the result as
// the
// wire error a client would see rather than as graphql-java's raw exception.
return GraphQL.newGraphQL(schema(orders))
.defaultDataFetcherExceptionHandler(
DataFetcherExceptionResolver.createExceptionHandler(
List.of(
new GraphQlDataFetcherExceptionResolver(GraphQlWireErrorMapper.masking()))))
.build()
.execute(input.transform(builder -> builder.dataLoaderRegistry(dataLoaders)));
}
+14 -2
View File
@@ -52,8 +52,19 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`.
| `bindAddress` | `127.0.0.1` | P1 insecure listener 바인드. loopback 주소만 허용한다 |
| `allowInsecureLocal` | `false` | local plaintext 위험을 명시적으로 승인하는 개발용 override |
| `reflectionEnabled` | `false` | v1 server reflection 노출을 독립적으로 opt-in 한다 |
| `shutdownGraceSeconds` | `5` | graceful shutdown 시 in-flight RPC 대기 초(0 이상) |
| `shutdownGraceSeconds` | `5` | graceful shutdown 전체 예산(초, 0 이상). drain 대기를 포함한다 |
| `shutdownDrainSeconds` | `2` | health NOT_SERVING 뒤 listener 를 열어 둔 채 기다리는 초. `shutdownGraceSeconds` 이하 |
| `maxInboundMessageBytes` | `1048576` | 요청 메시지 상한. 넘으면 `RESOURCE_EXHAUSTED` (플랫폼 `GrpcTransportLimits`와 같은 값) |
| `maxInboundMetadataBytes` | `8192` | 호출당 metadata 상한 (플랫폼과 같은 값) |
| `maxConcurrentCallsPerConnection` | `100` | 연결당 동시 호출(HTTP/2 stream) 상한. 넘친 호출은 클라이언트에서 기다린다 |
| `executorMaxPoolSize` | `32` | feature 호출을 실행하는 고정 스레드 수 (플랫폼 executor 기본값) |
| `executorQueueCapacity` | `256` | 스레드를 기다릴 수 있는 호출 수(1..10000). 넘친 호출은 즉시 `RESOURCE_EXHAUSTED` |
| `defaultDeadline` | `10s` | deadline 없는(또는 더 긴) feature 호출의 서버 deadline. 넘으면 `DEADLINE_EXCEEDED` |
| `keepAliveTime` / `keepAliveTimeout` | `30s` / `10s` | 서버 keep-alive ping 간격 / 응답 대기 (플랫폼 `GrpcServerProfile.stable`) |
| `permitKeepAliveTime` | `30s` | 클라이언트 ping 최소 간격. `keepAliveTime` 이하 |
| `maxConnectionAge` / `maxConnectionAgeGrace` | `30m` / `30s` | 연결 수명과 GOAWAY 뒤 유예 |
한도 값의 근거·플랫폼과의 대응·포화 동작은 [README.md](README.md) 「서버 한도」 절이 소유한다.
`port`는 0..65535 범위여야 한다. 현재 transport credential은 plaintext뿐이므로
`enabled=true`는 `allowInsecureLocal=true`와 실제 loopback `bindAddress`가 함께 없으면
configuration binding/startup 단계에서 실패한다.
@@ -93,9 +104,10 @@ listener 시작이 실패한다. 정책은 `Optional<Principal> authenticate(Met
- `GrpcSafeActivationTest`: 기본 비활성, 관련 빈 부재, 설정 검증, feature 인증 정책 필수 조건.
- `GrpcP1BoundaryWireTest`: 실제 loopback ephemeral Netty unary service의 auth 성공/실패,
reflection-off, handler/listener/observer/raw-status 오류 sanitization과 sentinel redaction.
서버 한도(메시지 크기, 기본 deadline, 연결당 동시 호출, executor 포화)도 같은 wire 에서 검증한다.
이 증거는 local insecure unary qualification일 뿐 production-ready 근거가 아니다. TLS/mTLS,
external bind, deadline, streaming/backpressure, generated protobuf 호환성은 P2로 남아 있다.
external bind, 메서드별 deadline, streaming/backpressure, generated protobuf 호환성은 P2로 남아 있다.
## Test
+73 -7
View File
@@ -26,7 +26,8 @@
- 필요한 설정: 전용 `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`
(기본 9090), `.bind-address`(기본 127.0.0.1), `.reflection-enabled`, `.shutdown-grace-seconds`.
(기본 9090), `.bind-address`(기본 127.0.0.1), `.reflection-enabled`, `.shutdown-grace-seconds`,
`.shutdown-drain-seconds`, 그리고 아래 「서버 한도」 절의 전송 한도 키.
## 왜 self-managed Netty 인가
@@ -37,9 +38,14 @@
- **`getPhase()` = `Integer.MAX_VALUE - 1`.** web 서버가 뜬 **뒤에** 시작하고 종료 시 web 서버
**전에** 멈춘다(SmartLifecycle: 높은 phase 가 늦게 시작·먼저 종료). gRPC 는 web 과 별개의 TCP
포트를 소유하는 부가 전송이므로 애플리케이션 수명주기 맨 바깥에 둔다.
- **graceful shutdown.** `shutdownGraceSeconds` 동안 in-flight RPC 를 기다린 뒤
`shutdownNow()`. 종료 진입 시 health 를 `enterTerminalState()`(NOT_SERVING)로 뒤집어
로드밸런서가 드레이닝을 인지하게 한다.
- **graceful shutdown.** 종료 진입 시 health 를 `enterTerminalState()`(NOT_SERVING)로 뒤집고,
listener 를 연 채로 `shutdownDrainSeconds`(기본 2초) 기다린 뒤 `shutdown()` → 남은 grace
(`shutdownGraceSeconds - shutdownDrainSeconds`) 동안 `awaitTermination` → `shutdownNow()` 순서로
닫는다. NOT_SERVING 과 listener 닫기를 같은 순간에 하면 health 확인이 UNAVAILABLE 로 끝나
로드밸런서가 드레이닝과 장애를 구분하지 못한다. drain 은 grace 예산 안에서 쓰며(drain > grace 는
기동 실패), `Health/Watch` 구독자는 즉시 알림을 받으므로 2초면 충분하다. 주기가 더 긴 poll 방식
probe 는 이 값으로 기다릴 수 없으니 `preStop` 지연으로 맞춘다. 끝나면 call/dispatch executor 와
deadline scheduler 도 `shutdownNow()` 한다.
- **fail-closed local insecure bind.** 모듈이 있으면 서버가 켜지지만 reflection은 비활성이다. 현재 구현의
plaintext credential은 `allowInsecureLocal=true`를 명시하고 실제 loopback 주소에 바인딩할
때만 허용한다. wildcard/외부 주소의 insecure 시작은 실패한다.
@@ -48,6 +54,62 @@
만들 수 없다. 그런 cluster-facing 노출은 TLS/mTLS credential 경로와 non-loopback
qualification이 추가된 뒤의 범위다.
## 서버 한도 — io.grpc 기본값을 쓰지 않는다 (리뷰 03-09)
io.grpc 기본값은 메시지 4 MiB, 연결당 동시 호출 무제한, 호출마다 스레드를 늘리는 cached
executor, 서버 deadline 없음, 연결 수명 무제한이다. 어댑터 서버는 이 값을 모두 명시한다.
| 키 (`app.grpc.server.*`) | 기본값 | 같은 값의 출처 (vendored 플랫폼) |
|---|---|---|
| `max-inbound-message-bytes` | 1048576 (1 MiB) | `GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES` |
| `max-inbound-metadata-bytes` | 8192 (8 KiB) | `GrpcTransportLimits.DEFAULT_MAX_METADATA_BYTES` |
| `executor-max-pool-size` | 32 | `GrpcPlatformProperties.executorMaxPoolSize` |
| `executor-queue-capacity` | 256 (최대 10000) | `GrpcPlatformProperties.executorQueueCapacity`, 상한은 `GrpcExecutorProfile` |
| `keep-alive-time` / `keep-alive-timeout` | 30s / 10s | `GrpcServerProfile.stable(..)` |
| `permit-keep-alive-time` | 30s | `GrpcServerProfile.stable(..)` |
| `max-connection-age` / `max-connection-age-grace` | 30m / 30s | `GrpcServerProfile.stable(..)` |
| `max-concurrent-calls-per-connection` | 100 | 플랫폼에 없음. RFC 9113 §6.5.2 가 권하는 `MAX_CONCURRENT_STREAMS` 하한 |
| `default-deadline` | 10s | 플랫폼은 메서드별 `GrpcDeadlineProfile` 만 있다. GraphQL 어댑터의 요청 예산 10초와 맞춤 |
- **값이 두 곳에 있는 이유.** 03-09 는 (a) 어댑터가 같은 이름·값을 자기 설정으로 노출, (b)
어댑터가 플랫폼 `GrpcServerProfile` 을 받음(registry edge 추가), (c) 현상 유지 중 (a)를 골랐다.
두 스택 분리(X1-#10)를 건드리지 않기 위해서다. 어댑터는 플랫폼 타입을 import 할 수 없어(registry
edge 없음, 플랫폼은 `optional-platforms` 별도 빌드) 상수를 직접 비교하는 테스트는 만들 수 없다.
대신 `GrpcSafeActivationTest.transportBoundDefaultsMatchTheVendoredPlatformDefaults` 가 위 표의
플랫폼 값을 literal 로 고정한다. 플랫폼 값을 바꾸면 이 표와 그 테스트를 같이 바꾼다.
- **duration 순서 검증.** `keep-alive-timeout < keep-alive-time`, `permit-keep-alive-time <=
keep-alive-time`, `max-connection-age-grace <= max-connection-age`, 모든 duration 양수 —
`GrpcServerProfile` 생성자가 거절하는 조합을 바인딩 단계에서 똑같이 거절한다.
- **keep-alive·connection age 를 loopback 에서도 켜는 이유.** 지금 listener 는 loopback 전용이라
중간 장비가 idle 연결을 끊는 일은 없다. 그래도 플랫폼과 같은 값을 둬서 non-loopback bind(P2)를
열 때 따로 정할 값이 남지 않게 했다. loopback 에서의 효과는 멈춘 클라이언트 연결을 30분에
정리하는 것뿐이다.
- **기본 deadline(`GrpcServerDeadlineInterceptor`).** 클라이언트가 deadline 없이 부른 feature
호출은 `default-deadline` 에서 `DEADLINE_EXCEEDED` 로 끝난다. 클라이언트 deadline 이 더 짧으면
그대로 두고(io.grpc 가 집행), 더 길면 서버 값으로 줄인다. derived `Context` 를 취소해도 io.grpc 는
스트림을 닫지 않으므로 인터셉터가 직접 닫고, 그 close 가 handler 의 쓰기와 겹치지 않게 call 을
직렬화한다. handler 는 `Context.current().isCancelled()` 로 만료를 본다. 확인하지 않는 handler 는
반환할 때까지 스레드를 잡는다 — deadline 이 풀어 주는 것은 호출자이지 스레드가 아니다. 상태에는
code/category trailer 를 붙이지 않는다(io.grpc 의 클라이언트 deadline 만료와 같은 모양).
health/reflection 에는 적용하지 않는다(`Health/Watch` 는 원래 오래 사는 스트림이다).
- **포화 시 동작(`GrpcCallAdmission`).** feature 호출은 `executor-max-pool-size +
executor-queue-capacity` 개까지만 받고, 넘친 호출은 handler 를 시작하지 않고 즉시
`RESOURCE_EXHAUSTED`(`RATE_LIMIT_EXCEEDED`, retryable)로 닫는다. 구현: io.grpc
`ServerCallExecutorSupplier`(`@ExperimentalApi`, 1.39부터)가 호출 시작 전에 permit 을 확인해
받은 호출만 고정 크기 work pool 로 옮기고, 못 받은 호출은 가장 바깥 인터셉터가 닫는다. 메서드
조회·context 정리·health·reflection 은 작은 dispatch pool 에서 돈다. 버린 대안:
- bounded `ThreadPoolExecutor` + `AbortPolicy` 만 두기 — 실행으로 확인한 결과 io.grpc 는 거절을
Netty 스레드 로그로만 남기고 스트림을 열어 둔다. 클라이언트는 자기 deadline 까지(없으면 영원히)
기다린다.
- caller-runs — handler 가 dispatch/Netty 스레드에서 돌아 같은 연결의 다른 호출을 모두 멈춘다.
- 큰(또는 무제한) 대기열 — 같은 실패를 모든 호출자의 deadline 뒤로 미룰 뿐이다.
- 플랫폼 `GrpcAdmissionController` 사용 — 03-09 (b)의 배선 결정이 필요하다.
work pool 대기열은 permit 수만큼 깊다. io.grpc 는 한 호출의 콜백을 직렬화하므로 받아들인 호출은
pool 에 많아야 작업 하나를 두고, 따라서 이 대기열은 차지 않는다(`AbortPolicy` 는 도달하지 않는
안전장치다). 대기열에서 기다린 시간은 서버 기본 deadline 에 들어가지 않는다 — 서버 deadline 은
handler 가 시작될 때부터 잰다. 클라이언트 deadline 은 도착 시점부터 잰다.
## 왜 `.proto` 도 protobuf 플러그인도 없는가
이 모듈은 protobuf 를 **하나도 컴파일하지 않는다** — `com.google.protobuf` 플러그인도,
@@ -117,8 +179,12 @@ Spring Boot BOM은 `io.grpc:*`/protobuf 버전을 관리하지 않는다. 이
`GrpcSafeActivationTest`는 disabled bean/listener 부재와 설정/인증-policy fail-closed를 검증한다.
`GrpcP1BoundaryWireTest`는 실제 loopback ephemeral Netty unary service로 auth 성공/실패,
reflection-off, 모든 오류 경로의 안정 code/category 및 sentinel redaction을 검증한다.
reflection-off, 모든 오류 경로의 안정 code/category 및 sentinel redaction을 검증한다. 서버 한도도
같은 wire 에서 검증한다: 1 MiB 초과 요청 `RESOURCE_EXHAUSTED`(정확히 1 MiB 는 통과), deadline 없는
느린 호출의 서버 기본 deadline `DEADLINE_EXCEEDED`, 더 짧은 클라이언트 deadline 유지, 연결당 동시
호출 상한, executor·대기열 포화 시 즉시 `RESOURCE_EXHAUSTED`. `GrpcServerRunnerBootTest`는 종료
drain 동안 listener 가 살아서 health NOT_SERVING 을 답하는지 검증한다.
이는 local plaintext unary 경계에 대한 P1 증거이며 production-ready 주장 근거가 아니다.
TLS/mTLS, external bind, deadline, streaming/backpressure, generated protobuf 호환성은 P2에서 별도
설계·검증해야 한다.
TLS/mTLS, external bind, 메서드별 deadline(지금은 서버 전체 기본값 하나), streaming/backpressure,
generated protobuf 호환성은 P2에서 별도 설계·검증해야 한다.
-1
View File
@@ -51,6 +51,5 @@ strictTestLanes {
requires 'dev.caskeleton.adapter.inbound.grpc.GrpcSafeActivationTest',
'dev.caskeleton.adapter.inbound.grpc.GrpcP1BoundaryWireTest'
rejectSkipped = true
jvmArgs '-Duser.timezone=UTC'
}
}
@@ -0,0 +1,120 @@
package dev.caskeleton.adapter.inbound.grpc;
import dev.caskeleton.shared.error.OperationalError;
import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallExecutorSupplier;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Bounds how many feature calls the server holds, and refuses the rest with {@code
* RESOURCE_EXHAUSTED} (review 03-09).
*
* <p>Why not just a bounded executor: when a bounded {@code ThreadPoolExecutor} rejects, io.grpc
* does not answer the call. The rejection is logged on the Netty thread and the stream stays open
* until the client's own deadline — forever for a client that set none. Admission therefore has to
* be decided before the call reaches the bounded pool, and the refusal has to be an ordinary call
* close.
*
* <p>How: io.grpc asks this {@link ServerCallExecutorSupplier} for each found method, on the
* 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.
*
* <p>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.
*
* <p>{@code ServerCallExecutorSupplier} is an io.grpc {@code @ExperimentalApi} (stable since 1.39).
* The alternative that avoids it is the platform's {@code GrpcAdmissionController}, which the
* adapter cannot reach without the separate wiring decision (review 03-09 option b).
*/
final class GrpcCallAdmission implements ServerCallExecutorSupplier, ServerInterceptor {
private final Set<String> featureServiceNames;
private final Semaphore permits;
private final Executor workExecutor;
private final GrpcStatusMapper statusMapper;
private final Set<Metadata> refused =
Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<>()));
GrpcCallAdmission(
Set<String> featureServiceNames,
int maxAdmittedCalls,
Executor workExecutor,
GrpcStatusMapper statusMapper) {
if (maxAdmittedCalls < 1) {
throw new IllegalArgumentException("admission needs at least one permit");
}
this.featureServiceNames = Set.copyOf(featureServiceNames);
this.permits = new Semaphore(maxAdmittedCalls);
this.workExecutor = workExecutor;
this.statusMapper = statusMapper;
}
@Override
public <Q, R> Executor getExecutor(ServerCall<Q, R> call, Metadata headers) {
if (!featureServiceNames.contains(call.getMethodDescriptor().getServiceName())) {
return null;
}
if (permits.tryAcquire()) {
return workExecutor;
}
refused.add(headers);
return null;
}
@Override
public <Q, R> ServerCall.Listener<Q> interceptCall(
ServerCall<Q, R> call, Metadata headers, ServerCallHandler<Q, R> next) {
if (refused.remove(headers)) {
call.close(
statusMapper.statusFor(OperationalError.RATE_LIMIT_EXCEEDED),
statusMapper.trailersFor(OperationalError.RATE_LIMIT_EXCEEDED));
return new ServerCall.Listener<>() {};
}
AtomicBoolean released = new AtomicBoolean();
Runnable release =
() -> {
if (released.compareAndSet(false, true)) {
permits.release();
}
};
ServerCall.Listener<Q> delegate;
try {
delegate = next.startCall(call, headers);
} catch (RuntimeException | Error e) {
release.run();
throw e;
}
return new SimpleForwardingServerCallListener<>(delegate) {
@Override
public void onComplete() {
try {
super.onComplete();
} finally {
release.run();
}
}
@Override
public void onCancel() {
try {
super.onCancel();
} finally {
release.run();
}
}
};
}
}
@@ -0,0 +1,145 @@
package dev.caskeleton.adapter.inbound.grpc;
import io.grpc.Context;
import io.grpc.Contexts;
import io.grpc.Deadline;
import io.grpc.ForwardingServerCall.SimpleForwardingServerCall;
import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import java.time.Duration;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Gives every feature call a server-side deadline (review 03-09).
*
* <p>io.grpc enforces only the deadline the client sent. A client that sends none gets a call that
* may hold an executor thread forever. This interceptor bounds such a call at {@code
* app.grpc.server.default-deadline}. A client deadline that is already shorter is left alone —
* io.grpc enforces it and the server value would never fire; a longer one is capped, because the
* server value is the most this server will spend on one call.
*
* <p>Cancelling a derived {@link Context} does not end the call by itself: io.grpc closes the
* stream only for the root context it created. So when the server deadline fires, this interceptor
* closes the call with {@code DEADLINE_EXCEEDED} itself. A {@link ServerCall} is not thread-safe
* and the deadline fires on the scheduler thread while the handler may still be writing, so the
* call handed inward is serialized and drops anything written after the close.
*
* <p>The handler sees the expiry as a cancelled {@code Context.current()}; a handler that never
* checks it keeps its thread until it returns. The deadline frees the caller, not the thread.
*
* <p>The status is plain {@code DEADLINE_EXCEEDED} without the code/category trailers, the same
* shape io.grpc gives a client-deadline expiry, so a client handles both the same way.
*/
final class GrpcServerDeadlineInterceptor implements ServerInterceptor {
private final long defaultDeadlineNanos;
private final ScheduledExecutorService scheduler;
GrpcServerDeadlineInterceptor(Duration defaultDeadline, ScheduledExecutorService scheduler) {
if (defaultDeadline == null || defaultDeadline.isZero() || defaultDeadline.isNegative()) {
throw new IllegalArgumentException("a server default deadline must be positive");
}
this.defaultDeadlineNanos = defaultDeadline.toNanos();
this.scheduler = scheduler;
}
@Override
public <Q, R> ServerCall.Listener<Q> interceptCall(
ServerCall<Q, R> call, Metadata headers, ServerCallHandler<Q, R> next) {
Context current = Context.current();
Deadline serverDeadline = Deadline.after(defaultDeadlineNanos, TimeUnit.NANOSECONDS);
Deadline clientDeadline = current.getDeadline();
if (clientDeadline != null && !serverDeadline.isBefore(clientDeadline)) {
return next.startCall(call, headers);
}
SerializedCall<Q, R> guarded = new SerializedCall<>(call);
Context.CancellableContext bounded = current.withDeadline(serverDeadline, scheduler);
bounded.addListener(
context -> {
if (context.cancellationCause() instanceof TimeoutException) {
guarded.closeOnDeadline();
}
},
Runnable::run);
ServerCall.Listener<Q> delegate = Contexts.interceptCall(bounded, guarded, headers, next);
return new SimpleForwardingServerCallListener<>(delegate) {
@Override
public void onComplete() {
try {
super.onComplete();
} finally {
bounded.cancel(null);
}
}
@Override
public void onCancel() {
try {
super.onCancel();
} finally {
bounded.cancel(null);
}
}
};
}
/** Serializes writes so the deadline close cannot race the handler's own writes. */
private static final class SerializedCall<Q, R> extends SimpleForwardingServerCall<Q, R> {
private boolean closed;
SerializedCall(ServerCall<Q, R> delegate) {
super(delegate);
}
synchronized void closeOnDeadline() {
if (!closed) {
closed = true;
super.close(
Status.DEADLINE_EXCEEDED.withDescription("server default deadline exceeded"),
new Metadata());
}
}
@Override
public synchronized void request(int numMessages) {
if (!closed) {
super.request(numMessages);
}
}
@Override
public synchronized void sendHeaders(Metadata headers) {
if (!closed) {
super.sendHeaders(headers);
}
}
@Override
public synchronized void sendMessage(R message) {
if (!closed) {
super.sendMessage(message);
}
}
@Override
public synchronized void close(Status status, Metadata trailers) {
if (!closed) {
closed = true;
super.close(status, trailers);
}
}
@Override
public synchronized boolean isReady() {
return !closed && super.isReady();
}
}
}
@@ -12,7 +12,15 @@ import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
@@ -41,6 +49,9 @@ public class GrpcServerRunner implements SmartLifecycle {
private final GrpcStatusMapper statusMapper;
private final HealthStatusManager healthStatusManager;
private volatile Server server;
private volatile ExecutorService dispatchExecutor;
private volatile ExecutorService workExecutor;
private volatile ScheduledExecutorService deadlineScheduler;
public GrpcServerRunner(
List<BindableService> services,
@@ -72,19 +83,55 @@ public class GrpcServerRunner implements SmartLifecycle {
policies.size() == 1 ? policies.getFirst() : null;
var address = new InetSocketAddress(properties.resolvedBindAddress(), properties.getPort());
var builder = NettyServerBuilder.forAddress(address, InsecureServerCredentials.create());
int maxAdmittedCalls =
properties.getExecutorMaxPoolSize() + properties.getExecutorQueueCapacity();
ExecutorService dispatch = dispatchExecutor();
ExecutorService work = workExecutor(properties.getExecutorMaxPoolSize(), maxAdmittedCalls);
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor(daemonThreads("grpc-server-deadline-"));
this.dispatchExecutor = dispatch;
this.workExecutor = work;
this.deadlineScheduler = scheduler;
var admission =
new GrpcCallAdmission(
featureServiceNames(featureServices), maxAdmittedCalls, work, statusMapper);
var builder =
NettyServerBuilder.forAddress(address, InsecureServerCredentials.create())
.executor(dispatch)
.callExecutor(admission)
.maxInboundMessageSize(properties.getMaxInboundMessageBytes())
.maxInboundMetadataSize(properties.getMaxInboundMetadataBytes())
.maxConcurrentCallsPerConnection(properties.getMaxConcurrentCallsPerConnection())
.keepAliveTime(properties.getKeepAliveTime().toNanos(), TimeUnit.NANOSECONDS)
.keepAliveTimeout(properties.getKeepAliveTimeout().toNanos(), TimeUnit.NANOSECONDS)
.permitKeepAliveTime(
properties.getPermitKeepAliveTime().toNanos(), TimeUnit.NANOSECONDS)
.maxConnectionAge(properties.getMaxConnectionAge().toNanos(), TimeUnit.NANOSECONDS)
.maxConnectionAgeGrace(
properties.getMaxConnectionAgeGrace().toNanos(), TimeUnit.NANOSECONDS);
var authenticationInterceptor =
authenticationPolicy == null
? null
: new GrpcAuthenticationInterceptor(authenticationPolicy, statusMapper);
// Last, so outermost: the correlation is on MDC before authentication or error mapping logs.
// Correlation is outside authentication and error mapping, so it is on MDC before they log.
var correlationInterceptor = new GrpcCorrelationInterceptor();
// Outside the rest: every inner interceptor and the handler write through its serialized call,
// so the deadline close cannot race them. Health and reflection get no server deadline because
// Health/Watch is a long-lived stream by design. Admission is outermost, so a refused call
// starts nothing.
var deadlineInterceptor =
new GrpcServerDeadlineInterceptor(properties.getDefaultDeadline(), scheduler);
int registered = 0;
for (BindableService service : featureServices) {
builder.addService(
ServerInterceptors.intercept(
service, exceptionInterceptor, authenticationInterceptor, correlationInterceptor));
service,
exceptionInterceptor,
authenticationInterceptor,
correlationInterceptor,
deadlineInterceptor,
admission));
registered++;
}
@@ -103,21 +150,76 @@ public class GrpcServerRunner implements SmartLifecycle {
registered,
properties.isReflectionEnabled());
} catch (IOException e) {
shutdownExecutors();
throw new UncheckedIOException(
"failed to start gRPC server on port " + properties.getPort(), e);
} catch (RuntimeException e) {
shutdownExecutors();
throw e;
}
}
/**
* Runs io.grpc's own dispatch work (method lookup, context closing) plus health and reflection.
* None of it is application code and none of it blocks, so a small fixed pool keeps up; its queue
* is unbounded on purpose, because a rejected dispatch task leaves a stream open with nobody to
* answer it (see {@link GrpcCallAdmission}). Its depth is bounded by the open streams, which
* {@code maxConcurrentCallsPerConnection} bounds per connection.
*/
private static ExecutorService dispatchExecutor() {
int threads = Math.max(2, Runtime.getRuntime().availableProcessors());
return Executors.newFixedThreadPool(threads, daemonThreads("grpc-server-dispatch-"));
}
/**
* Runs feature calls: a fixed pool in place of io.grpc's cached executor, which grows one thread
* per blocked call. Sizes are the platform's executor defaults. {@link GrpcCallAdmission} admits
* at most {@code maxAdmittedCalls} calls and each has at most one task here at a time, so the
* queue, as deep as the permit count, never fills; the abort policy is the unreachable backstop,
* not the overload behavior. Caller-runs was rejected because it would run a handler on the
* dispatch or Netty thread.
*/
private static ExecutorService workExecutor(int threads, int maxAdmittedCalls) {
ThreadPoolExecutor executor =
new ThreadPoolExecutor(
threads,
threads,
60,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(maxAdmittedCalls),
daemonThreads("grpc-server-call-"),
new ThreadPoolExecutor.AbortPolicy());
executor.allowCoreThreadTimeOut(true);
return executor;
}
private static Set<String> featureServiceNames(List<BindableService> featureServices) {
return featureServices.stream()
.map(service -> service.bindService().getServiceDescriptor().getName())
.collect(Collectors.toUnmodifiableSet());
}
private static ThreadFactory daemonThreads(String prefix) {
return Thread.ofPlatform().name(prefix, 0).daemon(true).factory();
}
@Override
public void stop() {
Server current = this.server;
if (current == null) {
return;
}
// NOT_SERVING first, then a drain delay with the listener still up: a server that shuts the
// listener at the same moment answers a health check with UNAVAILABLE, which a load balancer
// cannot tell apart from a crash. The drain is spent out of the same grace budget.
healthStatusManager.enterTerminalState();
long drainMillis = TimeUnit.SECONDS.toMillis(properties.getShutdownDrainSeconds());
long graceMillis = TimeUnit.SECONDS.toMillis(properties.getShutdownGraceSeconds());
try {
Thread.sleep(drainMillis);
current.shutdown();
if (!current.awaitTermination(properties.getShutdownGraceSeconds(), TimeUnit.SECONDS)) {
if (!current.awaitTermination(
Math.max(0, graceMillis - drainMillis), TimeUnit.MILLISECONDS)) {
current.shutdownNow();
}
log.info("gRPC server stopped");
@@ -126,6 +228,29 @@ public class GrpcServerRunner implements SmartLifecycle {
Thread.currentThread().interrupt();
} finally {
this.server = null;
shutdownExecutors();
}
}
/**
* The server is already terminated or forced down here, so a call still on the pool is one the
* grace budget gave up on: interrupt it rather than let it outlive the context.
*/
private void shutdownExecutors() {
ExecutorService work = this.workExecutor;
if (work != null) {
work.shutdownNow();
this.workExecutor = null;
}
ExecutorService dispatch = this.dispatchExecutor;
if (dispatch != null) {
dispatch.shutdownNow();
this.dispatchExecutor = null;
}
ScheduledExecutorService scheduler = this.deadlineScheduler;
if (scheduler != null) {
scheduler.shutdownNow();
this.deadlineScheduler = null;
}
}
@@ -4,8 +4,10 @@ import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
@@ -13,6 +15,14 @@ import org.springframework.validation.annotation.Validated;
* gRPC server settings bound from {@code app.grpc.server.*}. Typed configuration only (no
* per-module {@code yml}); values live in the composition-root {@code application.yml}, matching
* the ca-skeleton config convention. See README for the self-managed-Netty rationale.
*
* <p>The transport bounds (review 03-09) carry the names and default values of the vendored
* platform's {@code GrpcTransportLimits}, {@code GrpcServerProfile.stable(..)} and {@code
* GrpcPlatformProperties} executor keys, so the adapter server and the platform's Netty evidence
* describe the same server. The adapter cannot import those types (no registry edge, and the
* platform is a separate build), so the values are restated here and the README cites their source.
* io.grpc's own defaults — 4 MiB messages, unlimited calls per connection, an unbounded cached
* executor, no server deadline, no connection age — are what this class replaces.
*/
@ConfigurationProperties(prefix = "app.grpc.server", ignoreUnknownFields = false)
@Validated
@@ -42,6 +52,74 @@ public class GrpcServerSettings {
@Min(0)
private int shutdownGraceSeconds = 5;
/**
* Seconds, inside {@link #shutdownGraceSeconds}, during which health already says NOT_SERVING but
* the listener still accepts calls, so a health watcher can stop routing before the listener
* closes. Two seconds: a {@code Health/Watch} subscriber is told at once, and the remaining three
* seconds of the default grace stay for in-flight calls. A poll-based probe with a longer period
* needs a {@code preStop} delay instead; this value cannot outwait it.
*/
@Min(0)
private int shutdownDrainSeconds = 2;
/** Largest inbound message: 1 MiB, the platform's {@code DEFAULT_MAX_MESSAGE_BYTES}. */
@Min(1)
private int maxInboundMessageBytes = 1024 * 1024;
/**
* Largest inbound metadata per call: 8 KiB, the platform's {@code DEFAULT_MAX_METADATA_BYTES}.
*/
@Min(1)
private int maxInboundMetadataBytes = 8192;
/**
* HTTP/2 {@code SETTINGS_MAX_CONCURRENT_STREAMS} the server advertises: calls one connection may
* have open at once. 100 is the floor RFC 9113 §6.5.2 recommends, so a conforming client is not
* starved; a client over it waits for a free stream rather than failing. The platform has no
* equivalent value to mirror.
*/
@Min(1)
private int maxConcurrentCallsPerConnection = 100;
/** Threads running application work: the platform's {@code executor-max-pool-size}. */
@Min(1)
private int executorMaxPoolSize = 32;
/**
* Calls waiting for an executor thread: the platform's {@code executor-queue-capacity}. The upper
* bound is the platform's own refusal: a deeper queue holds work no caller is still waiting for.
*/
@Min(1)
@Max(10_000)
private int executorQueueCapacity = 256;
/**
* Deadline the server gives a feature call whose client sent none, and the most it gives one that
* sent a longer one. Ten seconds, the same per-request budget the GraphQL adapter uses. The
* platform states deadlines per method ({@code GrpcDeadlineProfile}) and has no server-wide value
* to mirror.
*/
@NotNull private Duration defaultDeadline = Duration.ofSeconds(10);
/** Server keep-alive ping interval: {@code GrpcServerProfile.stable(..)}'s 30 seconds. */
@NotNull private Duration keepAliveTime = Duration.ofSeconds(30);
/** How long a keep-alive ping may go unanswered: the platform's 10 seconds. */
@NotNull private Duration keepAliveTimeout = Duration.ofSeconds(10);
/** Most frequent client ping the server tolerates: the platform's 30 seconds. */
@NotNull private Duration permitKeepAliveTime = Duration.ofSeconds(30);
/**
* Connection age after which the server sends GOAWAY: the platform's 30 minutes. On the current
* loopback-only listener this only bounds a stuck client connection; once a non-loopback bind
* exists it is what lets a long-lived client move to a new instance during a rollout.
*/
@NotNull private Duration maxConnectionAge = Duration.ofMinutes(30);
/** Time in-flight calls get after a max-age GOAWAY: the platform's 30 seconds. */
@NotNull private Duration maxConnectionAgeGrace = Duration.ofSeconds(30);
public boolean isEnabled() {
return enabled;
}
@@ -90,6 +168,141 @@ public class GrpcServerSettings {
this.shutdownGraceSeconds = shutdownGraceSeconds;
}
public int getShutdownDrainSeconds() {
return shutdownDrainSeconds;
}
public void setShutdownDrainSeconds(int shutdownDrainSeconds) {
this.shutdownDrainSeconds = shutdownDrainSeconds;
}
public int getMaxInboundMessageBytes() {
return maxInboundMessageBytes;
}
public void setMaxInboundMessageBytes(int maxInboundMessageBytes) {
this.maxInboundMessageBytes = maxInboundMessageBytes;
}
public int getMaxInboundMetadataBytes() {
return maxInboundMetadataBytes;
}
public void setMaxInboundMetadataBytes(int maxInboundMetadataBytes) {
this.maxInboundMetadataBytes = maxInboundMetadataBytes;
}
public int getMaxConcurrentCallsPerConnection() {
return maxConcurrentCallsPerConnection;
}
public void setMaxConcurrentCallsPerConnection(int maxConcurrentCallsPerConnection) {
this.maxConcurrentCallsPerConnection = maxConcurrentCallsPerConnection;
}
public int getExecutorMaxPoolSize() {
return executorMaxPoolSize;
}
public void setExecutorMaxPoolSize(int executorMaxPoolSize) {
this.executorMaxPoolSize = executorMaxPoolSize;
}
public int getExecutorQueueCapacity() {
return executorQueueCapacity;
}
public void setExecutorQueueCapacity(int executorQueueCapacity) {
this.executorQueueCapacity = executorQueueCapacity;
}
public Duration getDefaultDeadline() {
return defaultDeadline;
}
public void setDefaultDeadline(Duration defaultDeadline) {
this.defaultDeadline = defaultDeadline;
}
public Duration getKeepAliveTime() {
return keepAliveTime;
}
public void setKeepAliveTime(Duration keepAliveTime) {
this.keepAliveTime = keepAliveTime;
}
public Duration getKeepAliveTimeout() {
return keepAliveTimeout;
}
public void setKeepAliveTimeout(Duration keepAliveTimeout) {
this.keepAliveTimeout = keepAliveTimeout;
}
public Duration getPermitKeepAliveTime() {
return permitKeepAliveTime;
}
public void setPermitKeepAliveTime(Duration permitKeepAliveTime) {
this.permitKeepAliveTime = permitKeepAliveTime;
}
public Duration getMaxConnectionAge() {
return maxConnectionAge;
}
public void setMaxConnectionAge(Duration maxConnectionAge) {
this.maxConnectionAge = maxConnectionAge;
}
public Duration getMaxConnectionAgeGrace() {
return maxConnectionAgeGrace;
}
public void setMaxConnectionAgeGrace(Duration maxConnectionAgeGrace) {
this.maxConnectionAgeGrace = maxConnectionAgeGrace;
}
@AssertTrue(message = "shutdown-drain-seconds must fit inside shutdown-grace-seconds")
public boolean isShutdownDrainWithinGrace() {
return shutdownDrainSeconds <= shutdownGraceSeconds;
}
/**
* The same orderings the platform's {@code GrpcServerProfile} refuses to break: every duration
* positive, a ping timeout below the ping interval, clients not allowed to ping less often than
* the server does, and a max-age grace no longer than the age it follows.
*/
@AssertTrue(
message =
"gRPC transport durations must be positive, keep-alive-timeout < keep-alive-time, "
+ "permit-keep-alive-time <= keep-alive-time and max-connection-age-grace <= "
+ "max-connection-age")
public boolean isTransportDurationsConsistent() {
if (!allPositive(
defaultDeadline,
keepAliveTime,
keepAliveTimeout,
permitKeepAliveTime,
maxConnectionAge,
maxConnectionAgeGrace)) {
return false;
}
return keepAliveTimeout.compareTo(keepAliveTime) < 0
&& permitKeepAliveTime.compareTo(keepAliveTime) <= 0
&& maxConnectionAgeGrace.compareTo(maxConnectionAge) <= 0;
}
private static boolean allPositive(Duration... values) {
for (Duration value : values) {
if (value == null || value.isZero() || value.isNegative()) {
return false;
}
}
return true;
}
@AssertTrue(
message = "insecure gRPC requires allow-insecure-local=true and a loopback bind address")
public boolean isInsecureLocalConfigurationValid() {
@@ -1,8 +1,10 @@
package dev.caskeleton.adapter.inbound.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import com.google.common.util.concurrent.ListenableFuture;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import dev.caskeleton.shared.error.OperationalError;
@@ -10,6 +12,7 @@ import io.grpc.BindableService;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientInterceptors;
import io.grpc.Context;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Metadata;
@@ -32,9 +35,14 @@ import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import org.junit.jupiter.api.DisplayName;
@@ -64,8 +72,18 @@ class GrpcP1BoundaryWireTest {
unaryMethod("ListenerThrow");
private static final MethodDescriptor<String, String> CLOSE_HANDLER_METHOD =
unaryMethod("CloseHandler");
private static final MethodDescriptor<String, String> SLOW_METHOD = unaryMethod("Slow");
private static final CountDownLatch CLOSE_HANDLER_RAN = new CountDownLatch(1);
/** The platform's GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES, which this adapter mirrors. */
private static final int ONE_MIB = 1024 * 1024;
/** How long the slow handler holds its thread unless its gRPC Context is cancelled first. */
private static final long SLOW_HANDLER_HOLD_MILLIS = 400;
private static final AtomicInteger SLOW_IN_FLIGHT = new AtomicInteger();
private static final AtomicInteger SLOW_MAX_IN_FLIGHT = new AtomicInteger();
private final ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withUserConfiguration(GrpcServerConfig.class, FeatureConfiguration.class)
@@ -203,6 +221,161 @@ class GrpcP1BoundaryWireTest {
});
}
@Test
@DisplayName("1 MiB를 넘는 요청 메시지는 handler에 닿기 전에 RESOURCE_EXHAUSTED로 거절된다")
void aRequestMessageOverOneMebibyteIsRejectedAsResourceExhausted() {
withChannel(
channel -> {
// given
String oversized = "x".repeat(ONE_MIB + 1);
// when
StatusRuntimeException failure =
catchThrowableOfType(
StatusRuntimeException.class,
() -> unary(authenticated(channel), UNARY_METHOD, oversized));
// then
assertThat(failure).isNotNull();
assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.RESOURCE_EXHAUSTED);
});
}
@Test
@DisplayName("정확히 1 MiB인 요청 메시지는 한도 안이라 feature handler에 닿는다")
void aRequestMessageOfExactlyOneMebibyteStillReachesTheHandler() {
withChannel(
channel -> {
// given
String atTheLimit = "x".repeat(ONE_MIB);
// when
String response = unary(authenticated(channel), UNARY_METHOD, atTheLimit);
// then
assertThat(response).hasSize("authorized-".length() + ONE_MIB);
});
}
@Test
@DisplayName("deadline 없이 부른 느린 호출은 서버 기본 deadline에서 DEADLINE_EXCEEDED로 끝난다")
void aSlowCallWithoutAClientDeadlineEndsAtTheServerDefaultDeadline() {
withChannel(
contextRunner.withPropertyValues("app.grpc.server.default-deadline=150ms"),
channel -> {
// given
ListenableFuture<String> withoutDeadline =
ClientCalls.futureUnaryCall(
authenticated(channel).newCall(SLOW_METHOD, CallOptions.DEFAULT), "slow");
// when
Throwable failure = catchThrowable(() -> withoutDeadline.get(5, TimeUnit.SECONDS));
// then
assertThat(Status.fromThrowable(failure).getCode())
.isEqualTo(Status.Code.DEADLINE_EXCEEDED);
});
}
@Test
@DisplayName("클라이언트 deadline이 서버 기본값보다 짧으면 클라이언트 deadline이 그대로 적용된다")
void aClientDeadlineShorterThanTheServerDefaultIsKept() {
withChannel(
contextRunner.withPropertyValues("app.grpc.server.default-deadline=10s"),
channel -> {
// given
long started = System.nanoTime();
// when
Throwable failure =
catchThrowable(
() ->
ClientCalls.blockingUnaryCall(
authenticated(channel),
SLOW_METHOD,
CallOptions.DEFAULT.withDeadlineAfter(100, TimeUnit.MILLISECONDS),
"slow"));
// then
assertThat(Status.fromThrowable(failure).getCode())
.isEqualTo(Status.Code.DEADLINE_EXCEEDED);
assertThat(Duration.ofNanos(System.nanoTime() - started))
.isLessThan(Duration.ofSeconds(5));
});
}
@Test
@DisplayName("연결당 동시 호출 상한이 1이면 같은 연결의 두 호출은 handler에서 겹치지 않는다")
void callsOnOneConnectionDoNotOverlapBeyondTheConcurrentCallCeiling() {
withChannel(
contextRunner.withPropertyValues("app.grpc.server.max-concurrent-calls-per-connection=1"),
channel -> {
// given
SLOW_MAX_IN_FLIGHT.set(0);
Channel caller = authenticated(channel);
CallOptions bounded = CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS);
ListenableFuture<String> first =
ClientCalls.futureUnaryCall(caller.newCall(SLOW_METHOD, bounded), "slow");
ListenableFuture<String> second =
ClientCalls.futureUnaryCall(caller.newCall(SLOW_METHOD, bounded), "slow");
// when
List<String> responses = List.of(getUnchecked(first), getUnchecked(second));
// then
assertThat(responses).containsExactly("slow-done", "slow-done");
assertThat(SLOW_MAX_IN_FLIGHT.get()).isEqualTo(1);
});
}
@Test
@DisplayName("스레드와 대기열이 모두 찬 서버는 넘친 호출을 기다리게 두지 않고 즉시 RESOURCE_EXHAUSTED로 거절한다")
void aCallBeyondTheExecutorAndQueueIsRefusedAtOnceAsResourceExhausted() {
withChannel(
contextRunner.withPropertyValues(
"app.grpc.server.executor-max-pool-size=1",
"app.grpc.server.executor-queue-capacity=1"),
channel -> {
// given
Channel caller = authenticated(channel);
CallOptions bounded = CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS);
List<ListenableFuture<String>> calls =
List.of(
ClientCalls.futureUnaryCall(caller.newCall(SLOW_METHOD, bounded), "slow"),
ClientCalls.futureUnaryCall(caller.newCall(SLOW_METHOD, bounded), "slow"),
ClientCalls.futureUnaryCall(caller.newCall(SLOW_METHOD, bounded), "slow"));
// when
List<Status> outcomes = calls.stream().map(GrpcP1BoundaryWireTest::outcome).toList();
// then
assertThat(outcomes)
.extracting(Status::getCode)
.containsExactlyInAnyOrder(
Status.Code.OK, Status.Code.OK, Status.Code.RESOURCE_EXHAUSTED);
assertThat(outcomes)
.filteredOn(status -> !status.isOk())
.extracting(Status::getDescription)
.containsExactly(ClientErrorMessages.of(Category.RATE_LIMIT));
});
}
private static Status outcome(ListenableFuture<String> call) {
Throwable failure = catchThrowable(() -> call.get(5, TimeUnit.SECONDS));
return failure == null ? Status.OK : Status.fromThrowable(failure);
}
private static String getUnchecked(ListenableFuture<String> future) {
try {
return future.get(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("interrupted while waiting for a call", e);
} catch (ExecutionException | TimeoutException e) {
throw new IllegalStateException("call did not complete", e);
}
}
private static boolean await(CountDownLatch latch) {
try {
return latch.await(5, TimeUnit.SECONDS);
@@ -213,7 +386,12 @@ class GrpcP1BoundaryWireTest {
}
private void withChannel(Consumer<ManagedChannel> assertion) {
contextRunner.run(
withChannel(contextRunner, assertion);
}
private static void withChannel(
ApplicationContextRunner runner, Consumer<ManagedChannel> assertion) {
runner.run(
context -> {
assertThat(context.getStartupFailure()).isNull();
int port = context.getBean(GrpcServerRunner.class).getListeningPort();
@@ -364,6 +542,14 @@ class GrpcP1BoundaryWireTest {
observer.onNext("authorized-" + request);
observer.onCompleted();
}))
.addMethod(
SLOW_METHOD,
ServerCalls.asyncUnaryCall(
(String request, StreamObserver<String> observer) -> {
holdUntilCancelled();
observer.onNext(request + "-done");
observer.onCompleted();
}))
.addMethod(
CLOSE_HANDLER_METHOD,
ServerCalls.asyncUnaryCall(
@@ -397,6 +583,24 @@ class GrpcP1BoundaryWireTest {
}
}
/**
* Holds the handler thread like a slow dependency would, but stops early when the call's gRPC
* Context is cancelled — the cooperative behavior a deadline is meant to trigger.
*/
private static void holdUntilCancelled() {
SLOW_MAX_IN_FLIGHT.accumulateAndGet(SLOW_IN_FLIGHT.incrementAndGet(), Math::max);
try {
long until = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(SLOW_HANDLER_HOLD_MILLIS);
while (System.nanoTime() < until && !Context.current().isCancelled()) {
Thread.sleep(10);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
SLOW_IN_FLIGHT.decrementAndGet();
}
}
private enum StringMarshaller implements MethodDescriptor.Marshaller<String> {
INSTANCE;
@@ -5,6 +5,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import io.grpc.BindableService;
import io.grpc.ServerServiceDefinition;
import io.grpc.protobuf.services.HealthStatusManager;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
@@ -102,6 +105,66 @@ class GrpcSafeActivationTest {
assertRootCauseContains(context.getStartupFailure(), "shutdownGraceSeconds"));
}
@Test
@DisplayName("전송 한도 기본값은 플랫폼 GrpcTransportLimits·GrpcServerProfile.stable·executor 기본값과 같다")
void transportBoundDefaultsMatchTheVendoredPlatformDefaults() {
// given — the adapter cannot import the platform types (no registry edge, separate build), so
// the expected values are the platform's literals, cited in the README beside each key.
GrpcServerSettings properties = new GrpcServerSettings();
// when
var defaults =
List.of(
properties.getMaxInboundMessageBytes(),
properties.getMaxInboundMetadataBytes(),
properties.getExecutorMaxPoolSize(),
properties.getExecutorQueueCapacity(),
properties.getKeepAliveTime(),
properties.getKeepAliveTimeout(),
properties.getPermitKeepAliveTime(),
properties.getMaxConnectionAge(),
properties.getMaxConnectionAgeGrace());
// then
assertThat(defaults)
.containsExactly(
1024 * 1024,
8192,
32,
256,
Duration.ofSeconds(30),
Duration.ofSeconds(10),
Duration.ofSeconds(30),
Duration.ofMinutes(30),
Duration.ofSeconds(30));
}
@Test
@DisplayName("drain 대기가 종료 grace보다 길면 기동이 실패한다")
void aDrainDelayLongerThanTheShutdownGraceFailsStartup() {
contextRunner
.withPropertyValues(
"app.grpc.server.port=0",
"app.grpc.server.allow-insecure-local=true",
"app.grpc.server.shutdown-grace-seconds=1",
"app.grpc.server.shutdown-drain-seconds=2")
.run(
context ->
assertRootCauseContains(context.getStartupFailure(), "shutdown-drain-seconds"));
}
@Test
@DisplayName("keep-alive timeout이 ping 간격 이상이면 기동이 실패한다")
void aKeepAliveTimeoutAtOrAboveTheIntervalFailsStartup() {
contextRunner
.withPropertyValues(
"app.grpc.server.port=0",
"app.grpc.server.allow-insecure-local=true",
"app.grpc.server.keep-alive-time=10s",
"app.grpc.server.keep-alive-timeout=10s")
.run(context -> assertRootCauseContains(context.getStartupFailure(), "keep-alive-timeout"));
}
@Test
void featureServiceRequiresACallerSuppliedAuthenticationPolicy() {
contextRunner
@@ -15,11 +15,13 @@ import io.grpc.reflection.v1.ServerReflectionRequest;
import io.grpc.reflection.v1.ServerReflectionResponse;
import io.grpc.reflection.v1.ServiceResponse;
import io.grpc.stub.StreamObserver;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
@@ -91,6 +93,55 @@ class GrpcServerRunnerBootTest {
});
}
@Test
@DisplayName("종료가 시작되면 drain 대기 동안 listener가 살아 있고 health는 NOT_SERVING을 보고한다")
void stoppingKeepsTheListenerUpReportingNotServingDuringTheDrainDelay() {
contextRunner
.withPropertyValues(
"app.grpc.server.shutdown-drain-seconds=2", "app.grpc.server.shutdown-grace-seconds=4")
.run(
context -> {
// given
GrpcServerRunner runner = context.getBean(GrpcServerRunner.class);
ManagedChannel channel =
ManagedChannelBuilder.forAddress("localhost", runner.getListeningPort())
.usePlaintext()
.build();
Thread stopping = Thread.ofVirtual().start(runner::stop);
try {
// when
ServingStatus duringDrain = firstStatusOtherThanServing(channel);
// then
assertThat(duringDrain).isEqualTo(ServingStatus.NOT_SERVING);
} finally {
stopping.join(Duration.ofSeconds(10));
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}
});
}
/**
* Polls health until it stops saying SERVING. A server that shut its listener the moment shutdown
* began answers this with UNAVAILABLE instead, which is what a load balancer cannot act on.
*/
private static ServingStatus firstStatusOtherThanServing(ManagedChannel channel)
throws InterruptedException {
long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
while (System.nanoTime() < until) {
ServingStatus status =
HealthGrpc.newBlockingStub(channel)
.withDeadlineAfter(1, TimeUnit.SECONDS)
.check(HealthCheckRequest.newBuilder().build())
.getStatus();
if (status != ServingStatus.SERVING) {
return status;
}
Thread.sleep(10);
}
return ServingStatus.SERVING;
}
@Configuration(proxyBeanMethods = false)
static class UnqualifiedServiceConfiguration {
+12
View File
@@ -0,0 +1,12 @@
# adapter:inbound:messaging
- Module ID `adapter-inbound-messaging`, Gradle path `:adapter:inbound:messaging`. Registry SSOT:
`src/config/architecture/modules.json`.
- Responsibility: the application's consume side of the vendored messaging platform — the inbox
parts the platform needs from the application (`JdbcInboxRepository` over the application
DataSource, a `TransactionRunner` over its `PlatformTransactionManager`) and the application's
`MessageHandler` implementations, each turning a delivery into one use case call.
- Boundaries: no business rule in a handler (HARD-STOP 4); no persistence entity or repository; no
broker SDK type. Allowed edges come only from the registry entry.
- Tests: focused auto-configuration and inbox behavior tests; `./gradlew :adapter:inbound:messaging:check`.
- Design and rejected alternatives: `README.md`.
+87
View File
@@ -0,0 +1,87 @@
# adapter:inbound:messaging — 이벤트 소비 경로
- Module ID: `adapter-inbound-messaging`
- Gradle path: `:adapter:inbound:messaging`
- Package: `dev.caskeleton.adapter.inbound.messaging`
- 테스트: `./gradlew :adapter:inbound:messaging:test --console=plain`
## 제공하는 것
소유자 결정 10("Kafka 소비 지원")을 application 쪽까지 잇는 최소 경로다(리뷰 2026-11-01 06-08).
```text
Kafka ─▶ platform consumer (starter-kafka)
└─ INBOX_TRANSACTIONAL destination이면
InboxMessageHandler ─▶ IdempotentConsumer.runOnce (platform이 감싼다)
├─ JdbcInboxRepository.reserve ← 이 leaf가 조립
└─ 애플리케이션 MessageHandler ─▶ use case
(같은 PlatformTransactionManager 트랜잭션) ← 이 leaf가 조립
```
- `MessagingInboxAutoConfiguration`: `MessageHandler` bean과 `DataSource`·`PlatformTransactionManager`가
있을 때만, platform inbox가 요구하는 두 부품을 만든다.
- `JdbcInboxRepository`(애플리케이션 DataSource). `DataSourceUtils`로 연결을 얻으므로 runner가 연
트랜잭션에 참여한다.
- `IdempotentConsumer.TransactionRunner`(애플리케이션 `PlatformTransactionManager` 위의
`TransactionTemplate`). inbox 예약과 use case의 JPA 쓰기가 한 트랜잭션에서 함께 커밋되거나 함께
롤백된다. handler가 실패하면 예약도 롤백되어 재전달이 효과를 다시 적용한다.
- platform starter(`MessagingReliabilityAutoConfiguration`)가 이 두 bean으로 `IdempotentConsumer`를
만든다. platform은 애플리케이션의 datasource·트랜잭션을 스스로 고르지 않는다는 기존 설계를 그대로 둔다.
- 애플리케이션의 handler(`MessageHandler<T>` 구현)는 이 leaf에 둔다. 컨트롤러가 HTTP 요청을 use case
호출로 바꾸듯 delivery를 use case 호출 하나로 바꾸는 inbound adapter다. 업무 규칙은 use case에 둔다.
## 추가할 한 줄
```groovy
// app-bootstrap/build.gradle — 기본 조립에는 없다
runtimeOnly project(':adapter:inbound:messaging') // 이벤트 소비 + inbox
```
`adapter:outbound:messaging-kafka` 줄(broker·platform)과 persistence-jpa(DataSource·트랜잭션)가 함께
있어야 한다. inbox 테이블(`messaging_inbox`)은 platform의
`messaging-reliability-jdbc-postgresql` `db/migration/messaging/V1101__messaging_inbox.sql`이 만든다.
그 위치를 애플리케이션 Flyway location에 넣는 일은 이번 변경에 포함되지 않았다(아래 "남은 것").
## destination 예시
```yaml
app:
messaging:
destinations:
order-events:
broker: kafka
kind: EVENT_STREAM
physical:
topic: order.events.v1
schema:
message-types: [order.created]
guarantees:
delivery: AT_LEAST_ONCE
external-side-effect: INBOX_TRANSACTIONAL # handler를 inbox로 감싼다
consumer:
group: order-projection # inbox의 consumer identity
dlq:
destination: order-events-dlq
```
handler 예시는 `MessagingInboxAutoConfigurationTest#exampleHandler`다.
## 고른 방법과 버린 대안
- 고름: platform은 `InboxRepository` + `TransactionRunner` bean이 있을 때만 `IdempotentConsumer`를
만들고, 두 부품은 이 application leaf가 준다. platform 경계(애플리케이션 datasource를 고르지 않음)와
registry 간선(messaging은 messaging만 의존)이 그대로다.
- 버림: app-bootstrap에서 handler·inbox를 직접 등록 — composition root에 업무 handler가 들어간다
(HARD-STOP 4).
- 버림: `adapter:outbound:messaging`(발행 bridge)에 소비까지 넣기 — 발행 bridge는
`messaging-core-api`만 보는 anti-corruption 경계이고, 소비는 inbound 방향이다.
- 버림: application-core에 소비 포트를 새로 만들어 platform `MessageHandler`로 감싸는 범용 bridge —
payload 타입 매핑과 결과 매핑 규칙을 먼저 정해야 해서 이번 범위보다 크다. 지금은 handler가 직접
use case를 부른다.
## 남은 것
- 실제 Kafka + PostgreSQL로 같은 메시지 두 번 전달 시 부작용 1회를 확인하는 lane이 없다. 지금은
platform `InboxMessageHandler`·`IdempotentConsumer`를 실제로 쓰고 inbox 저장소만 in-memory인 단위
테스트다.
- inbox migration location 연결과 inbox cleanup 스케줄은 이 leaf가 하지 않는다.
@@ -0,0 +1,35 @@
plugins {
id 'ca.spring-library'
id 'ca.spring-config'
}
// The application's consume side of the vendored messaging platform (review 2026-11-01 06-08),
// selected by one line in a composition root:
//
// runtimeOnly project(':adapter:inbound:messaging')
//
// The platform opens a consumer for every MessageHandler bean and, for a destination declared
// INBOX_TRANSACTIONAL, runs the handler inside an inbox reservation (IdempotentConsumer). It cannot
// build the inbox itself: the reservation must commit in the application's own transaction, against
// the application's own datasource. This leaf supplies exactly that — the JDBC inbox repository over
// the application DataSource and a transaction runner over its PlatformTransactionManager — and is
// where an application's message handlers live: an inbound adapter, which turns a delivery into a
// use case call, the same role a controller plays for HTTP.
dependencies {
implementation project(':application-core')
implementation project(':messaging:messaging-core-api')
implementation project(':messaging:messaging-reliability')
implementation project(':messaging:messaging-reliability-api')
// JdbcInboxRepository only. The leaf also exports the platform admin journal (api
// messaging-admin), which this leaf has no use for and no registered edge to; the starter puts it
// on the runtime classpath anyway.
implementation(project(':messaging:messaging-reliability-jdbc-postgresql')) {
exclude group: 'dev.caskeleton', module: 'messaging-admin'
}
implementation 'org.springframework.boot:spring-boot-autoconfigure'
implementation 'org.springframework:spring-jdbc'
implementation 'org.springframework:spring-tx'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
@@ -0,0 +1,152 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=testCompileClasspath
ch.qos.logback:logback-classic:1.5.38=testCompileClasspath,testRuntimeClasspath
ch.qos.logback:logback-core:1.5.38=testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-annotations:2.21=testCompileClasspath,testRuntimeClasspath
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
com.github.spotbugs:spotbugs:4.10.2=spotbugs
com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs
com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor
com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor
com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor
com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs
com.google.code.gson:gson:2.13.2=spotbugs
com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_annotations:2.38.0=testCompileClasspath
com.google.errorprone:error_prone_annotations:2.41.0=spotbugs
com.google.errorprone:error_prone_annotations:2.47.0=checkstyle
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor
com.google.guava:guava:33.6.0-jre=checkstyle
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath
commons-beanutils:commons-beanutils:1.11.0=checkstyle
commons-collections:commons-collections:3.2.2=checkstyle
commons-io:commons-io:2.21.0=spotbugs
commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
info.picocli:picocli:4.7.7=checkstyle
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath
jakarta.annotation:jakarta.annotation-api:3.0.0=testCompileClasspath,testRuntimeClasspath
jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=testCompileClasspath,testRuntimeClasspath
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor
jaxen:jaxen:2.0.6=spotbugs
net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath
net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath
net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath
net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
org.antlr:antlr4-runtime:4.13.2=checkstyle
org.apache.bcel:bcel:6.12.0=spotbugs
org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs
org.apache.commons:commons-text:1.15.0=spotbugs
org.apache.commons:commons-text:1.3=checkstyle
org.apache.httpcomponents:httpclient:4.5.13=checkstyle
org.apache.httpcomponents:httpcore:4.4.16=checkstyle
org.apache.logging.log4j:log4j-api:2.25.5=spotbugs,testCompileClasspath,testRuntimeClasspath
org.apache.logging.log4j:log4j-core:2.25.5=spotbugs
org.apache.logging.log4j:log4j-to-slf4j:2.25.5=testCompileClasspath,testRuntimeClasspath
org.apache.maven.doxia:doxia-core:1.12.0=checkstyle
org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle
org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle
org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle
org.apache.tomcat.embed:tomcat-embed-core:11.0.24=testCompileClasspath,testRuntimeClasspath
org.apache.tomcat.embed:tomcat-embed-el:11.0.24=testCompileClasspath,testRuntimeClasspath
org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=testCompileClasspath,testRuntimeClasspath
org.apache.xbean:xbean-reflect:3.7=checkstyle
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath
org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath
org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle
org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle
org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle
org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath
org.javassist:javassist:3.28.0-GA=checkstyle
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath
org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit:junit-bom:6.1.0=spotbugs
org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath
org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath
org.objenesis:objenesis:3.3=testRuntimeClasspath
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
org.osgi:org.osgi.annotation.bundle:2.0.0=testCompileClasspath
org.osgi:org.osgi.annotation.versioning:1.1.2=testCompileClasspath
org.osgi:org.osgi.resource:1.0.0=testCompileClasspath
org.osgi:org.osgi.service.serviceloader:1.0.0=testCompileClasspath
org.ow2.asm:asm-analysis:9.10.1=spotbugs
org.ow2.asm:asm-commons:9.10.1=spotbugs
org.ow2.asm:asm-tree:9.10.1=spotbugs
org.ow2.asm:asm-util:9.10.1=spotbugs
org.ow2.asm:asm:9.10.1=spotbugs
org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor
org.reflections:reflections:0.10.2=checkstyle
org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath
org.slf4j:jul-to-slf4j:2.0.18=testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.18=checkstyle
org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor
org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-logging:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-web-server:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-jdbc:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-tx:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath
org.yaml:snakeyaml:2.5=testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-core:3.1.5=testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-databind:3.1.5=testCompileClasspath,testRuntimeClasspath
tools.jackson:jackson-bom:3.1.5=testCompileClasspath,testRuntimeClasspath
empty=
@@ -0,0 +1,65 @@
package dev.caskeleton.adapter.inbound.messaging;
import dev.caskeleton.messaging.api.delivery.MessageHandler;
import dev.caskeleton.messaging.inbox.IdempotentConsumer;
import dev.caskeleton.messaging.inbox.JdbcInboxRepository;
import dev.caskeleton.messaging.reliability.InboxRepository;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
/**
* Supplies the platform's inbox with the application's datasource and transaction, so a handler of
* an {@code INBOX_TRANSACTIONAL} destination runs at most once per message and consumer group.
*
* <p>The platform ({@code MessagingReliabilityAutoConfiguration}) assembles its {@link
* IdempotentConsumer} only from an {@link InboxRepository} and a {@link
* IdempotentConsumer.TransactionRunner} the application provides, and refuses to start an {@code
* INBOX_TRANSACTIONAL} destination without it. This configuration provides both:
*
* <ul>
* <li>{@link JdbcInboxRepository} over the application {@link DataSource}. It takes its
* connection through {@code DataSourceUtils}, so it joins the transaction the runner opens.
* <li>A runner over the application {@link PlatformTransactionManager}: the reservation row and
* whatever the use case writes through JPA commit together, and a handler that fails rolls
* the reservation back with its effect, so the redelivery applies it.
* </ul>
*
* <p>Only while a {@link MessageHandler} exists — nothing to consume, nothing to assemble. Ordered
* before the platform root so its bean conditions see these beans.
*/
@AutoConfiguration(
afterName = {
"org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration",
"org.springframework.boot.hibernate.autoconfigure.HibernateJpaAutoConfiguration",
"org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration"
},
beforeName = "dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration")
@ConditionalOnBean({MessageHandler.class, DataSource.class, PlatformTransactionManager.class})
public class MessagingInboxAutoConfiguration {
/** The platform's JDBC inbox over the application datasource. */
@Bean
@ConditionalOnMissingBean(InboxRepository.class)
public JdbcInboxRepository messagingInboxRepository(DataSource dataSource) {
return new JdbcInboxRepository(dataSource);
}
/** 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);
return new IdempotentConsumer.TransactionRunner() {
@Override
public <T> T inTransaction(java.util.function.Supplier<T> work) {
return template.execute(status -> work.get());
}
};
}
}
@@ -0,0 +1 @@
dev.caskeleton.adapter.inbound.messaging.MessagingInboxAutoConfiguration
@@ -0,0 +1,212 @@
package dev.caskeleton.adapter.inbound.messaging;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.messaging.api.ContentType;
import dev.caskeleton.messaging.api.MessageEnvelope;
import dev.caskeleton.messaging.api.MessageId;
import dev.caskeleton.messaging.api.MessageType;
import dev.caskeleton.messaging.api.ProducerId;
import dev.caskeleton.messaging.api.SchemaVersion;
import dev.caskeleton.messaging.api.TraceContext;
import dev.caskeleton.messaging.api.delivery.DeliveryContext;
import dev.caskeleton.messaging.api.delivery.DeliveryMetadata;
import dev.caskeleton.messaging.api.delivery.HandleResult;
import dev.caskeleton.messaging.api.delivery.MessageDelivery;
import dev.caskeleton.messaging.api.delivery.MessageHandler;
import dev.caskeleton.messaging.api.destination.DestinationName;
import dev.caskeleton.messaging.api.destination.MessageDestination;
import dev.caskeleton.messaging.api.header.MessageHeaders;
import dev.caskeleton.messaging.inbox.IdempotentConsumer;
import dev.caskeleton.messaging.inbox.InboxMessageHandler;
import dev.caskeleton.messaging.inbox.JdbcInboxRepository;
import dev.caskeleton.messaging.reliability.InboxRepository;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.sql.DataSource;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionStatus;
/**
* The application side of the platform inbox (review 06-08): what this leaf assembles, when, and
* that a delivery handled through it runs its side effect once per message.
*/
class MessagingInboxAutoConfigurationTest {
private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z");
private static final DestinationName ORDERS = new DestinationName("order-events");
private final ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(MessagingInboxAutoConfiguration.class))
.withBean(DataSource.class, () -> Mockito.mock(DataSource.class))
.withBean(PlatformTransactionManager.class, RecordingTransactions::new);
@Test
@DisplayName("메시지 handler가 있으면 애플리케이션 datasource 위의 inbox와 트랜잭션 runner를 조립한다")
void aMessageHandlerAssemblesTheInboxOverTheApplicationDatasource() {
// when & then
runner
.withBean(MessageHandler.class, () -> exampleHandler(new ArrayList<>()))
.run(
context -> {
assertThat(context).hasSingleBean(JdbcInboxRepository.class);
assertThat(context).hasSingleBean(IdempotentConsumer.TransactionRunner.class);
});
}
@Test
@DisplayName("소비할 handler가 없으면 inbox를 조립하지 않는다")
void withoutAHandlerNothingIsAssembled() {
// when & then
runner.run(
context -> {
assertThat(context).doesNotHaveBean(InboxRepository.class);
assertThat(context).doesNotHaveBean(IdempotentConsumer.TransactionRunner.class);
});
}
@Test
@DisplayName("트랜잭션 runner는 성공하면 커밋하고 실패하면 롤백해 예약과 부작용을 함께 되돌린다")
void theRunnerCommitsOnSuccessAndRollsBackOnFailure() {
// given
RecordingTransactions transactions = new RecordingTransactions();
IdempotentConsumer.TransactionRunner runner =
new MessagingInboxAutoConfiguration().messagingInboxTransactions(transactions);
runner.inTransaction(() -> "applied");
// when
Throwable thrown =
catchThrowable(
() ->
runner.inTransaction(
() -> {
throw new IllegalStateException("use case failed");
}));
// then
assertThat(thrown).hasMessage("use case failed");
assertThat(transactions.outcomes).containsExactly("commit", "rollback");
}
@Test
@DisplayName("같은 메시지가 두 번 전달돼도 handler의 부작용은 한 번만 일어난다")
void theSameMessageDeliveredTwiceRunsTheSideEffectOnce() {
// given: the platform's inbox wrapper around an application handler, over this leaf's runner
List<String> effects = new ArrayList<>();
IdempotentConsumer inbox =
new IdempotentConsumer(
new InMemoryInbox(),
new MessagingInboxAutoConfiguration()
.messagingInboxTransactions(new RecordingTransactions()));
MessageHandler<String> handler =
new InboxMessageHandler<>(exampleHandler(effects), inbox, "order-projection", () -> NOW);
MessageDelivery<String> delivery = delivery(MessageId.newId());
handler.handle(delivery).toCompletableFuture().join();
// when
HandleResult redelivered = handler.handle(delivery).toCompletableFuture().join();
// then
assertThat(redelivered).isEqualTo(HandleResult.success());
assertThat(effects).containsExactly("o-1");
}
/** The shape of an application handler: a delivery becomes one use case call. */
private static MessageHandler<String> exampleHandler(List<String> effects) {
return new MessageHandler<>() {
@Override
public MessageDestination<String> destination() {
return new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class);
}
@Override
public CompletionStage<HandleResult> handle(MessageDelivery<String> delivery) {
effects.add(delivery.message().payload());
return CompletableFuture.completedFuture(HandleResult.success());
}
};
}
private static MessageDelivery<String> delivery(MessageId id) {
return new MessageDelivery<>(
new MessageEnvelope<>(
id,
new MessageType("order.created"),
new SchemaVersion(1),
NOW,
Optional.empty(),
new ProducerId("orders"),
Optional.empty(),
Optional.empty(),
ContentType.JSON,
Optional.empty(),
Optional.empty(),
Optional.empty(),
TraceContext.none(),
MessageHeaders.empty(),
"o-1"),
new DeliveryMetadata(
ORDERS, 1, false, Optional.empty(), Optional.empty(), Optional.empty(), NOW),
new DeliveryContext(NOW.plusSeconds(30), false, "order-projection"));
}
/** Records what the runner asked of the transaction manager. */
private static final class RecordingTransactions extends AbstractPlatformTransactionManager {
private static final long serialVersionUID = 1L;
private final transient List<String> outcomes = new ArrayList<>();
@Override
protected Object doGetTransaction() {
return new Object();
}
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {}
@Override
protected void doCommit(DefaultTransactionStatus status) {
outcomes.add("commit");
}
@Override
protected void doRollback(DefaultTransactionStatus status) {
outcomes.add("rollback");
}
}
private static final class InMemoryInbox implements InboxRepository {
private final Set<String> reserved = new LinkedHashSet<>();
@Override
public boolean reserve(MessageId messageId, String consumerId, Instant now) {
return reserved.add(messageId.value() + "|" + consumerId);
}
@Override
public boolean isProcessed(MessageId messageId, String consumerId) {
return reserved.contains(messageId.value() + "|" + consumerId);
}
@Override
public int purgeProcessedBefore(Instant processedBefore, int limit) {
return 0;
}
}
}
@@ -47,6 +47,34 @@ virtual thread 실행기는 `TaskDecorator` bean 을 요구한다(요청 상관
| `idempotency` | `JsonIdempotentResponseCodec` |
| `admin.route` | `WebRouteInventory` |
## 오류 응답
이 leaf 의 예외는 모두 `ApiErrorCarrier` 다. 코드는 `error.WebAdvancedError` 한 enum 이 정하고, web 의
`GlobalExceptionHandler.handleCarrier` 한 분기가 Envelope 로 답한다(별도 `@RestControllerAdvice` 없음).
예전에는 10종 모두 `500 INTERNAL_ERROR` 였다(리뷰 2026-11-01 02-07). 아래 표와 enum 은 같은 값을 말하고,
`WebAdvancedErrorMappingTest` 가 실제 응답으로 확인한다.
| 예외 | `error.code` | status | category | retryable | 응답에 더 실리는 것 | 클라이언트 행동 |
| --- | --- | --- | --- | --- | --- | --- |
| `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 문서를 고친다 |
| `PatchAuthorizationException` | `PATCH_PATH_FORBIDDEN` | 403 | `AUTHZ` | false | `details.refusedPaths` | 해당 경로를 빼거나 권한 확보 |
| `UnsupportedApiVersionException` | `API_VERSION_UNSUPPORTED` | 404 | `NOT_FOUND` | false | — | 지원 버전 경로로 |
| `SunsetViolationException` | `API_DEPRECATION_INVALID` | 500 | `INTERNAL` | false | — | 서버 설정 결함(등록 시점 오류) |
| `UntrustedTenantInputException` | `TENANT_INPUT_UNTRUSTED` | 403 | `AUTHZ` | false | — | 요청 입력으로 tenant 를 보내지 않는다 |
| `ReplayCursorExpiredException` | `STREAM_RESNAPSHOT_REQUIRED` | 410 | `NOT_FOUND` | false | — | 리소스를 다시 읽고 새 스트림(`docs/web/streaming-contract.md`) |
| `StreamItemTooLargeException` | `STREAM_ITEM_TOO_LARGE` | 500 | `INTERNAL` | false | — | 서버 데이터 문제. commit 뒤면 스트림 terminal failure 로 끝난다 |
| `RouteInventoryMismatchException` | `ROUTE_INVENTORY_MISMATCH` | 500 | `INTERNAL` | false | — | release gate 실패(요청 경로에서는 나오지 않아야 한다) |
- `Retry-After` 는 `WebAdvancedError` 가 web 의 `RetryAfterHint` 로 직접 말한다. web 의 `RetryAfterAdvisor`
표에 이 leaf 코드 이름을 넣지 않는다.
- `details` 는 `ClientSafeErrorDetails` 로 고른 값만 나간다. 예외 메시지는 나가지 않는다.
- 이 코드들은 `docs/registries/error-codes.yaml`(`OperationalError` SSOT) 밖이다. 5xx 는
`handleCarrier` 가 ERROR 로그를 남긴다(admission 거절 포함 — 경보 임계는 운영에서 정한다).
- 응답 status 가 이미 commit 된 스트림 안에서는 HTTP status 가 바뀌지 않는다. 위 표는 commit 전에 던져진
경우다.
## env 키
없다. 위 세 설정은 서비스가 자기 `application.yml` 에 둔다. 이 leaf 는 env key registry 에 키를
@@ -35,7 +35,6 @@ strictTestLanes {
lane('webAdvancedTest') {
tag = 'web-advanced'
description = 'Runs every web Advanced capability contract.'
jvmArgs '-Duser.timezone=UTC'
}
}
@@ -44,3 +43,10 @@ strictTestLanes {
tasks.named('mainCheck') {
dependsOn 'webAdvancedTest'
}
// RepresentationBackendScopeTest reads this script to check which scope declares the codec
// backends, and a scope change can leave the test runtime classpath as it was. The script is an
// input, or a cached `test`/`webAdvancedTest` passes for the old scope (review 2026-11-01 08-02).
tasks.withType(Test).configureEach {
inputs.file('build.gradle').withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('buildScript')
}
@@ -1,5 +1,9 @@
package dev.caskeleton.adapter.inbound.web.advanced.admin.route;
import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
/**
* The routes this deployment actually serves are not the routes it declared.
*
@@ -7,7 +11,8 @@ package dev.caskeleton.adapter.inbound.web.advanced.admin.route;
* disagreement with the approved manifest stops the release: an endpoint that appears without a
* review is an endpoint whose authorization, budget and idempotency policy nobody chose.
*/
public final class RouteInventoryMismatchException extends RuntimeException {
public final class RouteInventoryMismatchException extends RuntimeException
implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
@@ -15,4 +20,12 @@ public final class RouteInventoryMismatchException extends RuntimeException {
public RouteInventoryMismatchException(String message) {
super(message);
}
/**
* {@link WebAdvancedError#ROUTE_INVENTORY_MISMATCH}; see the leaf README for the client contract.
*/
@Override
public ApiErrorCode errorCode() {
return WebAdvancedError.ROUTE_INVENTORY_MISMATCH;
}
}
@@ -0,0 +1,80 @@
package dev.caskeleton.adapter.inbound.web.advanced.error;
import dev.caskeleton.adapter.inbound.web.observability.RetryAfterHint;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.Category;
/**
* The codes this leaf's exceptions carry to the client. Each exception implements {@link
* dev.caskeleton.shared.error.ApiErrorCarrier}, so the web adapter's one carrier branch answers it
* with this status — no second {@code @RestControllerAdvice}. The table the client reads is the
* leaf README's "오류 응답" section; it states the same values.
*
* <p>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).
*
* <p>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. */
PATCH_REJECTED(Category.VALIDATION, 400, false, 0),
/** The patch touches a field the caller may not modify. */
PATCH_PATH_FORBIDDEN(Category.AUTHZ, 403, false, 0),
/** The request addressed an API major version this deployment does not serve. */
API_VERSION_UNSUPPORTED(Category.NOT_FOUND, 404, false, 0),
/** A deprecation was declared with a past sunset or no link: a server configuration fault. */
API_DEPRECATION_INVALID(Category.INTERNAL, 500, false, 0),
/** Request input proposed a tenant; only authentication may establish one. */
TENANT_INPUT_UNTRUSTED(Category.AUTHZ, 403, false, 0),
/** The resume cursor is older than retained history. Re-read the resource, start a new stream. */
STREAM_RESNAPSHOT_REQUIRED(Category.NOT_FOUND, 410, false, 0),
/** One stream item exceeded the per-item ceiling: the server's data, not the request. */
STREAM_ITEM_TOO_LARGE(Category.INTERNAL, 500, false, 0),
/** Served routes differ from the approved manifest: a release-gate failure. */
ROUTE_INVENTORY_MISMATCH(Category.INTERNAL, 500, false, 0);
private final Category category;
private final int httpStatus;
private final boolean retryable;
private final int retryAfterSeconds;
WebAdvancedError(Category category, int httpStatus, boolean retryable, int retryAfterSeconds) {
this.category = category;
this.httpStatus = httpStatus;
this.retryable = retryable;
this.retryAfterSeconds = retryAfterSeconds;
}
@Override
public String code() {
return name();
}
@Override
public Category category() {
return category;
}
@Override
public int httpStatus() {
return httpStatus;
}
@Override
public boolean retryable() {
return retryable;
}
/** Only read for a retryable code ({@code RetryAfterAdvisor}); zero for the others. */
@Override
public int retryAfterSeconds() {
return retryAfterSeconds;
}
}
@@ -1,11 +1,21 @@
package dev.caskeleton.adapter.inbound.web.advanced.patch;
import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
/** A JSON Patch document that will not be applied, and was not partially applied either. */
public final class JsonPatchRejectedException extends RuntimeException {
public final class JsonPatchRejectedException extends RuntimeException implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
public JsonPatchRejectedException(String message) {
super(message);
}
/** {@link WebAdvancedError#PATCH_REJECTED}; see the leaf README for the client contract. */
@Override
public ApiErrorCode errorCode() {
return WebAdvancedError.PATCH_REJECTED;
}
}
@@ -1,5 +1,10 @@
package dev.caskeleton.adapter.inbound.web.advanced.patch;
import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError;
import dev.caskeleton.adapter.inbound.web.error.ClientSafeErrorDetails;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import java.util.Map;
import java.util.Objects;
/**
@@ -13,7 +18,8 @@ import java.util.Objects;
* server's, and returning it would turn {@code test} into a read primitive for fields the caller
* may not read.
*/
public final class JsonPatchTestFailedException extends RuntimeException {
public final class JsonPatchTestFailedException extends RuntimeException
implements ApiErrorCarrier, ClientSafeErrorDetails {
private static final long serialVersionUID = 1L;
@@ -28,4 +34,15 @@ public final class JsonPatchTestFailedException extends RuntimeException {
public String pointer() {
return pointer;
}
/** {@link WebAdvancedError#PATCH_TEST_FAILED}; see the leaf README for the client contract. */
@Override
public ApiErrorCode errorCode() {
return WebAdvancedError.PATCH_TEST_FAILED;
}
@Override
public Map<String, Object> clientDetails() {
return Map.of("pointer", pointer);
}
}
@@ -1,6 +1,11 @@
package dev.caskeleton.adapter.inbound.web.advanced.patch;
import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError;
import dev.caskeleton.adapter.inbound.web.error.ClientSafeErrorDetails;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
@@ -9,7 +14,8 @@ import java.util.Objects;
* <p>Names the fields, because the caller needs to know which of them was refused and the names are
* from the server's allowlist rather than from the request — so they are safe to echo.
*/
public final class PatchAuthorizationException extends RuntimeException {
public final class PatchAuthorizationException extends RuntimeException
implements ApiErrorCarrier, ClientSafeErrorDetails {
private static final long serialVersionUID = 1L;
@@ -24,4 +30,15 @@ public final class PatchAuthorizationException extends RuntimeException {
public List<String> refusedPaths() {
return refusedPaths;
}
/** {@link WebAdvancedError#PATCH_PATH_FORBIDDEN}; see the leaf README for the client contract. */
@Override
public ApiErrorCode errorCode() {
return WebAdvancedError.PATCH_PATH_FORBIDDEN;
}
@Override
public Map<String, Object> clientDetails() {
return Map.of("refusedPaths", refusedPaths);
}
}
@@ -1,5 +1,9 @@
package dev.caskeleton.adapter.inbound.web.advanced.security;
import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
/**
* A tenant was proposed by request input rather than established by authentication.
*
@@ -10,7 +14,8 @@ package dev.caskeleton.adapter.inbound.web.advanced.security;
* <p>The message names no value. Echoing the proposed tenant would put attacker-chosen content into
* the log line that reports the attempt.
*/
public final class UntrustedTenantInputException extends RuntimeException {
public final class UntrustedTenantInputException extends RuntimeException
implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
@@ -20,4 +25,12 @@ public final class UntrustedTenantInputException extends RuntimeException {
"a tenant was supplied by request input; only an authenticated tenant may scope a request,"
+ " because a caller-chosen one selects whose data is read");
}
/**
* {@link WebAdvancedError#TENANT_INPUT_UNTRUSTED}; see the leaf README for the client contract.
*/
@Override
public ApiErrorCode errorCode() {
return WebAdvancedError.TENANT_INPUT_UNTRUSTED;
}
}
@@ -1,5 +1,9 @@
package dev.caskeleton.adapter.inbound.web.advanced.stream.encoding;
import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
/**
* One stream item exceeded the policy's per-item ceiling.
*
@@ -8,7 +12,7 @@ package dev.caskeleton.adapter.inbound.web.advanced.stream.encoding;
* written — leaves the consumer resynchronising past a partial record, which is recoverable for
* JSON-seq and not for NDJSON.
*/
public final class StreamItemTooLargeException extends RuntimeException {
public final class StreamItemTooLargeException extends RuntimeException implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
@@ -30,4 +34,12 @@ public final class StreamItemTooLargeException extends RuntimeException {
public int maxBytes() {
return maxBytes;
}
/**
* {@link WebAdvancedError#STREAM_ITEM_TOO_LARGE}; see the leaf README for the client contract.
*/
@Override
public ApiErrorCode errorCode() {
return WebAdvancedError.STREAM_ITEM_TOO_LARGE;
}
}
@@ -1,5 +1,8 @@
package dev.caskeleton.adapter.inbound.web.advanced.stream.replay;
import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import java.util.Objects;
/**
@@ -10,7 +13,8 @@ import java.util.Objects;
* where the replay started, so nothing about the data says events are missing. An explicit
* resnapshot-required answer costs the client a full re-read and is the only honest option.
*/
public final class ReplayCursorExpiredException extends RuntimeException {
public final class ReplayCursorExpiredException extends RuntimeException
implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
@@ -25,4 +29,13 @@ public final class ReplayCursorExpiredException extends RuntimeException {
public WebStreamResumeCursor cursor() {
return cursor;
}
/**
* {@link WebAdvancedError#STREAM_RESNAPSHOT_REQUIRED}; see the leaf README for the client
* contract.
*/
@Override
public ApiErrorCode errorCode() {
return WebAdvancedError.STREAM_RESNAPSHOT_REQUIRED;
}
}
@@ -1,5 +1,9 @@
package dev.caskeleton.adapter.inbound.web.advanced.versioning;
import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
/**
* A deprecation was declared in a way a client cannot act on.
*
@@ -7,7 +11,7 @@ package dev.caskeleton.adapter.inbound.web.advanced.versioning;
* deprecation with no documentation link, is a promise the deployment cannot keep — and discovering
* that when the first client asks is discovering it from the client.
*/
public final class SunsetViolationException extends RuntimeException {
public final class SunsetViolationException extends RuntimeException implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
@@ -15,4 +19,12 @@ public final class SunsetViolationException extends RuntimeException {
public SunsetViolationException(String message) {
super(message);
}
/**
* {@link WebAdvancedError#API_DEPRECATION_INVALID}; see the leaf README for the client contract.
*/
@Override
public ApiErrorCode errorCode() {
return WebAdvancedError.API_DEPRECATION_INVALID;
}
}
@@ -1,5 +1,9 @@
package dev.caskeleton.adapter.inbound.web.advanced.versioning;
import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
/**
* A request addressed a major version this deployment does not serve.
*
@@ -10,7 +14,8 @@ package dev.caskeleton.adapter.inbound.web.advanced.versioning;
*
* <p>The message names the version and never the path. A path carries identifiers.
*/
public final class UnsupportedApiVersionException extends RuntimeException {
public final class UnsupportedApiVersionException extends RuntimeException
implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
@@ -36,4 +41,12 @@ public final class UnsupportedApiVersionException extends RuntimeException {
public static UnsupportedApiVersionException missingVersion() {
return new UnsupportedApiVersionException("the path carries no /api/v{major} version segment");
}
/**
* {@link WebAdvancedError#API_VERSION_UNSUPPORTED}; see the leaf README for the client contract.
*/
@Override
public ApiErrorCode errorCode() {
return WebAdvancedError.API_VERSION_UNSUPPORTED;
}
}
@@ -1,5 +1,9 @@
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;
/**
* An arrival was refused because the concurrency limit was full.
*
@@ -7,7 +11,7 @@ package dev.caskeleton.adapter.inbound.web.advanced.virtualthread;
* limit exists to produce — a request refused in a millisecond is strictly better for the client
* than the same request accepted and timed out thirty seconds later behind a full connection pool.
*/
public final class AdmissionRefusedException extends RuntimeException {
public final class AdmissionRefusedException extends RuntimeException implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
@@ -22,4 +26,10 @@ public final class AdmissionRefusedException extends RuntimeException {
public int limit() {
return limit;
}
/** {@link WebAdvancedError#ADMISSION_REFUSED}; see the leaf README for the client contract. */
@Override
public ApiErrorCode errorCode() {
return WebAdvancedError.ADMISSION_REFUSED;
}
}
@@ -0,0 +1,140 @@
package dev.caskeleton.adapter.inbound.web.advanced.error;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import dev.caskeleton.adapter.inbound.web.advanced.admin.route.RouteInventoryMismatchException;
import dev.caskeleton.adapter.inbound.web.advanced.patch.JsonPatchRejectedException;
import dev.caskeleton.adapter.inbound.web.advanced.patch.JsonPatchTestFailedException;
import dev.caskeleton.adapter.inbound.web.advanced.patch.PatchAuthorizationException;
import dev.caskeleton.adapter.inbound.web.advanced.security.UntrustedTenantInputException;
import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamItemTooLargeException;
import dev.caskeleton.adapter.inbound.web.advanced.stream.replay.ReplayCursorExpiredException;
import dev.caskeleton.adapter.inbound.web.advanced.stream.replay.WebStreamResumeCursor;
import dev.caskeleton.adapter.inbound.web.advanced.versioning.SunsetViolationException;
import dev.caskeleton.adapter.inbound.web.advanced.versioning.UnsupportedApiVersionException;
import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.AdmissionRefusedException;
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
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;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* Every exception this leaf throws reaches the client as the status and code the README table
* promises, through the web adapter's one carrier branch — never as {@code 500 INTERNAL_ERROR}.
*/
@Tag("web-advanced")
class WebAdvancedErrorMappingTest {
private static final Map<String, Supplier<RuntimeException>> FAILURES =
Map.of(
"admission", () -> new AdmissionRefusedException(8),
"patch-test", () -> new JsonPatchTestFailedException("/version"),
"patch-rejected", () -> new JsonPatchRejectedException("too many operations"),
"patch-forbidden", () -> new PatchAuthorizationException(List.of("/role")),
"version", () -> UnsupportedApiVersionException.unknownMajor(9),
"sunset", () -> new SunsetViolationException("sunset in the past"),
"tenant", UntrustedTenantInputException::new,
"cursor", () -> new ReplayCursorExpiredException(new WebStreamResumeCursor("42")),
"item", () -> new StreamItemTooLargeException(2048, 1024),
"inventory", () -> new RouteInventoryMismatchException("undeclared GET /x"));
private final MockMvc mvc =
MockMvcBuilders.standaloneSetup(new Probe())
.setControllerAdvice(new GlobalExceptionHandler(SpanErrorRecorder.NOOP))
.build();
static Stream<Arguments> documentedMappings() {
return Stream.of(
Arguments.of("admission", 503, "ADMISSION_REFUSED", "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),
Arguments.of("version", 404, "API_VERSION_UNSUPPORTED", "NOT_FOUND", false),
Arguments.of("sunset", 500, "API_DEPRECATION_INVALID", "INTERNAL", false),
Arguments.of("tenant", 403, "TENANT_INPUT_UNTRUSTED", "AUTHZ", false),
Arguments.of("cursor", 410, "STREAM_RESNAPSHOT_REQUIRED", "NOT_FOUND", false),
Arguments.of("item", 500, "STREAM_ITEM_TOO_LARGE", "INTERNAL", false),
Arguments.of("inventory", 500, "ROUTE_INVENTORY_MISMATCH", "INTERNAL", false));
}
@ParameterizedTest(name = "{0} -> {1} {2}")
@MethodSource("documentedMappings")
@DisplayName("web-advanced 예외는 문서에 적힌 상태·코드·재시도 여부로 나간다")
void eachExceptionLeavesWithItsDocumentedStatusAndCode(
String failure, int status, String code, String category, boolean retryable)
throws Exception {
// when
var result = mvc.perform(get("/fail/" + failure));
// then
result
.andExpect(status().is(status))
.andExpect(jsonPath("$.success").value(false))
.andExpect(jsonPath("$.error.code").value(code))
.andExpect(jsonPath("$.error.category").value(category))
.andExpect(jsonPath("$.error.retryable").value(retryable));
}
@Test
@DisplayName("동시성 한도 거절은 503에 Retry-After를 단다")
void anAdmissionRefusalCarriesRetryAfter() throws Exception {
// when
var result = mvc.perform(get("/fail/admission"));
// then
result
.andExpect(status().isServiceUnavailable())
.andExpect(header().string("Retry-After", "1"));
}
@Test
@DisplayName("patch test 실패는 실패한 pointer를 알려 주고 서버 값은 알려 주지 않는다")
void aFailedPatchTestNamesThePointerAndNotTheServerValue() throws Exception {
// when
var result = mvc.perform(get("/fail/patch-test"));
// then
result
.andExpect(status().isConflict())
.andExpect(jsonPath("$.error.details.pointer").value("/version"))
.andExpect(jsonPath("$.error.details.value").doesNotExist());
}
@Test
@DisplayName("patch 권한 거절은 거절된 경로 목록을 알려 준다")
void aRefusedPatchNamesTheRefusedPaths() throws Exception {
// when
var result = mvc.perform(get("/fail/patch-forbidden"));
// then
result
.andExpect(status().isForbidden())
.andExpect(jsonPath("$.error.details.refusedPaths", Matchers.contains("/role")));
}
@RestController
static class Probe {
@GetMapping("/fail/{failure}")
Map<String, String> fail(@PathVariable String failure) {
throw FAILURES.get(failure).get();
}
}
}
@@ -1,13 +1,19 @@
package dev.caskeleton.adapter.inbound.web.fileserver.config;
import dev.caskeleton.adapter.inbound.web.auth.CorsExposedHeaders;
import dev.caskeleton.adapter.inbound.web.fileserver.controller.FileDownloadController;
import dev.caskeleton.adapter.inbound.web.fileserver.controller.FileUploadController;
import dev.caskeleton.adapter.inbound.web.fileserver.draft12.Draft12Headers;
import dev.caskeleton.adapter.inbound.web.fileserver.draft12.Draft12UploadController;
import dev.caskeleton.adapter.inbound.web.fileserver.lifecycle.FileLifecycleController;
import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverExceptionHandler;
import dev.caskeleton.adapter.inbound.web.fileserver.tus.TusController;
import dev.caskeleton.adapter.inbound.web.fileserver.tus.TusHeaders;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpHeaders;
/**
* The public Fileserver HTTP surface, as one importable unit.
@@ -26,4 +32,27 @@ import org.springframework.context.annotation.Import;
FileserverExceptionHandler.class,
MvcTransferExecutorConfiguration.class
})
public class FileserverHttpSurfaceConfiguration {}
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.
*/
@Bean
CorsExposedHeaders fileserverCorsExposedHeaders() {
return new CorsExposedHeaders(
List.of(
TusHeaders.RESUMABLE,
TusHeaders.VERSION,
TusHeaders.EXTENSION,
TusHeaders.MAX_SIZE,
TusHeaders.UPLOAD_OFFSET,
TusHeaders.UPLOAD_LENGTH,
TusHeaders.UPLOAD_DEFER_LENGTH,
TusHeaders.UPLOAD_EXPIRES,
Draft12Headers.UPLOAD_COMPLETE,
Draft12Headers.UPLOAD_LIMIT,
HttpHeaders.CONTENT_DISPOSITION,
HttpHeaders.ACCEPT_RANGES));
}
}
@@ -0,0 +1,28 @@
package dev.caskeleton.adapter.inbound.web.fileserver.config;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.web.auth.CorsExposedHeaders;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class FileserverCorsExposedHeadersTest {
@Test
@DisplayName("fileserver HTTP 표면은 업로드 재개에 필요한 헤더를 CORS 노출 목록에 기여한다")
void theSurfaceContributesTheHeadersAResumingClientMustRead() {
// when
CorsExposedHeaders contributed =
new FileserverHttpSurfaceConfiguration().fileserverCorsExposedHeaders();
// then
assertThat(contributed.headerNames())
.contains(
"Tus-Resumable",
"Upload-Offset",
"Upload-Length",
"Upload-Expires",
"Upload-Complete",
"Content-Disposition");
}
}
+60 -3
View File
@@ -103,6 +103,13 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
- `AUTHZ_TENANT_MISMATCH` 는 여기서 추론 불가 — application-layer 의 cross-tenant 결정이며, 일반 `AccessDeniedException` 에는 `AUTHZ_INSUFFICIENT_PERMISSION`
만 방출한다.
### EnvelopeResponseWriter
- 컨버터 밖에서 본문을 직접 쓰는 거부 응답(보안 entry point·access-denied handler·rate-limit
interceptor)이 쓰는 하나의 writer. status·`application/json`·**UTF-8**·`ErrorResponseFactory` 본문을
정한다. Tomcat 의 기본 응답 문자셋은 ISO-8859-1 이라 문자셋을 빠뜨리면 한국어 문구가 `???` 가 된다
(리뷰 02-04 — rate-limit 이 그랬다). 거부별 헤더(`WWW-Authenticate`, `Retry-After`, `X-RateLimit-*`)는
호출자가 본문을 쓰기 전에 붙인다. GraphQL body limit filter 는 다른 leaf 라 자기 writer 를 쓴다(UTF-8 지정).
### AuthErrorResponseWriter
- **토큰/PII 리댁션.** 응답 본문엔 해당
코드의 일반 `client_safe_message` 만 담고, 원시 예외 텍스트·`Authorization` 헤더·issuer·audience 는
@@ -201,8 +208,14 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
하나로 매핑한다. 5xx 는 원인과 함께 로그를 남기고(persistence 는 분류만), retryable 코드는
`RetryAfterAdvisor`로 `Retry-After`를 붙인다.
- 개별 override 가 없는 Spring MVC 예외(필수 파라미터·헤더·part 누락, binding 실패 등)는
`handleExceptionInternal` override 가 상태 코드 → `OperationalError`로 바꿔 같은 Envelope 로 보낸다.
`handleExceptionInternal` override 가 상태 코드 → 코드로 바꿔 같은 Envelope 로 보낸다. 503(Spring 의
async 요청 시간 초과)은 `INTERNAL_ERROR` 가 아니라 `REQUEST_TIMEOUT`(503, retryable) 이다(리뷰 02-08).
`application/problem+json`은 나가지 않는다(I-3a).
- carrier 가 `ClientSafeErrorDetails` 도 구현하면 그 값이 `error.details` 가 된다(web-advanced 의 patch
pointer·거절 경로). 코드가 `RetryAfterHint` 를 구현하면 `Retry-After` 값은 그 코드가 정한다.
- **등록은 한 곳이다.** `WebMvcPlatformAutoConfiguration` 의 `@ConditionalOnMissingBean` bean 하나뿐이다.
`app.web.mvc.enabled=false` 면 이 핸들러·요청 id 필터·JSON 본문 상한·중복 키 거부가 함께 빠지고,
서비스가 셋을 직접 준다. 같은 타입 bean 을 주면 그것만 쓰인다(리뷰 02-10, `WebMvcPlatformAutoConfigurationTest`).
- `adapter-web` 에 위치하는 이유: 실행 앱이 어떤 sample 모듈에도 의존하지 않고 envelope 형식 에러 응답을
제공하도록.
- **`spanErrorRecorder`.** 프로덕션 코드를 특정 트레이서
@@ -220,6 +233,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
| `IllegalArgumentException` | `BAD_PARAMETER` | 400 | B3: 매퍼가 아닌 호출자의 일반 예외 |
| `ConstraintViolationException` | `VALIDATION_FAILED` | 400 | 정규화된 field + allowlisted reason code/fixed message 리스트를 details 로. interpolated message와 iterable key/index는 미노출 |
| `MethodArgumentTypeMismatchException` | `BAD_PARAMETER` | 400 | parameter·expectedType 을 details 로 |
| `HandlerMethodValidationException` | `VALIDATION_FAILED` | 400 | 컨트롤러 파라미터 제약(`@RequestParam @Max(10)`) 위반. 요청 본문 위반과 같은 코드·같은 details 모양(field=파라미터 이름, code=제약). 거절된 값은 미노출(리뷰 02-08) |
| `InvalidIdempotencyKeyException` | `IDEMPOTENCY_KEY_INVALID` | 400 | `IdempotencyKeyHeader.parse` 가 헤더 누락·문법 밖을 거부. `details.reason` = `MISSING`/`MALFORMED`, 키 원문 미노출(리뷰 02-12) |
| `InvalidBearerTokenException` | `INVALID_TOKEN` | 코드 상태 | |
| `AuthenticationException` | `UNAUTHENTICATED` | 코드 상태 | |
| `AccessDeniedException` | `SecurityErrorClassifier` 결정(예: `AUTHZ_INSUFFICIENT_PERMISSION`) | 분류기 결정 | 메서드-시큐리티 거부가 컨트롤러를 빠져나오면 여기 도달. 필터 계층 `EnvelopeAccessDeniedHandler` 와 **동일한 세분화 코드**를 내도록 무상태 classifier 에 위임 |
@@ -238,7 +253,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
| `MethodArgumentNotValidException` | `VALIDATION_FAILED` | 코드 상태 | 정규화된 field + allowlisted reason code/fixed message 리스트를 details 로. rejectedValue/defaultMessage/iterable key/index는 secret/PII 가능성이 있어 미노출 |
| `HttpMessageNotReadableException` | `VALIDATION_FAILED` | 코드 상태 | cause 클래스명을 details 로 |
| `NoHandlerFoundException`, `NoResourceFoundException` | `ROUTE_NOT_FOUND` | 코드 상태 | controller/static-resource 어느 404 경로도 같은 Envelope를 사용하고 raw request URL을 echo하지 않음 |
| 그 밖의 Spring MVC 예외(`MissingServletRequestParameterException`, `MissingRequestHeaderException`, `MissingServletRequestPartException`, `ServletRequestBindingException` …) | 상태 → `OperationalError`(4xx 는 대개 `BAD_PARAMETER`) | 코드 상태 | `handleExceptionInternal` override. problem+json 이 새지 않게 |
| `AsyncRequestTimeoutException` | `REQUEST_TIMEOUT` | 503 (retryable=true) | Spring 이 503 으로 분류한 일시적 시간 초과. 이전에는 `INTERNAL_ERROR` 500 이었다(리뷰 02-08) |
| 그 밖의 Spring MVC 예외(`MissingServletRequestParameterException`, `MissingRequestHeaderException`, `MissingServletRequestPartException`, `ServletRequestBindingException` …) | 상태 → 코드(4xx 는 대개 `BAD_PARAMETER`, 나머지 5xx 는 `INTERNAL_ERROR`) | 코드 상태 | `handleExceptionInternal` override. problem+json 이 새지 않게 |
| `ApiErrorCarrier` (위에 없는 adopter 예외 포함) | `errorCode()` | 코드 결정 | `handleCarrier` 한 분기 |
| `Exception` (catch-all) | `INTERNAL_ERROR` | 500 | span 에러 기록 + 불투명 문구(`ClientErrorMessages.OPAQUE`) |
@@ -258,6 +274,16 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
Boot `JsonMapper` 에 등록한다(shared-contract 는 Jackson 에 의존하지 않으므로 타입에 애너테이션을
달지 않는다). 키 목록과 근거는 `docs/web/http-contract.md` §1, 원문 키 집합 단언은
`EnvelopeWireShapeTest`.
- **이미 직렬화된 `byte[]` 본문은 감싸지 않는다.** 그 본문을 쓰는 converter 는 받은 값을 그대로 복사하므로
envelope 객체를 받으면 500 으로 끝난다. springdoc 이 OpenAPI 문서를 `byte[]` 로 돌려주어, 감싸던 시절에는
실행 중인 앱의 `/api/v3/api-docs` 가 항상 500 이었다(리뷰 09-04). `String` 반환은 감싸되 JSON 문자열로
직렬화해 넘긴다(리뷰 02-06). 단언은 `EnvelopeBodyAdviceTest`, 샘플 전체 조합의 `SampleApiDocsSystemTest`.
- **`String` 반환도 JSON 클라이언트에게는 Envelope 다.** `String` 은 `StringHttpMessageConverter` 가
Jackson 보다 먼저 고른다. 예전에는 그 컨버터에 `Envelope` 객체를 넘겨 `Accept: application/json` 이면
`ClassCastException` 500, `*/*` 면 200 text 였다(리뷰 02-06). 지금은 String 컨버터가 JSON 을 쓰게 될 때
advice 가 같은 mapper 로 Envelope 를 문자열로 직렬화해 넘긴다. 텍스트를 요청한 클라이언트는 그대로
문자열을 받는다. ArchUnit 으로 `String` 반환을 금지하는 안은 버렸다: `text/plain` 엔드포인트의 정당한
용도를 막고, 규칙을 돌리지 않는 서비스에는 함정이 그대로 남는다.
- 위치: sample 모듈이 아니라 adapter-web. 실행 앱은 adapter-web 에 의존하지만 sample-portfolio 에는 의존하지
않으므로, 응답 래핑이 실제로 동작하려면 여기 있어야 한다.
@@ -280,7 +306,11 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
`WebMvcRequestIdFilter` 의 것이다.
- **MDC 키 정책(D11/D19).** `MdcKeys` 의 snake_case 키 사용.
- **인바운드 id 헤더(D14/D15).** `X-Request-Id` 는 기본적으로 받지 않고 서버가 만든다(신뢰 설정 시 안전 문자만).
`X-Correlation-Id` 는 사용 전 sanitize(CR/LF + control 제거) 및 길이 제한. 부재/공백은 서버 생성.
`X-Correlation-Id` 는 요청 id 와 같은 규칙(`[A-Za-z0-9._-]{1,128}`, 앞뒤 공백 제거)을 통과하면 그대로
잇고, 아니면 서버가 새로 만든다. 예전에는 제어문자만 지우고 200자까지 그대로 내보내 공백·유니코드·DEL 이
응답 헤더와 `meta.correlationId` 에 실렸고, 짝 프론트의 envelope 검증(`[A-Za-z0-9._:-]{1,128}`)이 그
응답 전체를 거절했다(리뷰 02-11). 고친 값을 쓰지 않고 바꾸는 이유: 고친 값은 더 이상 호출자의 값이 아니라
상관관계를 잇지 못한다.
- **W3C `traceparent`(D5/D7/D4).** 유효한 인바운드 traceparent 가 있으면 채택해 그 `traceId`→MDC `trace_id`,
`spanId`→`span_id`. 부재/공백/무효면 fresh ROOT traceparent 생성(32-hex traceId, 16-hex spanId,
sampled=false)하여 MDC `trace_id` 가 **항상** 의미 있는 W3C id 이고 절대 null 이 아니게 한다(D4: 추적 비활성
@@ -351,6 +381,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
`X-RateLimit-*` 헤더를 포함한다(generated_if_missing=true).
- 한도 초과 거부 응답의 세 보장(RATE_LIMIT category + retryable + `Retry-After`)이 클라이언트가 이를 retryable
의존성 장애로 오분류하는 것을 막는다.
- 본문은 `EnvelopeResponseWriter` 로 쓴다(UTF-8).
---
@@ -369,6 +400,18 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
는 `Access-Control-Allow-Credentials: true` 와 함께 보낼 수 없다. Spring 런타임 검사에 의존하지 않고 기동
시점에 fail-fast 거부.
### CorsExposedHeaders
- 브라우저는 CORS 안전 목록 밖의 응답 헤더를 `Access-Control-Expose-Headers` 에 없으면 숨긴다. 예전에는
노출 목록이 비어 cross-origin 클라이언트가 `Retry-After`·`X-Request-Id`·`Location`·tus offset 을 못
읽었다(리뷰 02-05).
- `SecurityConfig` 는 `CorsExposedHeaders.PLATFORM`(이 leaf 가 쓰는 `Retry-After`, `X-Request-Id`,
`X-Correlation-Id`, `traceparent`, `Location`, `ETag`, `X-RateLimit-*`)에 모든 `CorsExposedHeaders` bean 을
더해 노출한다. 헤더를 쓰는 모듈이 기여한다(`RestrictedPathRule` 과 같은 방식). web-fileserver 는 tus·draft-12
헤더와 `Content-Disposition`·`Accept-Ranges` 를 기여한다.
- 설정 키(env)로 열지 않은 이유: 노출할 헤더는 코드가 쓰는 헤더라 운영자가 고를 값이 아니다. env 로 두면
기본 배포가 계속 깨지거나 모듈과 목록이 따로 논다. `*` 는 credentials 모드에서 리터럴 이름으로 취급돼
쓰지 않는다. 노출 헤더는 실제 응답에만 붙는다(preflight 에는 의미가 없다).
### EdgeRateLimitTransportSettings
- `app.rate-limit.*`은 HTTP enforcement, default policy ID, pseudonymization key version,
@@ -389,6 +432,16 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
Jackson 이 역직렬화하지 못해 absent / explicit-null 구분이 조용히 붕괴된다.
- 스켈레톤 전역 web 관심사(공유 `Patch<T>` 타입과 짝)라 도메인 샘플 모듈이 아니라 adapter-web 에 위치.
### IdempotencyKeyHeader
- KEYED 엔드포인트가 헤더를 키로 바꾸는 유일한 지점(리뷰 02-12). 문법: 보이는 ASCII(`0x21`–`0x7E`)
1~256자, trim·재작성 없음 — 짝 프론트의 `isValidIdempotencyKey` 와 같은 규칙.
- 누락과 형식 오류는 둘 다 `400 IDEMPOTENCY_KEY_INVALID`(`details.reason` = `MISSING`/`MALFORMED`).
헤더는 `required = false` 로 받고 `IdempotencyKeyHeader.parse` 를 부른다. `required = true` 면 누락이
`BAD_PARAMETER` 로 먼저 나간다.
- 공용으로 만든 것은 추출뿐이다. claim·fingerprint·replay 는 use case 와 `IdempotencyExecutor` 가 소유한다
(아래 idempotency 절). 대안 — 엔드포인트마다 검증(현상 유지)은 복사본이 갈라지고, 모든 POST 에 강제하는
필터는 KEYED 가 아닌 엔드포인트까지 막아 버렸다.
### ApiHeaders
- 인바운드 web 어댑터 전역의 HTTP 헤더명 상수 — `docs/registries/headers.yaml`의
코드 미러. 리터럴을 중앙집중해 controller/filter/advice 가 casing 으로 drift 하지 않게 하고, 레지스트리
@@ -415,6 +468,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
참조하지 않고 event-id fallback 정책만 소유한다.
### HeaderSanitizer
- 이제 `X-Correlation-Id` 는 쓰지 않는다(요청 id 규칙으로 바뀜, 리뷰 02-11). 공개 유틸리티로 남아 있다.
- 인바운드 헤더 값을 MDC/로그 도달 전에 무해화(D14, OWASP-LOG-C3/C5, CWE-117). 스켈레톤은 구조화 JSON 로깅을
가정하므로 위협은 CR/LF/제어문자를 통한 로그 라인 위조 — 값은 보존하되 `\r`/`\n`/ASCII 제어문자(`< 0x20`)를
제거 후 길이 제한.
@@ -436,6 +490,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
- 필드 `RETRY_AFTER_SECONDS` 는 error-codes.yaml 의 `retry_after_seconds` 컬럼 미러.
이 advisor 가 유일한 Retry-After 노출 지점이라 여기 중앙화한다.
`DEPENDENCY_4XX_CLIENT` 는 비재시도(retryable=false)라 `shouldAdvise` 가드로 empty 반환.
- 다른 leaf 가 소유한 코드는 이 표에 이름으로 넣지 않고 `RetryAfterHint` 를 구현해 값을 스스로 말한다
(web-advanced `ADMISSION_REFUSED` = 1초).
- `IDEMPOTENT_IN_FLIGHT` 는 2초: 기본 processing lease(30s)보다 짧아 첫 시도가 끝날 수 있는 동안
같은 키로 다시 묻게 한다. 근거와 클라이언트 행동은 `docs/web/http-contract.md` §2.
@@ -482,6 +538,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
replay / in-flight arbitration은 application use case가 소유**한다.
- web leaf에는 별도 DB replay 엔진을 두지 않는다. 같은 요청 의미를 web/application 두 계층이 서로 다른
fingerprint로 판정하면 동일 key의 의미가 endpoint마다 달라지기 때문이다.
- 헤더 → 키 변환은 `IdempotencyKeyHeader` 하나로 한다(위 settings / config / http 절).
- production 예시는 sample의 poster image publication 경로다. controller는 key를 받기만 하고,
`PublishPosterImageUseCase`가 application `IdempotencyExecutor`를 사용한다.
- response-loss system fixture도 동일한 application executor를 사용해, 연결이 끊긴 뒤 같은 key 재시도에서
+8 -5
View File
@@ -12,6 +12,9 @@ plugins {
// HTTP / web adapters. Depends on application and shared operational contracts.
dependencies {
implementation project(':application-core')
// A controller turns a path segment into the domain identifier the query carries
// (registry edge `adapter:inbound:web -> domain-core`); docs/manual/02-new-feature.md step 4.
implementation project(':domain-core')
// No `application-notification`. The notification HTTP surface is
// `adapter:inbound:web-notification`, which depends on this leaf rather than living inside it.
// `PresentationWebConfigTest` names the capability controllers as the examples of an absolute
@@ -38,6 +41,11 @@ dependencies {
// The operation controller's contract test drives the real use cases over the port owners'
// fakes (operation store, outbox, transaction port).
testImplementation testFixtures(project(':application-core'))
// The operation-id test runs the controller with the real UUIDv7 generator: the id is also the
// event id, and only the generator's output proves the platform will accept it.
testImplementation project(':adapter:outbound:identifier')
// A feature controller's contract test drives its use cases over the domain ports' fakes.
testImplementation testFixtures(project(':domain-core'))
}
tasks.named('test') {
@@ -139,21 +147,18 @@ strictTestLanes {
system()
sourceSet = 'systemTest'
description = 'Runs the Stable HTTP system contract against the default Tomcat runtime.'
jvmArgs '-Duser.timezone=UTC'
}
lane('performanceTest') {
performance()
sourceSet = 'performanceTest'
description = 'Runs Tomcat load, resource-bound, slow-client and graceful-shutdown checks.'
jvmArgs '-Duser.timezone=UTC'
}
lane('webJettyPerformanceTest') {
performance()
sourceSet = 'jettyCompatTest'
description = 'Runs Jetty load, resource-bound, slow-client and graceful-shutdown checks.'
jvmArgs '-Duser.timezone=UTC'
requires('dev.caskeleton.adapter.inbound.web.testkit.performance.JettyLoadAndShutdownIT')
}
@@ -161,7 +166,6 @@ strictTestLanes {
system()
sourceSet = 'jettyCompatTest'
description = 'Runs the Stable HTTP system contract against a real Jetty instead of Tomcat.'
jvmArgs '-Duser.timezone=UTC'
requires(
'dev.caskeleton.adapter.inbound.web.testkit.fault.JettyCommitThenConnectionResetIT',
'dev.caskeleton.adapter.inbound.web.testkit.mvc.JettyWebContractIT',
@@ -184,7 +188,6 @@ strictTestLanes {
tag = 'security-boundary'
description = 'Runs hermetic JWT/JWKS and CORS filter-boundary contracts with no skips.'
shouldRunAfter 'test'
jvmArgs '-Duser.timezone=UTC'
rejectSkipped = true
}
}
+1
View File
@@ -12,6 +12,7 @@ com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.5=compileClasspath,j
com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
com.fasterxml:classmate:1.7.3=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.github.f4b6a3:uuid-creator:6.1.1=jettyCompatTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
com.github.spotbugs:spotbugs:4.10.2=spotbugs
@@ -1,21 +1,18 @@
package dev.caskeleton.adapter.inbound.web.auth;
import dev.caskeleton.adapter.inbound.web.error.ErrorResponseFactory;
import dev.caskeleton.adapter.inbound.web.error.EnvelopeResponseWriter;
import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor;
import dev.caskeleton.shared.error.OperationalError;
import dev.caskeleton.shared.response.Envelope;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import tools.jackson.databind.ObjectMapper;
/**
* Writes a classified security failure to the servlet response as the skeleton-wide {@link
* Writes a classified security failure to the servlet response as the skeleton-wide {@code
* Envelope} (same shape as every other error), and logs it safely. The response body and log line
* carry only redacted, client-safe metadata. See README for the design rationale.
*/
@@ -39,10 +36,6 @@ class AuthErrorResponseWriter {
request.getMethod(),
request.getRequestURI());
response.setStatus(code.httpStatus());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
// A 401 response carries a minimal WWW-Authenticate header (no issuer / token detail).
if (code.httpStatus() == 401) {
response.setHeader(
@@ -55,7 +48,6 @@ class AuthErrorResponseWriter {
.ifPresent(
seconds -> response.setHeader(HttpHeaders.RETRY_AFTER, Integer.toString(seconds)));
Envelope<Void> body = ErrorResponseFactory.body(code, null);
objectMapper.writeValue(response.getWriter(), body);
EnvelopeResponseWriter.write(response, code, objectMapper);
}
}
@@ -0,0 +1,54 @@
package dev.caskeleton.adapter.inbound.web.auth;
import dev.caskeleton.adapter.inbound.web.http.ApiHeaders;
import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter;
import java.util.List;
import java.util.Objects;
/**
* Response headers a cross-origin browser client may read.
*
* <p>A browser hides every response header outside the CORS safelist unless the response names it
* in {@code Access-Control-Expose-Headers}. Without that, a client on another origin sees {@code
* Retry-After}, {@code X-Request-Id}, {@code Location} and the tus offsets as {@code null}: it
* cannot back off, quote a request id, follow a 202 or resume an upload.
*
* <p>The list is code, not configuration: these are headers this code writes, so the module that
* writes one contributes it, the same way {@link RestrictedPathRule} is contributed. {@link
* #PLATFORM} is what this leaf writes; a capability that writes more (the fileserver's tus and
* draft-12 headers) registers its own bean, and {@link SecurityConfig} exposes the union. A {@code
* *} would not do: with credentials the browser reads it as a header literally named {@code *}.
*
* @param headerNames header names to expose; never empty
*/
public record CorsExposedHeaders(List<String> headerNames) {
/** The headers {@code adapter:inbound:web} itself writes on a response. */
public static final CorsExposedHeaders PLATFORM =
new CorsExposedHeaders(
List.of(
ApiHeaders.RETRY_AFTER,
WebMvcRequestIdFilter.REQUEST_ID_HEADER,
WebMvcRequestIdFilter.CORRELATION_ID_HEADER,
WebMvcRequestIdFilter.TRACEPARENT_HEADER,
ApiHeaders.LOCATION,
ApiHeaders.ETAG,
ApiHeaders.X_RATELIMIT_LIMIT,
ApiHeaders.X_RATELIMIT_REMAINING,
ApiHeaders.X_RATELIMIT_RESET));
public CorsExposedHeaders {
Objects.requireNonNull(headerNames, "headerNames");
if (headerNames.isEmpty()) {
throw new IllegalArgumentException("headerNames must not be empty");
}
headerNames.forEach(
name -> {
if (name == null || name.isBlank() || "*".equals(name.strip())) {
throw new IllegalArgumentException(
"an exposed header is a concrete header name, not blank or \"*\"");
}
});
headerNames = List.copyOf(headerNames);
}
}
@@ -70,11 +70,12 @@ public class SecurityConfig {
AccessDeniedHandler accessDeniedHandler,
org.springframework.beans.factory.ObjectProvider<PrimitiveSessionSecurityContextRepository>
sessionSecurityContextRepository,
org.springframework.beans.factory.ObjectProvider<RestrictedPathRule> restrictedPaths)
org.springframework.beans.factory.ObjectProvider<RestrictedPathRule> restrictedPaths,
CorsConfigurationSource corsConfigurationSource)
throws Exception {
String[] publicPaths = securitySettings.publicPaths().toArray(new String[0]);
java.util.List<RestrictedPathRule> restricted = restrictedPaths.orderedStream().toList();
http.cors(c -> c.configurationSource(corsConfigurationSource()))
http.cors(c -> c.configurationSource(corsConfigurationSource))
// Disable Spring Security's default Cache-Control writer; CacheControlFilter
// owns the cache header policy. See README for the design rationale.
.headers(headers -> headers.cacheControl(cache -> cache.disable()))
@@ -141,8 +142,14 @@ public class SecurityConfig {
return http.build();
}
/**
* The CORS policy. Exposed headers are {@link CorsExposedHeaders#PLATFORM} plus every contributed
* {@link CorsExposedHeaders} bean; the browser applies them to actual responses, not preflights.
*/
@Bean
public CorsConfigurationSource corsConfigurationSource() {
public CorsConfigurationSource corsConfigurationSource(
org.springframework.beans.factory.ObjectProvider<CorsExposedHeaders>
contributedExposedHeaders) {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
if (!corsSettings.enabled()) {
return source; // no patterns registered -> Spring uses null config -> CORS inactive
@@ -153,6 +160,10 @@ public class SecurityConfig {
cfg.setAllowedHeaders(corsSettings.allowedHeaders());
cfg.setAllowCredentials(corsSettings.allowCredentials());
cfg.setMaxAge(corsSettings.maxAgeSeconds());
java.util.Set<String> exposed =
new java.util.LinkedHashSet<>(CorsExposedHeaders.PLATFORM.headerNames());
contributedExposedHeaders.orderedStream().forEach(c -> exposed.addAll(c.headerNames()));
cfg.setExposedHeaders(java.util.List.copyOf(exposed));
source.registerCorsConfiguration("/**", cfg);
return source;
}
@@ -3,29 +3,58 @@ package dev.caskeleton.adapter.inbound.web.envelope;
import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory;
import dev.caskeleton.shared.response.BulkEnvelope;
import dev.caskeleton.shared.response.Envelope;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
/**
* Wraps every JSON controller response in {@link Envelope} unless it is already an envelope
* variant, so the wire shape is always {@code {success, data | error, traceId}}. See README for the
* variant, so the wire shape is always {@code {success, data | error, meta}}. See README for the
* design rationale.
*
* <p>Skipped: already-{@link Envelope}/{@link BulkEnvelope} bodies, null/void (DELETE 204),
* non-JSON content types.
* non-JSON content types, and {@code byte[]} bodies. A {@code byte[]} body is already serialized
* and {@link ByteArrayHttpMessageConverter} copies it verbatim; handed an envelope object it fails
* the request with a 500. springdoc returns its OpenAPI document this way, so wrapping it broke
* {@code /v3/api-docs} on every composition that carries this advice (review 2026-11-01 09-04).
*
* <p>A {@code String} return value is written by {@link StringHttpMessageConverter}, which Spring
* picks before Jackson. Handing that converter an {@link Envelope} object is a {@code
* ClassCastException} and a 500 for every JSON client, while {@code curl} with {@code *}{@code /*}
* still sees {@code 200 text/plain}. So when the String converter is about to write JSON, the
* envelope is serialised here, with the same mapper and wire rules, and the converter writes that
* text (review 2026-11-01 02-06). A text client still gets the plain string.
*/
@RestControllerAdvice
public class EnvelopeBodyAdvice implements ResponseBodyAdvice<Object> {
private final ObjectMapper objectMapper;
/** Spring entry point: Boot's mapper, which already carries the envelope wire rules. */
@Autowired
public EnvelopeBodyAdvice(ObjectMapper objectMapper) {
this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper");
}
/** For standalone MockMvc and explicit wiring: a mapper with only the envelope wire rules. */
public EnvelopeBodyAdvice() {
this(JsonMapper.builder().addModule(EnvelopeWireFormatConfig.module()).build());
}
@Override
public boolean supports(
MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
return !ByteArrayHttpMessageConverter.class.isAssignableFrom(converterType);
}
@Override
@@ -45,6 +74,10 @@ public class EnvelopeBodyAdvice implements ResponseBodyAdvice<Object> {
if (selectedContentType != null && !MediaType.APPLICATION_JSON.includes(selectedContentType)) {
return body;
}
return Envelope.ok(body, ResponseMetaFactory.fromMdc());
Envelope<Object> envelope = Envelope.ok(body, ResponseMetaFactory.fromMdc());
if (StringHttpMessageConverter.class.isAssignableFrom(selectedConverterType)) {
return objectMapper.writeValueAsString(envelope);
}
return envelope;
}
}
@@ -25,6 +25,11 @@ public class EnvelopeWireFormatConfig {
@Bean
public SimpleModule envelopeWireFormatModule() {
return module();
}
/** The module itself, for a writer that has no Boot mapper to take it from. */
static SimpleModule module() {
SimpleModule module = new SimpleModule("EnvelopeWireFormatModule");
module.setMixInAnnotation(Envelope.class, OmitNullFields.class);
module.setMixInAnnotation(BulkEnvelope.class, OmitNullFields.class);
@@ -0,0 +1,15 @@
package dev.caskeleton.adapter.inbound.web.error;
/**
* An {@link dev.caskeleton.shared.error.ApiErrorCarrier} that has bounded, client-safe structure to
* put in {@code error.details} — a JSON pointer the client sent, field names from a server
* allowlist. {@link GlobalExceptionHandler#handleCarrier(Exception)} copies it to the wire.
*
* <p>Never the exception message, a server value, or anything the caller may not read: what this
* returns is published verbatim.
*/
public interface ClientSafeErrorDetails {
/** The value of {@code error.details}: a map or list of plain values. */
Object clientDetails();
}
@@ -6,6 +6,7 @@ import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
@@ -57,6 +58,16 @@ final class ClientSafeValidationDetails {
return detail(field, ruleFor(error.getCode()));
}
/**
* A violation of a constraint on a controller parameter. The last resolvable code is the bare
* constraint name ({@code Max}); the more specific ones name the controller method.
*/
static Map<String, Object> from(String parameter, MessageSourceResolvable error) {
String[] codes = error.getCodes();
String rawCode = codes == null || codes.length == 0 ? null : codes[codes.length - 1];
return detail(normalize(parameter), ruleFor(rawCode));
}
private static Map<String, Object> detail(String field, Rule rule) {
return Map.of("field", field, "code", rule.code(), "message", rule.message());
}
@@ -0,0 +1,42 @@
package dev.caskeleton.adapter.inbound.web.error;
import dev.caskeleton.shared.error.ApiErrorCode;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.springframework.http.MediaType;
import tools.jackson.databind.ObjectMapper;
/**
* Writes a failure {@code Envelope} straight to the servlet response, for the paths that refuse a
* request before a message converter exists to do it: the security entry point, the access-denied
* handler and the rate-limit interceptor.
*
* <p>The charset is the reason this is one class. A converter-written response is UTF-8 because the
* converter says so; a hand-written one is whatever the container defaults to, and Tomcat's default
* is ISO-8859-1, which turns the Korean client message into question marks. Each writer used to
* remember that on its own, and one forgot (review 2026-11-01 02-04).
*
* <p>Headers that belong to one refusal — {@code WWW-Authenticate}, {@code Retry-After}, {@code
* X-RateLimit-*} — stay with the caller and must be set before this writes the body.
*/
public final class EnvelopeResponseWriter {
private EnvelopeResponseWriter() {}
/**
* Sets the code's status and writes its envelope as UTF-8 JSON.
*
* @param response the response, not yet committed
* @param code the failure to answer with
* @param objectMapper Boot's mapper, so the envelope's wire rules apply
*/
public static void write(
HttpServletResponse response, ApiErrorCode code, ObjectMapper objectMapper)
throws IOException {
response.setStatus(code.httpStatus());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
objectMapper.writeValue(response.getWriter(), ErrorResponseFactory.body(code, null));
}
}
@@ -13,6 +13,7 @@ import dev.caskeleton.shared.error.PersistenceFailureException;
import dev.caskeleton.shared.response.Envelope;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import jakarta.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -20,6 +21,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
@@ -27,14 +29,20 @@ import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.validation.method.ParameterErrors;
import org.springframework.validation.method.ParameterValidationResult;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;
@@ -72,11 +80,18 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
this.spanErrorRecorder = spanErrorRecorder;
}
/**
* An {@link IllegalArgumentException} is read as "the request was wrong" and answered 400. One
* WARN line names the exception type, so a 400 that is really a misassembled server — code that
* should have thrown {@link IllegalStateException} — still leaves a trace. The message is not
* logged: it may echo request input.
*/
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Envelope<Void>> handleIllegalArgument(IllegalArgumentException ex) {
if (ex instanceof ApiErrorCarrier) {
return handleCarrier(ex);
}
log.warn("request refused as BAD_PARAMETER by {}", ex.getClass().getName());
return ErrorResponseFactory.envelope(OperationalError.BAD_PARAMETER, null);
}
@@ -178,7 +193,8 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
ResponseEntity.BodyBuilder builder = ResponseEntity.status(code.httpStatus());
RetryAfterAdvisor.retryAfterSeconds(code)
.ifPresent(seconds -> builder.header(ApiHeaders.RETRY_AFTER, String.valueOf(seconds)));
return builder.body(ErrorResponseFactory.body(code, null));
Object details = failure instanceof ClientSafeErrorDetails safe ? safe.clientDetails() : null;
return builder.body(ErrorResponseFactory.body(code, details));
}
private static PersistenceFailureException sanitizedPersistenceFailure(ApiErrorCode code) {
@@ -320,6 +336,53 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
HttpStatusCode.valueOf(OperationalError.ROUTE_NOT_FOUND.httpStatus()));
}
/**
* A Bean Validation constraint on a controller parameter ({@code @RequestParam @Max(10) int
* limit}) is the same violation as one on a request body, so it answers the same way: {@code
* VALIDATION_FAILED} with one bounded detail per violated parameter, never the rejected value.
*/
@Override
protected ResponseEntity<Object> handleHandlerMethodValidationException(
HandlerMethodValidationException ex,
HttpHeaders headers,
HttpStatusCode status,
WebRequest request) {
List<Map<String, Object>> violations = new ArrayList<>();
for (ParameterValidationResult result : ex.getParameterValidationResults()) {
if (result instanceof ParameterErrors errors) {
errors.getAllErrors().stream()
.map(ClientSafeValidationDetails::from)
.forEach(violations::add);
} else {
String parameter = parameterName(result.getMethodParameter());
result.getResolvableErrors().stream()
.map(error -> ClientSafeValidationDetails.from(parameter, error))
.forEach(violations::add);
}
}
return new ResponseEntity<>(
ErrorResponseFactory.body(OperationalError.VALIDATION_FAILED, violations),
HttpStatusCode.valueOf(OperationalError.VALIDATION_FAILED.httpStatus()));
}
/** The name the client used for the parameter: the binding annotation's, else the Java name. */
private static String parameterName(MethodParameter parameter) {
RequestParam param = parameter.getParameterAnnotation(RequestParam.class);
if (param != null && !param.name().isBlank()) {
return param.name();
}
RequestHeader header = parameter.getParameterAnnotation(RequestHeader.class);
if (header != null && !header.name().isBlank()) {
return header.name();
}
PathVariable path = parameter.getParameterAnnotation(PathVariable.class);
if (path != null && !path.name().isBlank()) {
return path.name();
}
String name = parameter.getParameterName();
return name == null ? "request" : name;
}
/**
* Every Spring MVC exception this class does not override individually — a missing required
* parameter, header or multipart part, a binding or conversion failure, an async timeout —
@@ -341,7 +404,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
&& servletRequest.getResponse().isCommitted()) {
return null;
}
OperationalError code = operationalErrorFor(statusCode);
ApiErrorCode code = errorCodeFor(statusCode);
if (code.httpStatus() >= 500) {
log.error("spring mvc failure classified as {}", code.code(), ex);
spanErrorRecorder.recordException(ex, code.code());
@@ -350,7 +413,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
ErrorResponseFactory.body(code, null), headers, HttpStatusCode.valueOf(code.httpStatus()));
}
private static OperationalError operationalErrorFor(HttpStatusCode status) {
private static ApiErrorCode errorCodeFor(HttpStatusCode status) {
return switch (status.value()) {
case 401 -> OperationalError.UNAUTHENTICATED;
case 403 -> OperationalError.FORBIDDEN;
@@ -362,6 +425,8 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
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;
default ->
status.is4xxClientError()
? OperationalError.BAD_PARAMETER
@@ -0,0 +1,55 @@
package dev.caskeleton.adapter.inbound.web.error;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.Category;
/**
* HTTP-only failure codes this adapter answers with, beside the skeleton-wide {@code
* OperationalError}. Like {@code RateLimitTransportError} they are not in {@code
* docs/registries/error-codes.yaml} (that registry is the {@code OperationalError} SSOT); their
* contract is {@code docs/web/http-contract.md} §4.
*/
public enum WebTransportError implements ApiErrorCode {
/**
* The servlet container's async timeout fired before the handler produced a result. Spring
* reports it as 503; it is transient, and the same request may finish next time.
*/
REQUEST_TIMEOUT(Category.TRANSIENT_DEPENDENCY, 503, true),
/**
* A KEYED endpoint got no {@code Idempotency-Key}, or one outside its grammar. Its own code so a
* client can tell "fix the key" from any other bad parameter.
*/
IDEMPOTENCY_KEY_INVALID(Category.VALIDATION, 400, false);
private final Category category;
private final int httpStatus;
private final boolean retryable;
WebTransportError(Category category, int httpStatus, boolean retryable) {
this.category = category;
this.httpStatus = httpStatus;
this.retryable = retryable;
}
@Override
public String code() {
return name();
}
@Override
public Category category() {
return category;
}
@Override
public int httpStatus() {
return httpStatus;
}
@Override
public boolean retryable() {
return retryable;
}
}
@@ -0,0 +1,51 @@
package dev.caskeleton.adapter.inbound.web.http;
import java.util.regex.Pattern;
/**
* A validated {@code Idempotency-Key} header value — the one place a KEYED endpoint turns the
* header into a key.
*
* <p>Grammar: 1 to 256 visible ASCII characters ({@code 0x21}–{@code 0x7E}), not trimmed or
* rewritten. It is the paired frontend's rule ({@code isValidIdempotencyKey}): fetch strips
* surrounding whitespace and refuses non-ByteString values, so anything outside it could not have
* been sent on purpose, and two keys differing only in whitespace would collide on the wire.
*
* <p>A missing header and a malformed one fail the same way, as {@link
* InvalidIdempotencyKeyException} — {@code 400 IDEMPOTENCY_KEY_INVALID} with {@code details.reason}
* — so a client can tell "fix the key" from any other bad parameter. Bind the header with {@code
* required = false} and call {@link #parse(String)}; a required binding would answer a missing key
* as a generic {@code BAD_PARAMETER} before this runs.
*
* <p>Only the extraction is shared. Claim, fingerprint and replay stay with the use case and {@code
* IdempotencyExecutor} (docs/web/http-contract.md §2).
*
* @param value the key exactly as the client sent it
*/
public record IdempotencyKeyHeader(String value) {
/** Longest key accepted, in characters (= bytes, the grammar being ASCII). */
public static final int MAX_LENGTH = 256;
private static final Pattern GRAMMAR = Pattern.compile("[\\x21-\\x7E]{1," + MAX_LENGTH + "}");
public IdempotencyKeyHeader {
if (value == null) {
throw InvalidIdempotencyKeyException.missing();
}
if (!GRAMMAR.matcher(value).matches()) {
throw InvalidIdempotencyKeyException.malformed();
}
}
/**
* Parses a header value as the request carried it.
*
* @param header the raw {@code Idempotency-Key} value, {@code null} when absent
* @return the validated key
* @throws InvalidIdempotencyKeyException when the header is absent or outside the grammar
*/
public static IdempotencyKeyHeader parse(String header) {
return new IdempotencyKeyHeader(header);
}
}
@@ -0,0 +1,48 @@
package dev.caskeleton.adapter.inbound.web.http;
import dev.caskeleton.adapter.inbound.web.error.ClientSafeErrorDetails;
import dev.caskeleton.adapter.inbound.web.error.WebTransportError;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import java.util.Map;
/**
* A KEYED request without a usable {@code Idempotency-Key}. Answered as {@code 400
* IDEMPOTENCY_KEY_INVALID}; {@code details.reason} is {@code MISSING} or {@code MALFORMED}. The key
* itself is never echoed.
*/
public final class InvalidIdempotencyKeyException extends IllegalArgumentException
implements ApiErrorCarrier, ClientSafeErrorDetails {
private static final long serialVersionUID = 1L;
private final String reason;
private InvalidIdempotencyKeyException(String reason, String message) {
super(message);
this.reason = reason;
}
static InvalidIdempotencyKeyException missing() {
return new InvalidIdempotencyKeyException(
"MISSING", "the Idempotency-Key header is required on this endpoint");
}
static InvalidIdempotencyKeyException malformed() {
return new InvalidIdempotencyKeyException(
"MALFORMED",
"the Idempotency-Key header must be 1.."
+ IdempotencyKeyHeader.MAX_LENGTH
+ " visible ASCII characters");
}
@Override
public ApiErrorCode errorCode() {
return WebTransportError.IDEMPOTENCY_KEY_INVALID;
}
@Override
public Map<String, Object> clientDetails() {
return Map.of("reason", reason);
}
}
@@ -20,18 +20,23 @@ import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
/**
* The HTTP adapter this leaf ships, minus its security posture: error envelope, filters, health
* endpoint, rate limiting and their settings. The JWT security chain is {@link
* WebSecurityAutoConfiguration}, a separate root an application can exclude on its own; method
* security is {@link WebMethodSecurityAutoConfiguration}, which stays when the chain is replaced.
* The HTTP adapter this leaf ships, minus its security posture: success envelope, filters, health
* endpoint, rate limiting and their settings. The error handler is not here: {@link
* WebMvcPlatformAutoConfiguration} defines it, once, behind {@code app.web.mvc.enabled}. The JWT
* security chain is {@link WebSecurityAutoConfiguration}, a separate root an application can
* exclude on its own; method security is {@link WebMethodSecurityAutoConfiguration}, which stays
* when the chain is replaced.
*
* <p>These used to be found by the composition root's component scan of the whole {@code
* dev.caskeleton} tree. Registering them here means an application gets them from this module being
* on its classpath, and its own scan never has to reach into adapter packages.
*
* <p>First among auto-configurations, which is where a scanned user configuration used to sit:
* {@link GlobalExceptionHandler} has to be defined before {@link WebMvcPlatformAutoConfiguration}
* offers its default.
* <p>First among auto-configurations, which is where a scanned user configuration used to sit.
*
* <p>{@link GlobalExceptionHandler} used to be imported here as well. That second, unconditional
* registration made {@code app.web.mvc.enabled=false} leave the handler in place while the request
* id filter and the JSON body ceiling went away, and it meant an adopter's handler of the same type
* sat beside this one rather than replacing it (review 2026-11-01 02-10).
*/
@AutoConfiguration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@@ -47,7 +52,6 @@ import org.springframework.core.Ordered;
HealthcheckController.class,
EnvelopeBodyAdvice.class,
EnvelopeWireFormatConfig.class,
GlobalExceptionHandler.class,
CacheControlFilter.class,
RequestLoggingFilter.class,
MdcCorrelationIdPortAdapter.class,
@@ -24,7 +24,9 @@ import tools.jackson.core.StreamReadFeature;
*
* <p>The {@code Envelope} error handler, the request-id filter and the request-body boundary (JSON
* size ceiling and duplicate-key refusal). HTTP errors are the {@code Envelope} this handler
* writes; {@code spring.mvc.problemdetails.enabled} stays false.
* writes; {@code spring.mvc.problemdetails.enabled} stays false. This is the only place the handler
* is registered, so {@code app.web.mvc.enabled=false} removes all four together: a service that
* turns the platform off supplies its own error handler, request ids and body ceiling.
*
* <p>Every bean is {@link ConditionalOnMissingBean}: the platform supplies the one that would
* otherwise be missing rather than the one that must be used.
@@ -27,8 +27,17 @@ import org.springframework.web.multipart.MaxUploadSizeExceededException;
* or understated body fails the read that crosses the ceiling.
*
* <p>The refusal is {@link MaxUploadSizeExceededException}, which the error handler already answers
* as {@code 413 PAYLOAD_TOO_LARGE} in the envelope. Other media types keep their own ceilings
* (multipart, form posts, upload protocols) and pass through untouched.
* as {@code 413 PAYLOAD_TOO_LARGE} in the envelope. {@code JsonBodyLimitFilterTest} pins both
* checks and the {@code +json} suffix types, so removing either one fails a test.
*
* <p><b>Only JSON is bounded here.</b> Multipart and form posts have their container ceilings, and
* the upload protocols (tus, draft-12, the raw file upload) and the notification callback read the
* stream themselves under their own limits. Every other body — {@code text/plain}, {@code
* application/octet-stream}, XML — has no platform ceiling: an endpoint that binds one with
* {@code @RequestBody String} or {@code byte[]} reads it to the end. Such an endpoint must bound
* the body itself. Bounding every media type except a list of exemptions was considered and not
* done: the raw upload accepts any content type on one path, so the exemption list would have to be
* per path and would turn a forgotten entry into a broken upload (review 2026-11-01 02-09).
*/
public final class JsonBodyLimitFilter extends OncePerRequestFilter implements Ordered {
@@ -2,7 +2,6 @@ package dev.caskeleton.adapter.inbound.web.mvc.filter;
import dev.caskeleton.adapter.inbound.web.core.WebRequestId;
import dev.caskeleton.adapter.inbound.web.core.WebTraceId;
import dev.caskeleton.adapter.inbound.web.observability.HeaderSanitizer;
import dev.caskeleton.shared.observability.MdcKeys;
import dev.caskeleton.shared.tracing.ActiveTrace;
import dev.caskeleton.shared.tracing.TraceParent;
@@ -53,7 +52,10 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements
/** The header a client may propose a request id in. */
public static final String REQUEST_ID_HEADER = "X-Request-Id";
/** The header a caller correlates its own requests by; sanitized, never trusted as an id. */
/**
* The header a caller correlates its own requests by. Kept when it matches the request id rule,
* replaced with a server-minted value when it does not.
*/
public static final String CORRELATION_ID_HEADER = "X-Correlation-Id";
/** The W3C trace context header. */
@@ -65,8 +67,6 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements
/** Printable, bounded, no separators a log parser would act on. */
private static final Pattern SAFE_IDENTIFIER = Pattern.compile("[A-Za-z0-9._-]{1,128}");
private static final int MAX_CORRELATION_ID_LENGTH = 200;
private final boolean trustInboundRequestId;
private final int order;
private final ActiveTrace activeTrace;
@@ -179,11 +179,16 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements
false));
}
/**
* The same rule as a request id, and replaced rather than repaired when it fails. Stripping
* control characters and cutting at 200 used to let spaces, Unicode and {@code DEL} through to
* the response header and {@code meta.correlationId}, where the paired frontend's envelope check
* ({@code [A-Za-z0-9._:-]{1,128}}) refuses the whole response (review 2026-11-01 02-11). A
* repaired value would also no longer be the caller's, so it could not correlate anything.
*/
private static String resolveCorrelationId(HttpServletRequest request) {
String clean =
HeaderSanitizer.sanitize(
request.getHeader(CORRELATION_ID_HEADER), MAX_CORRELATION_ID_LENGTH);
return clean == null || clean.isBlank() ? UUID.randomUUID().toString() : clean;
return sanitized(request.getHeader(CORRELATION_ID_HEADER))
.orElseGet(() -> UUID.randomUUID().toString());
}
private static Optional<String> sanitized(String candidate) {
@@ -40,6 +40,9 @@ public final class RetryAfterAdvisor {
if (!shouldAdvise(code)) {
return OptionalInt.empty();
}
if (code instanceof RetryAfterHint hint) {
return OptionalInt.of(hint.retryAfterSeconds());
}
Integer seconds = RETRY_AFTER_SECONDS.get(code.code());
return seconds == null ? OptionalInt.empty() : OptionalInt.of(seconds);
}
@@ -0,0 +1,14 @@
package dev.caskeleton.adapter.inbound.web.observability;
/**
* An {@link dev.caskeleton.shared.error.ApiErrorCode} that names its own {@code Retry-After}.
*
* <p>{@link RetryAfterAdvisor}'s table covers the skeleton-wide codes. A code owned by another leaf
* (web-advanced's admission refusal) states its delay here instead of being written into this
* leaf's table by name. Only consulted when the code is retryable.
*/
public interface RetryAfterHint {
/** Seconds a client should wait before sending the same request again; positive. */
int retryAfterSeconds();
}
@@ -7,6 +7,7 @@ import dev.caskeleton.application.idempotency.RequestFingerprint;
import dev.caskeleton.application.operation.CancelDurableOperationCommand;
import dev.caskeleton.application.operation.CancelDurableOperationUseCase;
import dev.caskeleton.application.operation.DurableOperationId;
import dev.caskeleton.application.operation.DurableOperationIdFactory;
import dev.caskeleton.application.operation.GetDurableOperationQuery;
import dev.caskeleton.application.operation.GetDurableOperationUseCase;
import dev.caskeleton.application.operation.OperationAcceptance;
@@ -18,7 +19,6 @@ import jakarta.validation.Valid;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
@@ -51,6 +51,7 @@ public class DurableOperationController {
private final SubmitDurableOperationUseCase submit;
private final GetDurableOperationUseCase get;
private final CancelDurableOperationUseCase cancel;
private final DurableOperationIdFactory operationIds;
/**
* A controller over the three operation use cases.
@@ -58,12 +59,15 @@ public class DurableOperationController {
* @param submit accepts work
* @param get reads one operation
* @param cancel requests cancellation
* @param operationIds mints the id of a new operation (a UUIDv7: it is also the event id)
*/
public DurableOperationController(
SubmitDurableOperationUseCase submit,
GetDurableOperationUseCase get,
CancelDurableOperationUseCase cancel) {
CancelDurableOperationUseCase cancel,
DurableOperationIdFactory operationIds) {
this.submit = Objects.requireNonNull(submit, "submit");
this.operationIds = Objects.requireNonNull(operationIds, "operationIds");
this.get = Objects.requireNonNull(get, "get");
this.cancel = Objects.requireNonNull(cancel, "cancel");
}
@@ -71,9 +75,10 @@ public class DurableOperationController {
/**
* Accepts an operation.
*
* <p>{@code 202} with the operation's {@code Location}. The id is minted here; a resubmission of
* the same work by the same caller is recognised by its payload fingerprint and answered with the
* operation that already exists, {@code alreadyAccepted} true and the same {@code Location}.
* <p>{@code 202} with the operation's {@code Location}. The id is minted here, by {@link
* DurableOperationIdFactory}; a resubmission of the same work by the same caller is recognised by
* its payload fingerprint and answered with the operation that already exists, {@code
* alreadyAccepted} true and the same {@code Location}.
*/
@PostMapping
public ResponseEntity<Envelope<OperationAcceptedHttpResponse>> submit(
@@ -83,7 +88,7 @@ public class DurableOperationController {
OperationAcceptance acceptance =
submit.handle(
new OperationCommand(
new DurableOperationId(UUID.randomUUID().toString()),
operationIds.newOperationId(),
request.operationName(),
principalId(principal),
tenantOf(principal),
@@ -1,18 +1,16 @@
package dev.caskeleton.adapter.inbound.web.ratelimit;
import dev.caskeleton.adapter.inbound.web.error.ErrorResponseFactory;
import dev.caskeleton.adapter.inbound.web.error.EnvelopeResponseWriter;
import dev.caskeleton.adapter.inbound.web.http.ApiHeaders;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.OperationalError;
import dev.caskeleton.shared.ratelimit.RateLimitDecision;
import dev.caskeleton.shared.ratelimit.RateLimitOutcome;
import dev.caskeleton.shared.response.Envelope;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import tools.jackson.databind.ObjectMapper;
@@ -75,10 +73,7 @@ public final class RateLimitInterceptor implements HandlerInterceptor {
}
private void reject(HttpServletResponse response, ApiErrorCode error) throws Exception {
response.setStatus(error.httpStatus());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
Envelope<Void> body = ErrorResponseFactory.body(error, null);
objectMapper.writeValue(response.getWriter(), body);
EnvelopeResponseWriter.write(response, error, objectMapper);
}
private static String retryAfterSeconds(Duration retryAfter) {
@@ -27,6 +27,15 @@ public record SecuritySettings(
List<String> publicPaths,
SessionCookieSettings session) {
this.authMode = authMode == null ? AuthenticationMode.JWT : authMode;
// An environment variable that is not set at all leaves `${APP_SECURITY_JWT_ISSUER}` behind:
// Boot binds an unresolvable placeholder as its literal text rather than failing. Read as a
// value it would pass the blank check and become the issuer (and the audience) every token is
// compared against, so it is treated as what it is — the value was never supplied.
issuerUri = unresolvedAsMissing(issuerUri);
audience =
audience == null
? null
: audience.stream().map(SecuritySettings::unresolvedAsMissing).toList();
if (this.authMode == AuthenticationMode.JWT && (issuerUri == null || issuerUri.isBlank())) {
throw new IllegalArgumentException(
"APP_SECURITY_JWT_ISSUER (app.security.issuer-uri) is required");
@@ -35,7 +44,11 @@ public record SecuritySettings(
this.audience =
audience == null
? List.of()
: audience.stream().map(String::trim).filter(value -> !value.isEmpty()).toList();
: audience.stream()
.filter(value -> value != null)
.map(String::trim)
.filter(value -> !value.isEmpty())
.toList();
if (this.authMode == AuthenticationMode.JWT && this.audience.isEmpty()) {
// No "skip the check" default: a token minted for another client of the same issuer must
// not authenticate here.
@@ -50,6 +63,11 @@ public record SecuritySettings(
this.session = session == null ? SessionCookieSettings.defaults() : session;
}
/** A value still holding a {@code ${...}} placeholder was never resolved, so it is absent. */
private static String unresolvedAsMissing(String value) {
return value != null && value.contains("${") ? null : value;
}
public SecuritySettings(String issuerUri, List<String> audience, List<String> publicPaths) {
this(AuthenticationMode.JWT, issuerUri, audience, publicPaths, null);
}
@@ -9,6 +9,7 @@ import dev.caskeleton.adapter.inbound.web.settings.CorsSettings;
import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings;
import jakarta.servlet.Filter;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@@ -163,6 +164,75 @@ class CorsSecurityFilterIntegrationTest {
});
}
@Test
@DisplayName("cross-origin 실제 응답은 클라이언트가 읽어야 하는 플랫폼 계약 헤더를 노출한다")
void anActualCrossOriginResponseExposesThePlatformContractHeaders() {
// given: CORS on for one origin, with credentials
withCors(
true,
ALLOWED_ORIGIN,
true,
mvc -> {
// when
MvcResult result =
mvc.perform(get("/public").header(HttpHeaders.ORIGIN, ALLOWED_ORIGIN))
.andExpect(status().isOk())
.andReturn();
// then: a browser hides every response header outside the CORS safelist unless named
assertThat(exposedHeaders(result))
.contains(
"Retry-After",
"X-Request-Id",
"X-Correlation-Id",
"traceparent",
"Location",
"ETag",
"X-RateLimit-Limit",
"X-RateLimit-Remaining",
"X-RateLimit-Reset");
});
}
@Test
@DisplayName("모듈이 기여한 노출 헤더는 플랫폼 목록에 더해진다")
void aContributedExposedHeaderIsAddedToThePlatformList() {
// given: a capability that writes its own response header contributes it
runner
.withBean(
"uploadHeaders",
CorsExposedHeaders.class,
() -> new CorsExposedHeaders(List.of("Upload-Offset")))
.withPropertyValues(
"app.security.auth-mode=jwt",
"app.security.issuer-uri=https://issuer.example.test",
"app.security.audience=ca-skeleton-api",
"app.security.public-paths=/public",
"app.cors.enabled=true",
"app.cors.allowed-origins[0]=" + ALLOWED_ORIGIN)
.run(
context -> {
MockMvc mvc =
MockMvcBuilders.standaloneSetup(new ProbeController())
.addFilters(context.getBean("springSecurityFilterChain", Filter.class))
.build();
// when
MvcResult result =
mvc.perform(get("/public").header(HttpHeaders.ORIGIN, ALLOWED_ORIGIN))
.andReturn();
// then
assertThat(exposedHeaders(result)).contains("Upload-Offset", "Retry-After");
});
}
private static List<String> exposedHeaders(MvcResult result) {
String exposed = result.getResponse().getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS);
assertThat(exposed).as("Access-Control-Expose-Headers").isNotNull();
return java.util.Arrays.stream(exposed.split(",")).map(String::trim).toList();
}
private void withCors(
boolean enabled, String origin, boolean credentials, ThrowingConsumer<MockMvc> assertion) {
runner
@@ -10,8 +10,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import dev.caskeleton.shared.response.BulkEnvelope;
import dev.caskeleton.shared.response.Envelope;
import dev.caskeleton.shared.response.ResponseMeta;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
@@ -20,6 +22,8 @@ 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.json.JsonCompareMode;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -49,6 +53,17 @@ class EnvelopeBodyAdviceTest {
return Envelope.ok(Map.of("k", "v"), new ResponseMeta("r", "t", "c"));
}
@GetMapping("/probe/text")
public String text() {
return "안녕";
}
/** Already-serialized JSON, the way springdoc returns its OpenAPI document. */
@GetMapping(value = "/probe/serialized", produces = MediaType.APPLICATION_JSON_VALUE)
public byte[] serialized() {
return "{\"openapi\":\"3.1.0\"}".getBytes(StandardCharsets.UTF_8);
}
@GetMapping("/probe/bulk")
public BulkEnvelope<Map<String, String>> bulk() {
return BulkEnvelope.allOk(List.of(Map.of("k", "v")), new ResponseMeta("r", "t", "c"));
@@ -89,6 +104,51 @@ class EnvelopeBodyAdviceTest {
.andExpect(content().string(not(containsString("\"data\""))));
}
@Test
@DisplayName("String을 반환하는 엔드포인트도 JSON을 요청하면 200 Envelope로 답한다")
void aStringReturningEndpointAnswersAJsonClientWithAnEnvelope() throws Exception {
// when
var result = mvc.perform(get("/probe/text").accept(MediaType.APPLICATION_JSON));
// then
result
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.data").value("안녕"))
.andExpect(jsonPath("$.meta").exists())
.andExpect(content().string(not(containsString("\"error\""))));
}
@Test
@DisplayName("String을 반환하는 엔드포인트는 텍스트를 요청한 클라이언트에게 텍스트로 답한다")
void aStringReturningEndpointAnswersATextClientWithText() throws Exception {
// when
var result = mvc.perform(get("/probe/text").accept(MediaType.TEXT_PLAIN));
// then
result
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN))
.andExpect(content().string("안녕"));
}
/**
* A body that is already JSON bytes cannot be put inside an envelope: the byte converter the
* response was negotiated for would receive the envelope object and fail with a 500.
*/
@Test
@DisplayName("이미 직렬화된 byte[] JSON 본문은 감싸지 않고 그대로 쓴다")
void alreadySerializedJsonIsWrittenAsItIs() throws Exception {
// given: 컨트롤러가 이미 직렬화된 JSON 바이트를 돌려준다(springdoc 방식)
// when
var result = mvc.perform(get("/probe/serialized"));
// then
result
.andExpect(status().isOk())
.andExpect(content().json("{\"openapi\":\"3.1.0\"}", JsonCompareMode.STRICT));
}
@SpringBootConfiguration
@EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
static class TestBootstrap {}
@@ -13,9 +13,11 @@ import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedExceptio
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice;
import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import jakarta.validation.constraints.Max;
import java.util.List;
import java.util.Map;
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.test.web.servlet.MockMvc;
@@ -27,6 +29,7 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
/**
@@ -118,9 +121,48 @@ class TransportErrorHandlingTest {
.andExpect(jsonPath("$.error.code").value("BAD_PARAMETER"));
}
@Test
@DisplayName("비동기 요청 시간 초과는 500이 아니라 재시도 가능한 503 REQUEST_TIMEOUT이다")
void anAsyncTimeoutIsARetryable503NotAnInternalError() throws Exception {
// when
var result = mvc.perform(get("/t/async-timeout"));
// then
result
.andExpect(status().isServiceUnavailable())
.andExpect(jsonPath("$.error.code").value("REQUEST_TIMEOUT"))
.andExpect(jsonPath("$.error.category").value("TRANSIENT_DEPENDENCY"))
.andExpect(jsonPath("$.error.retryable").value(true));
}
@Test
@DisplayName("컨트롤러 파라미터 제약 위반은 VALIDATION_FAILED와 위반한 파라미터 details로 나간다")
void aViolatedParameterConstraintIsValidationFailedNamingTheParameter() throws Exception {
// when
var result = mvc.perform(get("/t/bounded").param("limit", "99"));
// then
result
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED"))
.andExpect(jsonPath("$.error.details[0].field").value("limit"))
.andExpect(jsonPath("$.error.details[0].code").value("MAX"))
.andExpect(jsonPath("$.error.details[0].rejectedValue").doesNotExist());
}
@RestController
static class Probe {
@GetMapping("/t/async-timeout")
Map<String, String> asyncTimeout() {
throw new AsyncRequestTimeoutException();
}
@GetMapping("/t/bounded")
Map<String, Integer> bounded(@RequestParam("limit") @Max(10) int limit) {
return Map.of("limit", limit);
}
@PostMapping("/t/needs-header")
Map<String, String> needsHeader(@RequestHeader("Idempotency-Key") String key) {
return Map.of("ok", key);
@@ -0,0 +1,113 @@
package dev.caskeleton.adapter.inbound.web.http;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import java.util.Map;
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.MethodSource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
class IdempotencyKeyHeaderTest {
private final MockMvc mvc =
MockMvcBuilders.standaloneSetup(new KeyedProbe())
.setControllerAdvice(new GlobalExceptionHandler(SpanErrorRecorder.NOOP))
.build();
@Test
@DisplayName("보이는 ASCII 1~256자 키는 받은 그대로 쓰인다")
void aKeyInsideTheGrammarIsKeptExactly() {
// given
String key = "0190bd6e-7c3e:retry/1" + "x".repeat(235);
// when
IdempotencyKeyHeader parsed = IdempotencyKeyHeader.parse(key);
// then
assertThat(parsed.value()).isEqualTo(key).hasSize(256);
}
static Stream<String> keysOutsideTheGrammar() {
return Stream.of("", " ", " padded", "with space", "키", "tab\tkey", "x".repeat(257));
}
@ParameterizedTest(name = "[{index}] <{0}>")
@MethodSource("keysOutsideTheGrammar")
@DisplayName("문법 밖의 키는 MALFORMED로 거부된다")
void aKeyOutsideTheGrammarIsMalformed(String key) {
// when
Throwable thrown = catchThrowable(() -> IdempotencyKeyHeader.parse(key));
// then
assertThat(thrown).isInstanceOf(InvalidIdempotencyKeyException.class);
assertThat(((InvalidIdempotencyKeyException) thrown).clientDetails())
.isEqualTo(Map.of("reason", "MALFORMED"));
}
@Test
@DisplayName("헤더가 없으면 MISSING으로 거부된다")
void anAbsentHeaderIsMissing() {
// when
Throwable thrown = catchThrowable(() -> IdempotencyKeyHeader.parse(null));
// then
assertThat(((ApiErrorCarrier) thrown).errorCode().code()).isEqualTo("IDEMPOTENCY_KEY_INVALID");
assertThat(((InvalidIdempotencyKeyException) thrown).clientDetails())
.isEqualTo(Map.of("reason", "MISSING"));
}
@Test
@DisplayName("키가 없는 KEYED 요청은 400 IDEMPOTENCY_KEY_INVALID와 reason으로 답한다")
void aKeyedRequestWithoutAKeyIsAnswered400WithItsOwnCode() throws Exception {
// when
var result = mvc.perform(post("/keyed"));
// then
result
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.error.code").value("IDEMPOTENCY_KEY_INVALID"))
.andExpect(jsonPath("$.error.category").value("VALIDATION"))
.andExpect(jsonPath("$.error.retryable").value(false))
.andExpect(jsonPath("$.error.details.reason").value("MISSING"));
}
@Test
@DisplayName("형식이 틀린 키는 응답에 되돌려 쓰지 않는다")
void aMalformedKeyIsNotEchoed() throws Exception {
// when
var result = mvc.perform(post("/keyed").header(ApiHeaders.IDEMPOTENCY_KEY, "SECRET KEY"));
// then
result
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.error.details.reason").value("MALFORMED"))
.andExpect(content().string(not(containsString("SECRET"))));
}
@RestController
static class KeyedProbe {
@PostMapping("/keyed")
Map<String, String> keyed(
@RequestHeader(name = ApiHeaders.IDEMPOTENCY_KEY, required = false) String key) {
return Map.of("key", IdempotencyKeyHeader.parse(key).value());
}
}
}
@@ -3,10 +3,14 @@ package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
import dev.caskeleton.adapter.inbound.web.mvc.filter.JsonBodyLimitFilter;
import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter;
import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.jackson.autoconfigure.JacksonAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
@@ -66,6 +70,62 @@ class WebMvcPlatformAutoConfigurationTest {
.doesNotHaveBean(WebMvcRequestIdFilter.class));
}
/** Both roots this leaf registers, as a deployment that ships the leaf processes them. */
private final WebApplicationContextRunner shipped =
new WebApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
JacksonAutoConfiguration.class,
WebAdapterAutoConfiguration.class,
WebMvcPlatformAutoConfiguration.class))
// The access-log filter's one collaborator, which the application supplies.
.withBean(UserPrincipalPseudonymizerPort.class, () -> raw -> raw);
@Test
@DisplayName("leaf를 그대로 실으면 오류 핸들러는 하나만 등록된다")
void theShippedLeafRegistersExactlyOneErrorHandler() {
// when
shipped.run(
context ->
// then
assertThat(context).hasNotFailed().hasSingleBean(GlobalExceptionHandler.class));
}
@Test
@DisplayName("app.web.mvc.enabled=false면 leaf를 실어도 오류 핸들러·요청 id 필터·본문 상한이 모두 없다")
void switchingThePlatformOffRemovesTheErrorHandlerWithTheFilters() {
// when
shipped
.withPropertyValues("app.web.mvc.enabled=false")
.run(
context ->
// then
assertThat(context)
.hasNotFailed()
.doesNotHaveBean(GlobalExceptionHandler.class)
.doesNotHaveBean(WebMvcRequestIdFilter.class)
.doesNotHaveBean(JsonBodyLimitFilter.class));
}
@Test
@DisplayName("서비스가 같은 타입의 오류 핸들러를 주면 그것 하나만 쓰인다")
void anAdopterErrorHandlerIsTheOnlyOne() {
// given
var withAdopterHandler =
shipped.withBean(
"adopterErrorHandler",
GlobalExceptionHandler.class,
() -> new GlobalExceptionHandler(SpanErrorRecorder.NOOP));
// when
withAdopterHandler.run(
context -> {
// then
assertThat(context).hasNotFailed().hasSingleBean(GlobalExceptionHandler.class);
assertThat(context).hasBean("adopterErrorHandler");
});
}
@Test
@DisplayName("the request id is not trusted from a caller by default")
void theRequestIdIsNotTrustedByDefault() {
@@ -4,7 +4,11 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletInputStream;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -39,6 +43,63 @@ class JsonBodyLimitFilterTest {
.hasMessageContaining("16");
}
@Test
@DisplayName("선언 길이가 상한을 넘는 JSON 본문은 본문 스트림을 열기 전에 거부된다")
void aDeclaredOversizeIsRefusedBeforeTheBodyStreamIsOpened() {
// given: a container stream that records whether anybody opened it
AtomicBoolean streamOpened = new AtomicBoolean();
MockHttpServletRequest request =
new MockHttpServletRequest("POST", "/probe") {
@Override
public ServletInputStream getInputStream() {
streamOpened.set(true);
return super.getInputStream();
}
};
request.setContentType("application/json");
request.setContent(new byte[64]);
FilterChain opensTheStream = (req, res) -> req.getInputStream();
// when
Throwable thrown =
catchThrowable(
() -> filter.doFilter(request, new MockHttpServletResponse(), opensTheStream));
// then
assertThat(thrown).isInstanceOf(MaxUploadSizeExceededException.class);
assertThat(streamOpened)
.as("the declared length is refused without the container reading a byte")
.isFalse();
}
@Test
@DisplayName("+json 미디어 타입(merge-patch 등) 본문도 JSON 상한을 받는다")
void aStructuredJsonSuffixBodyIsBoundedToo() {
// given: an undeclared merge-patch body larger than the ceiling
MockHttpServletRequest request =
new MockHttpServletRequest("PATCH", "/probe") {
@Override
public long getContentLengthLong() {
return -1;
}
};
request.setContentType("application/merge-patch+json");
request.setContent(new byte[64]);
FilterChain readsEverything = (req, res) -> readAll(req.getInputStream());
// when
Throwable thrown =
catchThrowable(
() -> filter.doFilter(request, new MockHttpServletResponse(), readsEverything));
// then
assertThat(thrown).isInstanceOf(MaxUploadSizeExceededException.class);
}
private static void readAll(ServletInputStream stream) throws IOException {
stream.readAllBytes();
}
@Test
void nonJsonBodyReachesTheChainUnwrapped() throws Exception {
// given
@@ -8,9 +8,11 @@ import jakarta.servlet.DispatcherType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.slf4j.MDC;
import org.springframework.mock.web.MockFilterChain;
@@ -183,7 +185,8 @@ class WebMvcRequestIdFilterTest {
}
@Test
void inboundCorrelationIdLosesLineBreaksBeforeReachingMdc() throws Exception {
@DisplayName("줄바꿈을 담은 correlation id는 MDC에 닿기 전에 서버가 만든 값으로 바뀐다")
void inboundCorrelationIdWithLineBreaksNeverReachesMdc() throws Exception {
// given
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(CORRELATION_ID_HEADER, "foo\r\nFAKE LOG");
@@ -194,7 +197,49 @@ class WebMvcRequestIdFilterTest {
.doFilter(request, new MockHttpServletResponse(), (rq, rs) -> duringChain.putAll(mdc()));
// then
assertThat(duringChain.get(MdcKeys.CORRELATION_ID)).isEqualTo("fooFAKE LOG");
assertThat(duringChain.get(MdcKeys.CORRELATION_ID))
.doesNotContain("FAKE")
.matches(SAFE_IDENTIFIER);
}
@ParameterizedTest(name = "[{index}] {0}")
@MethodSource("correlationIdsOutsideTheRule")
@DisplayName("요청 id 규칙 밖의 correlation id는 응답·MDC 어디에도 그대로 나가지 않는다")
void aCorrelationIdOutsideTheRequestIdRuleIsReplaced(String proposed) throws Exception {
// given
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(CORRELATION_ID_HEADER, proposed);
MockHttpServletResponse response = new MockHttpServletResponse();
Map<String, String> duringChain = new HashMap<>();
// when
new WebMvcRequestIdFilter().doFilter(request, response, (rq, rs) -> duringChain.putAll(mdc()));
// then
String echoed = response.getHeader(CORRELATION_ID_HEADER);
assertThat(echoed).isNotEqualTo(proposed).matches(SAFE_IDENTIFIER);
assertThat(duringChain.get(MdcKeys.CORRELATION_ID)).isEqualTo(echoed);
}
static Stream<String> correlationIdsOutsideTheRule() {
return Stream.of(
"has space", "유니코드", "del" + (char) 0x7f + "char", "colon:is:outside", "x".repeat(129));
}
@Test
@DisplayName("요청 id 규칙 안의 correlation id는 그대로 이어진다")
void aCorrelationIdInsideTheRuleIsKept() throws Exception {
// given
String proposed = "order-42_retry.1";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(CORRELATION_ID_HEADER, proposed);
MockHttpServletResponse response = new MockHttpServletResponse();
// when
new WebMvcRequestIdFilter().doFilter(request, response, new MockFilterChain());
// then
assertThat(response.getHeader(CORRELATION_ID_HEADER)).isEqualTo(proposed);
}
@Test
@@ -238,5 +283,6 @@ class WebMvcRequestIdFilterTest {
}
private static final String NEWLINE = "\n";
private static final String SAFE_IDENTIFIER = "[A-Za-z0-9._-]{1,128}";
private static final String CORRELATION_ID_HEADER = "X-Correlation-Id";
}
@@ -12,6 +12,7 @@ import com.jayway.jsonpath.JsonPath;
import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal;
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice;
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
import dev.caskeleton.adapter.outbound.identifier.UuidV7DurableOperationIdFactory;
import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder;
import dev.caskeleton.application.operation.CancelDurableOperationUseCase;
import dev.caskeleton.application.operation.DurableOperationSubmittedContract;
@@ -65,9 +66,14 @@ class DurableOperationControllerTest {
DurableOperationController controller =
new DurableOperationController(
new SubmitDurableOperationUseCase(
operations, outbox, new FakeIntegrationEventEncoder(), transactions, clock),
operations,
outbox,
new FakeIntegrationEventEncoder(new DurableOperationSubmittedContract()),
transactions,
clock),
new GetDurableOperationUseCase(operations, transactions, clock),
new CancelDurableOperationUseCase(operations, transactions, clock));
new CancelDurableOperationUseCase(operations, transactions, clock),
new UuidV7DurableOperationIdFactory());
mvc =
MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(
@@ -98,6 +104,63 @@ class DurableOperationControllerTest {
.andExpect(jsonPath("$.data.alreadyAccepted").value(false));
}
/**
* The operation id becomes the submission event's id, and the messaging platform carries an event
* id only as a UUIDv7 message id. A v4 id was accepted here and refused at publish time, so every
* submission's event ended DEAD in the outbox (review 2026-11-01 06-06, found by the Kafka relay
* lane).
*/
@Test
@DisplayName("제출이 만든 operation id와 그 이벤트 id는 platform이 받는 정규 소문자 UUIDv7이다")
void aSubmissionMintsACanonicalUuidV7ThatIsAlsoItsEventId() throws Exception {
// given
signIn("alice");
// when
String operationId = operationIdOf(submit(REPORT).andReturn());
// then
java.util.UUID uuid = java.util.UUID.fromString(operationId);
assertThat(List.of(uuid.version(), uuid.variant(), uuid.toString()))
.containsExactly(7, 2, operationId);
assertThat(outbox.appended())
.singleElement()
.extracting(event -> event.eventId().value())
.isEqualTo(operationId);
}
/**
* The composition registered the use case but not its event contract. No request can fix that, so
* the client must not be told 400 "fix your request" — it is a 500 the server logs.
*/
@Test
void aSubmissionWhoseEventContractIsNotRegisteredIsAServerError() throws Exception {
// given
signIn("alice");
MockMvc unregistered =
MockMvcBuilders.standaloneSetup(
new DurableOperationController(
new SubmitDurableOperationUseCase(
operations, outbox, new FakeIntegrationEventEncoder(), transactions, clock),
new GetDurableOperationUseCase(operations, transactions, clock),
new CancelDurableOperationUseCase(operations, transactions, clock),
new UuidV7DurableOperationIdFactory()))
.setControllerAdvice(
new GlobalExceptionHandler(SpanErrorRecorder.NOOP), new EnvelopeBodyAdvice())
.setCustomArgumentResolvers(new AuthenticationPrincipalArgumentResolver())
.build();
// when
ResultActions response =
unregistered.perform(
post("/operations").contentType(MediaType.APPLICATION_JSON).content(REPORT));
// then
response
.andExpect(status().isInternalServerError())
.andExpect(jsonPath("$.error.code").value("INTERNAL_ERROR"));
}
@Test
void anIdenticalResubmissionPointsAtTheFirstOperation() throws Exception {
// given
@@ -3,13 +3,17 @@ package dev.caskeleton.adapter.inbound.web.ratelimit;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.web.http.ApiHeaders;
import dev.caskeleton.shared.error.ClientErrorMessages;
import dev.caskeleton.shared.error.OperationalError;
import dev.caskeleton.shared.ratelimit.RateLimitDecision;
import dev.caskeleton.shared.ratelimit.RateLimitOutcome;
import dev.caskeleton.shared.ratelimit.RateLimitSubjectDigest;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -56,6 +60,28 @@ class RateLimitInterceptorTest {
.contains("\"retryable\":true");
}
@Test
@DisplayName("거부 본문은 UTF-8로 나가 한국어 문구가 ClientErrorMessages와 같다")
void theRefusalBodyIsUtf8SoTheKoreanMessageSurvives() throws Exception {
// given: a response that writes ISO-8859-1 unless told otherwise, as Tomcat's does
RateLimitOutcome outcome =
evaluated(false, 1, 0, Duration.ofMillis(1500), Instant.parse("2026-06-09T12:00:02Z"));
ContainerDefaultCharsetResponse response = new ContainerDefaultCharsetResponse();
// when
interceptor(outcome).preHandle(request(), response, new Object());
// then
assertThat(response.getCharacterEncoding()).isEqualToIgnoringCase("UTF-8");
assertThat(
objectMapper
.readTree(response.getContentAsString(StandardCharsets.UTF_8))
.path("error")
.path("message")
.asString())
.isEqualTo(ClientErrorMessages.of(OperationalError.RATE_LIMIT_EXCEEDED));
}
@Test
void unavailableAndIndeterminateOutcomesMapTo503WithTheirOwnRetryHints() throws Exception {
MockHttpServletResponse unavailableResponse = new MockHttpServletResponse();
@@ -102,6 +128,40 @@ class RateLimitInterceptorTest {
.contains("\"retryable\":false");
}
/**
* Tomcat's writer is ISO-8859-1 until {@code setCharacterEncoding} or a {@code charset} content
* type parameter says otherwise; Spring's mock is more forgiving for JSON, so it would hide the
* defect this guards.
*/
private static final class ContainerDefaultCharsetResponse extends MockHttpServletResponse {
private String explicitEncoding;
private java.io.PrintWriter writer;
@Override
public void setCharacterEncoding(String encoding) {
explicitEncoding = encoding;
super.setCharacterEncoding(encoding);
}
@Override
public String getCharacterEncoding() {
return explicitEncoding == null ? StandardCharsets.ISO_8859_1.name() : explicitEncoding;
}
@Override
public java.io.PrintWriter getWriter() {
if (writer == null) {
writer =
new java.io.PrintWriter(
new java.io.OutputStreamWriter(
getOutputStream(), java.nio.charset.Charset.forName(getCharacterEncoding())),
true);
}
return writer;
}
}
private RateLimitInterceptor interceptor(RateLimitOutcome outcome) {
EdgeRateLimitTransportBridge bridge =
new EdgeRateLimitTransportBridge(
@@ -15,6 +15,44 @@ class SecuritySettingsTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner().withUserConfiguration(EnableProperties.class);
@Test
@DisplayName("issuer env가 아예 없어 자리표시자가 그대로 남으면 issuer 값으로 받지 않고 기동을 거부한다")
void anUnresolvedIssuerPlaceholderIsRefusedNotBound() {
// given
var unresolved =
runner.withPropertyValues(
"app.security.issuer-uri=${APP_SECURITY_JWT_ISSUER_UNSET_FOR_TEST}",
"app.security.audience=ca-skeleton-api");
// when
unresolved.run(
context -> {
// then
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.hasStackTraceContaining("APP_SECURITY_JWT_ISSUER");
});
}
@Test
@DisplayName("audience env가 아예 없어 자리표시자가 그대로 남으면 audience 값으로 받지 않고 기동을 거부한다")
void anUnresolvedAudiencePlaceholderIsRefusedNotBound() {
// given
var unresolved =
runner.withPropertyValues(
"app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton",
"app.security.audience=${APP_SECURITY_JWT_AUDIENCE_UNSET_FOR_TEST}");
// when
unresolved.run(
context -> {
// then
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.hasStackTraceContaining("APP_SECURITY_JWT_AUDIENCE");
});
}
@Test
void issuerUriMissingFailsStartup() {
runner.run(

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