fix(inbound)!: 네 전송이 같은 실패에 같은 코드와 로그로 답한다

문제(round7 리뷰 RR7-01-03~06):
- 분산 락 timeout(LockAcquisitionTimeoutException)이 ApiErrorCarrier가
  아니어서 web·GraphQL·gRPC 모두 500 INTERNAL_ERROR(재시도 불가)와
  "unhandled" ERROR로 답한다. 레지스트리·runbook·Javadoc은 409 재시도
  가능을 약속한다. web은 carrier가 되어도 Retry-After 표에 이 코드가
  없어 헤더가 빠진다.
- 다른 예외로 감싼 carrier를 gRPC만 원인 사슬에서 찾고 web·GraphQL·
  STOMP는 500 INTERNAL_ERROR로 답하며 SQL 원인째 ERROR로 남긴다.
- gRPC 서비스가 IllegalArgumentException을 원인으로 든 raw status를
  던지면 INTERNAL_ERROR·ERROR(입력이 든 메시지 첨부)이고, onError로
  넘기면 BAD_PARAMETER·WARN이다.
- STOMP @MessageMapping 앞에서 Spring이 거부한 클라이언트 메시지(읽지
  못한 payload, 비었거나 검증에 걸린 payload, 변환되지 않는
  @DestinationVariable·@Header)를 ERROR와 예외 메시지(받은 JSON 조각·
  값)로 남긴다.

고른 방법:
- shared-contract ApiErrorCarrier.firstIn(Throwable): 원인 사슬의 첫
  carrier를 찾는다(자기 자신 포함, 사슬이 돌면 멈춤). web 처리기 둘,
  GraphQL 매퍼, gRPC 인터셉터, STOMP advice와 ERROR 프레임이 모두 이
  함수를 쓰고 gRPC carrierOf와 STOMP의 carrier 루프는 지웠다. 로그 줄은
  찾은 carrier로 정해 감싼 persistence 실패도 분류 한 줄만 남는다
  (소유자 결정 2026-11-06 (a)).
- LockAcquisitionTimeoutException이 ApiErrorCarrier를 구현한다. errorCode()
  반환 타입은 OperationalError로 둔다(공변 반환, 호출부 변경 없음).
  RetryAfterAdvisor에 LOCK_ACQUISITION_TIMEOUT=1(레지스트리 값)을 더한다.
  버린 안: web 전용 @ExceptionHandler — GraphQL·gRPC가 그대로 남는다.
- gRPC close는 status 예외를 벗긴 실패 하나(failureBehind)로 carrier·IAE
  판정과 로그를 모두 한다. 버린 안: closeWithError에서 status를 다시
  만드는 것 — 판정과 로그가 또 다른 값을 볼 수 있다.
- ServerFailureLog.refused(code, failure): refusedArgument와 같은 WARN
  한 줄(타입만, 메시지·예외 없음). STOMP advice가 받은 메시지가 실린
  MessageConversionException과 MethodArgumentNotValidException을
  VALIDATION_FAILED, @DestinationVariable·@Header 대상
  ConversionFailedException을 BAD_PARAMETER로 남긴다(web이 같은 실패에
  답하는 코드). 응답을 쓰다 난 변환 실패는 받은 메시지가 없어 ERROR로
  남는다.

위험·한계:
- 응답이 바뀐다: 락 timeout 500 → 409(+Retry-After: 1), 감싼 carrier
  500 → 그 carrier 코드, IAE가 감싼 carrier 400 → carrier 코드, gRPC가
  던진 IAE 원인 raw status INTERNAL → INVALID_ARGUMENT. 업그레이드 안내
  B-45·B-46과 5절에 적었다.
- STOMP 쓰기/읽기 변환 실패 구분은 Spring 7.0.9 변환기가 읽기 실패에만
  failedMessage를 싣는 데 기댄다(바이트코드로 확인). 바뀌면
  aReplyTheConverterCannotWriteIsLoggedAtErrorWithTheFailure가 실패한다.
