fix(inbound)!: Retry-After를 레지스트리대로 붙이고 GraphQL 인자 거부를 맞춘다

문제(r8-f1 보고의 범위 밖 1·2, 소유자 답 2026-11-07 "권하는 안대로"):
- web RetryAfterAdvisor 표가 레지스트리 retry_after_seconds 칸의 미러인데
  7개가 빠졌다(DB_UNAVAILABLE 5, DB_SERIALIZATION_FAILURE 1, DB_DEADLOCK
  1, DB_IDLE_IN_TX_TIMEOUT 2, OUTBOX_PUBLISH_FAILED 30,
  JOB_EXECUTOR_REJECTED 5, JOB_TIMEOUT 10). 그래서 DB 일시 실패 응답에
  Retry-After가 없다. 대조하는 테스트가 없었다: advisor 단위 테스트는
  값을 코드마다 손으로 옮겼고, enum·레지스트리 대조 테스트는 category·
  status·retryable만 봤다.
- GraphQL @Argument 값이 파라미터 타입으로 바뀌지 않으면 Spring 인자
  binder가 BindException을 던지는데, 매퍼가 모르는 타입이라
  INTERNAL_ERROR로 가리고 예외째 ERROR로 남긴다. 그 메시지에
  rejected value [...]가 실린다.

고친 것:
- RetryAfterAdvisor 표를 Map.ofEntries로 바꾸고 7개를 채웠다(Map.of는
  10쌍이 상한). OperationalErrorRegistryContractTest(document-contract)에
  OperationalError마다 RetryAfterAdvisor.retryAfterSeconds와 레지스트리
  값이 같은지 보는 테스트를 더했다. 버린 안: advisor가 레지스트리를
  런타임에 읽는 것 — web leaf가 저장소 파일을 읽게 되고 jar에 실리지
  않는다.
- GraphQlWireErrorMapper가 BindException을 IllegalArgumentException과
  같은 "거부된 인자"로 본다: 등록된 매핑이 없으면 BAD_PARAMETER(REQUEST),
  로그는 ServerFailureLog.refused의 WARN 한 줄(타입만). web이 바뀌지 않는
  경로 변수에 답하는 것과 같다.
- 결정 색인 2.3절에 두 결정과 STOMP 필수 header 누락을 ERROR로 두는
  기본값(이유 포함)을 적었다. 업그레이드 안내 B-47·B-48.

위험·한계:
- 응답이 바뀐다: DB 일시 실패 넷에 Retry-After가 생기고, GraphQL 인자
  변환 실패가 INTERNAL_ERROR → BAD_PARAMETER.
- 대조 테스트는 OperationalError 코드만 본다. 다른 leaf의 코드는
  RetryAfterHint로 자기 값을 말한다(대조 대상 아님).
- BindException은 binder가 인자 변환을 모아 던질 때만 온다. @Valid
  검증(ConstraintViolationException)은 이 leaf에 Bean Validation이 없어
  다루지 않았다.

검증(desktop, flock /tmp/claude-gates/heavy.lock, 로그 ~/r8-f1-logs/round2/):
- RED(5f6a86d7 + 테스트만): 11건 실패. advisor 7개 코드 empty, 레지스트리
  대조 1건, GraphQL 3건(INTERNAL_ERROR, ERROR "graphql failure masked" +
  BindException "rejected value [alice@example.com]"). round2/red.log
- 이 트리(ca44d3fc): :ci :verifyDependencyLocks --warning-mode=fail rc=0
  (web test 341, graphql test 404, app-bootstrap test 225 skip 4 이전부터,
  architectureTest, verifyGraphQlApiSurface 포함)
- :sample-portfolio:check :sample-portfolio:qualityCheck rc=0
- :verifyStrictLaneStages --dry-run 두 빌드 rc=0, -p optional-platforms ci rc=0
- web·graphql systemTest, :conditionalTransportQualification rc=0
- :app-bootstrap:documentContractTest rc=0(67)
- web·graphql·app-bootstrap testQualityCheck rc=0
- scripts/verify-compose-profile-contracts.sh rc=0, scripts/check-work-docs.py rc=0

