fix(http)!: fileserver·notification HTTP와 bulk envelope를 공용 계약대로 답한다
문제: fileserver·notification의 HTTP 표면이 공용 계약(web AGENTS B8, http-contract §1, manual 11)과 달랐다. - fileserver batch는 part가 실패해도 success:true였고 결과를 data.results에 넣었다. fullySucceeded()를 아무도 부르지 않았다. 계약끼리도 달랐다(web B8의 BATCH_PARTIAL_FAILURE vs fileserver 계약의 200 + results[].error). - BulkEnvelope.partial의 error.message가 영어 고정 문구였고, BulkItemResult는 호출자 문구를 그대로 실었으며 null 키를 남겼다(mix-in 없음). - Content-Range가 CORS 노출 목록에 없어 브라우저가 다운로드를 이어 받지 못했다. - 알림 제출·template 게시의 모르는 channel·slot·locale이 details 없는 BAD_PARAMETER였고(주석은 validation error), template 경로가 lowerCamel이 아닌 /notification-templates였다. - 전송 넷(raw·multipart·draft-12·tus)이 이름 없는 업로드에 "upload.bin"을 지어 넣었다. 앱 정책 OriginalFilenamePolicy의 기본값은 "file"이라 업무 규칙이 두 곳에 있었다(HARD-STOP 4). - EnvelopeWireShapeTest는 http-contract §1의 증거로 쓰이는데 data null 키 생략, String → Envelope, unsorted page의 sort:null, 부분 실패 문구를 보지 않았다. 고른 방법: - 리뷰 README 6절 ①대로 fileserver batch도 공용 bulk envelope다. 모두 성공 → success:true + results, 하나라도 실패 → success:false + BATCH_PARTIAL_FAILURE + part별 details(index, status, id, code, message). 성공한 part는 되돌리지 않는다. BatchUploadResponse는 쓰는 곳이 없어져 지웠다. - BulkEnvelope.partial과 BulkItemResult.error(index, ApiErrorCode)는 category 고정 문구를 쓴다. BulkItemResult에 null 생략 mix-in을 더했다. - 알림 controller는 NotificationFieldRejection(VALIDATION_FAILED carrier, 필드를 짚는 details 하나, 거절한 값은 싣지 않음)을 던진다. template 경로는 /notificationTemplates다. 읽는 endpoint가 없어 201에 Location을 싣지 않고, manual 11 규칙에 그 경우를 적었다. - 전송은 이름이 없으면 빈 이름을 넘기고 OriginalFilenamePolicy가 정한다. - EnvelopeWireShapeTest에 빠진 넷을 더했다. EnvelopeTest의 when 둘인 시험을 둘로 나눴다. 버린 대안: /notification-templates를 별칭으로 남기기 — 같은 자원의 경로가 둘이 되고 인가·공개 경로 스냅숏이 둘을 따로 봐야 한다. 위험·한계: batch를 읽는 client, 알림 template 경로를 쓰는 client와 배포 스크립트, BulkItemResult.error(index, code, message)를 부르던 코드가 바뀐다 (upgrade 안내 6·7·10·11·12, 14). BREAKING CHANGE: fileserver batch 응답이 공용 bulk envelope가 됐다. 알림 template 경로가 /notificationTemplates다. 알림의 모르는 vocabulary 값은 VALIDATION_FAILED다. BulkItemResult.error는 ApiErrorCode를 받는다. 이름 없는 업로드의 표시 이름이 "file"이다. 할 일은 docs/upgrade/2026-11-round9-contracts.md. Refs: RR9-03-01, RR9-03-02, RR9-03-09, RR9-03-13, RR9-03-21, RR9-05-09
This commit is contained in:
@@ -63,7 +63,10 @@ V1__create_fileserver_metadata.sql → capability_schema_registry: jpa-fileser
|
||||
- **content가 아직 있으면 삭제는 `204`가 아니라 `202`로 답한다.** 파일은 이미 읽을 수 없고, 물리 회수는
|
||||
미뤘다. `202`를 실패로 다루면 쓸데없이 재시도한다.
|
||||
- **batch 업로드는 part가 실패해도 `200`으로 답한다.** batch는 명시적으로 원자적이지 않고, 상태 코드 하나로는
|
||||
부분 결과를 정직하게 알릴 수 없다. `results[].error`를 읽는다.
|
||||
부분 결과를 정직하게 알릴 수 없다. 판별은 `success`다. 모두 성공하면 `success: true`와 `results[]`, 하나라도
|
||||
실패하면 `success: false`, `error.code = BATCH_PARTIAL_FAILURE`와 part별 `error.details[]`(`index`, `status`,
|
||||
성공한 part의 `id`, 실패한 part의 `code`·`message`)다. 2026-11-12 전에는 실패가 있어도 `success: true`였다
|
||||
(`docs/upgrade/2026-11-round9-contracts.md`).
|
||||
- **결과를 모르는 실패는 재시도하면 안 된다.** 실패 Envelope의 `error.details`에서 `"ambiguous": true`를 본다.
|
||||
- **`If-Match`는 version 숫자가 아니라 strong ETag를 받는다.** client는 실제로 받은 표현에 대해서만 주장할 수
|
||||
있다.
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
## inbound
|
||||
|
||||
- [ ] 컨트롤러는 변환만 한다. repository·엔티티를 모른다.
|
||||
- [ ] 경로는 lowerCamel 복수형(AIP-122). 생성은 201 + `Location`.
|
||||
- [ ] 경로는 lowerCamel 복수형(AIP-122). 생성은 201 + `Location`. 만든 것을 읽는 endpoint가 없으면 `Location`을 싣지 않고 controller 주석에 그 이유를 적는다.
|
||||
- [ ] 도메인 규칙을 DTO bean validation에 다시 쓰지 않았다.
|
||||
- [ ] 엔드포인트를 더했으면 **요청률 제한**을 어디서 거는지(ingress/app) 배포 설계에 있다. 앱 기본 off·켜는 법은 [docs/security/rate-limiting.md](../security/rate-limiting.md).
|
||||
|
||||
|
||||
+5
-2
@@ -36,7 +36,9 @@ public class FileserverHttpSurfaceConfiguration {
|
||||
|
||||
/**
|
||||
* The response headers the upload and download routes write that a cross-origin browser must be
|
||||
* allowed to read: without {@code Upload-Offset} a tus or draft-12 client cannot resume.
|
||||
* allowed to read: without {@code Upload-Offset} a tus or draft-12 client cannot resume, and
|
||||
* without {@code Content-Range} a browser that resumes a download with {@code Range} cannot tell
|
||||
* which bytes a {@code 206} carries or how long the representation is from a {@code 416}.
|
||||
*/
|
||||
@Bean
|
||||
CorsExposedHeaders fileserverCorsExposedHeaders() {
|
||||
@@ -53,6 +55,7 @@ public class FileserverHttpSurfaceConfiguration {
|
||||
Draft12Headers.UPLOAD_COMPLETE,
|
||||
Draft12Headers.UPLOAD_LIMIT,
|
||||
HttpHeaders.CONTENT_DISPOSITION,
|
||||
HttpHeaders.ACCEPT_RANGES));
|
||||
HttpHeaders.ACCEPT_RANGES,
|
||||
HttpHeaders.CONTENT_RANGE));
|
||||
}
|
||||
}
|
||||
|
||||
+40
-12
@@ -4,12 +4,12 @@ import dev.caskeleton.adapter.inbound.web.core.OwnsAbsoluteWebRoute;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.config.BlockingTransferExecutor;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.config.FileserverWebProperties;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.dto.BatchUploadItemResult;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.dto.BatchUploadResponse;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.dto.UploadedFileResponse;
|
||||
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.mapper.UploadIntent;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.security.FileserverRequestContextFactory;
|
||||
import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory;
|
||||
import dev.caskeleton.application.fileserver.api.FileState;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileserverException;
|
||||
@@ -21,6 +21,9 @@ import dev.caskeleton.application.fileserver.port.in.UploadFileUseCase;
|
||||
import dev.caskeleton.application.fileserver.upload.CreateUploadRequest;
|
||||
import dev.caskeleton.application.fileserver.upload.FileView;
|
||||
import dev.caskeleton.application.fileserver.upload.FinalizeUploadRequest;
|
||||
import dev.caskeleton.shared.response.BulkEnvelope;
|
||||
import dev.caskeleton.shared.response.BulkItemResult;
|
||||
import dev.caskeleton.shared.response.ResponseMeta;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -117,23 +120,41 @@ public class FileUploadController {
|
||||
/**
|
||||
* Bounded multi-file upload.
|
||||
*
|
||||
* <p>The batch is explicitly non-atomic: each part is an independent file, a failure never rolls
|
||||
* back a sibling that already succeeded, and the response is always {@code 200} carrying the
|
||||
* ordered per-part outcome.
|
||||
* <p>The batch is explicitly non-atomic: each part is an independent file and a failure never
|
||||
* rolls back a sibling that already succeeded. The response is {@code 200} and the shared bulk
|
||||
* envelope (web AGENTS B8): every part succeeded → {@code success = true} and {@code results};
|
||||
* any part failed → {@code success = false}, {@code BATCH_PARTIAL_FAILURE} and the per-part
|
||||
* outcome in {@code error.details[]}. It used to answer {@code success = true} with the failures
|
||||
* inside {@code data}, so a client reading the discriminator saw a batch that worked (review
|
||||
* 2026-11-12).
|
||||
*/
|
||||
@PostMapping(
|
||||
path = "/v1/files:batch",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<BatchUploadResponse> uploadBatch(
|
||||
public ResponseEntity<BulkEnvelope<BatchUploadItemResult>> uploadBatch(
|
||||
@RequestParam("files") List<MultipartFile> files) {
|
||||
requirePartCountWithinPolicy(files.size());
|
||||
RequestContext context = contextFactory.current();
|
||||
List<BatchUploadItemResult> results = new ArrayList<>(files.size());
|
||||
List<PartOutcome> outcomes = new ArrayList<>(files.size());
|
||||
for (int index = 0; index < files.size(); index++) {
|
||||
results.add(uploadPart(files.get(index), index, context));
|
||||
outcomes.add(uploadPart(files.get(index), index, context));
|
||||
}
|
||||
ResponseMeta meta = ResponseMetaFactory.fromMdc();
|
||||
if (outcomes.stream().allMatch(PartOutcome::succeeded)) {
|
||||
return ResponseEntity.ok(
|
||||
BulkEnvelope.allOk(outcomes.stream().map(PartOutcome::result).toList(), meta));
|
||||
}
|
||||
return ResponseEntity.ok(
|
||||
BulkEnvelope.partial(outcomes.stream().map(PartOutcome::detail).toList(), meta));
|
||||
}
|
||||
|
||||
/** One part's result in both shapes the bulk envelope may need. */
|
||||
private record PartOutcome(BatchUploadItemResult result, BulkItemResult detail) {
|
||||
|
||||
boolean succeeded() {
|
||||
return result.error() == null;
|
||||
}
|
||||
return ResponseEntity.ok(new BatchUploadResponse(results));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -142,7 +163,7 @@ public class FileUploadController {
|
||||
* <p>A part failure is converted to a per-part problem instead of aborting the request, which is
|
||||
* what makes the endpoint's non-atomic contract observable rather than merely documented.
|
||||
*/
|
||||
private BatchUploadItemResult uploadPart(MultipartFile part, int index, RequestContext context) {
|
||||
private PartOutcome uploadPart(MultipartFile part, int index, RequestContext context) {
|
||||
String clientPartId = partId(part, index);
|
||||
try (InputStream body = part.getInputStream()) {
|
||||
UploadIntent intent = multipartMapper.map(part);
|
||||
@@ -150,14 +171,21 @@ public class FileUploadController {
|
||||
FileView view =
|
||||
transferExecutor.call(
|
||||
() -> upload(intent, content, part.getSize(), context, UploadMode.BATCH));
|
||||
return BatchUploadItemResult.accepted(clientPartId, view);
|
||||
return new PartOutcome(
|
||||
BatchUploadItemResult.accepted(clientPartId, view),
|
||||
BulkItemResult.ok(index, view.fileId().canonicalText()));
|
||||
} catch (FileserverException failure) {
|
||||
return BatchUploadItemResult.rejected(clientPartId, failure.code());
|
||||
return rejected(clientPartId, index, failure.code());
|
||||
} catch (IOException failure) {
|
||||
return BatchUploadItemResult.rejected(clientPartId, FileserverErrorCode.STORAGE_UNAVAILABLE);
|
||||
return rejected(clientPartId, index, FileserverErrorCode.STORAGE_UNAVAILABLE);
|
||||
}
|
||||
}
|
||||
|
||||
private static PartOutcome rejected(String clientPartId, int index, FileserverErrorCode code) {
|
||||
return new PartOutcome(
|
||||
BatchUploadItemResult.rejected(clientPartId, code), BulkItemResult.error(index, code));
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the application upload mode represented by this HTTP endpoint.
|
||||
*
|
||||
|
||||
+2
-1
@@ -239,8 +239,9 @@ public class Draft12UploadController {
|
||||
}
|
||||
}
|
||||
|
||||
/** The header's name, or empty: the application's {@code OriginalFilenamePolicy} names it. */
|
||||
private static String filename(HttpServletRequest request) {
|
||||
String header = request.getHeader("X-Filename");
|
||||
return header == null || header.isBlank() ? "upload.bin" : header;
|
||||
return header == null ? "" : header;
|
||||
}
|
||||
}
|
||||
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package dev.caskeleton.adapter.inbound.web.fileserver.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Ordered per-part outcome of one batch upload.
|
||||
*
|
||||
* <p>The endpoint answers {@code 200} even when some parts failed: the batch has no request-wide
|
||||
* atomicity, and pretending otherwise with a single status would hide the parts that succeeded.
|
||||
*/
|
||||
public record BatchUploadResponse(List<BatchUploadItemResult> results) {
|
||||
|
||||
public BatchUploadResponse {
|
||||
results = List.copyOf(results);
|
||||
}
|
||||
|
||||
/** True when every part succeeded, which the envelope layer reports as a plain success. */
|
||||
public boolean fullySucceeded() {
|
||||
return results.stream().allMatch(result -> result.error() == null);
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -13,16 +13,18 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
*/
|
||||
public final class MultipartUploadRequestMapper {
|
||||
|
||||
private static final String FALLBACK_FILENAME = "upload.bin";
|
||||
|
||||
public UploadIntent map(MultipartFile part) {
|
||||
return new UploadIntent(
|
||||
filename(part), claimedMediaType(part), OptionalLong.of(part.getSize()), Optional.empty());
|
||||
}
|
||||
|
||||
/**
|
||||
* The submitted name, or empty when there is none. Naming an unnamed upload is the application's
|
||||
* {@code OriginalFilenamePolicy}, one place for every transport (review 2026-11-12).
|
||||
*/
|
||||
private static String filename(MultipartFile part) {
|
||||
String submitted = part.getOriginalFilename();
|
||||
return submitted == null || submitted.isBlank() ? FALLBACK_FILENAME : submitted;
|
||||
return submitted == null ? "" : submitted;
|
||||
}
|
||||
|
||||
private static Optional<String> claimedMediaType(MultipartFile part) {
|
||||
|
||||
+2
-3
@@ -20,8 +20,6 @@ public final class RawUploadRequestMapper {
|
||||
public static final String FILENAME_HEADER = "X-Filename";
|
||||
public static final String DIGEST_HEADER = "X-Content-Sha256";
|
||||
|
||||
private static final String FALLBACK_FILENAME = "upload.bin";
|
||||
|
||||
private final boolean contentLengthRequired;
|
||||
|
||||
public RawUploadRequestMapper(boolean contentLengthRequired) {
|
||||
@@ -39,9 +37,10 @@ public final class RawUploadRequestMapper {
|
||||
filename(request), claimedMediaType(request), declaredLength, digest(request));
|
||||
}
|
||||
|
||||
/** The header's name, or empty: the application's {@code OriginalFilenamePolicy} names it. */
|
||||
private static String filename(HttpServletRequest request) {
|
||||
String header = request.getHeader(FILENAME_HEADER);
|
||||
return header == null || header.isBlank() ? FALLBACK_FILENAME : header;
|
||||
return header == null ? "" : header;
|
||||
}
|
||||
|
||||
private static Optional<String> claimedMediaType(HttpServletRequest request) {
|
||||
|
||||
+2
-1
@@ -112,7 +112,8 @@ public class TusController {
|
||||
create.handle(
|
||||
new CreateUploadCommand(
|
||||
new CreateUploadRequest(
|
||||
parser.filename(request).orElse("upload.bin"),
|
||||
// Empty when absent: OriginalFilenamePolicy names it, for every transport.
|
||||
parser.filename(request).orElse(""),
|
||||
Optional.ofNullable(parser.metadata(request).get("filetype")),
|
||||
parser.declaredLength(request),
|
||||
Optional.empty(),
|
||||
|
||||
+3
-2
@@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test;
|
||||
class FileserverCorsExposedHeadersTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("fileserver HTTP 표면은 업로드 재개에 필요한 헤더를 CORS 노출 목록에 기여한다")
|
||||
@DisplayName("fileserver HTTP 표면은 업로드·다운로드 재개에 필요한 헤더를 CORS 노출 목록에 기여한다")
|
||||
void theSurfaceContributesTheHeadersAResumingClientMustRead() {
|
||||
// when
|
||||
CorsExposedHeaders contributed =
|
||||
@@ -23,6 +23,7 @@ class FileserverCorsExposedHeadersTest {
|
||||
"Upload-Length",
|
||||
"Upload-Expires",
|
||||
"Upload-Complete",
|
||||
"Content-Disposition");
|
||||
"Content-Disposition",
|
||||
"Content-Range");
|
||||
}
|
||||
}
|
||||
|
||||
+22
-6
@@ -18,6 +18,7 @@ import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext;
|
||||
import dev.caskeleton.application.fileserver.upload.CreateUploadRequest;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
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.mock.web.MockMultipartFile;
|
||||
@@ -89,15 +90,19 @@ class FileUploadControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRawUploadWithoutAFilenameHeaderStillGetsASafeDisplayName() throws Exception {
|
||||
@DisplayName("이름 헤더 없는 raw 업로드는 전송이 이름을 지어 넣지 않고 앱 정책에 빈 이름을 넘긴다")
|
||||
void aRawUploadWithoutAFilenameHeaderLeavesTheNameToTheApplicationPolicy() throws Exception {
|
||||
// when
|
||||
mvc.perform(
|
||||
post("/v1/files:raw").contentType(MediaType.APPLICATION_OCTET_STREAM).content("abc"))
|
||||
.andExpect(status().isCreated());
|
||||
|
||||
// then
|
||||
assertThat(uploadService.requests())
|
||||
.singleElement()
|
||||
.extracting(CreateUploadRequest::originalFilename)
|
||||
.isEqualTo("upload.bin");
|
||||
.as("OriginalFilenamePolicy names an unnamed upload, once for every transport")
|
||||
.isEqualTo("");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -127,7 +132,9 @@ class FileUploadControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("모든 part가 성공한 batch는 success=true와 part별 results를 순서대로 준다")
|
||||
void batchReturnsPerPartResultsAndIsExplicitlyNonAtomic() throws Exception {
|
||||
// when / then
|
||||
mvc.perform(
|
||||
multipart("/v1/files:batch")
|
||||
.file(
|
||||
@@ -137,13 +144,17 @@ class FileUploadControllerTest {
|
||||
new MockMultipartFile(
|
||||
"files", "b.txt", "text/plain", "b".getBytes(StandardCharsets.UTF_8))))
|
||||
.andExpect(status().isOk())
|
||||
.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"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName(
|
||||
"한 part가 실패한 batch는 success=false, BATCH_PARTIAL_FAILURE, part별 details이고 성공한 part는 되돌리지 않는다")
|
||||
void aFailedBatchPartNeverRollsBackTheSiblingThatSucceeded() throws Exception {
|
||||
// given
|
||||
uploadService.failWith(
|
||||
body ->
|
||||
"b".equals(body)
|
||||
@@ -152,6 +163,7 @@ class FileUploadControllerTest {
|
||||
FileserverFailureContext.of(FileserverErrorCode.FILE_TOO_LARGE, false))
|
||||
: null);
|
||||
|
||||
// when / then
|
||||
mvc.perform(
|
||||
multipart("/v1/files:batch")
|
||||
.file(
|
||||
@@ -161,10 +173,14 @@ class FileUploadControllerTest {
|
||||
new MockMultipartFile(
|
||||
"files", "b.txt", "text/plain", "b".getBytes(StandardCharsets.UTF_8))))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.results[0].status").value("READY"))
|
||||
.andExpect(jsonPath("$.results[1].status").value("REJECTED"))
|
||||
.andExpect(jsonPath("$.results[1].error.code").value("FILE_TOO_LARGE"))
|
||||
.andExpect(jsonPath("$.results[1].error.category").value("VALIDATION"));
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
.andExpect(jsonPath("$.results").doesNotExist())
|
||||
.andExpect(jsonPath("$.error.code").value("BATCH_PARTIAL_FAILURE"))
|
||||
.andExpect(jsonPath("$.error.details[0].status").value("ok"))
|
||||
.andExpect(jsonPath("$.error.details[0].id").isNotEmpty())
|
||||
.andExpect(jsonPath("$.error.details[1].index").value(1))
|
||||
.andExpect(jsonPath("$.error.details[1].status").value("error"))
|
||||
.andExpect(jsonPath("$.error.details[1].code").value("FILE_TOO_LARGE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+19
@@ -48,6 +48,25 @@ class FileserverProblemHeaderParityTest {
|
||||
assertThat(headers).doesNotContainKey("Retry-After");
|
||||
}
|
||||
|
||||
@Test
|
||||
@org.junit.jupiter.api.DisplayName(
|
||||
"본문이 retryable=false로 좁히는 code는 발생이 retryable이어도 Retry-After를 싣지 않는다")
|
||||
void aCodeThatIsNeverRetryableAdvertisesNoRetryWhateverTheOccurrenceSaid() {
|
||||
// given
|
||||
FileserverException failure =
|
||||
new FileserverException(
|
||||
"no atomic publish",
|
||||
FileserverFailureContext.of(FileserverErrorCode.ATOMIC_PUBLISH_UNSUPPORTED, true));
|
||||
|
||||
// when
|
||||
Map<String, String> headers = FileserverProblemHeaders.of(failure);
|
||||
|
||||
// then
|
||||
assertThat(headers)
|
||||
.as("the body says retryable=false for this code; the header must not say otherwise")
|
||||
.doesNotContainKey("Retry-After");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsatisfiableRangeDisclosesTheRepresentationLength() {
|
||||
Map<String, String> headers =
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package dev.caskeleton.adapter.inbound.web.notification.platform.submission;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.error.ClientSafeErrorDetails;
|
||||
import dev.caskeleton.shared.error.ApiErrorCarrier;
|
||||
import dev.caskeleton.shared.error.ApiErrorCode;
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A request field whose value is outside the vocabulary this transport parses (a channel, a slot, a
|
||||
* language tag).
|
||||
*
|
||||
* <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.
|
||||
*/
|
||||
final class NotificationFieldRejection extends RuntimeException
|
||||
implements ApiErrorCarrier, ClientSafeErrorDetails {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final String field;
|
||||
|
||||
NotificationFieldRejection(String field, String reason, Throwable cause) {
|
||||
super(reason, cause);
|
||||
this.field = Objects.requireNonNull(field, "field");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiErrorCode errorCode() {
|
||||
return OperationalError.VALIDATION_FAILED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object clientDetails() {
|
||||
return List.of(Map.of("field", field, "code", "UNKNOWN_VALUE", "message", "허용된 값이 아닙니다."));
|
||||
}
|
||||
}
|
||||
+8
-5
@@ -92,15 +92,18 @@ public final class NotificationSubmissionController {
|
||||
/**
|
||||
* The channel a caller named.
|
||||
*
|
||||
* <p>Parsed here rather than bound by Jackson so an unknown name fails as a validation error
|
||||
* naming the vocabulary, instead of as a deserialization error naming a Java enum.
|
||||
* <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 IllegalArgumentException(
|
||||
"channel must be one of " + java.util.Arrays.toString(Channel.values()), unknown);
|
||||
throw new NotificationFieldRejection(
|
||||
"channel",
|
||||
"channel must be one of " + java.util.Arrays.toString(Channel.values()),
|
||||
unknown);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,7 +120,7 @@ public final class NotificationSubmissionController {
|
||||
}
|
||||
Locale parsed = Locale.forLanguageTag(tag.trim());
|
||||
if (parsed.equals(Locale.ROOT)) {
|
||||
throw new IllegalArgumentException("locale must be a BCP 47 language tag");
|
||||
throw new NotificationFieldRejection("locale", "locale must be a BCP 47 language tag", null);
|
||||
}
|
||||
return Optional.of(parsed);
|
||||
}
|
||||
|
||||
+21
-8
@@ -32,7 +32,12 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
* publish} and no application or transport ever called it.
|
||||
*
|
||||
* <p>{@code 201}, unlike a submission's {@code 202}: a published version is an immutable resource
|
||||
* that exists when the call returns, with nothing deferred to a worker.
|
||||
* that exists when the call returns, with nothing deferred to a worker. The response carries no
|
||||
* {@code Location}: there is no endpoint that reads a template version, and a {@code Location} that
|
||||
* answers 404 is worse than none. The body names the version and its digest.
|
||||
*
|
||||
* <p>The path is lowerCamel plural like every other collection (manual 11, AIP-122); it was {@code
|
||||
* /notification-templates} until 2026-11-12.
|
||||
*
|
||||
* <p>Authorized by {@code notification-template:publish}, which is deliberately not {@code
|
||||
* notification:submit}. Publishing a template changes what every future submission renders, and a
|
||||
@@ -45,7 +50,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
@RequestMapping("/notification-templates")
|
||||
@RequestMapping("/notificationTemplates")
|
||||
public final class NotificationTemplateController {
|
||||
|
||||
private final PublishNotificationTemplateUseCase publish;
|
||||
@@ -77,7 +82,7 @@ public final class NotificationTemplateController {
|
||||
locale(request.locale()),
|
||||
Optional.ofNullable(request.fallbackLocale())
|
||||
.filter(tag -> !tag.isBlank())
|
||||
.map(NotificationTemplateController::locale),
|
||||
.map(tag -> locale("fallbackLocale", tag)),
|
||||
slots(request.slots()),
|
||||
names(request.requiredVariables()),
|
||||
names(request.sensitiveVariables()));
|
||||
@@ -104,8 +109,10 @@ public final class NotificationTemplateController {
|
||||
try {
|
||||
slot = TemplateSlot.valueOf(name.trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException unknown) {
|
||||
throw new IllegalArgumentException(
|
||||
"slot must be one of " + java.util.Arrays.toString(TemplateSlot.values()), unknown);
|
||||
throw new NotificationFieldRejection(
|
||||
"slots",
|
||||
"slot must be one of " + java.util.Arrays.toString(TemplateSlot.values()),
|
||||
unknown);
|
||||
}
|
||||
slots.put(slot, content);
|
||||
});
|
||||
@@ -120,15 +127,21 @@ public final class NotificationTemplateController {
|
||||
try {
|
||||
return Channel.valueOf(name.trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException unknown) {
|
||||
throw new IllegalArgumentException(
|
||||
"channel must be one of " + java.util.Arrays.toString(Channel.values()), 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 IllegalArgumentException("locale must be a BCP 47 language tag");
|
||||
throw new NotificationFieldRejection(field, field + " must be a BCP 47 language tag", null);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
+13
@@ -31,6 +31,19 @@ class NotificationRoutePrefixTest {
|
||||
assertThat(prefixed.test(NotificationTemplateController.class)).isTrue();
|
||||
}
|
||||
|
||||
@org.junit.jupiter.api.Test
|
||||
@org.junit.jupiter.api.DisplayName("template 게시 경로는 다른 collection처럼 lowerCamel 복수형이다")
|
||||
void theTemplateCollectionPathIsLowerCamelPlural() {
|
||||
// when
|
||||
String[] paths =
|
||||
NotificationTemplateController.class
|
||||
.getAnnotation(org.springframework.web.bind.annotation.RequestMapping.class)
|
||||
.value();
|
||||
|
||||
// then
|
||||
assertThat(paths).containsExactly("/notificationTemplates");
|
||||
}
|
||||
|
||||
private static final class InspectablePathMatchConfigurer extends PathMatchConfigurer {
|
||||
|
||||
Predicate<Class<?>> prefix(String path) {
|
||||
|
||||
+35
@@ -2,13 +2,17 @@ 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.AcceptNotificationCommand;
|
||||
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
@@ -47,4 +51,35 @@ class NotificationSubmissionControllerTest {
|
||||
// then
|
||||
assertThat(List.of(status, accepted.size())).containsExactly(400, 0);
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@CsvSource({
|
||||
"channel, '\"channel\":\"PIGEON\",\"locale\":\"ko-KR\"'",
|
||||
"locale, '\"channel\":\"EMAIL\",\"locale\":\"%%%\"'"
|
||||
})
|
||||
@DisplayName("모르는 channel·locale은 그 필드를 짚는 400 VALIDATION_FAILED이고 use case에 닿지 않는다")
|
||||
void anUnknownVocabularyValueIsAValidationFailureNamingTheField(String field, String fields)
|
||||
throws Exception {
|
||||
// given
|
||||
String body =
|
||||
"{\"recipientRef\":\"r-1\","
|
||||
+ fields
|
||||
+ ",\"address\":\"a@example.com\",\"template\":\"welcome\",\"category\":\"TRANSACTIONAL\"}";
|
||||
|
||||
// when
|
||||
String response =
|
||||
mvc.perform(post("/notifications").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("%%%");
|
||||
assertThat(accepted).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
+2
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.envelope;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import dev.caskeleton.shared.response.ApiError;
|
||||
import dev.caskeleton.shared.response.BulkEnvelope;
|
||||
import dev.caskeleton.shared.response.BulkItemResult;
|
||||
import dev.caskeleton.shared.response.Envelope;
|
||||
import dev.caskeleton.shared.response.ResponseMeta;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
@@ -33,6 +34,7 @@ public class EnvelopeWireFormatConfig {
|
||||
SimpleModule module = new SimpleModule("EnvelopeWireFormatModule");
|
||||
module.setMixInAnnotation(Envelope.class, OmitNullFields.class);
|
||||
module.setMixInAnnotation(BulkEnvelope.class, OmitNullFields.class);
|
||||
module.setMixInAnnotation(BulkItemResult.class, OmitNullFields.class);
|
||||
module.setMixInAnnotation(ApiError.class, OmitNullFields.class);
|
||||
module.setMixInAnnotation(ResponseMeta.class, OmitNullFields.class);
|
||||
return module;
|
||||
|
||||
+84
@@ -5,6 +5,8 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyInFlightException;
|
||||
import dev.caskeleton.shared.error.ClientErrorMessages;
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import dev.caskeleton.shared.response.BulkEnvelope;
|
||||
import dev.caskeleton.shared.response.BulkItemResult;
|
||||
@@ -26,6 +28,7 @@ import org.springframework.boot.security.autoconfigure.SecurityAutoConfiguration
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
@@ -77,6 +80,33 @@ class EnvelopeWireShapeTest {
|
||||
new ResponseMeta("req-1", "trace-1", "corr-1").withPage(new PageMeta(0, 20, 1, "id")));
|
||||
}
|
||||
|
||||
@GetMapping("/probe/null-data")
|
||||
public Envelope<String> nullData() {
|
||||
return Envelope.ok(null, new ResponseMeta("req-1", "trace-1", "corr-1"));
|
||||
}
|
||||
|
||||
@GetMapping("/probe/text")
|
||||
public String text() {
|
||||
ids(true);
|
||||
return "hello";
|
||||
}
|
||||
|
||||
@GetMapping("/probe/page-unsorted")
|
||||
public Envelope<List<String>> pageUnsorted() {
|
||||
return Envelope.ok(
|
||||
List.of("a"),
|
||||
new ResponseMeta("req-1", "trace-1", "corr-1").withPage(new PageMeta(0, 20, 1, null)));
|
||||
}
|
||||
|
||||
@GetMapping("/probe/bulk-partial-items")
|
||||
public BulkEnvelope<String> bulkPartialItems() {
|
||||
return BulkEnvelope.partial(
|
||||
List.of(
|
||||
BulkItemResult.ok(0, "item-1"),
|
||||
BulkItemResult.error(1, OperationalError.MAPPING_FAILED)),
|
||||
new ResponseMeta("req-1", "trace-1", "corr-1"));
|
||||
}
|
||||
|
||||
@GetMapping("/probe/in-flight")
|
||||
public Map<String, String> inFlight() {
|
||||
ids(false);
|
||||
@@ -178,6 +208,60 @@ class EnvelopeWireShapeTest {
|
||||
assertThat(details.isArray() && details.isEmpty()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("성공인데 data가 null이면 data 키도 없다")
|
||||
void aNullDataOmitsTheDataKey() throws Exception {
|
||||
// when
|
||||
JsonNode body = rawBody("/probe/null-data");
|
||||
|
||||
// then
|
||||
assertThat(keys(body)).containsExactlyInAnyOrder("success", "meta");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("JSON을 요청하면 String 반환도 같은 Envelope의 data로 나간다")
|
||||
void aStringBodyIsAnEnvelopeWhenJsonIsAsked() throws Exception {
|
||||
// when
|
||||
JsonNode body =
|
||||
READER.readTree(
|
||||
mvc.perform(get("/probe/text").accept(MediaType.APPLICATION_JSON))
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString());
|
||||
|
||||
// then
|
||||
assertThat(keys(body)).containsExactlyInAnyOrder("success", "data", "meta");
|
||||
assertThat(body.get("data").asString()).isEqualTo("hello");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("정렬 없는 목록의 page는 sort 키를 null로 싣는다")
|
||||
void anUnsortedPageCarriesSortNull() throws Exception {
|
||||
// when
|
||||
JsonNode page = rawBody("/probe/page-unsorted").get("meta").get("page");
|
||||
|
||||
// then
|
||||
assertThat(keys(page)).containsExactlyInAnyOrder("number", "size", "total", "sort");
|
||||
assertThat(page.get("sort").isNull()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("bulk 부분 실패의 message는 고정 문구이고 항목은 자기 상태에 맞는 키만 싣는다")
|
||||
void aPartialFailureCarriesFixedWordingAndItemsWithoutNullKeys() throws Exception {
|
||||
// when
|
||||
JsonNode error = rawBody("/probe/bulk-partial-items").get("error");
|
||||
|
||||
// then
|
||||
assertThat(error.get("message").asString())
|
||||
.isEqualTo(ClientErrorMessages.of(OperationalError.BATCH_PARTIAL_FAILURE));
|
||||
assertThat(keys(error.get("details").get(0)))
|
||||
.containsExactlyInAnyOrder("index", "status", "id");
|
||||
assertThat(keys(error.get("details").get(1)))
|
||||
.containsExactlyInAnyOrder("index", "status", "code", "message");
|
||||
assertThat(error.get("details").get(1).get("message").asString())
|
||||
.isEqualTo(ClientErrorMessages.of(OperationalError.MAPPING_FAILED));
|
||||
}
|
||||
|
||||
private JsonNode rawBody(String path) throws Exception {
|
||||
String text = mvc.perform(get(path)).andReturn().getResponse().getContentAsString();
|
||||
return READER.readTree(text);
|
||||
|
||||
+3
-1
@@ -9,7 +9,9 @@ import java.util.OptionalLong;
|
||||
* Client intent when starting an upload.
|
||||
*
|
||||
* <p>{@code originalFilename} and {@code claimedMediaType} are untrusted: they are sanitized and
|
||||
* stored as display metadata, never used to build a physical key or to decide safety.
|
||||
* stored as display metadata, never used to build a physical key or to decide safety. A transport
|
||||
* that received no name passes an empty string; the display name of an unnamed upload is {@code
|
||||
* OriginalFilenamePolicy}'s to choose, not each transport's.
|
||||
*
|
||||
* <p>The request carries only what the client decides. The namespace and the session lifetime are
|
||||
* {@link UploadPolicy}'s, so no transport can pick its own.
|
||||
|
||||
@@ -49,7 +49,7 @@ case "${NOTIFICATION_SMOKE_PHASE}" in
|
||||
# reruns against a surviving volume is not a different lane; a 409 here means the platform
|
||||
# holds a version with this id and different content, which is a real failure.
|
||||
PUBLISH_STATUS="$(curl -s -o /tmp/publish.json -w '%{http_code}' \
|
||||
-X POST "${APP_BASE_URL}${BASE_PATH}/notification-templates" \
|
||||
-X POST "${APP_BASE_URL}${BASE_PATH}/notificationTemplates" \
|
||||
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "{\"templateId\":\"${TEMPLATE_ID}\",\"version\":1,\"channel\":\"EMAIL\",\"locale\":\"en\",
|
||||
|
||||
@@ -19,7 +19,7 @@ composition:notification-platform
|
||||
├─ adapter:outbound:notification provider(SMTP·SES), 저장 외 런타임, NotificationPlatformAutoConfiguration
|
||||
├─ adapter:outbound:persistence-notification (runtimeOnly) 알림 entity·저장소·Flyway stream
|
||||
├─ adapter:outbound:persistence-jpa (runtimeOnly) DataSource·Flyway core·TransactionPort
|
||||
└─ adapter:inbound:web-notification POST /notifications, POST /notification-templates,
|
||||
└─ adapter:inbound:web-notification POST /notifications, POST /notificationTemplates,
|
||||
POST /internal/notification/callbacks/{provider}/{profile}
|
||||
```
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package dev.caskeleton.shared.response;
|
||||
|
||||
import dev.caskeleton.shared.error.ClientErrorMessages;
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
import java.util.List;
|
||||
|
||||
@@ -25,7 +26,7 @@ public record BulkEnvelope<T>(boolean success, List<T> results, ApiError error,
|
||||
ApiError.withDetails(
|
||||
OperationalError.BATCH_PARTIAL_FAILURE.code(),
|
||||
OperationalError.BATCH_PARTIAL_FAILURE.category().name(),
|
||||
"One or more items failed; see details[] for the per-item outcome.",
|
||||
ClientErrorMessages.of(OperationalError.BATCH_PARTIAL_FAILURE),
|
||||
OperationalError.BATCH_PARTIAL_FAILURE.retryable(),
|
||||
details);
|
||||
return new BulkEnvelope<>(false, null, err, meta);
|
||||
|
||||
+10
-4
@@ -1,14 +1,20 @@
|
||||
package dev.caskeleton.shared.response;
|
||||
|
||||
import dev.caskeleton.shared.error.ApiErrorCode;
|
||||
import dev.caskeleton.shared.error.ClientErrorMessages;
|
||||
|
||||
/**
|
||||
* Per-item result inside a bulk endpoint's {@code error.details[]} array.
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code status = "ok"} + {@code id} when the item succeeded;
|
||||
* <li>{@code status = "error"} + {@code code} + {@code message} when failed.
|
||||
* <li>{@code status = "error"} + {@code code} + {@code message} when failed. The message is the
|
||||
* code's category wording from {@link ClientErrorMessages}, the same text a single-item
|
||||
* endpoint would send, never the caller's own text (review 2026-11-12).
|
||||
* </ul>
|
||||
*
|
||||
* <p>No debug payload — keeps the envelope safe to log/ship.
|
||||
* <p>No debug payload — keeps the envelope safe to log/ship. Absent members are omitted on the wire
|
||||
* like every other envelope field.
|
||||
*/
|
||||
public record BulkItemResult(int index, String status, String id, String code, String message) {
|
||||
|
||||
@@ -16,7 +22,7 @@ public record BulkItemResult(int index, String status, String id, String code, S
|
||||
return new BulkItemResult(index, "ok", id, null, null);
|
||||
}
|
||||
|
||||
public static BulkItemResult error(int index, String code, String message) {
|
||||
return new BulkItemResult(index, "error", null, code, message);
|
||||
public static BulkItemResult error(int index, ApiErrorCode code) {
|
||||
return new BulkItemResult(index, "error", null, code.code(), ClientErrorMessages.of(code));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@ package dev.caskeleton.shared.response;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.shared.error.ClientErrorMessages;
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class EnvelopeTest {
|
||||
@@ -31,16 +34,39 @@ class EnvelopeTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void bulkAllOkAndPartialCarryMeta() {
|
||||
BulkEnvelope<String> ok = BulkEnvelope.allOk(List.of("a"), META);
|
||||
@DisplayName("bulk 전체 성공은 success=true와 meta를 싣는다")
|
||||
void aFullySucceededBulkCarriesMeta() {
|
||||
// given
|
||||
List<String> results = List.of("a");
|
||||
|
||||
// when
|
||||
BulkEnvelope<String> ok = BulkEnvelope.allOk(results, META);
|
||||
|
||||
// then
|
||||
assertThat(ok.success()).isTrue();
|
||||
assertThat(ok.meta().requestId()).isEqualTo("req-1");
|
||||
}
|
||||
|
||||
BulkEnvelope<String> partial =
|
||||
BulkEnvelope.partial(List.of(BulkItemResult.error(0, "MAPPING_FAILED", "x")), META);
|
||||
@Test
|
||||
@DisplayName("bulk 부분 실패는 BATCH_PARTIAL_FAILURE와 category 고정 문구, 항목 코드의 고정 문구를 싣는다")
|
||||
void aPartiallyFailedBulkCarriesTheFixedWording() {
|
||||
// given
|
||||
List<BulkItemResult> details =
|
||||
List.of(
|
||||
BulkItemResult.ok(0, "f-1"), BulkItemResult.error(1, OperationalError.MAPPING_FAILED));
|
||||
|
||||
// when
|
||||
BulkEnvelope<String> partial = BulkEnvelope.partial(details, META);
|
||||
|
||||
// then
|
||||
assertThat(partial.success()).isFalse();
|
||||
assertThat(partial.error().code()).isEqualTo("BATCH_PARTIAL_FAILURE");
|
||||
assertThat(partial.error().category()).isEqualTo("VALIDATION");
|
||||
assertThat(partial.error().message())
|
||||
.isEqualTo(ClientErrorMessages.of(OperationalError.BATCH_PARTIAL_FAILURE));
|
||||
assertThat(details.get(1).message())
|
||||
.as("an item carries its code's wording, never text the caller chose")
|
||||
.isEqualTo(ClientErrorMessages.of(OperationalError.MAPPING_FAILED));
|
||||
assertThat(partial.meta().correlationId()).isEqualTo("corr-1");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user