- 고치지 않은 같은 모양(범위 밖, 보고에 적음): RetryAfterAdvisor 표에서
  빠진 레지스트리 값 7개, GraphQL @Argument BindException의
  INTERNAL_ERROR·ERROR, STOMP 필수 header 누락의 ERROR.

검증(desktop, flock /tmp/claude-gates/heavy.lock, 로그 ~/r8-f1-logs/):
- RED(기준 73d39212 + 테스트만): 7개 leaf에서 17건 실패, 모두 위 결함의
  값(500 INTERNAL_ERROR, INTERNAL, ERROR + 입력 메시지 등). red.log,
  red-websocket.log
- GREEN(이 트리 b540d48e): shared-contract 269, application-core 413(skip
  19, 이전부터), web 334, graphql 401, grpc 74, websocket 105,
  app-bootstrap 225(skip 4, 이전부터) 실패 0. green-test.log
- :ci :verifyDependencyLocks --warning-mode=fail rc=0
- :sample-portfolio:check :sample-portfolio:qualityCheck rc=0
- :verifyStrictLaneStages --dry-run, -p optional-platforms 같은 것 rc=0
- -p optional-platforms ci rc=0
- web·graphql·websocket systemTest, :conditionalTransportQualification
  rc=0(web 18, graphql 34+8, grpc 29, websocket 21+7)
- :app-bootstrap:documentContractTest rc=0(66)
- 바뀐 7개 leaf testQualityCheck rc=0
- scripts/verify-compose-profile-contracts.sh rc=0

