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.NotThreadSafe; 022import javax.annotation.concurrent.ThreadSafe; 023import java.io.IOException; 024import java.io.OutputStream; 025import java.nio.ByteBuffer; 026import java.time.Duration; 027import java.time.Instant; 028import java.util.Optional; 029 030/** 031 * Response output, runtime metadata, and resource ownership for a streaming HTTP response producer. 032 * <p> 033 * Output and resource operations belong to the thread executing {@link StreamingResponseWriter#writeTo(ResponseStream)}. 034 * After the callback returns, Soklet performs remaining normal finalization on that thread before sealing successful 035 * output. Cancelation callbacks may already have closed resources opened with coordinated close-as-abort. 036 * The request, deadline, idle timeout, graceful-shutdown state, and thread-safe cancelation token may be read from other threads. 037 * Each response execution receives its own stream. Applications must not manually close owned resources or use 038 * them after their owning lifetime. Duplicate active ownership of the same resource instance is rejected. 039 * <p> 040 * The built-in HTTP server commits status and headers before invoking the producer. A later producer failure 041 * aborts delivery and cannot replace that status. Perform fallible status selection before returning the response. 042 * Cancelation cooperatively interrupts the producer thread. Output that observes an elected cancelation preserves 043 * the interrupt flag when translating an interruption into {@link StreamingResponseCanceledException}; cleanup 044 * temporarily clears and subsequently restores it so owned resources can close. 045 * 046 * @author <a href="https://www.revetkn.com">Mark Allen</a> 047 */ 048@NotThreadSafe 049public interface ResponseStream { 050 /** 051 * The request that produced this streaming response. 052 * 053 * @return the request that produced this streaming response 054 */ 055 @NonNull 056 Request getRequest(); 057 058 /** 059 * The thread-safe cancelation token for this streaming response. 060 * 061 * @return the cancelation token 062 */ 063 @NonNull 064 CancelationToken getCancelationToken(); 065 066 /** 067 * Has the HTTP owner requested that this response finish during graceful shutdown? 068 * <p> 069 * This thread-safe, per-execution state becomes {@code true} when graceful shutdown 070 * requests completion while production is still live, including before a queued producer 071 * starts. Once requested, it stays {@code true}. A completed or canceled response receives 072 * no new request, and forced shutdown alone does not set this state. 073 * <p> 074 * The request is advisory. It does not cancel the token, interrupt the producer, abort 075 * resources, close output, or change the configured response deadline or idle timeout. 076 * Finite responses may continue draining. An indefinite feed should check between items 077 * and use bounded waits, finish its final output, then return normally. Output and normal 078 * finalization remain subject to disconnects, deadlines and forced cancelation. A request 079 * alone is not proof of successful response delivery or physical termination. 080 * 081 * @return {@code true} if graceful completion was requested for this execution 082 */ 083 @NonNull 084 Boolean isGracefulShutdownRequested(); 085 086 /** 087 * The absolute deadline for this stream, if one is configured. 088 * 089 * @return the streaming deadline, or {@link Optional#empty()} if no deadline is configured 090 */ 091 @NonNull 092 Optional<@NonNull Instant> getDeadline(); 093 094 /** 095 * The idle timeout for this stream, if one is configured. 096 * 097 * @return the streaming idle timeout, or {@link Optional#empty()} if disabled 098 */ 099 @NonNull 100 Optional<@NonNull Duration> getIdleTimeout(); 101 102 /** 103 * Writes bytes to the response stream. 104 * <p> 105 * Implementations copy the provided bytes before this method returns. 106 * 107 * @param bytes the bytes to write 108 * @throws IOException if the bytes cannot be written 109 * @throws InterruptedException if the writer is already interrupted or is interrupted while waiting for stream capacity 110 * @throws StreamingResponseCanceledException if the stream has been canceled 111 */ 112 void write(byte @NonNull [] bytes) throws IOException, 113 InterruptedException; 114 115 /** 116 * Writes a slice of a byte array, copying the bytes before this method returns. 117 * Bounds are validated before accepting bytes or draining earlier staged output. 118 * 119 * @param bytes the array containing the bytes to write 120 * @param offset the index of the first byte 121 * @param length the number of bytes to write 122 * @throws IOException if the bytes cannot be written 123 * @throws InterruptedException if the writer is already interrupted or is interrupted while waiting for stream capacity 124 * @throws StreamingResponseCanceledException if the stream has been canceled 125 * @throws IndexOutOfBoundsException if the slice is outside the array 126 */ 127 void write(byte @NonNull [] bytes, @NonNull Integer offset, @NonNull Integer length) throws IOException, InterruptedException; 128 129 /** 130 * Writes the remaining bytes of a byte buffer to the response stream without mutating the caller's buffer. 131 * <p> 132 * Implementations copy the remaining bytes before this method returns. 133 * 134 * @param byteBuffer the byte buffer to write 135 * @throws IOException if the bytes cannot be written 136 * @throws InterruptedException if the writer is already interrupted or is interrupted while waiting for stream capacity 137 * @throws StreamingResponseCanceledException if the stream has been canceled 138 */ 139 void write(@NonNull ByteBuffer byteBuffer) throws IOException, InterruptedException; 140 141 /** 142 * Creates an independently closeable Java I/O view of this response stream. 143 * <p> 144 * Views share bounded scalar-write staging with this stream. Mixing views and native output preserves write order. 145 * Closing a view flushes staged bytes and closes only that view, even if flushing fails; repeated close is a no-op. 146 * Other views and native output remain usable while the response permits writes. Closing a view does not close the socket. 147 * Soklet closes owned wrappers before flushing remaining staging on successful response finalization. 148 * <p> 149 * An interrupted view operation throws {@link java.io.InterruptedIOException}, retains the original interruption as 150 * its cause, and restores the interrupt flag. Its {@code bytesTransferred} counts bytes accepted from that call, 151 * excluding bytes staged by earlier calls; acceptance is not acknowledgment by the client. An already elected 152 * cancelation is reported as {@link StreamingResponseCanceledException} instead. I/O failure or interruption during 153 * an otherwise valid output operation is terminal, including when application code catches the exception. 154 * Argument, thread, and lifetime validation failures do not invalidate otherwise usable output. 155 * <p> 156 * Writes and flushes on a closed view or outside the response lifetime throw {@link IOException}; native output 157 * outside its lifetime throws {@link IllegalStateException}. All output operations, including view close, belong 158 * to the producer thread; use from another thread throws {@link IllegalStateException}. 159 * 160 * @return a new output view 161 * @throws IllegalStateException if called outside the output lifetime or from another thread 162 */ 163 @NonNull 164 OutputStream asOutputStream(); 165 166 /** 167 * Hints that buffered bytes should be made available to the transport promptly. 168 * <p> 169 * Calling this method is not required for correctness. Soklet flushes any remaining bytes when the stream completes successfully. 170 * 171 * @throws IOException if the stream cannot be flushed 172 * @throws InterruptedException if the writer is already interrupted or is interrupted while waiting for stream capacity 173 * @throws StreamingResponseCanceledException if the stream has been canceled 174 */ 175 void flush() throws IOException, InterruptedException; 176 177 /** 178 * Is this stream currently open for writes? 179 * 180 * @return {@code true} if open 181 */ 182 @NonNull 183 Boolean isOpen(); 184 185 /** 186 * Opens and owns a resource whose close operation can abort concurrent consumption. 187 * <p> 188 * Normal cleanup and cancelation coordinate one physical close attempt, including if close fails. 189 * The provider must support close racing use and unblocking that use; {@link AutoCloseable} alone does not 190 * establish this contract. Acquisition does not start if cancelation has already won. A resource returned 191 * after cancelation is disposed before it can be used. 192 * <p> 193 * A classic socket read can throw {@link java.net.SocketException} when cancelation closes its 194 * owned socket or input stream before producer interruption takes effect. This can produce a 195 * {@link LogEventType#RESPONSE_STREAM_FAILED} diagnostic while preserving the elected cancelation outcome. 196 * On platform threads, interruption alone does not unblock a classic socket read. This applies when a custom 197 * streaming executor uses platform threads. If cancelation must 198 * close the socket to unblock that read, its close-induced exception remains diagnostic when it escapes the producer. 199 * 200 * @param streamResourceFactory the checked resource factory 201 * @param <T> the resource type 202 * @return the resource owned by the innermost lexical lifetime, or the response lifetime 203 * @throws Exception if acquisition or disposal fails 204 */ 205 @NonNull 206 <T extends @NonNull AutoCloseable> T open(@NonNull StreamResourceFactory<? extends @NonNull T> streamResourceFactory) throws Exception; 207 208 /** 209 * Opens and owns a resource with a separate provider-supported abort operation. 210 * <p> 211 * Abort and final close are each attempted once. Final close runs on the producer thread and waits for an 212 * already-started abort; an abort can race a close that has already started. The provider must support these 213 * interactions. Passing {@code Resource::close} as the aborter can close twice and is not equivalent to 214 * {@link #open(StreamResourceFactory)}. 215 * 216 * @param streamResourceFactory the checked resource factory 217 * @param resourceAborter the checked concurrent abort operation 218 * @param <T> the resource type 219 * @return the resource owned by the innermost lexical lifetime, or the response lifetime 220 * @throws Exception if acquisition or disposal fails 221 */ 222 @NonNull 223 <T extends @NonNull AutoCloseable> T open(@NonNull StreamResourceFactory<? extends @NonNull T> streamResourceFactory, 224 @NonNull ResourceAborter<? super @NonNull T> resourceAborter) throws Exception; 225 226 /** 227 * Transfers an existing resource for finalization on the producer thread, without concurrent close-as-abort. 228 * <p> 229 * Useful for encoders whose close writes final response bytes. During the active producer lifetime, an offered 230 * resource is disposed if cancelation has already won. Calls before production, during cleanup, after lifetime 231 * completion, or from another thread are rejected before ownership transfers; the caller remains responsible 232 * for the resource in those cases. 233 * <p> 234 * Healthy encoder tail writes remain subject to response and idle deadlines. Time waiting for the HTTP 235 * output queue does not consume application-cleanup grace. After failure or cancelation, output attempted 236 * by managed resource close is discarded while close still releases the resource; ordinary producer writes 237 * continue to report the terminal outcome. Independent resource-close failures remain diagnostic errors. 238 * 239 * @param resource the resource whose ownership is transferred 240 * @param <T> the resource type 241 * @return the same resource 242 * @throws Exception if disposal after cancelation fails 243 */ 244 @NonNull 245 <T extends @NonNull AutoCloseable> T own(@NonNull T resource) throws Exception; 246 247 /** 248 * Uses a resource in a shorter lexical lifetime with coordinated close-as-abort. 249 * <p> 250 * Normal finalization closes the resource and every nested acquisition or adoption through this stream in reverse 251 * ownership order before the call returns. Cancelation callbacks have no guaranteed global abort order. 252 * The provider must support concurrent close as documented by 253 * {@link #open(StreamResourceFactory)}. 254 * 255 * @param streamResourceFactory the checked resource factory 256 * @param resourceConsumer the checked lexical body 257 * @param <T> the resource type 258 * @throws Exception if acquisition, the lexical body, or cleanup fails 259 */ 260 <T extends @NonNull AutoCloseable> void using(@NonNull StreamResourceFactory<? extends @NonNull T> streamResourceFactory, 261 @NonNull ResourceConsumer<? super @NonNull T> resourceConsumer) throws Exception; 262 263 /** 264 * Uses a resource in a shorter lexical lifetime with separate abort and final-close operations. 265 * <p> 266 * All nested acquisitions and adoptions end with this lexical body. The provider must support the concurrency 267 * contract documented by {@link #open(StreamResourceFactory, ResourceAborter)}. 268 * 269 * @param streamResourceFactory the checked resource factory 270 * @param resourceAborter the checked concurrent abort operation 271 * @param resourceConsumer the checked lexical body 272 * @param <T> the resource type 273 * @throws Exception if acquisition, the lexical body, or cleanup fails 274 */ 275 <T extends @NonNull AutoCloseable> void using(@NonNull StreamResourceFactory<? extends @NonNull T> streamResourceFactory, 276 @NonNull ResourceAborter<? super @NonNull T> resourceAborter, 277 @NonNull ResourceConsumer<? super @NonNull T> resourceConsumer) throws Exception; 278 279 /** 280 * A provider-supported concurrent abort operation, distinct from final close. 281 * Implementations reused across responses must support concurrent invocation. 282 * 283 * @param <T> the resource type 284 */ 285 @ThreadSafe 286 @FunctionalInterface 287 interface ResourceAborter<T extends @NonNull AutoCloseable> { 288 /** 289 * Aborts use of the resource. 290 * 291 * @param resource the owned resource 292 * @throws Exception if abort fails 293 */ 294 void abort(@NonNull T resource) throws Exception; 295 } 296 297 /** 298 * A lexical resource body invoked on the response producer thread. 299 * Implementations reused across responses must support concurrent invocation of their shared state; 300 * each response still confines its resource consumption to its own producer thread. 301 * 302 * @param <T> the resource type 303 */ 304 @ThreadSafe 305 @FunctionalInterface 306 interface ResourceConsumer<T extends @NonNull AutoCloseable> { 307 /** 308 * Uses the resource within its lexical lifetime. 309 * 310 * @param resource the owned resource 311 * @throws Exception if the lexical body fails 312 */ 313 void accept(@NonNull T resource) throws Exception; 314 } 315}