diff --git a/docs/fileserver/upgrade-guide.md b/docs/fileserver/upgrade-guide.md index af27de87..a8f12e31 100644 --- a/docs/fileserver/upgrade-guide.md +++ b/docs/fileserver/upgrade-guide.md @@ -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는 실제로 받은 표현에 대해서만 주장할 수 있다. diff --git a/docs/manual/11-checklist.md b/docs/manual/11-checklist.md index fff17a68..128f1ccc 100644 --- a/docs/manual/11-checklist.md +++ b/docs/manual/11-checklist.md @@ -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). diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java index 569f66c5..5ba1126c 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java @@ -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)); } } diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java index d7ee6fad..9ae7d824 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java @@ -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. * - *

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. + *

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 uploadBatch( + public ResponseEntity> uploadBatch( @RequestParam("files") List files) { requirePartCountWithinPolicy(files.size()); RequestContext context = contextFactory.current(); - List results = new ArrayList<>(files.size()); + List 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 { *

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. * diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java index 74638fc0..ea0c6b5c 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java @@ -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; } } diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadResponse.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadResponse.java deleted file mode 100644 index a79599a9..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/dto/BatchUploadResponse.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.dto; - -import java.util.List; - -/** - * Ordered per-part outcome of one batch upload. - * - *

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 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); - } -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/MultipartUploadRequestMapper.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/MultipartUploadRequestMapper.java index 365dc63f..844ae34d 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/MultipartUploadRequestMapper.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/MultipartUploadRequestMapper.java @@ -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 claimedMediaType(MultipartFile part) { diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/RawUploadRequestMapper.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/RawUploadRequestMapper.java index c06b5d06..4e6a96ae 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/RawUploadRequestMapper.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/RawUploadRequestMapper.java @@ -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 claimedMediaType(HttpServletRequest request) { diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java index ab2f3093..e40a0eba 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java @@ -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(), diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java index 78d58122..d22b4b54 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java @@ -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"); } } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java index 70ae0c27..fc876c72 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java @@ -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 diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java index 92b92605..54e9ffca 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java @@ -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 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 headers = diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejection.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejection.java new file mode 100644 index 00000000..6431b9be --- /dev/null +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationFieldRejection.java @@ -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). + * + *

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", "허용된 값이 아닙니다.")); + } +} 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 16434929..3f01c215 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 @@ -92,15 +92,18 @@ public final class NotificationSubmissionController { /** * The channel a caller named. * - *

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. + *

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); } diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java index 598dc701..446b4335 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java @@ -32,7 +32,12 @@ import org.springframework.web.bind.annotation.RestController; * publish} and no application or transport ever called it. * *

{@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. + * + *

The path is lowerCamel plural like every other collection (manual 11, AIP-122); it was {@code + * /notification-templates} until 2026-11-12. * *

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; } diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java index 771c7cd3..2c1d3805 100644 --- a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java @@ -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> prefix(String path) { diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java index 2270c921..6cb97c21 100644 --- a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionControllerTest.java @@ -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(); + } } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java index f75421a4..0967f597 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java @@ -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; diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java index 8f7abc31..d2495607 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java @@ -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 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> 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 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 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); diff --git a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadRequest.java b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadRequest.java index 91dcaef5..51c03330 100644 --- a/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadRequest.java +++ b/src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadRequest.java @@ -9,7 +9,9 @@ import java.util.OptionalLong; * Client intent when starting an upload. * *

{@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. * *

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. diff --git a/src/bootstrap/app/compose-lanes/smoke/notification-smoke.sh b/src/bootstrap/app/compose-lanes/smoke/notification-smoke.sh index f2850e4a..fe37d5bd 100755 --- a/src/bootstrap/app/compose-lanes/smoke/notification-smoke.sh +++ b/src/bootstrap/app/compose-lanes/smoke/notification-smoke.sh @@ -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\", diff --git a/src/bootstrap/notification-platform/README.md b/src/bootstrap/notification-platform/README.md index 30345276..962b47b1 100644 --- a/src/bootstrap/notification-platform/README.md +++ b/src/bootstrap/notification-platform/README.md @@ -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} ``` diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkEnvelope.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkEnvelope.java index 511ebdc8..76da7106 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkEnvelope.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkEnvelope.java @@ -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(boolean success, List 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); diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkItemResult.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkItemResult.java index 1f802f1d..1e2719c1 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkItemResult.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/BulkItemResult.java @@ -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. * *

* - *

No debug payload — keeps the envelope safe to log/ship. + *

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)); } } diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/response/EnvelopeTest.java b/src/shared-contract/src/test/java/dev/caskeleton/shared/response/EnvelopeTest.java index 69e1ccd2..d7d75737 100644 --- a/src/shared-contract/src/test/java/dev/caskeleton/shared/response/EnvelopeTest.java +++ b/src/shared-contract/src/test/java/dev/caskeleton/shared/response/EnvelopeTest.java @@ -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 ok = BulkEnvelope.allOk(List.of("a"), META); + @DisplayName("bulk 전체 성공은 success=true와 meta를 싣는다") + void aFullySucceededBulkCarriesMeta() { + // given + List results = List.of("a"); + + // when + BulkEnvelope ok = BulkEnvelope.allOk(results, META); + + // then assertThat(ok.success()).isTrue(); assertThat(ok.meta().requestId()).isEqualTo("req-1"); + } - BulkEnvelope partial = - BulkEnvelope.partial(List.of(BulkItemResult.error(0, "MAPPING_FAILED", "x")), META); + @Test + @DisplayName("bulk 부분 실패는 BATCH_PARTIAL_FAILURE와 category 고정 문구, 항목 코드의 고정 문구를 싣는다") + void aPartiallyFailedBulkCarriesTheFixedWording() { + // given + List details = + List.of( + BulkItemResult.ok(0, "f-1"), BulkItemResult.error(1, OperationalError.MAPPING_FAILED)); + + // when + BulkEnvelope 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"); } }