fix(web-advanced)!: patch·stream·virtual thread가 약속한 계약대로 답한다

문제: web-advanced의 계약 문서와 코드가 다섯 곳에서 갈렸다.
- patch 거부가 세 코드로 갈렸다. 형식 오류는 PATCH_REJECTED(400), 빈
  문서·연산 모양 오류·merge 깊이 초과는 IllegalArgumentException이라
  BAD_PARAMETER(400), 너무 깊은 pointer는 권한 거절 PATCH_PATH_FORBIDDEN(403)
  이었다. JSON이 아닌 본문과 결과가 대상 타입으로 읽히지 않는 patch는
  Jackson 예외로 catch-all에 닿아 500 INTERNAL_ERROR였다.
- patch-contract.md는 결과를 문서 전체로 검증한다고 했지만 두 applier는
  검증기를 받지 않았다.
- streaming-contract.md는 서버가 위치 증가를 강제하고 heartbeat·idle·max
  age·버퍼 상한·drain 재연결을 한다고 했다. MvcStreamWriter는 그 어느 것도
  하지 않았다.
- commit 뒤 Failure 기록이 어디에도 등록되지 않은 DEPENDENCY_FAILURE로
  고정이라, STREAM_ITEM_TOO_LARGE 같은 carrier 코드가 사라졌다.
- virtual thread profile은 503 + Retry-After를 약속했지만 admission guard는
  bean만 있었고 요청 경로에서 아무도 부르지 않았다.
- web AGENTS B2는 merge patch를 쓰지 않는다고 했고 patch-contract는 필드
  변경에 merge patch를 쓰라고 했다(정본 충돌).

고른 방법:
- 형식이 틀린 patch 문서는 모두 JsonPatchRejectedException(PATCH_REJECTED)
  이다. 본문 파싱과 결과 변환은 PatchBodies가 감싼다. 너무 깊은 pointer는
  권한 검사 앞에서 400으로 거절한다. 대상 타입이 객체가 아닌 것은 서버
  결함이라 IllegalStateException이다.
- 두 applier가 Bean Validation Validator를 받아 결과 객체 전체를 검증한다.
  위반은 @Valid 본문과 같은 ConstraintViolationException → VALIDATION_FAILED.
- writer는 위치가 앞 항목보다 크지 않으면 그 항목을 쓰지 않고 INTERNAL_ERROR
  Failure 기록으로 끝낸다. Failure 기록은 cause 사슬의 carrier 코드, 없으면
  INTERNAL_ERROR, 문구는 category 고정 문구다.
- writer가 할 수 없는 것(heartbeat, idle·max age, 버퍼, drain)은 계약
  문서를 고쳐 누가 하는지(WebStreamPolicy·Registry·DrainCoordinator를 쓰는
  서비스) 적었다. 요청 thread의 동기 writer라 heartbeat를 넣으려면 thread
  모델을 바꿔야 해서 버렸다.
- VirtualThreadAdmissionFilter가 모든 요청을 guard 아래 둔다(request-id
  filter 바로 뒤). async 요청은 async가 끝날 때 permit을 돌려준다. guard에
  Permit API를 더했다.
- 정본 충돌은 리뷰 README 6절 ③대로 patch-contract를 정본으로 두고 web
  AGENTS B2가 그쪽을 가리킨다.

위험·한계: patch를 쓰는 서비스는 applier 생성자에 Validator를 넘겨야
컴파일된다. client가 보는 patch·stream 오류 코드가 바뀐다. virtual thread
profile을 켠 배포는 처음으로 상한에 걸릴 수 있다(upgrade 안내 1~5).

BREAKING CHANGE: JsonMergePatchApplier·JsonPatchApplier 생성자가 Validator를
받는다. patch 거부는 모두 PATCH_REJECTED(400), 결과 제약 위반은
VALIDATION_FAILED, stream Failure 코드는 실패의 코드나 INTERNAL_ERROR다. 할
일은 docs/upgrade/2026-11-round9-contracts.md.

