fix(http): 새 눈 리뷰가 찾은 계약 빈틈을 닫는다
pr / done (pull_request) Canceled after 0s

PR 전 리뷰(계약·시험 렌즈, 구조 리뷰) 발견을 고친다.

- 상태만 아는 503·429(Spring이 던진 ResponseStatusException 등)가 SERVER_BUSY·
  RATE_LIMIT_EXCEEDED로 나가면서 Retry-After를 싣지 않았다. error dispatch는
  싣는데 handleExceptionInternal은 안 실었다. registry 값을 같은 advisor로 단다.
- virtual thread admission filter가 보안 chain 앞이라 cross-origin 거절 503에 CORS
  헤더가 없어 브라우저가 본문도 Retry-After도 못 읽었고, 인증 없는 요청도 permit을
  썼다. chain 바로 뒤(-99)로 옮겼다.
- permit을 한 번만 돌려주는 가드, onTimeout 뒤 onComplete, onStartAsync 재등록을
  지키는 시험이 없었다. 둘을 더했다.
- stream 위치 규칙이 writer와 WebStreamEvidence 두 곳에 있었다. 증거에
  requireNext를 두고 writer가 쓰기 전에 부른다.
- fileserver Retry-After가 좁히기 식을 복사했고 SERVER_BUSY 값을 두 번 적었다.
  ErrorResponseFactory.effectiveRetryable 하나를 같이 쓰고, 공용 이름의 code는
  RetryAfterAdvisor 값을 읽는다. 재시도 불가 code 전부가 헤더를 싣지 않는지 본다.
- batch 전체 성공의 results[]에 "error": null이 나갔다. 항목 record가 null을
  생략한다. batch 시험은 envelope wire 규칙을 실은 mapper로 키 집합을 본다.
- 알림 channel·locale 파싱이 두 controller에 있었다. NotificationVocabulary
  하나로 모으고, detail은 web 검증 어휘(INVALID)를 쓴다. 예외 이름을
  NotificationFieldRejectedException으로 바꿨다(THROWABLES_ARE_NAMED_EXCEPTION).
  template 게시의 거절 시험을 더했다.
- patch 전체 검증 설명에서 상태 전이 예를 뺐다. 검증 대상은 web 표현 DTO이고
  업무 규칙은 유스케이스의 것이다.
- web README의 RetryAfterHint 예시, upgrade 안내 행 넷(bulk 문구·null 키, stream
  역행 항목, 상태만 아는 503·429의 Retry-After, admission filter 순서)과 부분 실패의
  part 짚기(index)를 적었다.