BREAKING CHANGE: DB_UNAVAILABLE(5초)·DB_SERIALIZATION_FAILURE(1초)·
DB_DEADLOCK(1초)·DB_IDLE_IN_TX_TIMEOUT(2초) 응답에 Retry-After가 붙고,
GraphQL @Argument 변환 실패는 INTERNAL_ERROR 대신 BAD_PARAMETER로 답한다.
업그레이드 안내 B-47·B-48.
Refs: docs/work/reference/decisions.md 2.3절, docs/upgrade/2026-11-maturity-review.md B-47, B-48
This commit is contained in:
DongHyeonka
2026-11-07 01:38:36 +09:00
parent 5f6a86d7b7
commit ef8ef170e8
13 changed files with 277 additions and 38 deletions
+4 -1
View File
@@ -4,7 +4,7 @@
- 커밋: `34565130` High·P1 19건 · `1400dc15` 남은 발견·매뉴얼·생성 명령 · `5786126c` 남은 항목과 합친 뒤 결함 ·
`7ef8d0b4` 재리뷰 기록 · `bbe944bd` 재리뷰 결함 · `ecc74b7d` 2차 재리뷰 기록·이 안내 · `1885bf8d` 2차 재리뷰 결함 ·
`339cf8fd` 3차 확인 리뷰 기록 · `f40c03c6` 3차 확인 리뷰 Minor · `c2e55510` 마지막 확인 리뷰 기록 ·
`2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) · B4 성능 lane 단언 상시화(2026-11-06, B-43) · r8-f1 전송 오류 처리(2026-11-07, B-45·B-46) — `docs(...)` 커밋은 문서만 바꾼다
`2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) · B4 성능 lane 단언 상시화(2026-11-06, B-43) · r8-f1 전송 오류 처리(2026-11-07, B-45~B-48) — `docs(...)` 커밋은 문서만 바꾼다
- 근거 문서: `docs/reviews/2026-11-01-maturity-review/README.md` 13~16절, `docs/reviews/2026-11-03-rereview/README.md`
4·6·8~13절, 각 커밋의 `BREAKING CHANGE:` 꼬리말
- 아래 표의 각 줄은 위 범위의 diff와 코드로 확인했다. 확인하지 못한 것은 그 자리에 "확인 못 함"으로 적었고 9절에
@@ -102,6 +102,8 @@
| B-33 | DB 실패 분류: 낙관적 잠금 충돌 500 → 409 `DB_OPTIMISTIC_CONFLICT`. 커밋 단계 연결 끊김(08xxx, 40003 등)을 재시도 가능으로 답하던 것 → 500 `DB_COMPLETION_UNKNOWN`(retryable=false) | 응답 status·code가 바뀐다 | 409는 다시 읽고 재시도, `DB_COMPLETION_UNKNOWN`은 업무 데이터로 결과를 확인 | `34565130`, `1400dc15` · `src/adapter/outbound/persistence-jpa/.../failure/PersistenceExceptionTranslator.java` |
| B-45 | 분산 락 timeout(`LockAcquisitionTimeoutException`): 500 `INTERNAL_ERROR`(retryable=false) → 409 `LOCK_ACQUISITION_TIMEOUT`(retryable=true, `Retry-After: 1`). GraphQL extension `code`·`retryable`, gRPC `ABORTED` + trailer `error-code`도 같은 코드. 예외가 `ApiErrorCarrier`가 되어 레지스트리가 약속한 값으로 답한다. 4xx라 "unhandled exception" ERROR 줄이 사라진다 | 500을 "재시도 금지"로 읽던 클라이언트가 이제 409를 받는다. 이 예외에 자기 `@ExceptionHandler`를 둔 서비스는 그쪽 응답이 그대로 나간다 | `Retry-After` 뒤 같은 요청을 다시 보내게 한다. 자기 처리기를 두었다면 지워도 된다 | r8-f1(2026-11-07, 재리뷰 RR7-01-04) · `src/application-core/.../lock/LockAcquisitionTimeoutException.java`, `src/adapter/inbound/web/.../observability/RetryAfterAdvisor.java` |
| B-46 | 다른 예외로 감싼 carrier: web·GraphQL도 gRPC처럼 원인 사슬의 첫 carrier 코드로 답한다(전에는 500 `INTERNAL_ERROR`). `IllegalArgumentException`이 carrier를 감쌌으면 `BAD_PARAMETER` 대신 그 carrier 코드다. STOMP ERROR 프레임의 `error-code`도 `IllegalArgumentException` 뒤의 carrier를 그 코드로 낸다. gRPC는 `Status.INVALID_ARGUMENT.withCause(iae)`처럼 `IllegalArgumentException`을 원인으로 든 raw status를 던져도 `onError`로 넘긴 것과 같이 `INVALID_ARGUMENT`·`BAD_PARAMETER`다(전에는 던지면 `INTERNAL`) | 감싼 실패에 500·`INTERNAL`을 받던 클라이언트가 이제 그 carrier 코드(예: 503 `DB_UNAVAILABLE`)를 받는다 | 클라이언트 분기는 `error.code`로 한다(바꿀 것 없음). 감싼 실패를 일부러 500으로 보내려면 감싸지 말고 `IllegalStateException`을 던진다 | r8-f1(2026-11-07, 소유자 결정 2026-11-06, 재리뷰 RR7-01-05·RR7-01-03) · `src/shared-contract/.../error/ApiErrorCarrier.java` `firstIn`, 네 전송의 오류 처리기 |
| B-47 | `Retry-After`를 레지스트리 `retry_after_seconds`대로 붙인다. 새로 붙는 응답: 503 `DB_UNAVAILABLE` 5초, 409 `DB_SERIALIZATION_FAILURE`·`DB_DEADLOCK` 1초, 503 `DB_IDLE_IN_TX_TIMEOUT` 2초(나머지 `OUTBOX_PUBLISH_FAILED`·`JOB_*`는 HTTP로 나가지 않는 코드다). 전에는 web 표에서 빠져 헤더가 없었다. 표와 레지스트리를 `OperationalErrorRegistryContractTest`(document-contract, `mainCheck`)가 대조한다 | 이 응답에 `Retry-After`가 생긴다. 템플릿 `OperationalError` 행의 `retry_after_seconds`를 바꾼 서비스는 `RetryAfterAdvisor` 표도 같이 바꾸지 않으면 `mainCheck`가 실패한다(대조 대상은 `OperationalError` 코드뿐이다) | 헤더를 따르는 클라이언트는 그만큼 기다렸다 재시도한다. 자기 코드의 값은 그 코드가 `RetryAfterHint`로 말한다 | r8-f1(2026-11-07, 소유자 결정) · `src/adapter/inbound/web/.../observability/RetryAfterAdvisor.java`, `src/app-bootstrap/src/test/.../contract/OperationalErrorRegistryContractTest.java` |
| B-48 | GraphQL `@Argument` 값이 컨트롤러 파라미터 타입으로 바뀌지 않으면(Spring 인자 binder의 `BindException`) `INTERNAL_ERROR`(`INTERNAL`) 대신 `BAD_PARAMETER`(`REQUEST`, `BAD_REQUEST`)로 답한다. 로그는 ERROR + 예외(`rejected value [...]`가 실림) 대신 WARN 한 줄 `request refused as BAD_PARAMETER by org.springframework.validation.BindException (executionId=…)`이다 | 그 실패에 `INTERNAL_ERROR`를 받던 클라이언트가 `BAD_PARAMETER`를 받는다. ERROR 경보가 잘못된 인자에 울리지 않는다 | 클라이언트는 `extensions.code`로 가른다. `BindException`에 자기 `GraphQlExceptionResolver` 매핑을 둔 서비스는 그 매핑이 그대로 먼저다 | r8-f1(2026-11-07, 소유자 결정) · `src/adapter/inbound/graphql/.../error/GraphQlWireErrorMapper.java` |
### 3.4 빌드 게이트·아키텍처 규칙 — `ci`가 빨개진다
@@ -298,6 +300,7 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur
- CORS가 켜져 있으면 `Retry-After`·`X-Request-Id`·`X-Correlation-Id`·`traceparent` 등이 `Access-Control-Expose-Headers`에 있다(§3).
- 새 코드: `REQUEST_TIMEOUT`(503, retryable), web-advanced를 쓰는 서비스는 10종(3.3절 B-32).
- 분산 락 timeout은 409 `LOCK_ACQUISITION_TIMEOUT`(retryable, `Retry-After: 1`)이다. 전에는 500 `INTERNAL_ERROR`였다(3.3절 B-45).
- DB 일시 실패 넷(`DB_UNAVAILABLE` 등)에 레지스트리 값대로 `Retry-After`가 붙는다(3.3절 B-47). GraphQL `@Argument` 값이 타입에 맞지 않으면 `BAD_PARAMETER`다(B-48).
- 프론트 계약 문서(`clean-architecture-frontend-template` `docs/architecture/backend-api-and-server-state-contract.md` §4.1·§6)는
`docs/web/http-contract.md`를 가리켜야 한다.
- 프론트 세션에 넘긴 인계 문서(세션 scratchpad라 지워질 수 있음):
+3
View File
@@ -85,6 +85,9 @@
| 알림 category 생략 | 거부(400), 판정은 유스케이스 | 소유자 | 결정 13 |
| 오류 코드 로그 레벨 | `error-codes.yaml`에 `log_level` 칸을 두지 않는다. 레벨은 실패 종류·경로가 정한다(`ServerFailureLog`, 보안 필터 `AuthErrorResponseWriter`). 칸이 다시 생기면 `OperationalErrorRegistryContractTest`가 실패한다. 보안 필터는 5xx(`AUTH_JWKS_UNAVAILABLE`·`INTERNAL_AUTH_MISCONFIGURATION`)를 ERROR, 4xx를 WARN으로 남긴다. 401 서명·issuer·audience 불일치는 WARN | 소유자 | 2026-11-06, `docs/superpowers/specs/2026-11-06-error-code-log-level-design.md` 10절 |
| 감싼 carrier를 전송이 읽는 법 | web·GraphQL·STOMP·gRPC 네 전송 모두 원인 사슬의 첫 carrier를 본다. 감싼 carrier의 응답이 500 `INTERNAL_ERROR` 대신 그 carrier의 코드가 된다 | 소유자 | `1103` 18.4절(RR7-01-05), 2026-11-06 |
| `Retry-After` 값 | web `RetryAfterAdvisor` 표는 레지스트리 `retry_after_seconds` 칸과 코드마다 같다. 빠져 있던 7개(`DB_UNAVAILABLE` 5, `DB_SERIALIZATION_FAILURE` 1, `DB_DEADLOCK` 1, `DB_IDLE_IN_TX_TIMEOUT` 2, `OUTBOX_PUBLISH_FAILED` 30, `JOB_EXECUTOR_REJECTED` 5, `JOB_TIMEOUT` 10)를 채웠고, `OperationalErrorRegistryContractTest`가 둘을 대조한다 | 소유자 | 2026-11-07 총괄 세션 전달(소유자 원문 "권하는 안대로"), r8-f1 보고 「범위 밖」 1 |
| GraphQL 인자 변환 실패 | Spring GraphQL 인자 binder의 `BindException`(`@Argument` 값이 파라미터 타입으로 바뀌지 않음)은 `BAD_PARAMETER`(`REQUEST`)로 답하고, WARN 한 줄(예외 타입만, 입력값 없음)을 남긴다. web이 바뀌지 않는 경로 변수에 답하는 것과 같다 | 소유자 | 2026-11-07 같은 전달, r8-f1 보고 「범위 밖」 2 |
| STOMP 필수 header 누락 | 필수 header·destination 변수가 없을 때 Spring이 던지는 `MessageHandlingException`은 ERROR 그대로 둔다. 메시지에 입력값이 없고, Spring이 같은 타입으로 서버 실패(handler의 `Error` 등)도 감싸서 타입만으로는 클라이언트 탓을 가를 수 없다 | 기본값(2026-11-07) | 2026-11-07 총괄 지시, r8-f1 보고 「범위 밖」 3 |
### 2.4 멱등성
+1 -1
View File
@@ -123,7 +123,7 @@ application/platform namespace split.
pipeline(instrumentation), data fetcher resolver 세 곳이 같은 bean 을 받는다. 순서는 플랫폼 거부
(예외가 구현한 `error/GraphQlPlatformRejection`) → `ApiErrorCarrier`(자기 또는 원인 사슬의 첫 carrier의
`ApiErrorCode`) → 등록된
application 매핑(`GraphQlExceptionResolver`) → `IllegalArgumentException`=`BAD_PARAMETER`. 어디에도 안
application 매핑(`GraphQlExceptionResolver`) → `IllegalArgumentException`·인자 binder의 `BindException`=`BAD_PARAMETER`. 어디에도 안
걸린 예외는 `INTERNAL_ERROR` 로 가려지고, 같은 executionId 로 ERROR 로그 한 줄이 남는다. client 문구는
shared-contract `ClientErrorMessages`(Category 별 한국어 표), `retryable` 은 코드의 값이다. Category →
wire category/`ErrorType` 표는 mapper 의 `RENDERINGS` 하나뿐이고 [README.md](README.md)에 옮겨 둔다.
+5 -3
View File
@@ -73,9 +73,11 @@ instrumentation, data fetcher resolver 세 곳이 같은 bean 을 받는다).
application 의 멱등성 예외, DataLoader 키 실패(`GraphQlBatchLoadException`, **등록된 `ApiErrorCode`
만** — 소유자 결정 25)가 모두 여기로 온다.
3. **등록된 application 매핑**(`GraphQlExceptionResolver`).
4. **`IllegalArgumentException`** → `BAD_PARAMETER`(`REQUEST`, `BAD_REQUEST`) — web·gRPC·STOMP 와 같다.
로그도 같은 WARN 한 줄 `request refused as BAD_PARAMETER by <예외 타입> (executionId=<id>)` 이고,
입력값이 들 수 있는 메시지는 남기지 않는다.
4. **`IllegalArgumentException`과 인자 binder의 `BindException`** → `BAD_PARAMETER`(`REQUEST`, `BAD_REQUEST`) —
web·gRPC·STOMP 와 같다. `BindException`은 `@Argument` 값이 파라미터 타입으로 바뀌지 않을 때 Spring 이 컨트롤러
전에 던진다(web 의 경로 변수 변환 실패와 같은 답, 소유자 결정 2026-11-07). 로그도 같은 WARN 한 줄
`request refused as BAD_PARAMETER by <예외 타입> (executionId=<id>)` 이고, 입력값이 들 수 있는 메시지
(`BindException`은 `rejected value [...]`)는 남기지 않는다.
5. 나머지는 `INTERNAL_ERROR` 로 가려지고 같은 executionId 로 ERROR 로그 한 줄이 남는다.
- **client 문구**: shared-contract `ClientErrorMessages`(Category 별 한국어 문구 표 하나, 소유자
@@ -15,6 +15,7 @@ import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.graphql.execution.ErrorType;
import org.springframework.validation.BindException;
/**
* The one place a failure becomes something a client can see.
@@ -43,7 +44,8 @@ import org.springframework.graphql.execution.ErrorType;
* its detail in the log, such as the scope digest of an {@code IDEMPOTENCY_RECOVERY_REQUIRED}
* (review 2026-11-04 RR4-03-03); a persistence failure leaves its classification only. An unmapped
* {@link IllegalArgumentException} leaves the WARN line every transport writes for it, naming its
* type and never its message (review 2026-11-05 RR6-01-06).
* type and never its message (review 2026-11-05 RR6-01-06); so does an {@code @Argument} the
* argument binder refused, whose message quotes the rejected value.
*/
public final class GraphQlWireErrorMapper {
@@ -106,8 +108,11 @@ public final class GraphQlWireErrorMapper {
*
* <p>Order: a platform rejection, then an {@link ApiErrorCarrier} — the failure itself or the
* first one in its cause chain, as on every transport (review 2026-11-06 RR7-01-05) — then the
* application's registered mappings, then {@link IllegalArgumentException} as {@code
* BAD_PARAMETER} (the same answer every transport gives), and finally the masked internal error.
* application's registered mappings, then a refused argument as {@code BAD_PARAMETER} (the same
* answer every transport gives), and finally the masked internal error. A refused argument is an
* {@link IllegalArgumentException} or the {@link BindException} Spring for GraphQL's argument
* binder raises when an {@code @Argument} the client sent does not convert to the parameter's
* type, as the web adapter answers a path variable that does not (owner decision 2026-11-07).
* Platform rejections come first: an authorization denial raised from inside a resolver means the
* same thing to a client as one raised before execution. A registered mapping outranks the
* argument rule so an application that models its own {@code IllegalArgumentException} subtype
@@ -128,7 +133,8 @@ public final class GraphQlWireErrorMapper {
/**
* Writes {@link ServerFailureLog}'s line for a failure answered with a shared code: the carrier's
* line at ERROR — the carrier's, not a wrapper's — or nothing for a client-side carrier; an
* unmapped {@link IllegalArgumentException} the WARN line naming its type, as on every transport.
* unmapped refused argument the WARN line naming its type, as on every transport. A binding
* failure's message quotes the rejected value, so it is never logged.
*/
private static void logAnswer(
Throwable failure, ApiErrorCode shared, GraphQlErrorContext context) {
@@ -137,8 +143,8 @@ public final class GraphQlWireErrorMapper {
if (carrier.isPresent()) {
ServerFailureLog.of(carrier.get(), shared)
.ifPresent(line -> LOG.error(line.format(suffix), line.arguments(context.executionId())));
} else if (failure instanceof IllegalArgumentException refused) {
ServerFailureLog line = ServerFailureLog.refusedArgument(refused);
} else if (isRefusedArgument(failure)) {
ServerFailureLog line = ServerFailureLog.refused(OperationalError.BAD_PARAMETER, failure);
LOG.warn(line.format(suffix), line.arguments(context.executionId()));
}
}
@@ -198,7 +204,7 @@ public final class GraphQlWireErrorMapper {
* The shared code a failure carries, or {@code null}: the code of the first carrier in its cause
* chain.
*
* <p>An {@link IllegalArgumentException} the application did not register a mapping for is {@link
* <p>A refused argument the application did not register a mapping for is {@link
* OperationalError#BAD_PARAMETER}, as it is on the web, gRPC and STOMP transports.
*/
private ApiErrorCode sharedCodeOf(Throwable failure) {
@@ -206,9 +212,14 @@ public final class GraphQlWireErrorMapper {
if (carrier.isPresent()) {
return ((ApiErrorCarrier) carrier.get()).errorCode();
}
if (failure instanceof IllegalArgumentException && !applicationMappings.maps(failure)) {
if (isRefusedArgument(failure) && !applicationMappings.maps(failure)) {
return OperationalError.BAD_PARAMETER;
}
return null;
}
/** An argument the request got wrong: thrown as one, or refused by the argument binder. */
private static boolean isRefusedArgument(Throwable failure) {
return failure instanceof IllegalArgumentException || failure instanceof BindException;
}
}
@@ -23,6 +23,7 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
class GraphQlWireErrorMapperTest {
@@ -106,6 +107,21 @@ class GraphQlWireErrorMapperTest {
.containsExactly("BAD_PARAMETER", "REQUEST");
}
@org.junit.jupiter.api.Test
void anArgumentBindingFailureIsABadParameterRequestError() {
// given
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
BindException failure = new BindException(new Object(), "order");
// when
GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test());
// then
assertThat(error.extensions())
.extracting(extensions -> extensions.get("code"), extensions -> extensions.get("category"))
.containsExactly("BAD_PARAMETER", "REQUEST");
}
@org.junit.jupiter.api.Test
void anOversizedRequestIsPayloadTooLarge() {
// given
@@ -0,0 +1,127 @@
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.error.GraphQlWireErrorMapper;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.graphql.ResponseError;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.data.method.annotation.support.AnnotatedControllerConfigurer;
import org.springframework.graphql.execution.DefaultExecutionGraphQlService;
import org.springframework.graphql.execution.GraphQlSource;
import org.springframework.graphql.test.tester.ExecutionGraphQlServiceTester;
import org.springframework.stereotype.Controller;
/**
* A controller {@code @Argument} the client sent that does not convert to the parameter's type.
* Spring for GraphQL's argument binder refuses it with a {@code BindException} before the
* controller runs; the message of that exception quotes the rejected value. Driven through a real
* {@link AnnotatedControllerConfigurer} with this module's resolver, so the failure the mapper sees
* is the one Spring raises.
*/
class GraphQlArgumentBindingFailureTest {
private static final String SCHEMA = "type Query { order(id: ID!): String }";
private static final String QUERY = "{ order(id: \"alice@example.com\") }";
@Test
void anArgumentThatDoesNotConvertIsABadParameterRequestError() {
// when
List<ResponseError> errors = errorsOf(QUERY);
// then
assertThat(errors)
.singleElement()
.extracting(
error -> error.getExtensions().get("code"),
error -> error.getExtensions().get("category"))
.containsExactly("BAD_PARAMETER", "REQUEST");
}
@Test
void anArgumentThatDoesNotConvertIsLoggedAtWarnByItsTypeWithoutTheValue() {
// when
List<ILoggingEvent> logged = loggedWhile(() -> errorsOf(QUERY));
// then
assertThat(logged)
.singleElement()
.extracting(
ILoggingEvent::getLevel,
event ->
event.getFormattedMessage().replaceAll("executionId=[^)]*", "executionId=<id>"),
ILoggingEvent::getThrowableProxy)
.containsExactly(
Level.WARN,
"request refused as BAD_PARAMETER by org.springframework.validation.BindException"
+ " (executionId=<id>)",
null);
}
private static List<ResponseError> errorsOf(String document) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.registerBean(OrderController.class);
context.refresh();
AnnotatedControllerConfigurer controllers = new AnnotatedControllerConfigurer();
controllers.setApplicationContext(context);
controllers.afterPropertiesSet();
GraphQlSource source =
GraphQlSource.schemaResourceBuilder()
.schemaResources(new ByteArrayResource(SCHEMA.getBytes(StandardCharsets.UTF_8)))
.configureRuntimeWiring(controllers)
.exceptionResolvers(
List.of(new GraphQlDataFetcherExceptionResolver(GraphQlWireErrorMapper.masking())))
.build();
List<ResponseError> errors = new ArrayList<>();
try {
ExecutionGraphQlServiceTester.create(new DefaultExecutionGraphQlService(source))
.document(document)
.execute()
.errors()
.satisfy(errors::addAll);
} finally {
context.close();
}
return errors;
}
/** Every WARN or ERROR line this module writes while {@code action} runs. */
private static List<ILoggingEvent> loggedWhile(Runnable action) {
Logger logger = (Logger) LoggerFactory.getLogger("dev.caskeleton.adapter.inbound.graphql");
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
try {
action.run();
} finally {
logger.detachAppender(appender);
appender.stop();
}
return appender.list.stream()
.filter(event -> event.getLevel().isGreaterOrEqual(Level.WARN))
.toList();
}
/** A feature controller whose argument is an id type the client's value does not fit. */
@Controller
static class OrderController {
@QueryMapping
String order(@Argument UUID id) {
return id.toString();
}
}
}
+4 -2
View File
@@ -526,8 +526,10 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
(web-advanced `ADMISSION_REFUSED` = 1초).
- `IDEMPOTENT_IN_FLIGHT` 는 2초: 기본 processing lease(30s)보다 짧아 첫 시도가 끝날 수 있는 동안
같은 키로 다시 묻게 한다. 근거와 클라이언트 행동은 `docs/web/http-contract.md` §2.
- `LOCK_ACQUISITION_TIMEOUT` 은 1초(레지스트리 값). 표가 `Map.of` 의 상한인 10쌍을 채웠다. 더 넣으려면
`Map.ofEntries` 로 바꾼다.
- 표는 레지스트리의 `retry_after_seconds` 가 있는 행마다 한 줄이다(`LOCK_ACQUISITION_TIMEOUT` 1초, DB·outbox·job
코드 포함). `OperationalErrorRegistryContractTest`(app-bootstrap document-contract)가 `OperationalError` 마다 표와
레지스트리를 대조한다. 전에는 대조가 없어 7개가 빠진 채였다(advisor 단위 테스트는 값을 코드마다 손으로 옮겨
적었고, enum·레지스트리 대조 테스트는 category·status·retryable 만 봤다).
---
@@ -11,31 +11,36 @@ import java.util.OptionalInt;
*/
public final class RetryAfterAdvisor {
/** Per-code {@code Retry-After} values (seconds). */
/**
* Per-code {@code Retry-After} values (seconds): the registry's {@code retry_after_seconds}
* column, every row that has one. {@code OperationalErrorRegistryContractTest} (app-bootstrap,
* document-contract) fails when a code here and its registry row differ.
*/
private static final Map<String, Integer> RETRY_AFTER_SECONDS =
Map.of(
"RATE_LIMIT_EXCEEDED",
1,
Map.ofEntries(
Map.entry("RATE_LIMIT_EXCEEDED", 1),
// The application's value, which the processing-lease check also reads: the resend
// arrives while the first attempt can still finish. docs/web/http-contract.md §2.
"IDEMPOTENT_IN_FLIGHT",
Math.toIntExact(IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER.toSeconds()),
"AUTH_KID_UNKNOWN",
5,
"AUTH_JWKS_UNAVAILABLE",
30,
"DEPENDENCY_TIMEOUT",
2,
"DEPENDENCY_CONNECT_FAILED",
2,
"DEPENDENCY_DNS_FAILED",
5,
"DEPENDENCY_5XX_SERVER",
2,
"DEPENDENCY_CIRCUIT_OPEN",
10,
"LOCK_ACQUISITION_TIMEOUT",
1);
Map.entry(
"IDEMPOTENT_IN_FLIGHT",
Math.toIntExact(IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER.toSeconds())),
Map.entry("AUTH_KID_UNKNOWN", 5),
Map.entry("AUTH_JWKS_UNAVAILABLE", 30),
Map.entry("DEPENDENCY_TIMEOUT", 2),
Map.entry("DEPENDENCY_CONNECT_FAILED", 2),
Map.entry("DEPENDENCY_DNS_FAILED", 5),
Map.entry("DEPENDENCY_5XX_SERVER", 2),
Map.entry("DEPENDENCY_CIRCUIT_OPEN", 10),
Map.entry("LOCK_ACQUISITION_TIMEOUT", 1),
Map.entry("DB_UNAVAILABLE", 5),
Map.entry("DB_SERIALIZATION_FAILURE", 1),
Map.entry("DB_DEADLOCK", 1),
Map.entry("DB_IDLE_IN_TX_TIMEOUT", 2),
// Never on an HTTP response today (an async failure's 500 is a placeholder), kept so the
// table and the registry stay one-to-one.
Map.entry("OUTBOX_PUBLISH_FAILED", 30),
Map.entry("JOB_EXECUTOR_REJECTED", 5),
Map.entry("JOB_TIMEOUT", 10));
private RetryAfterAdvisor() {}
@@ -5,6 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.shared.error.OperationalError;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class RetryAfterAdvisorTest {
@@ -103,4 +105,21 @@ class RetryAfterAdvisorTest {
assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.LOCK_ACQUISITION_TIMEOUT))
.hasValue(1);
}
// docs/registries/error-codes.yaml retry_after_seconds of the database, outbox and job rows.
// RetryAfterAdvisor's table once left these out; the registry contract test (app-bootstrap
// OperationalErrorRegistryContractTest) now compares every code.
@ParameterizedTest
@CsvSource({
"DB_UNAVAILABLE, 5",
"DB_SERIALIZATION_FAILURE, 1",
"DB_DEADLOCK, 1",
"DB_IDLE_IN_TX_TIMEOUT, 2",
"OUTBOX_PUBLISH_FAILED, 30",
"JOB_EXECUTOR_REJECTED, 5",
"JOB_TIMEOUT, 10"
})
void aRetryableCodeWithARegisteredDelayHasThatRetryAfter(OperationalError code, int seconds) {
assertThat(RetryAfterAdvisor.retryAfterSeconds(code)).hasValue(seconds);
}
}
+2
View File
@@ -49,6 +49,8 @@
이 예외들의 메시지는 받은 JSON 조각이나 값을 담는다. 그래서 타입만 남긴다. 응답을 JSON으로 쓰지 못한
`MessageConversionException`은 받은 메시지가 실리지 않는다. 서버 탓이라 ERROR로 남는다.
- 그 밖의 예외는 예외와 함께 ERROR. 전에는 Spring이 예외 전체(persistence 실패의 SQL 원인 포함)를 ERROR로 남겼다.
필수 header·destination 변수가 없을 때의 `MessageHandlingException`도 ERROR다. 메시지에 입력값이 없고, Spring이
같은 타입으로 서버 실패도 감싸서 타입만으로는 클라이언트 탓을 가를 수 없다(결정 색인 기본값 2026-11-07).
- `LiveEventProjector<T>` bean이 정확히 하나 있는 `@DomainEvent` 타입만 broadcast한다. 도메인
객체를 그대로 직렬화하지 않고, projector가 만든 bounded `Map<String, String>`만 보낸다.
@@ -2,9 +2,11 @@ package dev.caskeleton.bootstrap.contract;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import dev.caskeleton.shared.error.OperationalError;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
@@ -12,7 +14,9 @@ import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -117,6 +121,50 @@ class OperationalErrorRegistryContractTest {
.isEmpty();
}
/**
* {@code RetryAfterAdvisor} is the one place the web adapter turns a code into a {@code
* Retry-After} header, and its table copies the registry's {@code retry_after_seconds} column.
* The enum-registry comparison above covers category, status and retryability only, and the
* advisor's unit tests copy values code by code, so seven registered delays were missing from the
* table and nothing failed (review 2026-11-07). This compares every code: a registered delay is
* the header, and no registered delay is no header.
*/
@Test
void everyRegisteredRetryAfterIsTheHeaderTheWebAdapterSends() {
// given
Map<String, Map<?, ?>> rows = registryRowsByCode();
Map<String, String> registered = new TreeMap<>();
Map<String, String> advised = new TreeMap<>();
// when
for (OperationalError code : OperationalError.values()) {
Object seconds = rows.getOrDefault(code.code(), Map.of()).get("retry_after_seconds");
registered.put(code.code(), seconds == null ? "none" : String.valueOf(seconds));
OptionalInt header = RetryAfterAdvisor.retryAfterSeconds(code);
advised.put(code.code(), header.isPresent() ? String.valueOf(header.getAsInt()) : "none");
}
// then
assertThat(advised).isNotEmpty().isEqualTo(registered);
}
/** Every registry row with a code, from every section, by its code. */
@SuppressWarnings("unchecked")
private static Map<String, Map<?, ?>> registryRowsByCode() {
Object loaded = new Yaml(new SafeConstructor(new LoaderOptions())).load(read(REGISTRY));
Map<String, Map<?, ?>> rows = new LinkedHashMap<>();
for (Object section : ((Map<String, Object>) loaded).values()) {
if (section instanceof List<?> entries) {
for (Object entry : entries) {
if (entry instanceof Map<?, ?> row && row.get("code") instanceof String code) {
rows.put(code, row);
}
}
}
}
return rows;
}
@SuppressWarnings("unchecked")
private static List<Map<String, Object>> registryRows() {
Object loaded = new Yaml(new SafeConstructor(new LoaderOptions())).load(read(REGISTRY));
+2 -1
View File
@@ -106,7 +106,8 @@ Spring/Lettuce 타입을 노출하지 않는다.
- 그 밖에 전송이 클라이언트 탓으로 알아보는 실패는 `refused(code, failure)`의 같은 모양 WARN 한 줄
`request refused as <code> by <예외 타입>`을 남긴다. code는 web이 같은 실패에 답하는 4xx 코드다. 지금은 STOMP가
읽지 못한 payload·검증 실패를 `VALIDATION_FAILED`로, 변환되지 않는 destination 변수·header를
`BAD_PARAMETER`로 남긴다(재리뷰 RR7-01-06).
`BAD_PARAMETER`로 남긴다(재리뷰 RR7-01-06). GraphQL은 인자 binder가 거부한 `@Argument`(`BindException`)를
`BAD_PARAMETER`로 남긴다(소유자 결정 2026-11-07).
### OperationalError (enum)
스켈레톤 공통 운영/전송/보안 에러 코드의 집합이다. `USER_NOT_FOUND` 같은 **도메인 전용 코드는