BREAKING CHANGE: 분산 락 timeout은 409 LOCK_ACQUISITION_TIMEOUT
(retryable, Retry-After: 1), 다른 예외로 감싼 carrier는 web·GraphQL에서도
그 carrier 코드, gRPC가 던진 IllegalArgumentException 원인 raw status는
INVALID_ARGUMENT로 답한다. 클라이언트는 error.code로 가르면 바꿀 것이
없다. 업그레이드 안내 B-45·B-46.
Refs: docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md RR7-01-03, RR7-01-04, RR7-01-05, RR7-01-06
This commit is contained in:
DongHyeonka
2026-11-07 01:14:10 +09:00
parent 73d39212f5
commit 5f6a86d7b7
30 changed files with 804 additions and 100 deletions
+12 -1
View File
@@ -79,7 +79,13 @@ Spring/Lettuce 타입을 노출하지 않는다.
`PersistenceFailureException`, `DependencyFailureException`)와 application 멱등성 예외는 모두
`ApiErrorCarrier` 를 구현한다. web·GraphQL·gRPC·STOMP 어댑터는 carrier 분기 하나로 매핑하므로
타입별 handler 를 따로 두지 않는다. `IllegalArgumentException` 은 모든 전송에서 `BAD_PARAMETER`
(400 / GraphQL `REQUEST` / gRPC `INVALID_ARGUMENT`)다.
(400 / GraphQL `REQUEST` / gRPC `INVALID_ARGUMENT`)다. application 분산 락 timeout
(`LockAcquisitionTimeoutException` → `LOCK_ACQUISITION_TIMEOUT`)도 carrier 다(재리뷰 RR7-01-04 전에는
carrier 가 아니어서 모든 전송이 `INTERNAL_ERROR` 로 답했다).
- 전송은 실패 자신만 보지 않고 원인 사슬의 첫 carrier 를 본다(`ApiErrorCarrier.firstIn`). use case나
adapter가 carrier를 다른 예외로 감싸 던져도 네 전송 모두 그 carrier의 코드로 답한다. 전에는 gRPC만 사슬을
따라가고 web·GraphQL·STOMP는 500 `INTERNAL_ERROR`로 답했다(소유자 결정 2026-11-06, 재리뷰 RR7-01-05).
사슬이 자기 자신으로 돌아오면 거기서 멈춘다.
### ServerFailureLog — 모든 전송이 같은 로그 줄로
- carrier로 답한 실패의 서버 로그 줄을 정한다. web·GraphQL·gRPC·STOMP 어댑터가 이 클래스 하나를 쓴다
@@ -91,11 +97,16 @@ Spring/Lettuce 타입을 노출하지 않는다.
사고가 아니다). `IDEMPOTENCY_RECOVERY_REQUIRED`는 예외 메시지 끝의 scope digest로 runbook이 기록을 찾는다.
- 전송은 자기 상관 정보를 뒤에 붙인다: gRPC ` (method=<서비스/메서드>)`, GraphQL ` (executionId=<id>)`.
예외는 늘 마지막 인자라 SLF4J가 예외로 받는다.
- 로그 줄은 찾은 carrier 의 타입으로 정한다. 감싼 persistence 실패도 감싼 예외나 SQL 원인 없이 분류 한 줄만 남는다.
- `IllegalArgumentException`을 `BAD_PARAMETER`로 답하면 네 전송 모두 `refusedArgument`의 WARN 한 줄
`request refused as BAD_PARAMETER by <예외 타입>`을 남긴다. 사고가 아니라 잘못된 요청이라 ERROR가 아니고,
사실은 서버 조립 실수(`IllegalStateException`이어야 할 것)인 400도 흔적이 남도록 타입은 적는다. 메시지는
입력값이 들 수 있어 남기지 않고 예외도 붙이지 않는다(재리뷰 RR6-01-06 전에는 web만 이 줄을 남기고 STOMP는
ERROR에 메시지까지 남겼다).
- 그 밖에 전송이 클라이언트 탓으로 알아보는 실패는 `refused(code, failure)`의 같은 모양 WARN 한 줄
`request refused as <code> by <예외 타입>`을 남긴다. code는 web이 같은 실패에 답하는 4xx 코드다. 지금은 STOMP가
읽지 못한 payload·검증 실패를 `VALIDATION_FAILED`로, 변환되지 않는 destination 변수·header를
`BAD_PARAMETER`로 남긴다(재리뷰 RR7-01-06).
### OperationalError (enum)
스켈레톤 공통 운영/전송/보안 에러 코드의 집합이다. `USER_NOT_FOUND` 같은 **도메인 전용 코드는
@@ -1,5 +1,10 @@
package dev.caskeleton.shared.error;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Optional;
import java.util.Set;
/**
* Transport-agnostic hook a throwable implements so a single inbound-adapter error handler can map
* it to a protocol status without the skeleton naming the feature. The throwable carries a stable
@@ -20,4 +25,28 @@ public interface ApiErrorCarrier {
/** The classified, client-facing operational code surfaced on the protocol status. */
ApiErrorCode errorCode();
/**
* The first carrier in {@code failure}'s cause chain — {@code failure} itself when it is one.
*
* <p>Every transport finds a failure's code through this, so a carrier that a use case or an
* adapter wrapped in another exception answers with its own code on web, GraphQL, gRPC and STOMP
* alike, instead of {@code INTERNAL_ERROR} on some of them (review 2026-11-06 RR7-01-05). The
* search stops where a cause chain loops back on itself.
*
* @param failure the failure a transport is answering; may be {@code null}
* @return the carrier as the throwable it is — hand that to {@link ServerFailureLog#of}, not the
* wrapper, so its type still decides what may be logged
*/
static Optional<Throwable> firstIn(Throwable failure) {
Set<Throwable> seen = Collections.newSetFromMap(new IdentityHashMap<>());
for (Throwable current = failure;
current != null && seen.add(current);
current = current.getCause()) {
if (current instanceof ApiErrorCarrier) {
return Optional.of(current);
}
}
return Optional.empty();
}
}
@@ -30,7 +30,12 @@ import java.util.Optional;
*
* <p>One line is not an error: {@link #refusedArgument(IllegalArgumentException)}, which every
* transport writes at WARN when it answers an {@link IllegalArgumentException} as {@link
* OperationalError#BAD_PARAMETER}.
* OperationalError#BAD_PARAMETER}, and {@link #refused(ApiErrorCode, Throwable)} for the other
* client failures a transport recognises.
*
* <p>The failure handed to {@link #of} is the carrier itself. A transport finds it with {@link
* ApiErrorCarrier#firstIn(Throwable)}, so a carrier wrapped in another exception is logged by its
* own type — a wrapped persistence failure still by its classification only.
*/
public final class ServerFailureLog {
@@ -89,8 +94,21 @@ public final class ServerFailureLog {
* @param failure the refused argument; a carrier is logged by {@link #of} instead
*/
public static ServerFailureLog refusedArgument(IllegalArgumentException failure) {
return refused(OperationalError.BAD_PARAMETER, failure);
}
/**
* The WARN line for any other failure a transport reads as the client's — a payload it could not
* read, an argument that failed validation — classified as the client-side {@code code} the web
* adapter answers the same failure with. It has {@link #refusedArgument}'s shape: the exception
* type, never its message (a parser's message quotes the input), nothing attached.
*
* @param code the client-side (4xx) code the failure is classified as
* @param failure the refused request's failure
*/
public static ServerFailureLog refused(ApiErrorCode code, Throwable failure) {
return new ServerFailureLog(
"request refused as " + OperationalError.BAD_PARAMETER.code() + " by {}",
"request refused as " + code.code() + " by {}",
new Object[] {failure.getClass().getName()},
null);
}
@@ -0,0 +1,67 @@
package dev.caskeleton.shared.error;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Optional;
import org.junit.jupiter.api.Test;
class ApiErrorCarrierTest {
@Test
void aCarrierIsItsOwnFirstCarrier() {
// given
MappingException carrier = new MappingException("mapping detail");
// when
Optional<Throwable> found = ApiErrorCarrier.firstIn(carrier);
// then
assertThat(found).containsSame(carrier);
}
@Test
void theFirstCarrierBehindWrappersIsFoundAndNotAnOuterOne() {
// given
MappingException inner = new MappingException("inner");
MappingException outer = new MappingException("outer", new IllegalStateException("x", inner));
IllegalStateException wrapper = new IllegalStateException("use case failed", outer);
// when
Optional<Throwable> found = ApiErrorCarrier.firstIn(wrapper);
// then
assertThat(found).containsSame(outer);
}
@Test
void aChainWithoutACarrierHasNone() {
// given
IllegalStateException failure =
new IllegalStateException("x", new IllegalArgumentException("y"));
// when
Optional<Throwable> found = ApiErrorCarrier.firstIn(failure);
// then
assertThat(found).isEmpty();
}
@Test
void aCauseChainThatLoopsEndsTheSearch() {
// given
IllegalStateException first = new IllegalStateException("first");
IllegalStateException second = new IllegalStateException("second", first);
first.initCause(second);
// when
Optional<Throwable> found = ApiErrorCarrier.firstIn(first);
// then
assertThat(found).isEmpty();
}
@Test
void noFailureHasNoCarrier() {
assertThat(ApiErrorCarrier.firstIn(null)).isEmpty();
}
}
@@ -104,6 +104,22 @@ class ServerFailureLogTest {
new Object[] {"java.lang.IllegalArgumentException", "orders.v1.Orders/Charge"});
}
@Test
void aRefusalNamesItsCodeAndTheExceptionTypeWithoutItsMessage() {
// given
RuntimeException failure =
new UnsupportedOperationException("Could not read JSON: {\"to\": \"alice@example.com");
// when
ServerFailureLog line = ServerFailureLog.refused(OperationalError.VALIDATION_FAILED, failure);
// then
assertThat(new Object[] {line.format(""), line.arguments()})
.containsExactly(
"request refused as VALIDATION_FAILED by {}",
new Object[] {"java.lang.UnsupportedOperationException"});
}
@Test
void aTransportsOwnFieldsGoBetweenTheClassificationAndTheAttachedFailure() {
// given