Refs: RR9-03-01, RR9-03-02, RR9-03-06, RR9-03-13, RR9-03-15, RR9-03-23, RR9-03-24, RR9-03-25, RR9-03-27
This commit is contained in:
DongHyeonka
2026-11-13 05:09:45 +09:00
parent f12d007e91
commit 377cf17653
22 changed files with 416 additions and 142 deletions
+1 -1
View File
@@ -99,7 +99,7 @@ servlet chain에서 `app.fileserver-platform.security.admin-roles`로 막고,
batch 업로드는 공용 bulk envelope다. 모든 part가 성공하면 `success: true`와 `results[]`(part마다 `clientPartId`,
`status`, `fileId`)다. 한 part라도 거부되면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`, `error.details[]`다.
`details[]` 항목은 part 순서의 `index`, `status`(`ok`·`error`), 성공한 part의 `id`(fileId), 거부된 part의 `code`와
category 고정 문구 `message`다. 성공한 part는 되돌리지 않는다.
category 고정 문구 `message`다. 부분 실패에서 part는 요청에 보낸 순서의 `index`로 짚는다(`clientPartId`는 전부 성공한 `results[]`에만 있다). 성공한 part는 되돌리지 않는다.
### Envelope 규칙의 프로토콜 예외
+5 -1
View File
@@ -17,7 +17,7 @@
| 3 | patch 결과가 Bean Validation 제약을 어기면 `400 VALIDATION_FAILED`와 필드별 `details`가 나간다. patch 대상 타입의 제약을 확인한다 | 전에는 제약을 어긴 객체가 그대로 저장 경로로 갔다 | web-advanced patch를 쓰는 서비스 |
| 4 | 스트림 `Failure` 기록의 `code`가 실패의 코드(예: `STREAM_ITEM_TOO_LARGE`) 또는 `INTERNAL_ERROR`다. `DEPENDENCY_FAILURE`로 분기하던 client를 고친다 | 그 분기가 다시는 맞지 않는다 | NDJSON·JSON-seq stream을 읽는 client |
| 5 | virtual thread profile을 켠 배포는 이제 실제로 허가 상한을 건다. `admission-limit`이 부하에 맞는지 본다 | 전에는 상한이 없어 모든 요청이 들어왔다. 이제 넘치면 `503 SERVER_BUSY`와 `Retry-After: 1`이다 | `app.web.advanced.mvc-virtual-threads.enabled=true`인 배포 |
| 6 | fileserver batch(`POST /v1/files:batch`)를 읽는 client는 `success`로 가른다. 모두 성공하면 `success: true`와 최상위 `results[]`, 하나라도 실패하면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`, part별 `error.details[]`(`index`, `status`, `id`, `code`, `message`)다 | 전에는 실패가 있어도 `success: true`이고 결과가 `data.results[]`에 있었다. 옛 경로로 읽던 client는 결과를 못 찾는다 | fileserver를 쓰는 서비스와 그 client |
| 6 | fileserver batch(`POST /v1/files:batch`)를 읽는 client는 `success`로 가른다. 모두 성공하면 `success: true`와 최상위 `results[]`, 하나라도 실패하면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`, part별 `error.details[]`(`index`, `status`, `id`, `code`, `message`)다. 부분 실패에서는 part를 요청 순서 `index`로 짚는다(`clientPartId`는 전부 성공한 `results[]`에만 있다) | 전에는 실패가 있어도 `success: true`이고 결과가 `data.results[]`에 있었다. 옛 경로로 읽던 client는 결과를 못 찾는다 | fileserver를 쓰는 서비스와 그 client |
| 7 | `BulkItemResult.error(index, code, message)`를 부르던 코드를 `BulkItemResult.error(index, ApiErrorCode)`로 바꾼다. 문구는 code의 category 고정 문구가 된다 | 컴파일이 실패한다 | bulk endpoint를 둔 서비스 |
| 8 | 서버 포화 거절을 읽는 client는 `SERVER_BUSY`(503, retryable, `Retry-After: 1`)로 본다. web-advanced `ADMISSION_REFUSED`, fileserver instance·전송 pool 포화의 `TRANSFER_ADMISSION_REJECTED`(429), gRPC 포화의 `RESOURCE_EXHAUSTED`/`RATE_LIMIT_EXCEEDED`가 이 코드로 바뀌었다(gRPC status는 `UNAVAILABLE`). 호출자 자신의 동시 전송 초과만 `TRANSFER_ADMISSION_REJECTED` 429로 남는다 | 옛 코드로 분기하던 재시도 로직이 맞지 않는다. 자바에서 `WebAdvancedError.ADMISSION_REFUSED`를 참조하던 코드는 컴파일이 실패한다 | 세 전송의 client, web-advanced 코드를 참조하던 서비스 |
| 9 | 컨테이너가 넘긴 503(필터의 `sendError(503)` 등)은 `SERVER_BUSY`다. 비동기 요청 시간 초과만 `REQUEST_TIMEOUT`이다 | 전에는 모든 503이 `REQUEST_TIMEOUT`이었다 | web을 쓰는 모든 서비스의 client |
@@ -26,3 +26,7 @@
| 12 | 이름 없이 올린 파일의 표시 이름이 `upload.bin`에서 `file`이 된다(모든 전송에서 같다) | 표시 이름이 바뀐다. 동작은 같다 | fileserver를 쓰는 서비스 |
| 13 | fileserver `ATOMIC_PUBLISH_UNSUPPORTED`(재시도 불가 code)는 더 이상 `Retry-After`를 싣지 않는다. 본문 `retryable=false`와 맞춘 것이다 | 그 헤더로 재시도하던 client가 재시도하지 않는다(원래 재시도해도 소용없는 실패다) | fileserver client |
| 14 | 브라우저 client는 `Content-Range`를 읽을 수 있다(CORS 노출 목록에 더함) | — 더하기만 한 변경 | fileserver 다운로드를 이어 받는 브라우저 client |
| 15 | bulk 부분 실패의 `error.message`가 영어 문구에서 category 고정 문구(`ClientErrorMessages`)로 바뀌었다. 항목(`details[]`)은 자기 상태에 맞는 키만 싣는다(성공 항목에 `code`·`message` 키 없음, 실패 항목에 `id` 키 없음) | 문구로 분기하던 client(원래 하면 안 된다)나 null 키를 기대하던 strict client가 다르게 본다 | bulk endpoint를 둔 서비스의 client |
| 16 | 스트림에서 위치가 앞 항목보다 크지 않은 항목은 이제 나가지 않고, 스트림이 `INTERNAL_ERROR` `Failure` 기록으로 끝난다(전에는 그 항목을 쓴 뒤 끝났다) | 서버 결함이 있는 source의 client가 마지막 항목을 받지 않는다 | NDJSON·JSON-seq stream을 읽는 client |
| 17 | 상태만 아는 503·429(Spring이 던진 `ResponseStatusException` 등)도 registry의 `Retry-After`를 싣는다 | — 헤더를 더하기만 한 변경 | web을 쓰는 서비스의 client |
| 18 | virtual thread admission filter가 Spring Security chain 뒤에서 돈다. 인증·권한에서 거절된 요청은 허가를 쓰지 않고, 거절 503에 CORS 헤더가 붙는다 | — | virtual thread profile을 켠 배포 |
+3 -3
View File
@@ -64,13 +64,13 @@ JSON Patch 문서는 전부 적용되거나 하나도 적용되지 않는다.
## 검증
patch를 적용한 결과는 필드 하나씩이 아니라 문서 전체로 검증한다. 필드 하나하나는 모두 유효한 patch가 유효하지 않은
객체를 만들 수 있다. 서로 맞아야 하는 두 필드, 허락되지 않은 상태 전이 같은 것이다. 바뀐 것만 검증하면 그중 아무것도
보지 못한다.
객체를 만들 수 있다. 서로 맞아야 하는 두 필드가 그런 예다. 바뀐 것만 검증하면 그것을 보지 못한다.
- 두 applier는 서비스의 Bean Validation `Validator`를 생성자로 받고, 결과 객체 전체를 검증한 뒤에 돌려준다. 위반은
`@Valid` 본문과 같은 `400 VALIDATION_FAILED`와 필드별 `details`다.
- 결과가 자원 타입으로 읽히지 않으면(숫자 자리에 문자열) `400 PATCH_REJECTED`다.
- 상태 전이처럼 업무 규칙인 검증은 여기서 하지 않는다. 유스케이스가 한다.
- 검증하는 대상은 web 표현 DTO이고, 제약은 요청 문법이다(web AGENTS B4·C1). 상태 전이처럼 업무 규칙인 검증은 여기서
하지 않는다. 결과를 command로 바꿔 받은 유스케이스가 한다.
## 선행 조건
+3 -2
View File
@@ -36,8 +36,9 @@ app:
`VirtualThreadAdmissionGuard`는 pool이 아니라 공정한 semaphore다. 스레드를 제한하면 기다림을 되돌려 놓고 virtual
thread로 얻은 것을 버리게 된다. virtual thread 만 개가 있어도 백 개만 허가를 쥐고 나머지는 문 앞에서 거부된다.
상한은 `VirtualThreadAdmissionFilter`가 모든 요청에 건다. request-id filter 바로 뒤, 보안 chain보다 앞이라 거부된 요청은
아무 일도 하지 않는다. async 요청은 async 일이 끝날 때까지 허가를 쥔다. 넘겨준 순간 돌려주면 넘기는 일만 제한하고 정작
상한은 `VirtualThreadAdmissionFilter`가 모든 요청에 건다. Spring Security chain 바로 뒤라, 거절 응답에도 CORS 헤더가
붙어 브라우저가 503과 `Retry-After`를 읽고, 보안 chain이 거절한 요청(인증 없음, 권한 없음)은 허가를 쓰지 않는다. 거절된
요청은 handler에 닿지 않는다. async 요청은 async 일이 끝날 때까지 허가를 쥔다. 넘겨준 순간 돌려주면 넘기는 일만 제한하고 정작
하류 pool을 쓰는 일은 제한하지 못한다.
거부는 **`Retry-After`가 붙은 503**(공용 코드 `SERVER_BUSY`)이고, 상한이 만들려는 결과가 바로 그것이다. 1밀리초 만에 거부된 요청이, 받아들여진 뒤
@@ -24,9 +24,9 @@ import java.util.Objects;
* terminal record before closing, and classify a write failure rather than letting it become a 500
* on a response that is already 200.
*
* <p>Positions are enforced here: an item whose sequence is not above the previous one is a server
* fault, and the stream ends with a terminal failure record instead of handing the client a repeat
* or a rewind it would apply.
* <p>Positions are enforced before each write, by {@code WebStreamEvidence#requireNext}: an item
* whose sequence is not above the previous one is a server fault, and the stream ends with a
* terminal failure record instead of handing the client a repeat or a rewind it would apply.
*
* <p>What this writer does not do: it writes synchronously from an iterator on the request thread,
* so it sends no heartbeat while the source is blocked, enforces no idle timeout or maximum age,
@@ -72,13 +72,9 @@ public final class MvcStreamWriter {
try {
while (records.hasNext()) {
NdjsonRecord<T> record = records.next();
if (record instanceof NdjsonRecord.Item<T> item && item.sequence() <= lastSequence) {
throw new IllegalStateException(
"stream position "
+ item.sequence()
+ " does not follow "
+ lastSequence
+ "; positions strictly increase");
if (record instanceof NdjsonRecord.Item<T> item) {
// WebStreamEvidence owns the rule; asked before the write so the item never leaves.
evidence.requireNext(new StreamSequence(item.sequence()));
}
writeRecord(record, output);
if (record instanceof NdjsonRecord.Item<T> item) {
@@ -22,8 +22,8 @@ import tools.jackson.databind.ObjectMapper;
*
* <p>The guard alone was a bean nothing called: the profile promised a {@code 503} with {@code
* Retry-After} past the limit, and a deployment that switched it on admitted every arrival (review
* 2026-11-12). A filter, not an interceptor, so the limit covers the whole request including the
* security chain, and refuses before any of it runs.
* 2026-11-12). A filter, not an interceptor, so the limit covers the handler and its async work;
* ordered after the security chain (see {@link #ORDER}).
*
* <p>A request that goes async keeps its permit until the async work ends: releasing when this
* thread returns would bound only the hand-off, and the work the limit protects the downstream
@@ -31,8 +31,15 @@ import tools.jackson.databind.ObjectMapper;
*/
public final class VirtualThreadAdmissionFilter extends OncePerRequestFilter implements Ordered {
/** Right after the request-id filter, so a refusal still carries the request id. */
public static final int ORDER = Ordered.HIGHEST_PRECEDENCE + 11;
/**
* Right after the Spring Security filter chain (Boot's {@code SecurityProperties
* .DEFAULT_FILTER_ORDER}, -100). Two reasons. The chain applies CORS, so a cross-origin refusal
* carries {@code Access-Control-Allow-Origin} and the browser can read its 503 and {@code
* Retry-After}; in front of the chain it reached the page as a network error. And a request the
* chain refuses (unauthenticated, forbidden) never takes a permit from the admitted ones (review
* 2026-11-12).
*/
public static final int ORDER = -99;
private final VirtualThreadAdmissionGuard guard;
private final ObjectMapper objectMapper;
@@ -31,8 +31,10 @@ final class PatchBodies {
/**
* The patched tree as the target type, validated as a whole document.
*
* <p>Whole, not field by field: two fields that must agree, or a state only some transitions
* allow, are invisible to a check of the changed fields alone. A violation is the same {@link
* <p>Whole, not field by field: two fields whose values must agree are invisible to a check of
* the changed fields alone. {@code T} is the web representation DTO, whose constraints are
* request syntax (web AGENTS B4·C1); business rules such as allowed state transitions belong to
* the use case the caller hands the result to as a command. A violation is the same {@link
* ConstraintViolationException} a {@code @Valid} body raises, so the client gets {@code 400
* VALIDATION_FAILED} with the per-field details it already knows.
*/
@@ -38,6 +38,22 @@ public final class WebStreamEvidence {
return streamId;
}
/**
* Refuse a position before it is written: the same check {@link #recordDelivered} makes after the
* write, so a writer can keep a repeat or a rewind off the wire instead of only recording it.
*
* @throws IllegalStateException if the position does not advance, or the stream already ended
*/
public void requireNext(StreamSequence sequence) {
Objects.requireNonNull(sequence, "sequence");
lock.lock();
try {
requireAdvances(sequence);
} finally {
lock.unlock();
}
}
/**
* Record that an item reached the transport.
*
@@ -47,20 +63,7 @@ public final class WebStreamEvidence {
Objects.requireNonNull(sequence, "sequence");
lock.lock();
try {
if (termination != null) {
throw new IllegalStateException(
"an item was delivered after the stream ended as "
+ termination
+ "; the terminal envelope has already told the client there is nothing more");
}
if (lastDelivered != null && sequence.compareTo(lastDelivered) <= 0) {
throw new IllegalStateException(
"stream position went from "
+ lastDelivered.value()
+ " to "
+ sequence.value()
+ "; a client deduplicating on position would silently drop this item");
}
requireAdvances(sequence);
lastDelivered = sequence;
deliveredCount++;
} finally {
@@ -68,6 +71,24 @@ public final class WebStreamEvidence {
}
}
/** Callers hold the lock. */
private void requireAdvances(StreamSequence sequence) {
if (termination != null) {
throw new IllegalStateException(
"an item was delivered after the stream ended as "
+ termination
+ "; the terminal envelope has already told the client there is nothing more");
}
if (lastDelivered != null && sequence.compareTo(lastDelivered) <= 0) {
throw new IllegalStateException(
"stream position went from "
+ lastDelivered.value()
+ " to "
+ sequence.value()
+ "; a client deduplicating on position would silently drop this item");
}
}
/** Record how the stream ended. The first call wins; the end happens once. */
public void recordTermination(WebStreamTermination how, Instant at) {
Objects.requireNonNull(how, "how");
@@ -1,13 +1,18 @@
package dev.caskeleton.adapter.inbound.web.advanced.mvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.AdmissionRefusedException;
import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadAdmissionGuard;
import jakarta.servlet.AsyncEvent;
import jakarta.servlet.AsyncListener;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockAsyncContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import tools.jackson.databind.json.JsonMapper;
@@ -89,4 +94,57 @@ class VirtualThreadAdmissionFilterTest {
.isEqualTo(1);
assertThat(guard.active()).isZero();
}
@Test
@DisplayName("async 시간 초과 뒤 완료가 또 와도 permit은 한 번만 돌아가 상한이 늘지 않는다")
void aTimeoutFollowedByCompletionReleasesThePermitOnce() throws Exception {
// given
VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO);
VirtualThreadAdmissionFilter filter =
new VirtualThreadAdmissionFilter(guard, JsonMapper.shared());
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/orders");
request.setAsyncSupported(true);
filter.doFilter(
request, new MockHttpServletResponse(), (req, res) -> request.startAsync(req, res));
MockAsyncContext async = (MockAsyncContext) request.getAsyncContext();
AsyncEvent event = new AsyncEvent(async);
// when — a container calls onTimeout, then onComplete, for one timed-out request
for (AsyncListener listener : async.getListeners()) {
listener.onTimeout(event);
listener.onComplete(event);
}
// then
assertThat(guard.active()).isZero();
try (VirtualThreadAdmissionGuard.Permit only = guard.enter()) {
assertThat(catchThrowable(guard::enter))
.as("a permit released twice would let a second request past a limit of one")
.isInstanceOf(AdmissionRefusedException.class);
}
}
@Test
@DisplayName("async가 다시 시작되면 새 cycle에도 permit을 돌려주는 listener가 붙는다")
void aRestartedAsyncCycleKeepsTheReleaseListener() throws Exception {
// given
VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO);
VirtualThreadAdmissionFilter filter =
new VirtualThreadAdmissionFilter(guard, JsonMapper.shared());
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/orders");
request.setAsyncSupported(true);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, (req, res) -> request.startAsync(req, res));
MockAsyncContext first = (MockAsyncContext) request.getAsyncContext();
MockAsyncContext restarted = new MockAsyncContext(request, response);
// when
for (AsyncListener listener : first.getListeners()) {
listener.onStartAsync(new AsyncEvent(restarted));
}
restarted.complete();
// then
assertThat(guard.active()).isZero();
}
}
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.inbound.web.fileserver.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
import dev.caskeleton.application.fileserver.upload.FileView;
import dev.caskeleton.shared.error.ClientErrorMessages;
@@ -12,7 +13,11 @@ import dev.caskeleton.shared.response.ApiError;
* rolls back a sibling that already succeeded. A rejected part carries the same {@link ApiError}
* the single-file endpoints put in their Envelope: stable code, category, the shared client message
* and {@code retryable}. The server-side message never crosses this boundary.
*
* <p>Absent members are omitted on the wire, like every envelope field (http-contract §1): an
* accepted part has no {@code error} key rather than {@code "error": null}.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public record BatchUploadItemResult(
String clientPartId, String status, String fileId, ApiError error) {
@@ -1,10 +1,13 @@
package dev.caskeleton.adapter.inbound.web.fileserver.problem;
import dev.caskeleton.adapter.inbound.web.error.ErrorResponseFactory;
import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpRangeNotSatisfiableException;
import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
import dev.caskeleton.application.fileserver.api.error.FileserverException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.OptionalInt;
/**
* The headers a Fileserver failure carries, owned once for every transport.
@@ -30,7 +33,6 @@ public final class FileserverProblemHeaders {
private static final Map<FileserverErrorCode, Integer> RETRY_AFTER_SECONDS =
Map.of(
FileserverErrorCode.TRANSFER_ADMISSION_REJECTED, 1,
FileserverErrorCode.SERVER_BUSY, 1,
FileserverErrorCode.STORAGE_UNAVAILABLE, 30,
FileserverErrorCode.TRANSFER_TIMEOUT, 5,
FileserverErrorCode.FILE_NOT_READY, 2,
@@ -45,13 +47,17 @@ public final class FileserverProblemHeaders {
*/
public static Map<String, String> of(FileserverException failure) {
Map<String, String> headers = new LinkedHashMap<>();
Integer retryAfter = RETRY_AFTER_SECONDS.get(failure.code());
// Only a failure the server itself called retryable advertises a retry: telling a client to
// come back after a permanent rejection is worse than saying nothing. The same narrowing as the
// body (ErrorResponseFactory): the occurrence can only narrow its code, so a code that is never
// retryable never carries the header, whatever the occurrence said (review 2026-11-12).
if (retryAfter != null && failure.code().retryable() && failure.context().retryable()) {
headers.put("Retry-After", String.valueOf(retryAfter));
// come back after a permanent rejection is worse than saying nothing. The body's own rule
// (ErrorResponseFactory.effectiveRetryable): the occurrence can only narrow its code, so a code
// that is never retryable never carries the header, whatever the occurrence said. A code that
// shares its name with an operational one (SERVER_BUSY) takes the registry's value from
// RetryAfterAdvisor rather than a second copy here.
if (ErrorResponseFactory.effectiveRetryable(failure.code(), failure.context().retryable())) {
Integer own = RETRY_AFTER_SECONDS.get(failure.code());
OptionalInt seconds =
own != null ? OptionalInt.of(own) : RetryAfterAdvisor.retryAfterSeconds(failure.code());
seconds.ifPresent(value -> headers.put("Retry-After", String.valueOf(value)));
}
if (failure instanceof HttpRangeNotSatisfiableException unsatisfiable) {
headers.put("Content-Range", "bytes */" + unsatisfiable.representationLength());
@@ -7,6 +7,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeWireFormatConfig;
import dev.caskeleton.adapter.inbound.web.fileserver.mapper.MultipartUploadRequestMapper;
import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapper;
import dev.caskeleton.adapter.inbound.web.fileserver.testkit.FileserverWebFixtures;
@@ -17,13 +18,19 @@ import dev.caskeleton.application.fileserver.api.error.FileserverException;
import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext;
import dev.caskeleton.application.fileserver.upload.CreateUploadRequest;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.util.TreeSet;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
class FileUploadControllerTest {
@@ -42,6 +49,11 @@ class FileUploadControllerTest {
FileserverWebFixtures.contextFactory(),
FileserverWebFixtures.transferExecutor(),
FileserverWebFixtures.properties()))
// The envelope wire rules a deployment's mapper carries, so a key the wire omits is
// asserted absent rather than merely null.
.setMessageConverters(
new JacksonJsonHttpMessageConverter(
JsonMapper.builder().addModule(EnvelopeWireFormatConfig.module()).build()))
.build();
}
@@ -147,7 +159,12 @@ class FileUploadControllerTest {
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.results.length()").value(2))
.andExpect(jsonPath("$.results[0].clientPartId").value("a.txt"))
.andExpect(jsonPath("$.results[1].clientPartId").value("b.txt"));
.andExpect(jsonPath("$.results[1].clientPartId").value("b.txt"))
.andExpect(
result ->
assertThat(keys(json(result).get("results").get(0)))
.as("an accepted part carries no error key, not \"error\": null")
.containsExactlyInAnyOrder("clientPartId", "status", "fileId"));
}
@Test
@@ -174,7 +191,11 @@ class FileUploadControllerTest {
"files", "b.txt", "text/plain", "b".getBytes(StandardCharsets.UTF_8))))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(false))
.andExpect(jsonPath("$.results").doesNotExist())
.andExpect(
result ->
assertThat(keys(json(result)))
.as("a partial failure has no results key at all")
.containsExactlyInAnyOrder("success", "error", "meta"))
.andExpect(jsonPath("$.error.code").value("BATCH_PARTIAL_FAILURE"))
.andExpect(jsonPath("$.error.details[0].status").value("ok"))
.andExpect(jsonPath("$.error.details[0].id").isNotEmpty())
@@ -197,4 +218,14 @@ class FileUploadControllerTest {
assertThat(body).doesNotContain("/tmp").doesNotContain("multipart").doesNotContain("staging");
}
private static JsonNode json(MvcResult result) throws Exception {
return JsonMapper.shared().readTree(result.getResponse().getContentAsString());
}
private static Set<String> keys(JsonNode node) {
Set<String> keys = new TreeSet<>();
node.properties().forEach(entry -> keys.add(entry.getKey()));
return keys;
}
}
@@ -67,6 +67,40 @@ class FileserverProblemHeaderParityTest {
.doesNotContainKey("Retry-After");
}
@Test
@org.junit.jupiter.api.DisplayName(
"공용 이름의 SERVER_BUSY는 registry 값(RetryAfterAdvisor)으로 Retry-After를 싣는다")
void aSharedSaturationCodeTakesTheRegistrysRetryAfter() {
// given
FileserverException failure =
new FileserverException(
"pool full", FileserverFailureContext.of(FileserverErrorCode.SERVER_BUSY, true));
// when
Map<String, String> headers = FileserverProblemHeaders.of(failure);
// then
assertThat(headers).containsEntry("Retry-After", "1");
}
@org.junit.jupiter.params.ParameterizedTest(name = "{0}")
@org.junit.jupiter.params.provider.EnumSource(FileserverErrorCode.class)
@org.junit.jupiter.api.DisplayName("재시도 불가 code는 발생이 재시도 가능이라고 해도 Retry-After를 싣지 않는다")
void aNonRetryableCodeNeverAdvertisesARetry(FileserverErrorCode code) {
// given
org.junit.jupiter.api.Assumptions.assumeFalse(code.retryable(), "a retryable code may");
FileserverException failure =
new FileserverException("refused", FileserverFailureContext.of(code, true));
// when
Map<String, String> headers = FileserverProblemHeaders.of(failure);
// then
assertThat(headers)
.as("the body narrows retryable to false for %s; the header must agree", code)
.doesNotContainKey("Retry-After");
}
@Test
void anUnsatisfiableRangeDisclosesTheRepresentationLength() {
Map<String, String> headers =
@@ -15,16 +15,17 @@ import java.util.Objects;
* <p>The same answer a body constraint gets — {@code 400 VALIDATION_FAILED} with one {@code {field,
* code, message}} detail — rather than the {@code BAD_PARAMETER} a bare {@code
* IllegalArgumentException} reaches, which named nothing the client could correct (review
* 2026-11-12). The rejected value is not echoed.
* 2026-11-12). The detail uses web's validation vocabulary for a value no rule names ({@code
* INVALID}, its fixed wording). The rejected value is not echoed.
*/
final class NotificationFieldRejection extends RuntimeException
final class NotificationFieldRejectedException extends RuntimeException
implements ApiErrorCarrier, ClientSafeErrorDetails {
private static final long serialVersionUID = 1L;
private final String field;
NotificationFieldRejection(String field, String reason, Throwable cause) {
NotificationFieldRejectedException(String field, String reason, Throwable cause) {
super(reason, cause);
this.field = Objects.requireNonNull(field, "field");
}
@@ -36,6 +37,6 @@ final class NotificationFieldRejection extends RuntimeException
@Override
public Object clientDetails() {
return List.of(Map.of("field", field, "code", "UNKNOWN_VALUE", "message", "허용된 값이 아닙니다."));
return List.of(Map.of("field", field, "code", "INVALID", "message", "값이 올바르지 않습니다."));
}
}
@@ -1,7 +1,6 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.submission;
import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory;
import dev.caskeleton.application.notification.platform.api.routing.Channel;
import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationCommand;
import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationUseCase;
import dev.caskeleton.shared.response.Envelope;
@@ -70,7 +69,7 @@ public final class NotificationSubmissionController {
new AcceptNotificationCommand(
Optional.empty(),
request.recipientRef(),
channel(request.channel()),
NotificationVocabulary.channel(request.channel()),
request.address(),
request.template(),
// An omitted version or locale stays omitted: the use case owns both defaults.
@@ -89,39 +88,10 @@ public final class NotificationSubmissionController {
ResponseMetaFactory.fromMdc()));
}
/**
* The channel a caller named.
*
* <p>Parsed here rather than bound by Jackson so an unknown name fails as a validation error on
* the {@code channel} field ({@code VALIDATION_FAILED}), instead of as a deserialization error
* naming a Java enum.
*/
private static Channel channel(String name) {
try {
return Channel.valueOf(name.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException unknown) {
throw new NotificationFieldRejection(
"channel",
"channel must be one of " + java.util.Arrays.toString(Channel.values()),
unknown);
}
}
/**
* The locale a caller named, or none.
*
* <p>{@link Locale#forLanguageTag} answers {@code Locale.ROOT} for anything it cannot parse
* rather than failing, so an unparseable tag is refused explicitly — silently rendering a Korean
* notification in the root locale is the kind of wrong that reaches a recipient.
*/
private static Optional<Locale> locale(String tag) {
if (tag == null || tag.isBlank()) {
return Optional.empty();
}
Locale parsed = Locale.forLanguageTag(tag.trim());
if (parsed.equals(Locale.ROOT)) {
throw new NotificationFieldRejection("locale", "locale must be a BCP 47 language tag", null);
}
return Optional.of(parsed);
return Optional.of(NotificationVocabulary.locale("locale", tag));
}
}
@@ -1,16 +1,11 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.submission;
import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory;
import dev.caskeleton.application.notification.platform.api.routing.Channel;
import dev.caskeleton.application.notification.platform.port.in.PublishNotificationTemplateCommand;
import dev.caskeleton.application.notification.platform.port.in.PublishNotificationTemplateUseCase;
import dev.caskeleton.application.notification.platform.template.TemplateSlot;
import dev.caskeleton.shared.response.Envelope;
import jakarta.validation.Valid;
import java.util.EnumMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
@@ -78,12 +73,12 @@ public final class NotificationTemplateController {
new PublishNotificationTemplateCommand(
request.templateId(),
Optional.ofNullable(request.version()),
channel(request.channel()),
locale(request.locale()),
NotificationVocabulary.channel(request.channel()),
NotificationVocabulary.locale("locale", request.locale()),
Optional.ofNullable(request.fallbackLocale())
.filter(tag -> !tag.isBlank())
.map(tag -> locale("fallbackLocale", tag)),
slots(request.slots()),
.map(tag -> NotificationVocabulary.locale("fallbackLocale", tag)),
NotificationVocabulary.slots(request.slots()),
names(request.requiredVariables()),
names(request.sensitiveVariables()));
@@ -94,55 +89,7 @@ public final class NotificationTemplateController {
ResponseMetaFactory.fromMdc()));
}
/**
* The slots a caller named.
*
* <p>An unknown slot name is refused rather than dropped. Silently ignoring it publishes a
* template missing the content the caller wrote, and the failure then arrives at render time as a
* missing required slot for a template that looks published and complete.
*/
private static Map<TemplateSlot, String> slots(Map<String, String> source) {
Map<TemplateSlot, String> slots = new EnumMap<>(TemplateSlot.class);
source.forEach(
(name, content) -> {
TemplateSlot slot;
try {
slot = TemplateSlot.valueOf(name.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException unknown) {
throw new NotificationFieldRejection(
"slots",
"slot must be one of " + java.util.Arrays.toString(TemplateSlot.values()),
unknown);
}
slots.put(slot, content);
});
return slots;
}
private static Set<String> names(List<String> source) {
return source == null ? Set.of() : Set.copyOf(source);
}
private static Channel channel(String name) {
try {
return Channel.valueOf(name.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException unknown) {
throw new NotificationFieldRejection(
"channel",
"channel must be one of " + java.util.Arrays.toString(Channel.values()),
unknown);
}
}
private static Locale locale(String tag) {
return locale("locale", tag);
}
private static Locale locale(String field, String tag) {
Locale parsed = Locale.forLanguageTag(tag.trim());
if (parsed.equals(Locale.ROOT)) {
throw new NotificationFieldRejection(field, field + " must be a BCP 47 language tag", null);
}
return parsed;
}
}
@@ -0,0 +1,65 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.submission;
import dev.caskeleton.application.notification.platform.api.routing.Channel;
import dev.caskeleton.application.notification.platform.template.TemplateSlot;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Locale;
import java.util.Map;
/**
* The names a notification request may use for a channel, a template slot and a locale, parsed once
* for both controllers.
*
* <p>Parsed here rather than bound by Jackson so an unknown name fails as a validation error on its
* field ({@link NotificationFieldRejectedException}, {@code VALIDATION_FAILED}) instead of as a
* deserialization error naming a Java enum.
*/
final class NotificationVocabulary {
private NotificationVocabulary() {}
static Channel channel(String name) {
try {
return Channel.valueOf(name.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException unknown) {
throw new NotificationFieldRejectedException(
"channel", "channel must be one of " + Arrays.toString(Channel.values()), unknown);
}
}
/**
* A BCP 47 tag. {@link Locale#forLanguageTag} answers {@code Locale.ROOT} for anything it cannot
* parse rather than failing, so an unparseable tag is refused explicitly: silently rendering in
* the root locale is the kind of wrong that reaches a recipient.
*/
static Locale locale(String field, String tag) {
Locale parsed = Locale.forLanguageTag(tag.trim());
if (parsed.equals(Locale.ROOT)) {
throw new NotificationFieldRejectedException(
field, field + " must be a BCP 47 language tag", null);
}
return parsed;
}
/**
* The slots a caller named. An unknown slot is refused rather than dropped: ignoring it publishes
* a template missing the content the caller wrote, which then fails at render time as a missing
* required slot of a template that looks published and complete.
*/
static Map<TemplateSlot, String> slots(Map<String, String> source) {
Map<TemplateSlot, String> slots = new EnumMap<>(TemplateSlot.class);
source.forEach(
(name, content) -> {
TemplateSlot slot;
try {
slot = TemplateSlot.valueOf(name.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException unknown) {
throw new NotificationFieldRejectedException(
"slots", "slot must be one of " + Arrays.toString(TemplateSlot.values()), unknown);
}
slots.put(slot, content);
});
return slots;
}
}
@@ -0,0 +1,67 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.submission;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
import dev.caskeleton.application.notification.platform.port.in.PublishNotificationTemplateCommand;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
class NotificationTemplateControllerTest {
private final List<PublishNotificationTemplateCommand> published = new ArrayList<>();
private final MockMvc mvc =
MockMvcBuilders.standaloneSetup(
new NotificationTemplateController(
command -> {
published.add(command);
throw new IllegalStateException("the probe stops after recording");
}))
.setControllerAdvice(new GlobalExceptionHandler(SpanErrorRecorder.NOOP))
.build();
@ParameterizedTest(name = "{0}")
@CsvSource(
delimiter = '|',
value = {
"channel|\"channel\":\"PIGEON\",\"locale\":\"ko-KR\",\"slots\":{\"SUBJECT\":\"s\"}",
"locale|\"channel\":\"EMAIL\",\"locale\":\"%%%\",\"slots\":{\"SUBJECT\":\"s\"}",
"fallbackLocale|\"channel\":\"EMAIL\",\"locale\":\"ko-KR\",\"fallbackLocale\":\"%%%\",\"slots\":{\"SUBJECT\":\"s\"}",
"slots|\"channel\":\"EMAIL\",\"locale\":\"ko-KR\",\"slots\":{\"FOOTNOTE\":\"s\"}"
})
@DisplayName("template 게시의 모르는 값은 그 필드를 짚는 400 VALIDATION_FAILED이고 use case에 닿지 않는다")
void anUnknownVocabularyValueIsAValidationFailureNamingTheField(String field, String fields)
throws Exception {
// given
String body = "{\"templateId\":\"welcome\"," + fields + "}";
// when
String response =
mvc.perform(
post("/notificationTemplates")
.contentType(MediaType.APPLICATION_JSON)
.content(body))
.andExpect(status().isBadRequest())
.andReturn()
.getResponse()
.getContentAsString();
// then
assertThat(response)
.contains("\"code\":\"VALIDATION_FAILED\"")
.contains("\"field\":\"" + field + "\"")
.doesNotContain("PIGEON")
.doesNotContain("FOOTNOTE");
assertThat(published).isEmpty();
}
}
+1 -1
View File
@@ -532,7 +532,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
이 advisor 가 유일한 Retry-After 노출 지점이라 여기 중앙화한다.
`DEPENDENCY_4XX_CLIENT` 는 비재시도(retryable=false)라 `shouldAdvise` 가드로 empty 반환.
- 다른 leaf 가 소유한 코드는 이 표에 이름으로 넣지 않고 `RetryAfterHint` 를 구현해 값을 스스로 말한다
(web-advanced `ADMISSION_REFUSED` = 1초).
(web-advanced `WebAdvancedError`). 서버 포화는 공용 `SERVER_BUSY`(1초)이고 이 표에 있다.
- `IDEMPOTENT_IN_FLIGHT` 는 2초: 기본 processing lease(30s)보다 짧아 첫 시도가 끝날 수 있는 동안
같은 키로 다시 묻게 한다. 근거와 클라이언트 행동은 `docs/web/http-contract.md` §2.
- 표는 레지스트리의 `retry_after_seconds` 가 있는 행마다 한 줄이다(`LOCK_ACQUISITION_TIMEOUT` 1초, DB·outbox·job
@@ -31,6 +31,14 @@ public final class ErrorResponseFactory {
return body(code, code.retryable(), details);
}
/**
* Whether this occurrence may be retried: the occurrence can only narrow its code. The one rule
* for the body's {@code retryable} and for any {@code Retry-After} a transport adds beside it.
*/
public static boolean effectiveRetryable(ApiErrorCode code, boolean occurrenceRetryable) {
return code.retryable() && occurrenceRetryable;
}
/**
* Body whose {@code retryable} is decided for this occurrence.
*
@@ -39,7 +47,7 @@ public final class ErrorResponseFactory {
*/
public static Envelope<Void> body(ApiErrorCode code, boolean retryable, Object details) {
String message = ClientErrorMessages.of(code);
boolean effectiveRetryable = code.retryable() && retryable;
boolean effectiveRetryable = effectiveRetryable(code, retryable);
ApiError err =
details == null
? ApiError.of(code.code(), code.category().name(), message, effectiveRetryable)
@@ -417,7 +417,20 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
log.error("spring mvc failure classified as {}", code.code(), ex);
spanErrorRecorder.recordException(ex, code.code());
}
// The code's registry Retry-After, as the error dispatch (EnvelopeErrorController) adds it: a
// 503 classified SERVER_BUSY or a 429 RATE_LIMIT_EXCEEDED left without it here (review
// 2026-11-12). A header Spring already prepared wins.
// Copied: the headers Spring hands over may be read-only.
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.putAll(headers);
if (!responseHeaders.containsHeader(ApiHeaders.RETRY_AFTER)) {
RetryAfterAdvisor.retryAfterSeconds(code)
.ifPresent(
seconds -> responseHeaders.set(ApiHeaders.RETRY_AFTER, String.valueOf(seconds)));
}
return new ResponseEntity<>(
ErrorResponseFactory.body(code, null), headers, HttpStatusCode.valueOf(code.httpStatus()));
ErrorResponseFactory.body(code, null),
responseHeaders,
HttpStatusCode.valueOf(code.httpStatus()));
}
}
@@ -124,6 +124,32 @@ class TransportErrorHandlingTest {
.andExpect(jsonPath("$.error.code").value("BAD_PARAMETER"));
}
@Test
@DisplayName("상태만 아는 503은 SERVER_BUSY이고 registry의 Retry-After를 싣는다")
void aBare503IsServerBusyWithItsRetryAfter() throws Exception {
// when
var result = mvc.perform(get("/t/status-503"));
// then
result
.andExpect(status().isServiceUnavailable())
.andExpect(jsonPath("$.error.code").value("SERVER_BUSY"))
.andExpect(header().string("Retry-After", "1"));
}
@Test
@DisplayName("상태만 아는 429도 RATE_LIMIT_EXCEEDED의 Retry-After를 싣는다")
void aBare429CarriesItsRetryAfter() throws Exception {
// when
var result = mvc.perform(get("/t/status-429"));
// then
result
.andExpect(status().isTooManyRequests())
.andExpect(jsonPath("$.error.code").value("RATE_LIMIT_EXCEEDED"))
.andExpect(header().string("Retry-After", "1"));
}
@Test
@DisplayName("비동기 요청 시간 초과는 500이 아니라 재시도 가능한 503 REQUEST_TIMEOUT이다")
void anAsyncTimeoutIsARetryable503NotAnInternalError() throws Exception {
@@ -199,6 +225,18 @@ class TransportErrorHandlingTest {
throw new AsyncRequestTimeoutException();
}
@GetMapping("/t/status-503")
Map<String, String> status503() {
throw new org.springframework.web.server.ResponseStatusException(
org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE);
}
@GetMapping("/t/status-429")
Map<String, String> status429() {
throw new org.springframework.web.server.ResponseStatusException(
org.springframework.http.HttpStatus.TOO_MANY_REQUESTS);
}
@GetMapping("/t/bounded")
Map<String, Integer> bounded(@RequestParam("limit") @Max(10) int limit) {
return Map.of("limit", limit);