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 org.jspecify.annotations.NonNull; 020 021import javax.annotation.concurrent.ThreadSafe; 022import java.io.IOException; 023import java.nio.channels.SeekableByteChannel; 024import java.nio.file.Path; 025import java.nio.file.attribute.BasicFileAttributes; 026 027import static java.util.Objects.requireNonNull; 028 029/** 030 * A known-length, finalized HTTP response body. 031 * <p> 032 * This type describes the body to write; it is not itself responsible for writing to a transport. Bodies may be backed 033 * by bytes, files, file channels, or byte buffers. 034 * <p> 035 * These descriptors are thread-safe value holders, but they do not take ownership of or make immutable their backing 036 * content. From construction until every response using a descriptor has completed, callers must not concurrently 037 * mutate a backing byte array or byte-buffer content, modify a path-backed file region, or close or modify a borrowed 038 * file channel. A channel configured with {@link FileChannel#getCloseOnComplete()} 039 * is closed after delivery or abandonment by closing the containing 040 * {@link MarshaledResponse}. Soklet's built-in transports implement this ownership; 041 * a custom transport must invoke {@link MarshaledResponse#close()} itself. 042 * 043 * <p> 044 * This type may gain reviewed permitted subtypes in Soklet 4.x; use a forward-compatible default when switching over its values. 045 * 046 * @author <a href="https://www.revetkn.com">Mark Allen</a> 047 */ 048@ThreadSafe 049public sealed interface MarshaledResponseBody permits MarshaledResponseBody.Bytes, MarshaledResponseBody.File, MarshaledResponseBody.FileChannel, MarshaledResponseBody.ByteBuffer, MarshaledResponseBody.SecureFile { 050 /** 051 * The number of bytes this body will write. 052 * 053 * @return the body length 054 */ 055 @NonNull 056 Long getLength(); 057 058 /** 059 * A finalized response body backed by a byte array. 060 * 061 * @author <a href="https://www.revetkn.com">Mark Allen</a> 062 */ 063 @ThreadSafe 064 final class Bytes implements MarshaledResponseBody { 065 066 private final byte @NonNull [] bytes; 067 068 public Bytes(byte @NonNull [] bytes) { 069 this.bytes = requireNonNull(bytes); 070 } 071 072 /** 073 * The byte array backing this body. 074 * <p> 075 * For compatibility with prior {@link MarshaledResponse} behavior, this array is not defensively copied. Callers 076 * must not mutate it from construction until every response using this body has completed. 077 * 078 * @return the bytes to write 079 */ 080 public byte @NonNull [] getBytes() { 081 return this.bytes; 082 } 083 084 @Override 085 @NonNull 086 public Long getLength() { 087 return Long.valueOf(getBytes().length); 088 } 089 } 090 091 /** 092 * A finalized response body backed by a file path. 093 * <p> 094 * The referenced file region remains caller-owned and must not be modified while a response is using it. 095 * <p> 096 * The standard HTTP server allows native transfer for the JDK's standard file channels when the platform supports it. 097 * Channels from other filesystem providers, including ZIP and JAR filesystems, use a socket adapter. This can lose 098 * zero-copy transfer, reduce throughput, and use more CPU. 099 * 100 * @author <a href="https://www.revetkn.com">Mark Allen</a> 101 */ 102 @ThreadSafe 103 final class File implements MarshaledResponseBody { 104 @NonNull 105 private final Path path; 106 @NonNull 107 private final Long offset; 108 @NonNull 109 private final Long count; 110 111 public File(@NonNull Path path, @NonNull Long offset, @NonNull Long count) { 112 this.path = requireNonNull(path); 113 this.offset = requireNonNull(offset); 114 this.count = requireNonNull(count); 115 validateOffsetAndCount(offset, count); 116 } 117 118 /** 119 * The file path backing this body. 120 * 121 * @return the file path 122 */ 123 @NonNull 124 public Path getPath() { 125 return this.path; 126 } 127 128 /** 129 * The zero-based file offset from which response bytes should be written. 130 * 131 * @return the file offset 132 */ 133 @NonNull 134 public Long getOffset() { 135 return this.offset; 136 } 137 138 /** 139 * The number of file bytes to write. 140 * 141 * @return the byte count 142 */ 143 @NonNull 144 public Long getCount() { 145 return this.count; 146 } 147 148 @Override 149 @NonNull 150 public Long getLength() { 151 return getCount(); 152 } 153 } 154 155 /** 156 * A static-file body acquired under the helper's trusted immutable-root contract. 157 * Soklet creates these descriptors for {@link StaticFiles}; an application cannot construct one 158 * directly. The opened channel is owned by the transport for the duration of delivery. 159 * <p> 160 * Custom transports must use {@link #openChannel()}, apply {@link #getOffset()} and {@link #getCount()}, 161 * and close the channel after delivery or failure. A transport that cannot handle this descriptor 162 * must reject it; opening the path separately loses the helper's root and file validation. 163 */ 164 @ThreadSafe 165 final class SecureFile implements MarshaledResponseBody { 166 private final @NonNull SecureStaticFileRoot root; 167 private final @NonNull Path path; 168 private final @NonNull Long offset; 169 private final @NonNull Long count; 170 private final @NonNull BasicFileAttributes attributes; 171 172 SecureFile(@NonNull SecureStaticFileRoot root, @NonNull Path path, @NonNull Long offset, @NonNull Long count, 173 @NonNull BasicFileAttributes attributes) { 174 this.root = requireNonNull(root); 175 this.path = requireNonNull(path); 176 this.offset = requireNonNull(offset); 177 this.count = requireNonNull(count); 178 this.attributes = requireNonNull(attributes); 179 validateOffsetAndCount(offset, count); 180 } 181 182 /** 183 * Opens the approved file after validating the captured root and expected file metadata. 184 * The immutable-root contract of {@link StaticFiles} applies to every acquisition. 185 * The caller must close the returned channel. 186 * 187 * @return an open channel for the response body 188 * @throws IOException if a change is detected or acquisition fails 189 */ 190 public @NonNull SeekableByteChannel openChannel() throws IOException { 191 return root.open(path, attributes); 192 } 193 194 /** @return the zero-based starting byte offset */ 195 public @NonNull Long getOffset() { 196 return offset; 197 } 198 199 /** @return the number of bytes to send */ 200 public @NonNull Long getCount() { 201 return count; 202 } 203 204 /** @return the number of bytes to send */ 205 @Override 206 public @NonNull Long getLength() { 207 return count; 208 } 209 } 210 211 /** 212 * A finalized response body backed by a {@link java.nio.channels.FileChannel}. 213 * <p> 214 * The channel remains caller-owned while a response is using it. Callers must not close it or modify the referenced 215 * region concurrently. The receiving transport closes the channel after delivery 216 * or abandonment only when {@link #getCloseOnComplete()} is {@code true}, by 217 * closing the containing {@link MarshaledResponse}. Custom transports must invoke 218 * {@link MarshaledResponse#close()} themselves at the terminal delivery point. 219 * <p> 220 * The standard HTTP server allows native transfer for the JDK's standard file channels when the platform supports it. 221 * Custom channels, including delegating wrappers and channels from other filesystem providers, use a socket adapter 222 * to identify target failures without risking another write after uncertain partial progress. This can lose zero-copy 223 * transfer, reduce throughput, and use more CPU. Supplying a wrapper's underlying JDK channel can retain native transfer 224 * only when bypassing the wrapper preserves the intended bytes, behavior, and ownership. 225 * <p> 226 * A custom channel's {@link java.nio.channels.FileChannel#transferTo(long, long, java.nio.channels.WritableByteChannel)} 227 * runs on the socket event loop. It must honor partial and zero-byte target writes and return the completed byte count; 228 * it must not spin or block waiting for socket capacity to finish the requested transfer. 229 * 230 * @author <a href="https://www.revetkn.com">Mark Allen</a> 231 */ 232 @ThreadSafe 233 final class FileChannel implements MarshaledResponseBody { 234 private final java.nio.channels.@NonNull FileChannel channel; 235 @NonNull 236 private final Long offset; 237 @NonNull 238 private final Long count; 239 @NonNull 240 private final Boolean closeOnComplete; 241 242 public FileChannel(java.nio.channels.@NonNull FileChannel channel, 243 @NonNull Long offset, 244 @NonNull Long count, 245 @NonNull Boolean closeOnComplete) { 246 this.channel = requireNonNull(channel); 247 this.offset = requireNonNull(offset); 248 this.count = requireNonNull(count); 249 this.closeOnComplete = requireNonNull(closeOnComplete); 250 validateOffsetAndCount(offset, count); 251 } 252 253 /** 254 * The file channel backing this body. 255 * 256 * @return the file channel 257 */ 258 public java.nio.channels.@NonNull FileChannel getChannel() { 259 return this.channel; 260 } 261 262 /** 263 * The zero-based channel offset from which response bytes should be written. 264 * 265 * @return the channel offset 266 */ 267 @NonNull 268 public Long getOffset() { 269 return this.offset; 270 } 271 272 /** 273 * The number of channel bytes to write. 274 * 275 * @return the byte count 276 */ 277 @NonNull 278 public Long getCount() { 279 return this.count; 280 } 281 282 /** 283 * Whether Soklet should close this caller-supplied channel after the response completes or fails. 284 * 285 * @return {@code true} if Soklet should close the channel 286 */ 287 @NonNull 288 public Boolean getCloseOnComplete() { 289 return this.closeOnComplete; 290 } 291 292 @Override 293 @NonNull 294 public Long getLength() { 295 return getCount(); 296 } 297 } 298 299 /** 300 * A finalized response body backed by a {@link java.nio.ByteBuffer}. 301 * <p> 302 * The buffer's position and limit at construction time define the response slice. The descriptor retains a 303 * read-only view, but the caller's original buffer may still share its content; callers must not mutate that content 304 * while a response is using this body. 305 * 306 * @author <a href="https://www.revetkn.com">Mark Allen</a> 307 */ 308 @ThreadSafe 309 final class ByteBuffer implements MarshaledResponseBody { 310 private final java.nio.@NonNull ByteBuffer buffer; 311 312 public ByteBuffer(java.nio.@NonNull ByteBuffer buffer) { 313 this.buffer = requireNonNull(buffer).slice().asReadOnlyBuffer(); 314 } 315 316 /** 317 * The read-only buffer slice backing this body. 318 * 319 * @return a read-only duplicate of the response buffer 320 */ 321 public java.nio.@NonNull ByteBuffer getBuffer() { 322 return this.buffer.asReadOnlyBuffer(); 323 } 324 325 @Override 326 @NonNull 327 public Long getLength() { 328 return Long.valueOf(this.buffer.remaining()); 329 } 330 } 331 332 private static void validateOffsetAndCount(@NonNull Long offset, @NonNull Long count) { 333 requireNonNull(offset); 334 requireNonNull(count); 335 336 if (offset < 0) 337 throw new IllegalArgumentException("Offset must be >= 0."); 338 339 if (count < 0) 340 throw new IllegalArgumentException("Count must be >= 0."); 341 342 if (Long.MAX_VALUE - offset < count) 343 throw new IllegalArgumentException("Offset plus count exceeds maximum supported file position."); 344 } 345}