001/* 002 * Copyright 2022-2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.soklet; 018 019import com.soklet.internal.spring.LinkedCaseInsensitiveMap; 020import org.jspecify.annotations.NonNull; 021import org.jspecify.annotations.Nullable; 022 023import javax.annotation.concurrent.NotThreadSafe; 024import javax.annotation.concurrent.ThreadSafe; 025import java.io.EOFException; 026import java.io.IOException; 027import java.io.UncheckedIOException; 028import java.nio.ByteBuffer; 029import java.nio.channels.FileChannel; 030import java.nio.channels.SeekableByteChannel; 031import java.nio.file.Files; 032import java.nio.file.Path; 033import java.nio.file.attribute.BasicFileAttributes; 034import java.time.Instant; 035import java.util.Collections; 036import java.util.ArrayList; 037import java.util.Map; 038import java.util.Map.Entry; 039import java.util.Optional; 040import java.util.List; 041import java.util.function.Consumer; 042 043import static java.lang.String.format; 044import static java.nio.file.StandardOpenOption.READ; 045import static java.util.Objects.requireNonNull; 046import static com.soklet.internal.ObjectIdentity.sameInstance; 047 048/** 049 * A prepared HTTP response representation, with a transport-ready body descriptor rather than an arbitrary logical body. 050 * <p> 051 * This value does not bypass the remaining response pipeline. Soklet may create replacement responses while applying 052 * interceptor selection, CORS, {@link ResponseMarshaler#postProcess(MarshaledResponse)}, HEAD/bodyless projection, 053 * and transport framing or compression. The original instance is not mutated by these transformations. 054 * <p> 055 * Your application's {@link ResponseMarshaler} is responsible for taking the {@link Response} returned by a <em>Resource Method</em> as input 056 * and converting its {@link Response#getBody()} to a {@link MarshaledResponseBody}. 057 * <p> 058 * For example, if a {@link Response} were to specify a body of {@code List.of("one", "two")}, a {@link ResponseMarshaler} might 059 * convert it to the JSON string {@code ["one", "two"]} and provide as output a corresponding {@link MarshaledResponse} with a byte-array-backed body containing UTF-8 bytes that represent {@code ["one", "two"]}. 060 * <p> 061 * Alternatively, a <em>Resource Method</em> can return a {@link MarshaledResponse} 062 * directly to supply a prepared body, such as an image or PDF, without ordinary 063 * body serialization. Configured {@link ResponseMarshaler#postProcess(MarshaledResponse)} 064 * and HEAD/bodyless/transport finalization still apply during Soklet dispatch. 065 * <p> 066 * Instances can be acquired via the {@link #withResponse(Response)}, {@link #withStatusCode(Integer)}, or {@link #withFile(Path, Request)} builder factory methods. 067 * Convenience instance factories are also available via {@link #fromResponse(Response)} and {@link #fromStatusCode(Integer)}. 068 * <p> 069 * Header and cookie collections are immutable snapshots. Response-body descriptors retain caller-supplied backing 070 * resources; callers must honor the ownership and mutation requirements documented by {@link MarshaledResponseBody} 071 * and {@link StreamingResponseBody}. 072 * <p> 073 * The built-in HTTP transport requires final ordinary response statuses from {@code 200} through 074 * {@code 599}. For finite responses it owns {@code Connection}, {@code Content-Length} and 075 * {@code Transfer-Encoding} framing and removes other hop-by-hop and Connection-nominated fields. 076 * A valid explicit length supplied by final HEAD marshaling is preserved when its status allows it. 077 * The default HEAD marshaler derives length from a supplied GET body, preserves an explicit length 078 * on an already bodyless HEAD response, and omits length when unknown. It does not invent a length 079 * for {@code 304} responses. A validated {@code 426} 080 * response may advertise {@code Upgrade}. For the JDK's standard file-channel implementation, 081 * file-backed delivery passes the real socket to 082 * {@link FileChannel#transferTo(long, long, java.nio.channels.WritableByteChannel)}, allowing 083 * native transfer when supported. Custom and other provider file channels instead write through 084 * a socket adapter that distinguishes target failures without a retry or probe write after uncertain progress. 085 * Zero-copy is not a cross-platform guarantee. 086 * <p> 087 * Full documentation is available at <a href="https://www.soklet.com/docs/response-writing">https://www.soklet.com/docs/response-writing</a>. 088 * 089 * @author <a href="https://www.revetkn.com">Mark Allen</a> 090 */ 091@ThreadSafe 092public final class MarshaledResponse { 093 @NonNull 094 private final Integer statusCode; 095 @NonNull 096 private final Map<@NonNull String, @NonNull List<@NonNull String>> headers; 097 @NonNull 098 private final List<@NonNull ResponseCookie> cookies; 099 @Nullable 100 private final MarshaledResponseBody body; 101 @Nullable 102 private final StreamingResponseBody streamingResponseBody; 103 @NonNull 104 private final List<@NonNull FileChannel> retainedChannels; 105 @Nullable 106 private final Object postProcessingToken; 107 108 /** 109 * Copies a logical response's status, headers, cookies, and existing {@code byte[]} body into a builder. 110 * <p> 111 * This method does not invoke a {@link ResponseMarshaler} or serialize the body. A body of any other type is omitted, 112 * including {@link String}, {@link MarshaledResponseBody}, and {@link StreamingResponseBody}. Serialize logical data 113 * explicitly, or configure the returned builder's body or streaming response body before building it. 114 * 115 * @param response the logical response whose values are used to prime this builder 116 * @return the builder 117 */ 118 @NonNull 119 public static Builder withResponse(@NonNull Response response) { 120 requireNonNull(response); 121 122 Object rawBody = response.getBody().orElse(null); 123 MarshaledResponseBody body = null; 124 125 if (rawBody != null && rawBody instanceof byte[] byteArrayBody) 126 body = new MarshaledResponseBody.Bytes(byteArrayBody); 127 128 Builder builder = new Builder(response.getStatusCode()) 129 .headers(response.getHeaders()) 130 .cookies(response.getCookies()); 131 132 if (body != null) 133 builder.body(body); 134 135 return builder; 136 } 137 138 /** 139 * Copies a logical response's status, headers, cookies, and existing {@code byte[]} body without serialization. 140 * Bodies of other types are omitted, as specified by {@link #withResponse(Response)}. 141 * 142 * @param response the logical response whose values are used to construct this instance 143 * @return a {@link MarshaledResponse} instance 144 */ 145 @NonNull 146 public static MarshaledResponse fromResponse(@NonNull Response response) { 147 return withResponse(response).build(); 148 } 149 150 /** 151 * Acquires a builder for {@link MarshaledResponse} instances. 152 * 153 * @param statusCode the HTTP status code for this response 154 * @return the builder 155 */ 156 @NonNull 157 public static Builder withStatusCode(@NonNull Integer statusCode) { 158 requireNonNull(statusCode); 159 return new Builder(statusCode); 160 } 161 162 /** 163 * Creates a {@link MarshaledResponse} with the given status code and no additional customization. 164 * 165 * @param statusCode the HTTP status code for this response 166 * @return a {@link MarshaledResponse} instance 167 */ 168 @NonNull 169 public static MarshaledResponse fromStatusCode(@NonNull Integer statusCode) { 170 return withStatusCode(statusCode).build(); 171 } 172 173 /** 174 * Acquires a file-specific builder for {@link MarshaledResponse} instances. 175 * <p> 176 * Files are special among known-length response bodies: correct file responses can depend on request 177 * headers such as {@code Range}, {@code If-Range}, {@code If-Match}, and {@code If-None-Match}, plus 178 * filesystem metadata such as length and last-modified time. This custom factory keeps that behavior 179 * in one place. Other known-length body types should use {@link Builder#body(MarshaledResponseBody)} 180 * or one of its overloads. 181 * 182 * @param path the file path to write 183 * @param request the incoming request whose method and conditional/range headers should be honored 184 * @return a file-specific builder 185 */ 186 @NonNull 187 public static FileBuilder withFile(@NonNull Path path, 188 @NonNull Request request) { 189 requireNonNull(path); 190 requireNonNull(request); 191 return new FileBuilder(path, request); 192 } 193 194 @NonNull 195 static FileBuilder withFile(@NonNull Path path, 196 @NonNull Request request, 197 @NonNull BasicFileAttributes attributes) { 198 requireNonNull(path); 199 requireNonNull(request); 200 requireNonNull(attributes); 201 return new FileBuilder(path, request).attributes(attributes); 202 } 203 204 /** 205 * Vends a mutable copier seeded with this instance's data, suitable for building new instances. 206 * 207 * @return a copier for this instance 208 */ 209 @NonNull 210 public Copier copy() { 211 return new Copier(this); 212 } 213 214 MarshaledResponse(@NonNull Builder builder) { 215 requireNonNull(builder); 216 217 this.statusCode = builder.statusCode; 218 this.headers = immutableHeaders(builder.headers); 219 this.cookies = builder.cookies == null ? List.of() : List.copyOf(builder.cookies); 220 this.body = builder.body; 221 this.streamingResponseBody = builder.streamingResponseBody; 222 this.postProcessingToken = builder.postProcessingToken; 223 224 if (getBody().isPresent() && getStreamingResponseBody().isPresent()) 225 throw new IllegalStateException("A MarshaledResponse may not specify both a known-length body and a streaming response body."); 226 227 if (getStreamingResponseBody().isPresent()) { 228 if (isBodylessStatusCode(getStatusCode())) 229 throw new IllegalStateException(format("HTTP status code %d must not include a streaming response body.", getStatusCode())); 230 231 if (this.headers.containsKey("Content-Length")) 232 throw new IllegalStateException("Streaming responses must not specify Content-Length."); 233 234 if (this.headers.containsKey("Transfer-Encoding")) 235 throw new IllegalStateException("Streaming responses must not specify Transfer-Encoding."); 236 } 237 this.retainedChannels = retainedChannels(builder.retainedChannels, this.body); 238 } 239 240 @Override 241 @NonNull 242 public String toString() { 243 return format("%s{statusCode=%s, headers=<redacted>, cookies=<redacted>, body=%s}", 244 getClass().getSimpleName(), getStatusCode(), 245 getStreamingResponseBody().isPresent() ? "<streaming>" : format("%d bytes", getBodyLength())); 246 } 247 248 /** 249 * The HTTP status code for this response. 250 * 251 * @return the status code 252 */ 253 @NonNull 254 public Integer getStatusCode() { 255 return this.statusCode; 256 } 257 258 /** 259 * The HTTP headers to write for this response. 260 * <p> 261 * Soklet writes one header line per value, preserving list order and repeated values. 262 * <p> 263 * The returned map and its value lists are immutable snapshots. 264 * 265 * @return the headers to write 266 */ 267 @NonNull 268 public Map<@NonNull String, @NonNull List<@NonNull String>> getHeaders() { 269 return this.headers; 270 } 271 272 /** 273 * The HTTP cookies to write for this response. 274 * <p> 275 * The returned list is an immutable snapshot and preserves cookie order and repeated cookies. 276 * 277 * @return the cookies to write 278 */ 279 @NonNull 280 public List<@NonNull ResponseCookie> getCookies() { 281 return this.cookies; 282 } 283 284 @NonNull 285 private static Map<@NonNull String, @NonNull List<@NonNull String>> immutableHeaders( 286 @Nullable Map<@NonNull String, @NonNull List<@NonNull String>> headers) { 287 if (headers == null || headers.isEmpty()) 288 return Map.of(); 289 290 Map<String, List<String>> copiedHeaders = Utilities.immutableValueLists(headers, true); 291 292 for (Entry<String, List<String>> entry : copiedHeaders.entrySet()) { 293 String headerName = entry.getKey(); 294 for (String headerValue : entry.getValue()) 295 Utilities.validateHeaderNameAndValue(headerName, headerValue); 296 } 297 298 return copiedHeaders; 299 } 300 301 302 /** 303 * The finalized HTTP response body to write, if available. 304 * 305 * @return the response body to write, or {@link Optional#empty()}) if no body should be written 306 */ 307 @NonNull 308 public Optional<@NonNull MarshaledResponseBody> getBody() { 309 return Optional.ofNullable(this.body); 310 } 311 312 /** 313 * The finalized streaming HTTP response body to write, if available. 314 * 315 * @return the streaming response body to write, or {@link Optional#empty()} if no stream should be written 316 */ 317 @NonNull 318 public Optional<@NonNull StreamingResponseBody> getStreamingResponseBody() { 319 return Optional.ofNullable(this.streamingResponseBody); 320 } 321 322 /** 323 * Whether this response has a streaming response body. 324 * 325 * @return {@code true} if this response is streaming 326 */ 327 @NonNull 328 public Boolean isStreaming() { 329 return getStreamingResponseBody().isPresent(); 330 } 331 332 /** 333 * The number of bytes this response body will write. 334 * 335 * @return the body length, or {@code 0} if no body is present 336 */ 337 @NonNull 338 public Long getBodyLength() { 339 MarshaledResponseBody body = getBody().orElse(null); 340 return body == null ? 0L : body.getLength(); 341 } 342 343 /** 344 * Releases this response's owned channels after delivery completes or is abandoned. 345 * <p> 346 * Built-in transports perform this cleanup automatically. Custom transports must call this method 347 * after completing or abandoning delivery, including streaming responses. It also releases owned 348 * predecessor channels retained by response transformations. Borrowed channels and unopened 349 * path-backed bodies are unaffected. Repeated calls are safe. 350 * 351 * Do not call this method from a response interceptor that is returning the response for delivery, 352 * or use an application cleanup scope that ends before delivery. 353 * 354 * @throws UncheckedIOException if an owned channel cannot be closed 355 */ 356 public void close() { 357 closeChannels(ownedChannels(), null); 358 } 359 360 boolean isPostProcessedFor(@NonNull Object token) { return sameInstance(this.postProcessingToken, token); } 361 362 @NonNull MarshaledResponse markPostProcessed(@NonNull Object token) { 363 requireNonNull(token); 364 if (isPostProcessedFor(token)) return this; 365 Copier copier = copy(); 366 copier.builder.postProcessingToken = token; 367 return copier.finish(); 368 } 369 370 boolean hasOwnedChannels() { 371 return !this.retainedChannels.isEmpty() || this.body instanceof MarshaledResponseBody.FileChannel channel 372 && channel.getCloseOnComplete(); 373 } 374 375 @NonNull List<@NonNull FileChannel> ownedChannels() { 376 if (!(this.body instanceof MarshaledResponseBody.FileChannel channel) || !channel.getCloseOnComplete()) 377 return this.retainedChannels; 378 List<FileChannel> channels = new ArrayList<>(this.retainedChannels); 379 channels.add(channel.getChannel()); 380 return channels; 381 } 382 383 @NonNull MarshaledResponse retainingChannels(@NonNull List<@NonNull FileChannel> channels) { 384 if (channels.isEmpty()) return this; 385 Copier copier = copy(); 386 copier.builder.retainChannels(channels); 387 return copier.finish(); 388 } 389 390 private static @NonNull List<@NonNull FileChannel> retainedChannels(@NonNull List<@NonNull FileChannel> candidates, 391 @Nullable MarshaledResponseBody body) { 392 if (candidates.isEmpty()) return List.of(); 393 java.util.Set<FileChannel> seen = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>()); 394 List<FileChannel> retained = new ArrayList<>(); 395 for (FileChannel channel : candidates) { 396 if (body instanceof MarshaledResponseBody.FileChannel current && sameInstance(current.getChannel(), channel)) 397 continue; // The final descriptor decides whether its own channel is owned or borrowed. 398 if (seen.add(channel)) retained.add(channel); 399 } 400 // Copying a descriptor never releases resources belonging to the original. 401 // The selected response's terminal owner releases all retained predecessors. 402 return List.copyOf(retained); 403 } 404 405 static void closeChannels(@NonNull List<@NonNull FileChannel> channels, @Nullable Throwable primaryFailure) { 406 if (channels.isEmpty()) return; 407 Throwable failure = primaryFailure; 408 java.util.Set<FileChannel> seen = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>()); 409 for (FileChannel channel : channels) { 410 if (!seen.add(channel)) continue; 411 try { channel.close(); } 412 catch (IOException | RuntimeException | Error closeFailure) { 413 Throwable reported = closeFailure instanceof IOException io 414 ? new UncheckedIOException("Unable to close file-channel response body.", io) : closeFailure; 415 if (failure == null) failure = reported; 416 else if (!sameInstance(failure, reported)) failure.addSuppressed(reported); 417 } 418 } 419 if (primaryFailure == null) { 420 if (failure instanceof RuntimeException runtime) throw runtime; 421 if (failure instanceof Error error) throw error; 422 } 423 } 424 425 byte @Nullable [] bodyBytesOrNull() { 426 Throwable failure = null; 427 try { return materializeBodyBytes(); } 428 catch (RuntimeException | Error thrown) { failure = thrown; throw thrown; } 429 finally { closeChannels(this.retainedChannels, failure); } 430 } 431 432 private byte @Nullable [] materializeBodyBytes() { 433 MarshaledResponseBody body = getBody().orElse(null); 434 435 if (body == null) 436 return null; 437 438 if (body instanceof MarshaledResponseBody.Bytes bytes) 439 return bytes.getBytes(); 440 441 if (body instanceof MarshaledResponseBody.File file) 442 return materializeFile(file.getPath(), file.getOffset(), file.getCount()); 443 444 if (body instanceof MarshaledResponseBody.FileChannel fileChannel) 445 return materializeFileChannel(fileChannel.getChannel(), fileChannel.getOffset(), fileChannel.getCount(), fileChannel.getCloseOnComplete()); 446 447 if (body instanceof MarshaledResponseBody.SecureFile secureFile) 448 return materializeSecureFile(secureFile); 449 450 if (body instanceof MarshaledResponseBody.ByteBuffer byteBuffer) 451 return materializeByteBuffer(byteBuffer.getBuffer()); 452 453 throw new IllegalStateException(format("Unsupported marshaled response body type: %s", body.getClass().getName())); 454 } 455 456 byte @NonNull [] bodyBytesOrEmpty() { 457 byte[] bytes = bodyBytesOrNull(); 458 return bytes == null ? Utilities.emptyByteArray() : bytes; 459 } 460 461 /** 462 * Builder used to construct instances of {@link MarshaledResponse} via {@link MarshaledResponse#withResponse(Response)} or {@link MarshaledResponse#withStatusCode(Integer)}. 463 * <p> 464 * Known-length bodies and streaming bodies are mutually exclusive. This builder does not automatically clear one 465 * when the other is set; use {@link #withoutBody()} or {@link #withoutStreamingResponseBody()} before {@link #build()} when 466 * switching body modes. 467 * <p> 468 * This class is intended for use by a single thread. 469 * 470 * @author <a href="https://www.revetkn.com">Mark Allen</a> 471 */ 472 @NotThreadSafe 473 public static final class Builder { 474 @NonNull 475 private Integer statusCode; 476 @Nullable 477 private List<@NonNull ResponseCookie> cookies; 478 @Nullable 479 private Map<@NonNull String, @NonNull List<@NonNull String>> headers; 480 @Nullable 481 private MarshaledResponseBody body; 482 @Nullable 483 private StreamingResponseBody streamingResponseBody; 484 @NonNull 485 private List<@NonNull FileChannel> retainedChannels = List.of(); 486 @Nullable 487 private Object postProcessingToken; 488 489 private void retainChannels(@NonNull List<@NonNull FileChannel> channels) { 490 if (channels.isEmpty()) return; 491 if (this.retainedChannels.isEmpty()) this.retainedChannels = new ArrayList<>(); 492 this.retainedChannels.addAll(channels); 493 } 494 495 Builder(@NonNull Integer statusCode) { 496 requireNonNull(statusCode); 497 this.statusCode = statusCode; 498 } 499 500 @NonNull 501 public Builder statusCode(@NonNull Integer statusCode) { 502 requireNonNull(statusCode); 503 this.statusCode = statusCode; 504 return this; 505 } 506 507 /** 508 * Replaces the configured response cookies. 509 * 510 * @param cookies cookies to write, or {@code null} or an empty list to configure no cookies 511 * @return this builder 512 */ 513 @NonNull 514 public Builder cookies(@Nullable List<@NonNull ResponseCookie> cookies) { 515 this.cookies = cookies; 516 return this; 517 } 518 519 /** 520 * Replaces the configured response headers. 521 * 522 * @param headers headers to write, or {@code null} or an empty map to configure no headers 523 * @return this builder 524 */ 525 @NonNull 526 public Builder headers(@Nullable Map<@NonNull String, @NonNull List<@NonNull String>> headers) { 527 this.headers = headers; 528 return this; 529 } 530 531 /** 532 * Sets a byte-array-backed response body, or removes any current body if {@code bytes} is {@code null}. 533 * 534 * @param bytes the response bytes to write, or {@code null} for no body 535 * @return this builder 536 */ 537 @NonNull 538 public Builder body(byte @Nullable [] bytes) { 539 return bytes == null 540 ? withoutBody() 541 : body(new MarshaledResponseBody.Bytes(bytes)); 542 } 543 544 /** 545 * Sets a response body descriptor, or removes any current body if {@code body} is {@code null}. 546 * 547 * @param body the response body descriptor to write, or {@code null} for no body 548 * @return this builder 549 */ 550 @NonNull 551 public Builder body(@Nullable MarshaledResponseBody body) { 552 if (body == null) 553 return withoutBody(); 554 555 this.body = body; 556 return this; 557 } 558 559 /** 560 * Sets a path-backed response body, or removes any current body if {@code path} is {@code null}. 561 * 562 * @param path the file path to write, or {@code null} for no body 563 * @return this builder 564 */ 565 @NonNull 566 public Builder body(@Nullable Path path) { 567 if (path == null) 568 return withoutBody(); 569 570 this.body = fileBody(path); 571 return this; 572 } 573 574 /** 575 * Sets a ranged path-backed response body. 576 * 577 * @param path the file path to write 578 * @param offset the zero-based file offset from which response bytes should be written 579 * @param count the number of file bytes to write 580 * @return this builder 581 */ 582 @NonNull 583 public Builder body(@NonNull Path path, @NonNull Long offset, @NonNull Long count) { 584 requireNonNull(path); 585 this.body = fileBody(path, offset, count); 586 return this; 587 } 588 589 /** 590 * Sets a file-channel-backed response body. 591 * 592 * @param fileChannel the file channel to write 593 * @param offset the zero-based channel offset from which response bytes should be written 594 * @param count the number of channel bytes to write 595 * @param closeOnComplete whether Soklet should close the channel after response completion 596 * @return this builder 597 */ 598 @NonNull 599 public Builder body(@NonNull FileChannel fileChannel, 600 @NonNull Long offset, 601 @NonNull Long count, 602 @NonNull Boolean closeOnComplete) { 603 requireNonNull(fileChannel); 604 this.body = fileChannelBody(fileChannel, offset, count, closeOnComplete); 605 return this; 606 } 607 608 /** 609 * Sets a byte-buffer-backed response body, or removes any current body if {@code byteBuffer} is {@code null}. 610 * 611 * @param byteBuffer the byte buffer to write, or {@code null} for no body 612 * @return this builder 613 */ 614 @NonNull 615 public Builder body(@Nullable ByteBuffer byteBuffer) { 616 if (byteBuffer == null) 617 return withoutBody(); 618 619 this.body = new MarshaledResponseBody.ByteBuffer(byteBuffer); 620 return this; 621 } 622 623 /** 624 * Sets a streaming response body, or removes any current stream if {@code streamingResponseBody} is {@code null}. 625 * <p> 626 * A response may have a known-length body or a stream, but not both. Setting a stream does not remove any 627 * current known-length body; call {@link #withoutBody()} first if replacing a known-length body with a stream. 628 * {@link #build()} rejects responses that still specify both. 629 * 630 * @param streamingResponseBody the streaming response body to write, or {@code null} for no stream 631 * @return this builder 632 */ 633 @NonNull 634 public Builder streamingResponseBody(@Nullable StreamingResponseBody streamingResponseBody) { 635 if (streamingResponseBody == null) 636 return withoutStreamingResponseBody(); 637 638 this.streamingResponseBody = streamingResponseBody; 639 return this; 640 } 641 642 /** 643 * Sets a streaming response body backed by the given writer callback. 644 * <p> 645 * The callback is retained for response production and is not invoked while building the response. 646 * This follows the body-selection rules of {@link #streamingResponseBody(StreamingResponseBody)}: 647 * a current known-length body is not removed, and {@link #build()} rejects a response that specifies both. 648 * Use {@link #withoutStreamingResponseBody()} to remove the stream. 649 * 650 * @param streamingResponseWriter the callback that writes the response 651 * @return this builder 652 */ 653 @NonNull 654 public Builder stream(@NonNull StreamingResponseWriter streamingResponseWriter) { 655 return streamingResponseBody(StreamingResponseBody.fromWriter(streamingResponseWriter)); 656 } 657 658 /** 659 * Removes the response body from this builder. 660 * <p> 661 * If the current body owns a caller-supplied {@link FileChannel}, the channel is closed before it is 662 * removed. Path-backed file bodies are lazy and do not hold open resources at this point. 663 * 664 * @return this builder 665 */ 666 @NonNull 667 public Builder withoutBody() { 668 releaseBodyResources(this.body); 669 this.body = null; 670 return this; 671 } 672 673 /** 674 * Removes the streaming response body from this builder. 675 * 676 * @return this builder 677 */ 678 @NonNull 679 public Builder withoutStreamingResponseBody() { 680 this.streamingResponseBody = null; 681 return this; 682 } 683 684 @NonNull 685 public MarshaledResponse build() { 686 return new MarshaledResponse(this); 687 } 688 } 689 690 /** 691 * File-specific builder used by {@link MarshaledResponse#withFile(Path, Request)}. 692 * <p> 693 * Files are special among known-length response bodies because validators, byte ranges, and 694 * {@code HEAD} behavior depend on the current request and filesystem metadata. This builder produces 695 * the final {@link MarshaledResponse} directly from those inputs; for ordinary precomputed bytes, 696 * buffers, channels, or path-backed bodies without HTTP file semantics, use {@link Builder#body(byte[])}, 697 * {@link Builder#body(ByteBuffer)}, {@link Builder#body(FileChannel, Long, Long, Boolean)}, or 698 * {@link Builder#body(Path)} instead. 699 * <p> 700 * This class is intended for use by a single thread. 701 * 702 * @author <a href="https://www.revetkn.com">Mark Allen</a> 703 */ 704 @NotThreadSafe 705 public static final class FileBuilder { 706 private final FileResponse.@NonNull Builder builder; 707 private final FileResponse.@NonNull RequestContext requestContext; 708 709 private FileBuilder(@NonNull Path path, 710 @NonNull Request request) { 711 requireNonNull(path); 712 requireNonNull(request); 713 this.builder = FileResponse.withPath(path); 714 this.requestContext = FileResponse.RequestContext.fromRequest(request); 715 } 716 717 /** 718 * Sets the {@code Content-Type} header for the file representation. 719 * 720 * @param contentType the content type, or {@code null} or a blank string to clear the configured value and omit the 721 * header 722 * @return this builder 723 */ 724 @NonNull 725 public FileBuilder contentType(@Nullable String contentType) { 726 this.builder.contentType(contentType); 727 return this; 728 } 729 730 /** 731 * Sets the {@code Content-Encoding} header for the file representation. 732 * 733 * @param contentEncoding the content encoding, or {@code null} or a blank string to clear the configured value and 734 * omit the header 735 * @return this builder 736 */ 737 @NonNull 738 public FileBuilder contentEncoding(@Nullable String contentEncoding) { 739 this.builder.contentEncoding(contentEncoding); 740 return this; 741 } 742 743 /** 744 * Sets the entity tag used for conditional requests and the {@code ETag} header. 745 * 746 * @param entityTag the entity tag, or {@code null} to clear the configured value and omit the header 747 * @return this builder 748 */ 749 @NonNull 750 public FileBuilder entityTag(@Nullable EntityTag entityTag) { 751 this.builder.entityTag(entityTag); 752 return this; 753 } 754 755 /** 756 * Sets the last-modified time used for conditional requests and the {@code Last-Modified} header. 757 * 758 * @param lastModified the last-modified time, or {@code null} to clear the configured value and omit the header 759 * @return this builder 760 */ 761 @NonNull 762 public FileBuilder lastModified(@Nullable Instant lastModified) { 763 this.builder.lastModified(lastModified); 764 return this; 765 } 766 767 /** 768 * Sets the {@code Cache-Control} header. 769 * 770 * @param cacheControl the cache-control value, or {@code null} or a blank string to clear the configured value and 771 * omit the header 772 * @return this builder 773 */ 774 @NonNull 775 public FileBuilder cacheControl(@Nullable String cacheControl) { 776 this.builder.cacheControl(cacheControl); 777 return this; 778 } 779 780 /** 781 * Replaces the additional response headers. 782 * <p> 783 * Headers controlled by the file response are rejected during {@link #build()}; use the corresponding dedicated 784 * builder methods where available. 785 * 786 * @param headers additional headers to write, or {@code null} or an empty map to configure no additional headers 787 * @return this builder 788 */ 789 @NonNull 790 public FileBuilder headers(@Nullable Map<@NonNull String, @NonNull List<@NonNull String>> headers) { 791 this.builder.headers(headers); 792 return this; 793 } 794 795 /** 796 * Controls whether byte-range requests are honored. 797 * 798 * @param rangeRequests {@code true} to honor byte-range requests, {@code false} to ignore them, or {@code null} to 799 * restore the default of {@code true} 800 * @return this builder 801 */ 802 @NonNull 803 public FileBuilder rangeRequests(@Nullable Boolean rangeRequests) { 804 this.builder.rangeRequests(rangeRequests); 805 return this; 806 } 807 808 @NonNull 809 FileBuilder attributes(@Nullable BasicFileAttributes attributes) { 810 this.builder.attributes(attributes); 811 return this; 812 } 813 814 @NonNull 815 public MarshaledResponse build() { 816 return this.builder.build().marshaledResponseFor(this.requestContext); 817 } 818 } 819 820 /** 821 * Builder used to copy instances of {@link MarshaledResponse} via {@link MarshaledResponse#copy()}. 822 * <p> 823 * This class is intended for use by a single thread. 824 * 825 * @author <a href="https://www.revetkn.com">Mark Allen</a> 826 */ 827 @NotThreadSafe 828 public static final class Copier { 829 @NonNull 830 private final Builder builder; 831 832 Copier(@NonNull MarshaledResponse marshaledResponse) { 833 requireNonNull(marshaledResponse); 834 835 this.builder = new Builder(marshaledResponse.getStatusCode()) 836 .headers(Utilities.mutableValueLists(marshaledResponse.getHeaders(), true)) 837 .cookies(new ArrayList<>(marshaledResponse.getCookies())); 838 839 this.builder.postProcessingToken = marshaledResponse.postProcessingToken; 840 this.builder.retainChannels(marshaledResponse.ownedChannels()); 841 marshaledResponse.getBody().ifPresent(this.builder::body); 842 marshaledResponse.getStreamingResponseBody().ifPresent(this.builder::streamingResponseBody); 843 } 844 845 private void retainCurrentBody() { 846 if (this.builder.body instanceof MarshaledResponseBody.FileChannel channel && channel.getCloseOnComplete()) 847 this.builder.retainChannels(List.of(channel.getChannel())); 848 } 849 850 @NonNull 851 public Copier statusCode(@NonNull Integer statusCode) { 852 requireNonNull(statusCode); 853 this.builder.statusCode(statusCode); 854 return this; 855 } 856 857 /** 858 * Replaces the copied response headers. 859 * 860 * @param headers headers to write 861 * @return this copier 862 */ 863 @NonNull 864 public Copier headers(@NonNull Map<@NonNull String, @NonNull List<@NonNull String>> headers) { 865 this.builder.headers(headers); 866 return this; 867 } 868 869 /** 870 * Mutates the currently configured response headers in place. 871 * <p> 872 * The consumer may add, replace, remove, or clear header entries. If no header map is configured, the consumer 873 * receives a new mutable, empty map. 874 * 875 * @param headersConsumer consumer that mutates the response headers 876 * @return this copier 877 */ 878 @NonNull 879 public Copier headers( 880 @NonNull Consumer<@NonNull Map<@NonNull String, 881 @NonNull List<@NonNull String>>> headersConsumer) { 882 requireNonNull(headersConsumer); 883 884 this.builder.headers(Utilities.mutableValueLists(this.builder.headers, true)); 885 886 headersConsumer.accept(this.builder.headers); 887 return this; 888 } 889 890 /** 891 * Replaces the copied response cookies. 892 * 893 * @param cookies cookies to write, or {@code null} or an empty list to configure no cookies 894 * @return this copier 895 */ 896 @NonNull 897 public Copier cookies(@Nullable List<@NonNull ResponseCookie> cookies) { 898 this.builder.cookies(cookies); 899 return this; 900 } 901 902 /** 903 * Mutates the currently configured response cookies in place. 904 * <p> 905 * The consumer may add, remove, or clear cookies. If no cookie list is configured, the consumer receives a new 906 * mutable, empty list. 907 * 908 * @param cookiesConsumer consumer that mutates the response cookies 909 * @return this copier 910 */ 911 @NonNull 912 public Copier cookies( 913 @NonNull Consumer<@NonNull List<@NonNull ResponseCookie>> 914 cookiesConsumer) { 915 requireNonNull(cookiesConsumer); 916 917 this.builder.cookies(new ArrayList<>(this.builder.cookies == null ? List.of() : this.builder.cookies)); 918 919 cookiesConsumer.accept(this.builder.cookies); 920 return this; 921 } 922 923 /** 924 * Replaces the known-length response body with a byte-array-backed body, or removes the current known-length body 925 * if {@code bytes} is {@code null}. 926 * 927 * @param bytes the response bytes to write, or {@code null} for no known-length body 928 * @return this copier 929 */ 930 @NonNull 931 public Copier body(byte @Nullable [] bytes) { 932 if (bytes == null) return withoutBody(); 933 retainCurrentBody(); 934 this.builder.body(bytes); 935 return this; 936 } 937 938 /** 939 * Replaces the known-length response body, or removes the current known-length body if {@code body} is 940 * {@code null}. 941 * 942 * @param body the response body descriptor to write, or {@code null} for no known-length body 943 * @return this copier 944 */ 945 @NonNull 946 public Copier body(@Nullable MarshaledResponseBody body) { 947 if (body == null) return withoutBody(); 948 retainCurrentBody(); 949 this.builder.body(body); 950 return this; 951 } 952 953 /** 954 * Replaces the known-length response body with a path-backed body, or removes the current known-length body if 955 * {@code path} is {@code null}. 956 * 957 * @param path the file path to write, or {@code null} for no known-length body 958 * @return this copier 959 */ 960 @NonNull 961 public Copier body(@Nullable Path path) { 962 if (path == null) return withoutBody(); 963 retainCurrentBody(); 964 this.builder.body(path); 965 return this; 966 } 967 968 @NonNull 969 public Copier body(@NonNull Path path, @NonNull Long offset, @NonNull Long count) { 970 retainCurrentBody(); 971 this.builder.body(path, offset, count); 972 return this; 973 } 974 975 @NonNull 976 public Copier body(@NonNull FileChannel fileChannel, 977 @NonNull Long offset, 978 @NonNull Long count, 979 @NonNull Boolean closeOnComplete) { 980 retainCurrentBody(); 981 this.builder.body(fileChannel, offset, count, closeOnComplete); 982 return this; 983 } 984 985 /** 986 * Replaces the known-length response body with a byte-buffer-backed body, or removes the current known-length body 987 * if {@code byteBuffer} is {@code null}. 988 * 989 * @param byteBuffer the byte buffer to write, or {@code null} for no known-length body 990 * @return this copier 991 */ 992 @NonNull 993 public Copier body(@Nullable ByteBuffer byteBuffer) { 994 if (byteBuffer == null) return withoutBody(); 995 retainCurrentBody(); 996 this.builder.body(byteBuffer); 997 return this; 998 } 999 1000 /** 1001 * Replaces the streaming response body, or removes the current stream if {@code streamingResponseBody} is {@code null}. 1002 * <p> 1003 * This does not remove a known-length response body; {@link #finish()} rejects a response that still specifies 1004 * both body modes. 1005 * 1006 * @param streamingResponseBody the streaming response body to write, or {@code null} for no stream 1007 * @return this copier 1008 */ 1009 @NonNull 1010 public Copier streamingResponseBody(@Nullable StreamingResponseBody streamingResponseBody) { 1011 this.builder.streamingResponseBody(streamingResponseBody); 1012 return this; 1013 } 1014 1015 /** 1016 * Replaces the streaming response body with one backed by the given writer callback. 1017 * <p> 1018 * The callback is retained for response production and is not invoked while copying the response. 1019 * This follows the body-selection rules of {@link #streamingResponseBody(StreamingResponseBody)}: 1020 * a current known-length body is not removed, and {@link #finish()} rejects a response that specifies both. 1021 * Use {@link #withoutStreamingResponseBody()} to remove the stream. 1022 * 1023 * @param streamingResponseWriter the callback that writes the response 1024 * @return this copier 1025 */ 1026 @NonNull 1027 public Copier stream(@NonNull StreamingResponseWriter streamingResponseWriter) { 1028 return streamingResponseBody(StreamingResponseBody.fromWriter(streamingResponseWriter)); 1029 } 1030 1031 /** 1032 * Removes the response body from this copier. 1033 * <p> 1034 * An owned channel remains open while copying, including when the replacement is bodyless or 1035 * independent bytes. The completed response retains that predecessor until its terminal owner invokes 1036 * {@link MarshaledResponse#close()}. A replacement channel or stream may still use it. 1037 * Path-backed bodies do not hold open resources. 1038 * 1039 * @return this copier 1040 */ 1041 @NonNull 1042 public Copier withoutBody() { 1043 retainCurrentBody(); 1044 this.builder.body = null; 1045 return this; 1046 } 1047 1048 /** 1049 * Removes the streaming response body from this copier. 1050 * 1051 * @return this copier 1052 */ 1053 @NonNull 1054 public Copier withoutStreamingResponseBody() { 1055 this.builder.withoutStreamingResponseBody(); 1056 return this; 1057 } 1058 1059 @NonNull 1060 public MarshaledResponse finish() { 1061 return this.builder.build(); 1062 } 1063 } 1064 1065 private static MarshaledResponseBody.@NonNull File fileBody(@NonNull Path path) { 1066 Long size = fileSize(path); 1067 return new MarshaledResponseBody.File(path, 0L, size); 1068 } 1069 1070 private static MarshaledResponseBody.@NonNull File fileBody(@NonNull Path path, @NonNull Long offset, @NonNull Long count) { 1071 Long size = fileSize(path); 1072 validateRangeWithinLength(offset, count, size); 1073 return new MarshaledResponseBody.File(path, offset, count); 1074 } 1075 1076 private static MarshaledResponseBody.@NonNull FileChannel fileChannelBody(@NonNull FileChannel fileChannel, 1077 @NonNull Long offset, 1078 @NonNull Long count, 1079 @NonNull Boolean closeOnComplete) { 1080 requireNonNull(fileChannel); 1081 requireNonNull(closeOnComplete); 1082 validateRangeWithinLength(offset, count, fileChannelSize(fileChannel)); 1083 return new MarshaledResponseBody.FileChannel(fileChannel, offset, count, closeOnComplete); 1084 } 1085 1086 private static void releaseBodyResources(@Nullable MarshaledResponseBody body) { 1087 if (!(body instanceof MarshaledResponseBody.FileChannel fileChannelBody) || !fileChannelBody.getCloseOnComplete()) 1088 return; 1089 1090 try { 1091 fileChannelBody.getChannel().close(); 1092 } catch (IOException e) { 1093 throw new UncheckedIOException("Unable to close file-channel response body.", e); 1094 } 1095 } 1096 1097 @NonNull 1098 private static Long fileSize(@NonNull Path path) { 1099 requireNonNull(path); 1100 1101 if (!Files.isRegularFile(path)) 1102 throw new IllegalArgumentException(format("File body path must reference a regular file: %s", path)); 1103 1104 if (!Files.isReadable(path)) 1105 throw new IllegalArgumentException(format("File body path must be readable: %s", path)); 1106 1107 try { 1108 return Files.size(path); 1109 } catch (IOException e) { 1110 throw new UncheckedIOException(format("Unable to determine file body length for path: %s", path), e); 1111 } 1112 } 1113 1114 @NonNull 1115 private static Long fileChannelSize(@NonNull FileChannel fileChannel) { 1116 requireNonNull(fileChannel); 1117 1118 try { 1119 return fileChannel.size(); 1120 } catch (IOException e) { 1121 throw new UncheckedIOException("Unable to determine file-channel body length.", e); 1122 } 1123 } 1124 1125 private static void validateRangeWithinLength(@NonNull Long offset, @NonNull Long count, @NonNull Long length) { 1126 requireNonNull(offset); 1127 requireNonNull(count); 1128 requireNonNull(length); 1129 1130 if (offset < 0) 1131 throw new IllegalArgumentException("Offset must be >= 0."); 1132 1133 if (count < 0) 1134 throw new IllegalArgumentException("Count must be >= 0."); 1135 1136 if (Long.MAX_VALUE - offset < count) 1137 throw new IllegalArgumentException("Offset plus count exceeds maximum supported file position."); 1138 1139 if (offset + count > length) 1140 throw new IllegalArgumentException(format("Offset plus count must be <= body length %d.", length)); 1141 } 1142 1143 private static boolean isBodylessStatusCode(@NonNull Integer statusCode) { 1144 requireNonNull(statusCode); 1145 return (statusCode >= 100 && statusCode < 200) || statusCode == 204 || statusCode == 205 || statusCode == 304; 1146 } 1147 1148 private static byte @NonNull [] materializeFile(@NonNull Path path, @NonNull Long offset, @NonNull Long count) { 1149 try (FileChannel fileChannel = FileChannel.open(path, READ)) { 1150 return materializeFileChannel(fileChannel, offset, count, false); 1151 } catch (IOException e) { 1152 throw new UncheckedIOException(format("Unable to read file response body: %s", path), e); 1153 } 1154 } 1155 1156 private static byte @NonNull [] materializeSecureFile(MarshaledResponseBody.@NonNull SecureFile file) { 1157 if (file.getCount() > Integer.MAX_VALUE) 1158 throw new IllegalStateException("Response body is too large to materialize as a byte array."); 1159 byte[] bytes = new byte[Math.toIntExact(file.getCount())]; 1160 try (SeekableByteChannel channel = file.openChannel()) { 1161 channel.position(file.getOffset()); 1162 ByteBuffer buffer = ByteBuffer.wrap(bytes); 1163 while (buffer.hasRemaining()) { 1164 int read = channel.read(buffer); 1165 if (read <= 0) 1166 throw new EOFException("File ended before the expected response body length was read."); 1167 } 1168 return bytes; 1169 } catch (IOException e) { 1170 throw new UncheckedIOException("Unable to materialize secure static-file response body.", e); 1171 } 1172 } 1173 1174 private static byte @NonNull [] materializeFileChannel(@NonNull FileChannel fileChannel, 1175 @NonNull Long offset, 1176 @NonNull Long count, 1177 @NonNull Boolean closeOnComplete) { 1178 requireNonNull(fileChannel); 1179 requireNonNull(offset); 1180 requireNonNull(count); 1181 requireNonNull(closeOnComplete); 1182 1183 if (closeOnComplete) { 1184 try (FileChannel managedFileChannel = fileChannel) { 1185 return materializeFileChannel(managedFileChannel, offset, count, false); 1186 } catch (IOException e) { 1187 throw new UncheckedIOException("Unable to close file-channel response body.", e); 1188 } 1189 } 1190 1191 if (count > Integer.MAX_VALUE) 1192 throw new IllegalStateException("Response body is too large to materialize as a byte array."); 1193 1194 byte[] bytes = new byte[Math.toIntExact(count)]; 1195 ByteBuffer buffer = ByteBuffer.wrap(bytes); 1196 long position = offset; 1197 1198 try { 1199 while (buffer.hasRemaining()) { 1200 int read = fileChannel.read(buffer, position); 1201 if (read < 0) 1202 throw new EOFException("File ended before the expected response body length was read."); 1203 if (read == 0) 1204 throw new EOFException("File did not provide the expected response body length."); 1205 position += read; 1206 } 1207 return bytes; 1208 } catch (IOException e) { 1209 throw new UncheckedIOException("Unable to materialize file-channel response body.", e); 1210 } 1211 } 1212 1213 1214 private static byte @NonNull [] materializeByteBuffer(@NonNull ByteBuffer byteBuffer) { 1215 requireNonNull(byteBuffer); 1216 1217 ByteBuffer duplicate = byteBuffer.asReadOnlyBuffer(); 1218 byte[] bytes = new byte[duplicate.remaining()]; 1219 duplicate.get(bytes); 1220 return bytes; 1221 } 1222}