Refs: RR9-03-23, RR9-03-24, RR9-03-25, RR9-03-26, RR9-03-27, RR9-03-28
This commit is contained in:
DongHyeonka
2026-11-13 04:08:16 +09:00
parent fe0f8141ec
commit 18188f78c9
23 changed files with 610 additions and 54 deletions
+19
View File
@@ -0,0 +1,19 @@
# 업그레이드 안내 — 2026-11 HTTP 계약·오류 코드 정리
- 범위: web-advanced(patch·stream·virtual thread), fileserver·notification HTTP, 전송 오류 코드를 약속한 계약에 맞춘
변경. 응답 코드·모양이 바뀐 곳이 있다. 아래 표가 그 목록이다.
- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 계약·오류 코드 발견
## 1. 누가 읽나
이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스와, 그 서비스의 HTTP 응답을 읽는 client 팀이 읽는다.
## 2. 할 일
| # | 할 일 | 안 하면 | 해당 서비스 |
| --- | --- | --- | --- |
| 1 | `JsonMergePatchApplier`·`JsonPatchApplier`를 만드는 코드에 셋째 인자로 Boot의 `jakarta.validation.Validator` bean을 넘긴다 | 컴파일이 실패한다 | web-advanced patch를 쓰는 서비스 |
| 2 | patch 거부를 읽는 client는 `PATCH_REJECTED`(400) 하나로 본다. 전에는 JSON이 아닌 본문이 `500 INTERNAL_ERROR`, 빈 문서·연산 모양 오류·merge 깊이 초과가 `400 BAD_PARAMETER`, 너무 깊은 pointer가 `403 PATCH_PATH_FORBIDDEN`이었다 | client가 옛 코드로 분기하던 곳이 다른 코드를 받는다 | patch route를 둔 서비스와 그 client |
| 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 ADMISSION_REFUSED`와 `Retry-After: 1`이다 | `app.web.advanced.mvc-virtual-threads.enabled=true`인 배포 |
+1 -1
View File
@@ -10,7 +10,7 @@ Advanced capability는 따로 된 leaf `adapter:inbound:web-advanced`(`src/adapt
| Capability | 켜는 법 | 더하는 것 | 테스트 |
| --- | --- | --- | --- |
| MVC virtual thread | `app.web.advanced.mvc-virtual-threads.enabled=true`(+ 허가 상한과 예산) | **모든** 요청에 대한 다른 스케줄링 모델 | `MvcAdvancedConfigurationTest`, `VirtualThreadAdmissionTest` |
| MVC virtual thread | `app.web.advanced.mvc-virtual-threads.enabled=true`(+ 허가 상한과 예산) | **모든** 요청에 대한 다른 스케줄링 모델과 요청마다 거는 허가 상한(`VirtualThreadAdmissionFilter`) | `MvcAdvancedConfigurationTest`, `VirtualThreadAdmissionTest`, `VirtualThreadAdmissionFilterTest` |
| NDJSON 스트리밍 | `app.web.advanced.ndjson.enabled=true` | 오래 사는 connection | `MvcStreamingWiringTest`, `WebStreamCoreTest`, `WebStreamDrainTest`, `WebStreamingSoakIT` |
| JSON text sequence(RFC 7464) | `app.web.advanced.json-sequence.enabled=true` | 오래 사는 connection | NDJSON과 같다 |
| JSON Merge Patch(RFC 7396) | 라이브러리 — `JsonMergePatchApplier` | 부분 문서 | `JsonMergePatchApplierTest` |
+9
View File
@@ -38,6 +38,10 @@ route는 정확히 하나만 받고, 다른 것을 보내면 최선의 짐작
**한도.** 연산은 최대 100개, pointer 깊이는 최대 16, merge patch 중첩 깊이는 최대 32. 앞의 둘은 곱해진다. 연산마다
서버가 먼저 깊이 복사한 문서 위로 pointer를 따라 걷는다.
**거부 코드.** 형식이 틀린 문서(JSON이 아닌 본문, 빈 문서, 한도 초과, 연산 모양 오류)는 모두 `400 PATCH_REJECTED`다.
허용 목록 밖의 경로만 `403 PATCH_PATH_FORBIDDEN`이고, 실패한 `test`는 `409 PATCH_TEST_FAILED`다. 너무 깊은 pointer는
권한 문제가 아니라 형식 문제라 400이다.
## 원자성
JSON Patch 문서는 전부 적용되거나 하나도 적용되지 않는다. 모든 연산은 작업 사본에서 돈다. 모든 연산이 성공하고
@@ -63,6 +67,11 @@ patch를 적용한 결과는 필드 하나씩이 아니라 문서 전체로 검
객체를 만들 수 있다. 서로 맞아야 하는 두 필드, 허락되지 않은 상태 전이 같은 것이다. 바뀐 것만 검증하면 그중 아무것도
보지 못한다.
- 두 applier는 서비스의 Bean Validation `Validator`를 생성자로 받고, 결과 객체 전체를 검증한 뒤에 돌려준다. 위반은
`@Valid` 본문과 같은 `400 VALIDATION_FAILED`와 필드별 `details`다.
- 결과가 자원 타입으로 읽히지 않으면(숫자 자리에 문자열) `400 PATCH_REJECTED`다.
- 상태 전이처럼 업무 규칙인 검증은 여기서 하지 않는다. 유스케이스가 한다.
## 선행 조건
patch route는 `If-Match`를 요구한다. 그 사이에 바뀐 자원에 대한 부분 갱신은 본 적 없는 버전에 변경을 적용한다.
+16 -11
View File
@@ -12,8 +12,9 @@ writer는 `adapter:inbound:web-advanced`(골라 쓰는 leaf, `app.web.advanced.n
connection은 결과를 알 수 없다. 끝은 셋이다.
1. **`Complete` envelope.** stream이 끝났다. `lastSequence`가 마지막 위치다.
2. **`Failure` 기록.** commit 뒤에 무언가 실패했다. 오류 code와 client에게 보여도 되는 메시지를 담는다. 상태는 여전히
200이다.
2. **`Failure` 기록.** commit 뒤에 무언가 실패했다. 상태는 여전히 200이다. `code`는 실패한 예외의 코드다(예:
`STREAM_ITEM_TOO_LARGE`). 코드가 없는 실패는 등록된 `INTERNAL_ERROR`다. `message`는 그 category의 고정 문구다. commit 전에
던져졌다면 받았을 코드·문구와 같다.
3. **둘 다 아님.** stream 중간에 connection이 닫혔다. 서버는 이것을 `ABRUPT_CLOSE`로 기록한다. client 쪽에서는 *끝
envelope를 찾지 않는 한* 끝난 stream과 구분할 수 없다.
@@ -23,7 +24,7 @@ connection은 결과를 알 수 없다. 끝은 셋이다.
## 위치
모든 `Item`은 1부터 세는 `sequence`를 가진다. 위치는 엄격히 증가하고, 서버가 그것을 강제한다. 반복이나 후퇴는 client가
견뎌야 할 것이 아니라 서버 쪽 오류다.
견뎌야 할 것이 아니라 서버 쪽 오류다. writer는 그런 항목을 쓰지 않고 stream을 `INTERNAL_ERROR` `Failure` 기록으로 끝낸다.
0은 절대 유효한 위치가 아니다. 첫 항목이 0을 주장한 stream과 sequence를 아예 정하지 않은 stream이 똑같아 보이기
때문이다.
@@ -55,21 +56,25 @@ resnapshot은 자원을 보통 endpoint에서 다시 읽고 새 stream을 시작
## Heartbeat와 시간 초과
서버는 `heartbeatInterval`마다 keepalive를 쓴다. 그보다 오래 아무것도 보지 못한 client는 connection이 죽었다고 봐야
한다. socket에서는 조용한 connection과 끊긴 connection이 같고, heartbeat가 둘을 가른다.
writer(`MvcStreamWriter`)는 요청 thread에서 source를 차례로 쓴다. 그래서 heartbeat를 보내지 않고, `idleTimeout`·
`maxStreamAge`로 stream을 닫지도 않는다. 그 값은 `WebStreamPolicy`에 있고, 자기 stream을 `WebStreamRegistry`에 올려
돌리는 서비스가 쓴다.
stream은 `idleTimeout`(만든 것이 없음)과 `maxStreamAge`(활동과 상관없음)에 닫힌다. 둘 다 보통의 끝이고, connection이
허락하면 둘 다 끝 envelope를 보낸다.
- client는 heartbeat를 기대하지 않는다. 자기 읽기 시간 초과를 두고, 그 시간에 아무것도 오지 않으면 끝 envelope 없이
닫힌 것으로 보고 이어 받기 cursor로 다시 연결한다.
- socket에서는 조용한 connection과 끊긴 connection이 같다. heartbeat가 필요한 route는 서비스가 그것을 더하고 이 문서의
route 설명에 적는다.
## 느린 소비자
서버는 뒤처진 소비자를 위해 최대 `maxBufferedItems`까지만 버퍼링한다. 그것을 넘으면 버퍼를 키우지 않고 connection을
닫는다. 따라가지 못하는 client는 서버가 밀린 것을 쥐고 있기를 기대하지 말고, 이어 받기 cursor로 다시 연결한다.
writer는 버퍼를 두지 않는다. 느린 소비자는 서버의 쓰기를 막고, 그동안 source도 멈춘다. 서버 heap에 밀린 항목이 쌓이지
않는다. `maxBufferedItems`는 버퍼를 두는 서비스 구현의 한도다. 따라가지 못하는 client는 이어 받기 cursor로 다시 연결한다.
## 종료
rolling 배포 중에는 노드가 받기를 멈추기 전에 열린 stream이 다시 연결하라는 요청을 받는다. 바로 다시 연결한다. 노드는
drain 기한에 아직 열린 것을 강제로 닫고, 그것은 갑작스러운 닫힘으로 도착한다.
drain 순서(받기를 멈추고, 다시 연결을 요청하고, 기한에 강제로 닫기)는 `WebStreamDrainCoordinator`에 있다. 서비스가
자기 stream을 `WebStreamRegistry`에 등록하고 그 조정기를 종료 순서에 넣었을 때만 돈다. 기본 writer만 쓰는 배포에서는
종료 때 열린 stream이 갑작스러운 닫힘으로 끝난다.
갑작스러운 닫힘에 backoff와 jitter 없이 바로 다시 연결하지 않는다. 노드의 stream이 한꺼번에 끊겼을 때 모든 client가
한꺼번에 다시 연결하면 그것이 교체 노드를 쓰러뜨린다.
+5 -1
View File
@@ -36,7 +36,11 @@ app:
`VirtualThreadAdmissionGuard`는 pool이 아니라 공정한 semaphore다. 스레드를 제한하면 기다림을 되돌려 놓고 virtual
thread로 얻은 것을 버리게 된다. virtual thread 만 개가 있어도 백 개만 허가를 쥐고 나머지는 문 앞에서 거부된다.
거부는 **`Retry-After`가 붙은 503**이고, 상한이 만들려는 결과가 바로 그것이다. 1밀리초 만에 거부된 요청이, 받아들여진 뒤
상한은 `VirtualThreadAdmissionFilter`가 모든 요청에 건다. request-id filter 바로 뒤, 보안 chain보다 앞이라 거부된 요청은
아무 일도 하지 않는다. async 요청은 async 일이 끝날 때까지 허가를 쥔다. 넘겨준 순간 돌려주면 넘기는 일만 제한하고 정작
하류 pool을 쓰는 일은 제한하지 못한다.
거부는 **`Retry-After`가 붙은 503**(`ADMISSION_REFUSED`)이고, 상한이 만들려는 결과가 바로 그것이다. 1밀리초 만에 거부된 요청이, 받아들여진 뒤
가득 찬 pool 뒤에서 30초 뒤에 시간 초과가 난 같은 요청보다 client에게 확실히 낫다.
semaphore는 일부러 공정하다. 불공정한 것이 빠르지만, 새로 온 요청이 기다리던 요청을 앞지르게 두고, 앞지름당한
+1 -1
View File
@@ -58,7 +58,7 @@ virtual thread 실행기는 `TaskDecorator` bean 을 요구한다(요청 상관
| --- | --- | --- | --- | --- | --- | --- |
| `AdmissionRefusedException` | `ADMISSION_REFUSED` | 503 | `TRANSIENT_DEPENDENCY` | true | `Retry-After: 1` | 잠시 뒤 같은 요청 |
| `JsonPatchTestFailedException` | `PATCH_TEST_FAILED` | 409 | `CONFLICT` | false | `details.pointer`(서버 값은 없음) | 다시 읽고 새 patch |
| `JsonPatchRejectedException` | `PATCH_REJECTED` | 400 | `VALIDATION` | false | — | patch 문서를 고친다 |
| `JsonPatchRejectedException` | `PATCH_REJECTED` | 400 | `VALIDATION` | false | — | patch 문서를 고친다. JSON이 아닌 본문, 빈 문서, 한도·깊이 초과, 연산 모양 오류, 결과가 자원 타입으로 읽히지 않는 patch가 모두 이 코드다 |
| `PatchAuthorizationException` | `PATCH_PATH_FORBIDDEN` | 403 | `AUTHZ` | false | `details.refusedPaths` | 해당 경로를 빼거나 권한 확보 |
| `UnsupportedApiVersionException` | `API_VERSION_UNSUPPORTED` | 404 | `NOT_FOUND` | false | — | 지원 버전 경로로 |
| `SunsetViolationException` | `API_DEPRECATION_INVALID` | 500 | `INTERNAL` | false | — | 서버 설정 결함(등록 시점 오류) |
@@ -6,6 +6,10 @@ import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamTermination;
import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.NdjsonRecord;
import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamFraming;
import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.ClientErrorMessages;
import dev.caskeleton.shared.error.OperationalError;
import java.io.IOException;
import java.io.OutputStream;
import java.time.Clock;
@@ -20,6 +24,16 @@ 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>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, and
* keeps no buffer (a slow consumer blocks the source instead). Those bounds are in {@code
* WebStreamPolicy} and the drain in {@code WebStreamDrainCoordinator} for a service that runs its
* streams through {@code WebStreamRegistry}; {@code docs/web/streaming-contract.md} says which.
*
* <p>**Flushing after every record is not optional.** Without it the container buffers, and a
* streaming response that arrives in one chunk at the end is a slow non-streaming response — which
* passes every test that checks the body and fails the only thing the client wanted.
@@ -58,6 +72,14 @@ 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");
}
writeRecord(record, output);
if (record instanceof NdjsonRecord.Item<T> item) {
evidence.recordDelivered(new StreamSequence(item.sequence()));
@@ -91,13 +113,17 @@ public final class MvcStreamWriter {
}
// Otherwise the source failed after commit. The status is already 200, so the failure goes
// into the stream as a terminal record — and if even that cannot be written, it is an abrupt
// close and is recorded as one rather than counted as a completion.
// close and is recorded as one rather than counted as a completion. The record carries the
// failure's own code when it has one (a carrier anywhere in the cause chain, such as
// STREAM_ITEM_TOO_LARGE), else the registered INTERNAL_ERROR, and the category's fixed message:
// the same code and wording a client would have read before commit.
ApiErrorCode code =
ApiErrorCarrier.firstIn(failure)
.map(carrier -> ((ApiErrorCarrier) carrier).errorCode())
.orElse(OperationalError.INTERNAL_ERROR);
try {
writeRecord(
new NdjsonRecord.Failure<T>(
lastSequence,
"DEPENDENCY_FAILURE",
"the stream ended early because a dependency failed"),
new NdjsonRecord.Failure<T>(lastSequence, code.code(), ClientErrorMessages.of(code)),
output);
evidence.recordTermination(WebStreamTermination.TERMINAL_ERROR_RECORD, clock.instant());
return WebStreamTermination.TERMINAL_ERROR_RECORD;
@@ -0,0 +1,111 @@
package dev.caskeleton.adapter.inbound.web.advanced.mvc;
import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.AdmissionRefusedException;
import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadAdmissionGuard;
import dev.caskeleton.adapter.inbound.web.error.EnvelopeResponseWriter;
import dev.caskeleton.adapter.inbound.web.http.ApiHeaders;
import dev.caskeleton.adapter.inbound.web.observability.RetryAfterHint;
import jakarta.servlet.AsyncEvent;
import jakarta.servlet.AsyncListener;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import org.springframework.core.Ordered;
import org.springframework.web.filter.OncePerRequestFilter;
import tools.jackson.databind.ObjectMapper;
/**
* Puts every request under the virtual-thread admission limit.
*
* <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.
*
* <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 pools
* from happens after it.
*/
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;
private final VirtualThreadAdmissionGuard guard;
private final ObjectMapper objectMapper;
public VirtualThreadAdmissionFilter(VirtualThreadAdmissionGuard guard, ObjectMapper objectMapper) {
this.guard = Objects.requireNonNull(guard, "guard");
this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper");
}
@Override
public int getOrder() {
return ORDER;
}
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
VirtualThreadAdmissionGuard.Permit permit;
try {
permit = guard.enter();
} catch (AdmissionRefusedException refused) {
if (refused.errorCode() instanceof RetryAfterHint hint) {
response.setHeader(ApiHeaders.RETRY_AFTER, Integer.toString(hint.retryAfterSeconds()));
}
EnvelopeResponseWriter.write(response, refused.errorCode(), objectMapper);
return;
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new ServletException("interrupted while waiting for admission", interrupted);
}
boolean handedToAsync = false;
try {
chain.doFilter(request, response);
if (request.isAsyncStarted()) {
request.getAsyncContext().addListener(new ReleaseWhenDone(permit));
handedToAsync = true;
}
} finally {
if (!handedToAsync) {
permit.close();
}
}
}
/** Releases the permit when the async request ends, however it ends. */
private static final class ReleaseWhenDone implements AsyncListener {
private final VirtualThreadAdmissionGuard.Permit permit;
ReleaseWhenDone(VirtualThreadAdmissionGuard.Permit permit) {
this.permit = permit;
}
@Override
public void onComplete(AsyncEvent event) {
permit.close();
}
@Override
public void onTimeout(AsyncEvent event) {
permit.close();
}
@Override
public void onError(AsyncEvent event) {
permit.close();
}
@Override
public void onStartAsync(AsyncEvent event) {
// A restarted async cycle drops the listeners of the previous one.
event.getAsyncContext().addListener(this);
}
}
}
@@ -13,6 +13,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.TaskDecorator;
import org.springframework.core.task.support.TaskExecutorAdapter;
import tools.jackson.databind.ObjectMapper;
/**
* Wires the virtual-thread executor and, in the same configuration, the admission limit.
@@ -57,6 +58,17 @@ public class VirtualThreadMvcConfiguration {
properties.getAdmissionLimit(), properties.getAdmissionWait());
}
/**
* The request path through the guard: without this the guard is a bean nothing calls, and the
* profile admits every arrival while promising a 503 past the limit.
*/
@Bean
@ConditionalOnMissingBean
public VirtualThreadAdmissionFilter virtualThreadAdmissionFilter(
VirtualThreadAdmissionGuard guard, ObjectMapper objectMapper) {
return new VirtualThreadAdmissionFilter(guard, objectMapper);
}
/**
* The executor Spring MVC dispatches async request handling onto.
*
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.inbound.web.advanced.patch;
import jakarta.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@@ -23,14 +24,19 @@ import tools.jackson.databind.node.ObjectNode;
public final class JsonMergePatchApplier {
private final ObjectMapper mapper;
private final Validator validator;
private final PatchFieldAuthorization authorization;
/**
* @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean)
* @param authorization which fields may be modified
* @param validator the service's Bean Validation validator (Boot's {@code Validator} bean); the
* patched document is validated whole before it is returned
*/
public JsonMergePatchApplier(ObjectMapper mapper, PatchFieldAuthorization authorization) {
public JsonMergePatchApplier(
ObjectMapper mapper, PatchFieldAuthorization authorization, Validator validator) {
this.mapper = Objects.requireNonNull(mapper, "mapper");
this.validator = Objects.requireNonNull(validator, "validator");
this.authorization = Objects.requireNonNull(authorization, "authorization");
}
@@ -52,7 +58,8 @@ public final class JsonMergePatchApplier {
authorization.validate(patch.fieldNames());
JsonNode before = mapper.valueToTree(current);
if (!before.isObject()) {
throw new IllegalArgumentException("a merge patch target must serialize to a JSON object");
// The target type is the server's choice, so this is a server fault, not a bad request.
throw new IllegalStateException("a merge patch target must serialize to a JSON object");
}
ObjectNode after = merge((ObjectNode) before.deepCopy(), patch.root());
List<String> modified = new ArrayList<>();
@@ -63,7 +70,7 @@ public final class JsonMergePatchApplier {
modified.add(field);
}
}
return new PatchResult<>(mapper.treeToValue(after, type), modified);
return new PatchResult<>(PatchBodies.toTarget(mapper, validator, after, type), modified);
}
private static ObjectNode merge(ObjectNode target, ObjectNode patch) {
@@ -25,7 +25,7 @@ public record JsonMergePatchDocument(ObjectNode root) {
Objects.requireNonNull(root, "root");
int depth = depthOf(root, 1);
if (depth > MAX_DEPTH) {
throw new IllegalArgumentException(
throw new JsonPatchRejectedException(
"a merge patch nested "
+ depth
+ " deep exceeds the "
@@ -56,17 +56,17 @@ public record JsonMergePatchDocument(ObjectNode root) {
*
* @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean)
* @param body the request body
* @throws IllegalArgumentException if the body is not a JSON object
* @throws JsonPatchRejectedException if the body is not JSON or not a JSON object
*/
public static JsonMergePatchDocument parse(ObjectMapper mapper, byte[] body) {
Objects.requireNonNull(mapper, "mapper");
Objects.requireNonNull(body, "body");
JsonNode parsed = mapper.readTree(body);
JsonNode parsed = PatchBodies.readTree(mapper, body);
if (!parsed.isObject()) {
// RFC 7396 permits a scalar or an array as a whole-document replacement. Refused here: a
// merge patch that replaces the entire resource is a PUT, and routing it through the patch
// path skips the full-document validation a PUT gets.
throw new IllegalArgumentException(
throw new JsonPatchRejectedException(
"a merge patch must be a JSON object; a scalar or array patch replaces the whole "
+ "resource, which is a PUT and belongs on the PUT route with its validation");
}
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.inbound.web.advanced.patch;
import jakarta.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@@ -27,14 +28,19 @@ import tools.jackson.databind.node.ObjectNode;
public final class JsonPatchApplier {
private final ObjectMapper mapper;
private final Validator validator;
private final JsonPointerAuthorization authorization;
/**
* @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean)
* @param authorization which pointers may be modified
* @param validator the service's Bean Validation validator (Boot's {@code Validator} bean); the
* patched document is validated whole before it is returned
*/
public JsonPatchApplier(ObjectMapper mapper, JsonPointerAuthorization authorization) {
public JsonPatchApplier(
ObjectMapper mapper, JsonPointerAuthorization authorization, Validator validator) {
this.mapper = Objects.requireNonNull(mapper, "mapper");
this.validator = Objects.requireNonNull(validator, "validator");
this.authorization = Objects.requireNonNull(authorization, "authorization");
}
@@ -61,9 +67,9 @@ public final class JsonPatchApplier {
}
}
if (working.equals(before)) {
return new PatchResult<>(mapper.treeToValue(working, type), List.of());
return new PatchResult<>(PatchBodies.toTarget(mapper, validator, working, type), List.of());
}
return new PatchResult<>(mapper.treeToValue(working, type), touched);
return new PatchResult<>(PatchBodies.toTarget(mapper, validator, working, type), touched);
}
private JsonNode applyOne(JsonNode root, JsonPatchOperation operation) {
@@ -24,7 +24,7 @@ public record JsonPatchDocument(List<JsonPatchOperation> operations) {
public JsonPatchDocument {
operations = List.copyOf(Objects.requireNonNull(operations, "operations"));
if (operations.isEmpty()) {
throw new IllegalArgumentException(
throw new JsonPatchRejectedException(
"an empty patch document changes nothing; sending one is a client bug and answering 200 "
+ "hides it");
}
@@ -43,11 +43,12 @@ public record JsonPatchDocument(List<JsonPatchOperation> operations) {
*
* @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean)
* @param body the request body
* @throws JsonPatchRejectedException if the body is not JSON or not a valid patch document
*/
public static JsonPatchDocument parse(ObjectMapper mapper, byte[] body) {
Objects.requireNonNull(mapper, "mapper");
Objects.requireNonNull(body, "body");
JsonNode root = mapper.readTree(body);
JsonNode root = PatchBodies.readTree(mapper, body);
if (!root.isArray()) {
throw new JsonPatchRejectedException(
"an RFC 6902 patch is an array of operations; an object here is a merge patch sent to "
@@ -26,22 +26,22 @@ public record JsonPatchOperation(
Objects.requireNonNull(value, "value");
Objects.requireNonNull(from, "from");
if (!path.isEmpty() && !path.startsWith("/")) {
throw new IllegalArgumentException("a JSON Pointer is empty or starts with '/': " + path);
throw new JsonPatchRejectedException("a JSON Pointer is empty or starts with '/': " + path);
}
if (kind.requiresValue() != value.isPresent()) {
throw new IllegalArgumentException(
throw new JsonPatchRejectedException(
kind.wireName()
+ (kind.requiresValue()
? " requires a value member"
: " carries no value member, and one here means the client meant a different op"));
}
if (kind.requiresFrom() != from.isPresent()) {
throw new IllegalArgumentException(
throw new JsonPatchRejectedException(
kind.wireName()
+ (kind.requiresFrom() ? " requires a from member" : " carries no from member"));
}
if (from.isPresent() && !from.get().isEmpty() && !from.get().startsWith("/")) {
throw new IllegalArgumentException("a JSON Pointer is empty or starts with '/'");
throw new JsonPatchRejectedException("a JSON Pointer is empty or starts with '/'");
}
if (kind == JsonPatchOperationKind.MOVE
&& from.isPresent()
@@ -49,7 +49,7 @@ public record JsonPatchOperation(
// RFC 6902 section 4.4: the target cannot be inside the source. Moving a subtree into itself
// is not a thing that has a result, and an implementation that tries produces either an
// infinite structure or a silently truncated one.
throw new IllegalArgumentException("a move cannot target a location inside its own source");
throw new JsonPatchRejectedException("a move cannot target a location inside its own source");
}
}
@@ -66,10 +66,21 @@ public final class JsonPointerAuthorization {
/**
* Check every pointer a document names, including {@code from} pointers.
*
* @throws PatchAuthorizationException naming all of them
* @throws JsonPatchRejectedException if a pointer is deeper than {@link #MAX_POINTER_DEPTH}: a
* malformed document, not a permission question
* @throws PatchAuthorizationException naming every pointer the caller may not modify
*/
public void validate(List<JsonPatchOperation> operations) {
Objects.requireNonNull(operations, "operations");
for (JsonPatchOperation operation : operations) {
boolean tooDeep =
depthOf(operation.path()) > MAX_POINTER_DEPTH
|| operation.from().filter(from -> depthOf(from) > MAX_POINTER_DEPTH).isPresent();
if (tooDeep) {
throw new JsonPatchRejectedException(
"a JSON Pointer deeper than " + MAX_POINTER_DEPTH + " segments is over the limit");
}
}
List<String> refused = new ArrayList<>();
for (JsonPatchOperation operation : operations) {
if (operation.kind().mutating() && !writable(operation.path())) {
@@ -0,0 +1,53 @@
package dev.caskeleton.adapter.inbound.web.advanced.patch;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import java.util.Set;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
/**
* The two places a patch meets Jackson, answered as the patch's fault rather than the server's.
*
* <p>A body that is not JSON, and a patched tree that no longer reads as the target type (a string
* where a number was), are both the client's document. Left to Jackson they reached the web
* adapter's catch-all as {@code 500 INTERNAL_ERROR}; here they are {@code 400 PATCH_REJECTED} like
* every other patch the server will not apply (review 2026-11-12).
*/
final class PatchBodies {
private PatchBodies() {}
static JsonNode readTree(ObjectMapper mapper, byte[] body) {
try {
return mapper.readTree(body);
} catch (JacksonException notJson) {
throw new JsonPatchRejectedException("the patch body is not a JSON document");
}
}
/**
* 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
* ConstraintViolationException} a {@code @Valid} body raises, so the client gets {@code 400
* VALIDATION_FAILED} with the per-field details it already knows.
*/
static <T> T toTarget(ObjectMapper mapper, Validator validator, JsonNode patched, Class<T> type) {
T result;
try {
result = mapper.treeToValue(patched, type);
} catch (JacksonException wrongShape) {
throw new JsonPatchRejectedException(
"the patched document no longer reads as the resource: a value has the wrong type");
}
Set<ConstraintViolation<T>> violations = validator.validate(result);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
return result;
}
}
@@ -4,6 +4,7 @@ import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -57,17 +58,42 @@ public final class VirtualThreadAdmissionGuard {
*/
public <T> T run(java.util.concurrent.Callable<T> work) throws Exception {
Objects.requireNonNull(work, "work");
try (Permit permit = enter()) {
return work.call();
}
}
/**
* Take a permit for work that does not end on this thread, such as an async request.
*
* @return the permit; closing it releases, and closing it twice releases once
* @throws AdmissionRefusedException if no permit became available in time
* @throws InterruptedException if interrupted while waiting
*/
public Permit enter() throws InterruptedException {
if (!permits.tryAcquire(acquireTimeout.toMillis(), TimeUnit.MILLISECONDS)) {
rejected.incrementAndGet();
throw new AdmissionRefusedException(limit);
}
int current = active.incrementAndGet();
peakActive.accumulateAndGet(current, Math::max);
try {
return work.call();
} finally {
active.decrementAndGet();
permits.release();
return new Permit();
}
/** One admitted unit of work. */
public final class Permit implements AutoCloseable {
private final AtomicBoolean released = new AtomicBoolean();
private Permit() {}
/** Release, once. An async request ends through more than one listener callback. */
@Override
public void close() {
if (released.compareAndSet(false, true)) {
active.decrementAndGet();
permits.release();
}
}
}
@@ -68,6 +68,7 @@ class MvcAdvancedConfigurationTest {
.hasNotFailed()
.doesNotHaveBean(StreamRecordEncoder.class)
.doesNotHaveBean(VirtualThreadAdmissionGuard.class)
.doesNotHaveBean(VirtualThreadAdmissionFilter.class)
.doesNotHaveBean(AsyncTaskExecutor.class));
}
@@ -125,6 +126,7 @@ class MvcAdvancedConfigurationTest {
.hasNotFailed()
.hasSingleBean(VirtualThreadProfile.class)
.hasSingleBean(VirtualThreadAdmissionGuard.class)
.hasSingleBean(VirtualThreadAdmissionFilter.class)
.hasBean("applicationTaskExecutor");
assertThat(context.getBean(VirtualThreadAdmissionGuard.class).limit()).isEqualTo(100);
assertThat(context.getBean(VirtualThreadProfile.class).databasePoolSize())
@@ -92,7 +92,10 @@ class MvcStreamingWiringTest {
writer.write(failingAfter(NdjsonRecord.item(1, "a")), output, evidence);
assertThat(how).isEqualTo(WebStreamTermination.TERMINAL_ERROR_RECORD);
assertThat(output.text()).contains("DEPENDENCY_FAILURE");
assertThat(output.text())
.as("a failure without a code of its own is the registered INTERNAL_ERROR")
.contains("\"code\":\"INTERNAL_ERROR\"")
.doesNotContain("DEPENDENCY_FAILURE");
assertThat(evidence.termination()).contains(WebStreamTermination.TERMINAL_ERROR_RECORD);
}
@@ -129,6 +132,58 @@ class MvcStreamingWiringTest {
.hasMessageContaining("exceeds the 16 byte ceiling");
}
@Test
@DisplayName("commit 뒤 실패 기록은 실패한 예외의 코드와 고정 문구를 싣는다")
void aTerminalRecordCarriesTheFailuresOwnCode() {
// given
CountingStream output = new CountingStream();
WebStreamPolicy small =
new WebStreamPolicy(
Duration.ofSeconds(15), Duration.ofSeconds(60), Duration.ofMinutes(30), 8, 200);
MvcStreamWriter writer =
new MvcStreamWriter(encoder(small), StreamFraming.NDJSON, Clock.systemUTC());
WebStreamEvidence evidence = new WebStreamEvidence(new StreamId("feed"), NOW);
// when
WebStreamTermination how =
writer.write(
List.<NdjsonRecord<String>>of(
NdjsonRecord.item(1, "a"), NdjsonRecord.item(2, "x".repeat(1_000)))
.iterator(),
output,
evidence);
// then
assertThat(how).isEqualTo(WebStreamTermination.TERMINAL_ERROR_RECORD);
assertThat(output.text())
.contains("\"code\":\"STREAM_ITEM_TOO_LARGE\"")
.contains(dev.caskeleton.shared.error.ClientErrorMessages.OPAQUE);
}
@Test
@DisplayName("위치가 앞 항목보다 크지 않으면 서버 오류로 끝내고 그 항목은 쓰지 않는다")
void aRepeatedPositionEndsTheStreamInsteadOfReachingTheClient() {
// given
CountingStream output = new CountingStream();
MvcStreamWriter writer =
new MvcStreamWriter(
encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON, Clock.systemUTC());
WebStreamEvidence evidence = new WebStreamEvidence(new StreamId("feed"), NOW);
// when
WebStreamTermination how =
writer.write(
List.<NdjsonRecord<String>>of(
NdjsonRecord.item(1, "a"), NdjsonRecord.item(2, "b"), NdjsonRecord.item(2, "c"))
.iterator(),
output,
evidence);
// then
assertThat(how).isEqualTo(WebStreamTermination.TERMINAL_ERROR_RECORD);
assertThat(output.text()).doesNotContain("\"c\"").contains("\"code\":\"INTERNAL_ERROR\"");
}
/** A stream that counts flushes and can fail on a chosen write. */
private static final class CountingStream extends OutputStream {
@@ -0,0 +1,87 @@
package dev.caskeleton.adapter.inbound.web.advanced.mvc;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadAdmissionGuard;
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.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import tools.jackson.databind.json.JsonMapper;
/** The request path through the admission guard. */
@Tag("web-advanced")
class VirtualThreadAdmissionFilterTest {
@Test
@DisplayName("한도가 차면 요청은 controller에 닿지 않고 503 ADMISSION_REFUSED와 Retry-After를 받는다")
void aFullLimitRefusesWith503AndRetryAfter() throws Exception {
// given
VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO);
VirtualThreadAdmissionFilter filter =
new VirtualThreadAdmissionFilter(guard, JsonMapper.shared());
AtomicInteger reached = new AtomicInteger();
MockHttpServletResponse response = new MockHttpServletResponse();
// when
try (VirtualThreadAdmissionGuard.Permit held = guard.enter()) {
filter.doFilter(
new MockHttpServletRequest("GET", "/orders"),
response,
(request, servletResponse) -> reached.incrementAndGet());
}
// then
assertThat(reached).as("the guard was a bean nothing called").hasValue(0);
assertThat(response.getStatus()).isEqualTo(503);
assertThat(response.getHeader("Retry-After")).isEqualTo("1");
assertThat(response.getContentAsString()).contains("ADMISSION_REFUSED");
assertThat(guard.rejectedCount()).isEqualTo(1);
}
@Test
@DisplayName("동기 요청은 끝나면 permit을 돌려준다")
void aSynchronousRequestReleasesItsPermit() throws Exception {
// given
VirtualThreadAdmissionGuard guard = new VirtualThreadAdmissionGuard(1, Duration.ZERO);
VirtualThreadAdmissionFilter filter =
new VirtualThreadAdmissionFilter(guard, JsonMapper.shared());
AtomicInteger activeInside = new AtomicInteger(-1);
// when
filter.doFilter(
new MockHttpServletRequest("GET", "/orders"),
new MockHttpServletResponse(),
(request, response) -> activeInside.set(guard.active()));
// then
assertThat(activeInside).hasValue(1);
assertThat(guard.active()).isZero();
}
@Test
@DisplayName("async 요청은 async 일이 끝날 때까지 permit을 쥔다")
void anAsyncRequestHoldsItsPermitUntilTheAsyncWorkEnds() 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();
// when
filter.doFilter(request, response, (req, res) -> request.startAsync(req, res));
int activeAfterHandOff = guard.active();
request.getAsyncContext().complete();
// then
assertThat(activeAfterHandOff)
.as("releasing on hand-off would bound only the hand-off, not the work")
.isEqualTo(1);
assertThat(guard.active()).isZero();
}
}
@@ -2,7 +2,12 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
@@ -20,12 +25,15 @@ import tools.jackson.databind.json.JsonMapper;
class JsonMergePatchApplierTest {
private static final ObjectMapper MAPPER = JsonMapper.shared();
private static final Validator VALIDATOR =
Validation.buildDefaultValidatorFactory().getValidator();
/** A target with a mandatory field and two optional ones. */
record Profile(String displayName, String description, String nickname) {}
private static JsonMergePatchApplier applier(String... writableFields) {
return new JsonMergePatchApplier(MAPPER, PatchFieldAuthorization.allow(writableFields));
return new JsonMergePatchApplier(
MAPPER, PatchFieldAuthorization.allow(writableFields), VALIDATOR);
}
private static JsonMergePatchDocument patch(String json) {
@@ -118,7 +126,7 @@ class JsonMergePatchApplierTest {
// A whole-document replacement is a PUT, and routing it through the patch path skips the
// full-document validation a PUT gets.
assertThatThrownBy(() -> patch("[1,2,3]"))
.isInstanceOf(IllegalArgumentException.class)
.isInstanceOf(JsonPatchRejectedException.class)
.hasMessageContaining("belongs on the PUT route");
}
@@ -135,7 +143,7 @@ class JsonMergePatchApplierTest {
deep.append("}".repeat(40));
assertThatThrownBy(() -> patch(deep.toString()))
.isInstanceOf(IllegalArgumentException.class)
.isInstanceOf(JsonPatchRejectedException.class)
.hasMessageContaining("can turn into a 400");
}
@@ -153,4 +161,38 @@ class JsonMergePatchApplierTest {
assertThat(PatchMediaType.MERGE_PATCH).isEqualTo("application/merge-patch+json");
assertThat(PatchMediaType.JSON_PATCH).isEqualTo("application/json-patch+json");
}
@Test
@DisplayName("JSON이 아닌 merge patch 본문은 400 PATCH_REJECTED로 거절된다")
void aMergePatchBodyThatIsNotJsonIsRejected() {
// given
String notJson = "displayName=new";
// when
Throwable thrown = catchThrowable(() -> patch(notJson));
// then
assertThat(thrown).isInstanceOf(JsonPatchRejectedException.class);
}
/** A target whose field may be patched but not deleted. */
record Required(@NotNull String displayName, String nickname) {}
@Test
@DisplayName("merge patch 결과는 문서 전체로 검증되고 위반은 VALIDATION_FAILED가 받는 예외로 나간다")
void theMergedDocumentIsValidatedWhole() {
// given
JsonMergePatchApplier applier =
new JsonMergePatchApplier(MAPPER, PatchFieldAuthorization.allow("displayName"), VALIDATOR);
JsonMergePatchDocument deleting = patch("{\"displayName\":null}");
// when
Throwable thrown =
catchThrowable(() -> applier.apply(new Required("old", "n"), deleting, Required.class));
// then
assertThat(thrown)
.as("the patch is allowed field by field; only the whole document breaks the constraint")
.isInstanceOf(ConstraintViolationException.class);
}
}
@@ -2,7 +2,12 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.NotBlank;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
@@ -21,6 +26,8 @@ import tools.jackson.databind.json.JsonMapper;
class JsonPatchApplierTest {
private static final ObjectMapper MAPPER = JsonMapper.shared();
private static final Validator VALIDATOR =
Validation.buildDefaultValidatorFactory().getValidator();
/** A target with a scalar, a nested object and a list. */
record Profile(String displayName, int version, Address address, List<String> tags) {}
@@ -33,7 +40,8 @@ class JsonPatchApplierTest {
}
private static JsonPatchApplier applier(String... writablePrefixes) {
return new JsonPatchApplier(MAPPER, JsonPointerAuthorization.allow(writablePrefixes));
return new JsonPatchApplier(
MAPPER, JsonPointerAuthorization.allow(writablePrefixes), VALIDATOR);
}
private static JsonPatchDocument patch(String json) {
@@ -212,10 +220,10 @@ class JsonPatchApplierTest {
// Discovered halfway through, it would be a document that has already modified the working
// copy.
assertThatThrownBy(() -> patch("[{\"op\":\"replace\",\"path\":\"/displayName\"}]"))
.isInstanceOf(IllegalArgumentException.class)
.isInstanceOf(JsonPatchRejectedException.class)
.hasMessageContaining("requires a value member");
assertThatThrownBy(() -> patch("[{\"op\":\"move\",\"path\":\"/displayName\"}]"))
.isInstanceOf(IllegalArgumentException.class)
.isInstanceOf(JsonPatchRejectedException.class)
.hasMessageContaining("requires a from member");
}
@@ -224,7 +232,7 @@ class JsonPatchApplierTest {
void moveIntoOwnSourceIsRefused() {
assertThatThrownBy(
() -> patch("[{\"op\":\"move\",\"from\":\"/address\",\"path\":\"/address/self\"}]"))
.isInstanceOf(IllegalArgumentException.class)
.isInstanceOf(JsonPatchRejectedException.class)
.hasMessageContaining("inside its own source");
}
@@ -232,7 +240,77 @@ class JsonPatchApplierTest {
@DisplayName("an empty patch document is refused")
void emptyDocumentIsRefused() {
assertThatThrownBy(() -> patch("[]"))
.isInstanceOf(IllegalArgumentException.class)
.isInstanceOf(JsonPatchRejectedException.class)
.hasMessageContaining("client bug");
}
@Test
@DisplayName("JSON이 아닌 본문은 400 PATCH_REJECTED로 거절된다")
void aBodyThatIsNotJsonIsRejectedAsAPatch() {
// given
String notJson = "op=replace&path=/displayName";
// when
Throwable thrown = catchThrowable(() -> patch(notJson));
// then
assertThat(thrown)
.as("left to Jackson the parse error reached the catch-all as 500 INTERNAL_ERROR")
.isInstanceOf(JsonPatchRejectedException.class);
}
@Test
@DisplayName("너무 깊은 pointer는 권한 거절(403)이 아니라 문서 거절(400)이다")
void aTooDeepPointerIsAMalformedDocumentNotAPermissionRefusal() {
// given
String deep = "/displayName" + "/x".repeat(JsonPointerAuthorization.MAX_POINTER_DEPTH);
JsonPatchDocument document =
patch("[{\"op\":\"replace\",\"path\":\"" + deep + "\",\"value\":\"v\"}]");
// when
Throwable thrown =
catchThrowable(
() -> applier("/displayName").apply(profile(), document, Profile.class));
// then
assertThat(thrown).isInstanceOf(JsonPatchRejectedException.class);
}
@Test
@DisplayName("patch 결과가 대상 타입으로 읽히지 않으면 400 PATCH_REJECTED다")
void aPatchThatBreaksTheTargetTypeIsRejected() {
// given
JsonPatchDocument document =
patch("[{\"op\":\"replace\",\"path\":\"/version\",\"value\":\"not-a-number\"}]");
// when
Throwable thrown =
catchThrowable(
() -> applier("/version").apply(profile(), document, Profile.class));
// then
assertThat(thrown).isInstanceOf(JsonPatchRejectedException.class);
}
/** A target with a constraint across the whole document. */
record Named(@NotBlank String displayName, String nickname) {}
@Test
@DisplayName("patch 결과는 문서 전체로 검증되고 위반은 VALIDATION_FAILED가 받는 예외로 나간다")
void thePatchedDocumentIsValidatedWhole() {
// given
JsonPatchApplier applier =
new JsonPatchApplier(MAPPER, JsonPointerAuthorization.allow("/displayName"), VALIDATOR);
JsonPatchDocument blanking =
patch("[{\"op\":\"replace\",\"path\":\"/displayName\",\"value\":\" \"}]");
// when
Throwable thrown =
catchThrowable(() -> applier.apply(new Named("old", "n"), blanking, Named.class));
// then
assertThat(thrown)
.as("each operation is well formed, and only the whole document breaks the constraint")
.isInstanceOf(ConstraintViolationException.class);
}
}
+5 -3
View File
@@ -62,9 +62,11 @@ bridge, `JsonIdempotentResponseCodec`, route 목록)는 골라 쓰는 leaf `adap
**않는다** — ArchUnit 규칙 `REQUEST_DTOS_DO_NOT_SILENCE_UNKNOWN_FIELDS`가 막는다. 요청 record에는
wrapper 타입(`Integer`, `Long`, `Boolean`, `Optional<T>`)을 써서 JSON `null`이 primitive `0`이 되지 못하게
한다.
- **B2 — PATCH 뜻.** RFC 7396 `application/merge-patch+json`(`null = 삭제`)을 쓰지 않는다. PATCH endpoint는
*없음*(바꾸지 않음), *명시한 null*(필드 비움), *값*(바꿈)을 구별해야 한다. 요청 record에
`org.openapitools:jackson-databind-nullable`(`JsonNullable<T>`)이나 `Optional<T>` wrapper를 쓴다.
- **B2 — PATCH 뜻.** 이 leaf의 `application/json` PATCH DTO는 *없음*(바꾸지 않음), *명시한 null*(필드 비움),
*값*(바꿈)을 구별해야 한다. 요청 record에 `org.openapitools:jackson-databind-nullable`(`JsonNullable<T>`)이나
`Optional<T>` wrapper를 쓴다. RFC 7396 merge patch(`application/merge-patch+json`, `null = 삭제`)와 RFC 6902 JSON
Patch는 `adapter:inbound:web-advanced`의 applier로 받는다. 어느 것을 언제 쓰는지와 거부 규칙의 정본은
`docs/web/patch-contract.md`다.
- **B3 — mapper 안의 실패.** record 정규 생성자의 `IllegalArgumentException`, MapStruct가 생성한 NPE, ACL
정규화 실패 등은 `MappingException`을 던져 대응시킨다. 전역 handler가 그것을 `MAPPING_FAILED`(HTTP 400)로
보내고, `BAD_PARAMETER`나 `INTERNAL_ERROR`로 보내지 않는다. mapper가 아닌 호출자의 평범한