diff --git a/docs/fileserver/http-contract.md b/docs/fileserver/http-contract.md index d5518f01..3178e907 100644 --- a/docs/fileserver/http-contract.md +++ b/docs/fileserver/http-contract.md @@ -99,7 +99,7 @@ servlet chain에서 `app.fileserver-platform.security.admin-roles`로 막고, batch 업로드는 공용 bulk envelope다. 모든 part가 성공하면 `success: true`와 `results[]`(part마다 `clientPartId`, `status`, `fileId`)다. 한 part라도 거부되면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`, `error.details[]`다. `details[]` 항목은 part 순서의 `index`, `status`(`ok`·`error`), 성공한 part의 `id`(fileId), 거부된 part의 `code`와 -category 고정 문구 `message`다. 성공한 part는 되돌리지 않는다. +category 고정 문구 `message`다. 부분 실패에서 part는 요청에 보낸 순서의 `index`로 짚는다(`clientPartId`는 전부 성공한 `results[]`에만 있다). 성공한 part는 되돌리지 않는다. ### Envelope 규칙의 프로토콜 예외 diff --git a/docs/upgrade/2026-11-round9-contracts.md b/docs/upgrade/2026-11-round9-contracts.md index 5731f75c..650bcc8c 100644 --- a/docs/upgrade/2026-11-round9-contracts.md +++ b/docs/upgrade/2026-11-round9-contracts.md @@ -17,7 +17,7 @@ | 3 | patch 결과가 Bean Validation 제약을 어기면 `400 VALIDATION_FAILED`와 필드별 `details`가 나간다. patch 대상 타입의 제약을 확인한다 | 전에는 제약을 어긴 객체가 그대로 저장 경로로 갔다 | web-advanced patch를 쓰는 서비스 | | 4 | 스트림 `Failure` 기록의 `code`가 실패의 코드(예: `STREAM_ITEM_TOO_LARGE`) 또는 `INTERNAL_ERROR`다. `DEPENDENCY_FAILURE`로 분기하던 client를 고친다 | 그 분기가 다시는 맞지 않는다 | NDJSON·JSON-seq stream을 읽는 client | | 5 | virtual thread profile을 켠 배포는 이제 실제로 허가 상한을 건다. `admission-limit`이 부하에 맞는지 본다 | 전에는 상한이 없어 모든 요청이 들어왔다. 이제 넘치면 `503 SERVER_BUSY`와 `Retry-After: 1`이다 | `app.web.advanced.mvc-virtual-threads.enabled=true`인 배포 | -| 6 | fileserver batch(`POST /v1/files:batch`)를 읽는 client는 `success`로 가른다. 모두 성공하면 `success: true`와 최상위 `results[]`, 하나라도 실패하면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`, part별 `error.details[]`(`index`, `status`, `id`, `code`, `message`)다 | 전에는 실패가 있어도 `success: true`이고 결과가 `data.results[]`에 있었다. 옛 경로로 읽던 client는 결과를 못 찾는다 | fileserver를 쓰는 서비스와 그 client | +| 6 | fileserver batch(`POST /v1/files:batch`)를 읽는 client는 `success`로 가른다. 모두 성공하면 `success: true`와 최상위 `results[]`, 하나라도 실패하면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`, part별 `error.details[]`(`index`, `status`, `id`, `code`, `message`)다. 부분 실패에서는 part를 요청 순서 `index`로 짚는다(`clientPartId`는 전부 성공한 `results[]`에만 있다) | 전에는 실패가 있어도 `success: true`이고 결과가 `data.results[]`에 있었다. 옛 경로로 읽던 client는 결과를 못 찾는다 | fileserver를 쓰는 서비스와 그 client | | 7 | `BulkItemResult.error(index, code, message)`를 부르던 코드를 `BulkItemResult.error(index, ApiErrorCode)`로 바꾼다. 문구는 code의 category 고정 문구가 된다 | 컴파일이 실패한다 | bulk endpoint를 둔 서비스 | | 8 | 서버 포화 거절을 읽는 client는 `SERVER_BUSY`(503, retryable, `Retry-After: 1`)로 본다. web-advanced `ADMISSION_REFUSED`, fileserver instance·전송 pool 포화의 `TRANSFER_ADMISSION_REJECTED`(429), gRPC 포화의 `RESOURCE_EXHAUSTED`/`RATE_LIMIT_EXCEEDED`가 이 코드로 바뀌었다(gRPC status는 `UNAVAILABLE`). 호출자 자신의 동시 전송 초과만 `TRANSFER_ADMISSION_REJECTED` 429로 남는다 | 옛 코드로 분기하던 재시도 로직이 맞지 않는다. 자바에서 `WebAdvancedError.ADMISSION_REFUSED`를 참조하던 코드는 컴파일이 실패한다 | 세 전송의 client, web-advanced 코드를 참조하던 서비스 | | 9 | 컨테이너가 넘긴 503(필터의 `sendError(503)` 등)은 `SERVER_BUSY`다. 비동기 요청 시간 초과만 `REQUEST_TIMEOUT`이다 | 전에는 모든 503이 `REQUEST_TIMEOUT`이었다 | web을 쓰는 모든 서비스의 client | @@ -26,3 +26,7 @@ | 12 | 이름 없이 올린 파일의 표시 이름이 `upload.bin`에서 `file`이 된다(모든 전송에서 같다) | 표시 이름이 바뀐다. 동작은 같다 | fileserver를 쓰는 서비스 | | 13 | fileserver `ATOMIC_PUBLISH_UNSUPPORTED`(재시도 불가 code)는 더 이상 `Retry-After`를 싣지 않는다. 본문 `retryable=false`와 맞춘 것이다 | 그 헤더로 재시도하던 client가 재시도하지 않는다(원래 재시도해도 소용없는 실패다) | fileserver client | | 14 | 브라우저 client는 `Content-Range`를 읽을 수 있다(CORS 노출 목록에 더함) | — 더하기만 한 변경 | fileserver 다운로드를 이어 받는 브라우저 client | +| 15 | bulk 부분 실패의 `error.message`가 영어 문구에서 category 고정 문구(`ClientErrorMessages`)로 바뀌었다. 항목(`details[]`)은 자기 상태에 맞는 키만 싣는다(성공 항목에 `code`·`message` 키 없음, 실패 항목에 `id` 키 없음) | 문구로 분기하던 client(원래 하면 안 된다)나 null 키를 기대하던 strict client가 다르게 본다 | bulk endpoint를 둔 서비스의 client | +| 16 | 스트림에서 위치가 앞 항목보다 크지 않은 항목은 이제 나가지 않고, 스트림이 `INTERNAL_ERROR` `Failure` 기록으로 끝난다(전에는 그 항목을 쓴 뒤 끝났다) | 서버 결함이 있는 source의 client가 마지막 항목을 받지 않는다 | NDJSON·JSON-seq stream을 읽는 client | +| 17 | 상태만 아는 503·429(Spring이 던진 `ResponseStatusException` 등)도 registry의 `Retry-After`를 싣는다 | — 헤더를 더하기만 한 변경 | web을 쓰는 서비스의 client | +| 18 | virtual thread admission filter가 Spring Security chain 뒤에서 돈다. 인증·권한에서 거절된 요청은 허가를 쓰지 않고, 거절 503에 CORS 헤더가 붙는다 | — | virtual thread profile을 켠 배포 | diff --git a/docs/web/patch-contract.md b/docs/web/patch-contract.md index c340fe85..5ab4cdb2 100644 --- a/docs/web/patch-contract.md +++ b/docs/web/patch-contract.md @@ -64,13 +64,13 @@ JSON Patch 문서는 전부 적용되거나 하나도 적용되지 않는다. ## 검증 patch를 적용한 결과는 필드 하나씩이 아니라 문서 전체로 검증한다. 필드 하나하나는 모두 유효한 patch가 유효하지 않은 -객체를 만들 수 있다. 서로 맞아야 하는 두 필드, 허락되지 않은 상태 전이 같은 것이다. 바뀐 것만 검증하면 그중 아무것도 -보지 못한다. +객체를 만들 수 있다. 서로 맞아야 하는 두 필드가 그런 예다. 바뀐 것만 검증하면 그것을 보지 못한다. - 두 applier는 서비스의 Bean Validation `Validator`를 생성자로 받고, 결과 객체 전체를 검증한 뒤에 돌려준다. 위반은 `@Valid` 본문과 같은 `400 VALIDATION_FAILED`와 필드별 `details`다. - 결과가 자원 타입으로 읽히지 않으면(숫자 자리에 문자열) `400 PATCH_REJECTED`다. -- 상태 전이처럼 업무 규칙인 검증은 여기서 하지 않는다. 유스케이스가 한다. +- 검증하는 대상은 web 표현 DTO이고, 제약은 요청 문법이다(web AGENTS B4·C1). 상태 전이처럼 업무 규칙인 검증은 여기서 + 하지 않는다. 결과를 command로 바꿔 받은 유스케이스가 한다. ## 선행 조건 diff --git a/docs/web/virtual-thread-profile.md b/docs/web/virtual-thread-profile.md index 94522c31..aac36da7 100644 --- a/docs/web/virtual-thread-profile.md +++ b/docs/web/virtual-thread-profile.md @@ -36,8 +36,9 @@ app: `VirtualThreadAdmissionGuard`는 pool이 아니라 공정한 semaphore다. 스레드를 제한하면 기다림을 되돌려 놓고 virtual thread로 얻은 것을 버리게 된다. virtual thread 만 개가 있어도 백 개만 허가를 쥐고 나머지는 문 앞에서 거부된다. -상한은 `VirtualThreadAdmissionFilter`가 모든 요청에 건다. request-id filter 바로 뒤, 보안 chain보다 앞이라 거부된 요청은 -아무 일도 하지 않는다. async 요청은 async 일이 끝날 때까지 허가를 쥔다. 넘겨준 순간 돌려주면 넘기는 일만 제한하고 정작 +상한은 `VirtualThreadAdmissionFilter`가 모든 요청에 건다. Spring Security chain 바로 뒤라, 거절 응답에도 CORS 헤더가 +붙어 브라우저가 503과 `Retry-After`를 읽고, 보안 chain이 거절한 요청(인증 없음, 권한 없음)은 허가를 쓰지 않는다. 거절된 +요청은 handler에 닿지 않는다. async 요청은 async 일이 끝날 때까지 허가를 쥔다. 넘겨준 순간 돌려주면 넘기는 일만 제한하고 정작 하류 pool을 쓰는 일은 제한하지 못한다. 거부는 **`Retry-After`가 붙은 503**(공용 코드 `SERVER_BUSY`)이고, 상한이 만들려는 결과가 바로 그것이다. 1밀리초 만에 거부된 요청이, 받아들여진 뒤 diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java index d0634a5e..aee74a29 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java @@ -24,9 +24,9 @@ import java.util.Objects; * terminal record before closing, and classify a write failure rather than letting it become a 500 * on a response that is already 200. * - *
Positions are enforced here: an item whose sequence is not above the previous one is a server - * fault, and the stream ends with a terminal failure record instead of handing the client a repeat - * or a rewind it would apply. + *
Positions are enforced before each write, by {@code WebStreamEvidence#requireNext}: an item + * whose sequence is not above the previous one is a server fault, and the stream ends with a + * terminal failure record instead of handing the client a repeat or a rewind it would apply. * *
What this writer does not do: it writes synchronously from an iterator on the request thread,
* so it sends no heartbeat while the source is blocked, enforces no idle timeout or maximum age,
@@ -72,13 +72,9 @@ public final class MvcStreamWriter {
try {
while (records.hasNext()) {
NdjsonRecord The guard alone was a bean nothing called: the profile promised a {@code 503} with {@code
* Retry-After} past the limit, and a deployment that switched it on admitted every arrival (review
- * 2026-11-12). A filter, not an interceptor, so the limit covers the whole request including the
- * security chain, and refuses before any of it runs.
+ * 2026-11-12). A filter, not an interceptor, so the limit covers the handler and its async work;
+ * ordered after the security chain (see {@link #ORDER}).
*
* A request that goes async keeps its permit until the async work ends: releasing when this
* thread returns would bound only the hand-off, and the work the limit protects the downstream
@@ -31,8 +31,15 @@ import tools.jackson.databind.ObjectMapper;
*/
public final class VirtualThreadAdmissionFilter extends OncePerRequestFilter implements Ordered {
- /** Right after the request-id filter, so a refusal still carries the request id. */
- public static final int ORDER = Ordered.HIGHEST_PRECEDENCE + 11;
+ /**
+ * Right after the Spring Security filter chain (Boot's {@code SecurityProperties
+ * .DEFAULT_FILTER_ORDER}, -100). Two reasons. The chain applies CORS, so a cross-origin refusal
+ * carries {@code Access-Control-Allow-Origin} and the browser can read its 503 and {@code
+ * Retry-After}; in front of the chain it reached the page as a network error. And a request the
+ * chain refuses (unauthenticated, forbidden) never takes a permit from the admitted ones (review
+ * 2026-11-12).
+ */
+ public static final int ORDER = -99;
private final VirtualThreadAdmissionGuard guard;
private final ObjectMapper objectMapper;
diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java
index cca6b7af..63853ad5 100644
--- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java
+++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchBodies.java
@@ -31,8 +31,10 @@ final class PatchBodies {
/**
* The patched tree as the target type, validated as a whole document.
*
- * Whole, not field by field: two fields that must agree, or a state only some transitions
- * allow, are invisible to a check of the changed fields alone. A violation is the same {@link
+ * Whole, not field by field: two fields whose values must agree are invisible to a check of
+ * the changed fields alone. {@code T} is the web representation DTO, whose constraints are
+ * request syntax (web AGENTS B4·C1); business rules such as allowed state transitions belong to
+ * the use case the caller hands the result to as a command. A violation is the same {@link
* ConstraintViolationException} a {@code @Valid} body raises, so the client gets {@code 400
* VALIDATION_FAILED} with the per-field details it already knows.
*/
diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java
index f02a2b1f..10927ca7 100644
--- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java
+++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java
@@ -38,6 +38,22 @@ public final class WebStreamEvidence {
return streamId;
}
+ /**
+ * Refuse a position before it is written: the same check {@link #recordDelivered} makes after the
+ * write, so a writer can keep a repeat or a rewind off the wire instead of only recording it.
+ *
+ * @throws IllegalStateException if the position does not advance, or the stream already ended
+ */
+ public void requireNext(StreamSequence sequence) {
+ Objects.requireNonNull(sequence, "sequence");
+ lock.lock();
+ try {
+ requireAdvances(sequence);
+ } finally {
+ lock.unlock();
+ }
+ }
+
/**
* Record that an item reached the transport.
*
@@ -47,20 +63,7 @@ public final class WebStreamEvidence {
Objects.requireNonNull(sequence, "sequence");
lock.lock();
try {
- if (termination != null) {
- throw new IllegalStateException(
- "an item was delivered after the stream ended as "
- + termination
- + "; the terminal envelope has already told the client there is nothing more");
- }
- if (lastDelivered != null && sequence.compareTo(lastDelivered) <= 0) {
- throw new IllegalStateException(
- "stream position went from "
- + lastDelivered.value()
- + " to "
- + sequence.value()
- + "; a client deduplicating on position would silently drop this item");
- }
+ requireAdvances(sequence);
lastDelivered = sequence;
deliveredCount++;
} finally {
@@ -68,6 +71,24 @@ public final class WebStreamEvidence {
}
}
+ /** Callers hold the lock. */
+ private void requireAdvances(StreamSequence sequence) {
+ if (termination != null) {
+ throw new IllegalStateException(
+ "an item was delivered after the stream ended as "
+ + termination
+ + "; the terminal envelope has already told the client there is nothing more");
+ }
+ if (lastDelivered != null && sequence.compareTo(lastDelivered) <= 0) {
+ throw new IllegalStateException(
+ "stream position went from "
+ + lastDelivered.value()
+ + " to "
+ + sequence.value()
+ + "; a client deduplicating on position would silently drop this item");
+ }
+ }
+
/** Record how the stream ended. The first call wins; the end happens once. */
public void recordTermination(WebStreamTermination how, Instant at) {
Objects.requireNonNull(how, "how");
diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java
index a5c10cd1..18dbb94d 100644
--- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java
+++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadAdmissionFilterTest.java
@@ -1,13 +1,18 @@
package dev.caskeleton.adapter.inbound.web.advanced.mvc;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.catchThrowable;
+import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.AdmissionRefusedException;
import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadAdmissionGuard;
+import jakarta.servlet.AsyncEvent;
+import jakarta.servlet.AsyncListener;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
+import org.springframework.mock.web.MockAsyncContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import tools.jackson.databind.json.JsonMapper;
@@ -89,4 +94,57 @@ class VirtualThreadAdmissionFilterTest {
.isEqualTo(1);
assertThat(guard.active()).isZero();
}
+
+ @Test
+ @DisplayName("async 시간 초과 뒤 완료가 또 와도 permit은 한 번만 돌아가 상한이 늘지 않는다")
+ void aTimeoutFollowedByCompletionReleasesThePermitOnce() throws Exception {
+ // given
+ VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO);
+ VirtualThreadAdmissionFilter filter =
+ new VirtualThreadAdmissionFilter(guard, JsonMapper.shared());
+ MockHttpServletRequest request = new MockHttpServletRequest("GET", "/orders");
+ request.setAsyncSupported(true);
+ filter.doFilter(
+ request, new MockHttpServletResponse(), (req, res) -> request.startAsync(req, res));
+ MockAsyncContext async = (MockAsyncContext) request.getAsyncContext();
+ AsyncEvent event = new AsyncEvent(async);
+
+ // when — a container calls onTimeout, then onComplete, for one timed-out request
+ for (AsyncListener listener : async.getListeners()) {
+ listener.onTimeout(event);
+ listener.onComplete(event);
+ }
+
+ // then
+ assertThat(guard.active()).isZero();
+ try (VirtualThreadAdmissionGuard.Permit only = guard.enter()) {
+ assertThat(catchThrowable(guard::enter))
+ .as("a permit released twice would let a second request past a limit of one")
+ .isInstanceOf(AdmissionRefusedException.class);
+ }
+ }
+
+ @Test
+ @DisplayName("async가 다시 시작되면 새 cycle에도 permit을 돌려주는 listener가 붙는다")
+ void aRestartedAsyncCycleKeepsTheReleaseListener() throws Exception {
+ // given
+ VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO);
+ VirtualThreadAdmissionFilter filter =
+ new VirtualThreadAdmissionFilter(guard, JsonMapper.shared());
+ MockHttpServletRequest request = new MockHttpServletRequest("GET", "/orders");
+ request.setAsyncSupported(true);
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ filter.doFilter(request, response, (req, res) -> request.startAsync(req, res));
+ MockAsyncContext first = (MockAsyncContext) request.getAsyncContext();
+ MockAsyncContext restarted = new MockAsyncContext(request, response);
+
+ // when
+ for (AsyncListener listener : first.getListeners()) {
+ listener.onStartAsync(new AsyncEvent(restarted));
+ }
+ restarted.complete();
+
+ // then
+ assertThat(guard.active()).isZero();
+ }
}
diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadItemResult.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadItemResult.java
index b2131c4c..72bbf272 100644
--- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadItemResult.java
+++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadItemResult.java
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.inbound.web.fileserver.dto;
+import com.fasterxml.jackson.annotation.JsonInclude;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
import dev.caskeleton.application.fileserver.upload.FileView;
import dev.caskeleton.shared.error.ClientErrorMessages;
@@ -12,7 +13,11 @@ import dev.caskeleton.shared.response.ApiError;
* rolls back a sibling that already succeeded. A rejected part carries the same {@link ApiError}
* the single-file endpoints put in their Envelope: stable code, category, the shared client message
* and {@code retryable}. The server-side message never crosses this boundary.
+ *
+ * Absent members are omitted on the wire, like every envelope field (http-contract §1): an
+ * accepted part has no {@code error} key rather than {@code "error": null}.
*/
+@JsonInclude(JsonInclude.Include.NON_NULL)
public record BatchUploadItemResult(
String clientPartId, String status, String fileId, ApiError error) {
diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java
index 1a6ad304..6d68a418 100644
--- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java
+++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java
@@ -1,10 +1,13 @@
package dev.caskeleton.adapter.inbound.web.fileserver.problem;
+import dev.caskeleton.adapter.inbound.web.error.ErrorResponseFactory;
import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpRangeNotSatisfiableException;
+import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
import dev.caskeleton.application.fileserver.api.error.FileserverException;
import java.util.LinkedHashMap;
import java.util.Map;
+import java.util.OptionalInt;
/**
* The headers a Fileserver failure carries, owned once for every transport.
@@ -30,7 +33,6 @@ public final class FileserverProblemHeaders {
private static final Map The same answer a body constraint gets — {@code 400 VALIDATION_FAILED} with one {@code {field,
* code, message}} detail — rather than the {@code BAD_PARAMETER} a bare {@code
* IllegalArgumentException} reaches, which named nothing the client could correct (review
- * 2026-11-12). The rejected value is not echoed.
+ * 2026-11-12). The detail uses web's validation vocabulary for a value no rule names ({@code
+ * INVALID}, its fixed wording). The rejected value is not echoed.
*/
-final class NotificationFieldRejection extends RuntimeException
+final class NotificationFieldRejectedException extends RuntimeException
implements ApiErrorCarrier, ClientSafeErrorDetails {
private static final long serialVersionUID = 1L;
private final String field;
- NotificationFieldRejection(String field, String reason, Throwable cause) {
+ NotificationFieldRejectedException(String field, String reason, Throwable cause) {
super(reason, cause);
this.field = Objects.requireNonNull(field, "field");
}
@@ -36,6 +37,6 @@ final class NotificationFieldRejection extends RuntimeException
@Override
public Object clientDetails() {
- return List.of(Map.of("field", field, "code", "UNKNOWN_VALUE", "message", "허용된 값이 아닙니다."));
+ return List.of(Map.of("field", field, "code", "INVALID", "message", "값이 올바르지 않습니다."));
}
}
diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java
index 3f01c215..9bc663d0 100644
--- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java
+++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java
@@ -1,7 +1,6 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.submission;
import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory;
-import dev.caskeleton.application.notification.platform.api.routing.Channel;
import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationCommand;
import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationUseCase;
import dev.caskeleton.shared.response.Envelope;
@@ -70,7 +69,7 @@ public final class NotificationSubmissionController {
new AcceptNotificationCommand(
Optional.empty(),
request.recipientRef(),
- channel(request.channel()),
+ NotificationVocabulary.channel(request.channel()),
request.address(),
request.template(),
// An omitted version or locale stays omitted: the use case owns both defaults.
@@ -89,39 +88,10 @@ public final class NotificationSubmissionController {
ResponseMetaFactory.fromMdc()));
}
- /**
- * The channel a caller named.
- *
- * Parsed here rather than bound by Jackson so an unknown name fails as a validation error on
- * the {@code channel} field ({@code VALIDATION_FAILED}), instead of as a deserialization error
- * naming a Java enum.
- */
- private static Channel channel(String name) {
- try {
- return Channel.valueOf(name.trim().toUpperCase(Locale.ROOT));
- } catch (IllegalArgumentException unknown) {
- throw new NotificationFieldRejection(
- "channel",
- "channel must be one of " + java.util.Arrays.toString(Channel.values()),
- unknown);
- }
- }
-
- /**
- * The locale a caller named, or none.
- *
- * {@link Locale#forLanguageTag} answers {@code Locale.ROOT} for anything it cannot parse
- * rather than failing, so an unparseable tag is refused explicitly — silently rendering a Korean
- * notification in the root locale is the kind of wrong that reaches a recipient.
- */
private static Optional 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 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